Skip to main content

expand

Function expand 

Source
pub fn expand(value: u64, mask: u64) -> u64
Expand description

Parallel bit deposit: scatter the lowest mask.count_ones() bits of value into the set positions of mask, preserving their order. All other bits in the result are zero; excess input bits are ignored.

This is the inverse of compress on the selected bits: expand(compress(value, mask), mask) == value & mask.

Equivalent to the x86 BMI2 PDEP instruction. When compiled with the bmi2 target feature enabled (for example -C target-cpu=x86-64-v3) this lowers to the hardware pdep instruction; otherwise it falls back to a portable scalar loop that visits whichever is fewer: unset or set bits in mask.

§Functional Example

Using 8 bits for brevity (the function operates on all 64). The low bits of value are scattered into the set positions of mask:

bit:     7 6 5 4 3 2 1 0
value:   0 0 0 b c e f h
mask:    0 1 1 0 1 1 0 1
result:  0 b c 0 e f 0 h

§Code Example

assert_eq!(expand(0b0000_1010, 0b0110_1101), 0b0010_0100);
let value = 0b1011_0100;
let mask = 0b0110_1101;
assert_eq!(expand(compress(value, mask), mask), value & mask);