bitfield: add shift_left/1 and shift_right/1 methods to BitField (#22700)

This commit is contained in:
kbkpbot 2024-10-31 03:55:42 +08:00 committed by GitHub
parent d79b85099c
commit 2f75348b67
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 40 additions and 0 deletions

View File

@ -600,6 +600,32 @@ pub fn (instance BitField) rotate(offset int) BitField {
return output
}
// shift_left shift-left the bits by `count` positions.
pub fn (instance BitField) shift_left(count int) BitField {
size := instance.size
if count <= 0 {
return instance
} else if count >= size {
// return zeroes
return new(size)
}
zeroes := new(count)
return join(instance.slice(count, size), zeroes)
}
// shift_right shift-right the bits by `count` positions.
pub fn (instance BitField) shift_right(count int) BitField {
size := instance.size
if count <= 0 {
return instance
} else if count >= size {
// return zeroes
return new(size)
}
zeroes := new(count)
return join(zeroes, instance.slice(0, size - count))
}
// Internal functions
// clear_tail clears the extra bits that are not part of the bitfield, but yet are allocated
@[inline]

View File

@ -358,3 +358,17 @@ fn test_bf_printing() {
println(input)
assert true
}
fn test_bf_shift() {
str := '0001001101111111'
bf := bitfield.from_str(str)
bf_left := bf.shift_left(4)
assert bf_left.str() == '0011011111110000'
bf_right := bf.shift_right(4)
assert bf_right.str() == '0000000100110111'
bf_large_left := bf.shift_left(100)
bf_large_right := bf.shift_right(100)
assert bf_large_left.str() == '0000000000000000'
assert bf_large_right.str() == '0000000000000000'
}