mirror of
https://github.com/vlang/v.git
synced 2025-09-08 06:41:58 -04:00
bitfield: add shift_left/1
and shift_right/1
methods to BitField
(#22700)
This commit is contained in:
parent
d79b85099c
commit
2f75348b67
@ -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]
|
||||
|
@ -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'
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user