Skip to main content

javm_transpiler/
emitter.rs

1//! PVM bitmask packer.
2//!
3//! Internally the transpiler tracks instruction starts as a `Vec<u8>`
4//! parallel to the code bytes (one byte per code byte; 0 =
5//! continuation, 1 = instruction start). The chain Image's wire
6//! format uses the compact bit-packed form (one bit per code byte).
7//! [`pack_bitmask`] converts.
8
9/// Pack a bitmask array (one byte per bit, 0 or 1) into packed bytes (LSB first).
10pub fn pack_bitmask(bitmask: &[u8]) -> Vec<u8> {
11    let packed_len = bitmask.len().div_ceil(8);
12    let mut packed = vec![0u8; packed_len];
13    for (i, &bit) in bitmask.iter().enumerate() {
14        if bit != 0 {
15            packed[i / 8] |= 1 << (i % 8);
16        }
17    }
18    packed
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[test]
26    fn test_pack_bitmask() {
27        assert_eq!(pack_bitmask(&[1, 1, 1]), vec![0x07]);
28        assert_eq!(pack_bitmask(&[1, 0, 1, 0, 1, 0, 1, 0]), vec![0x55]);
29        assert_eq!(pack_bitmask(&[1, 0, 1, 0, 1, 0, 1, 0, 1]), vec![0x55, 0x01]);
30    }
31}