pymatching 0.1.0

Safe Rust bindings for the PyMatching quantum error-correction decoder
Documentation
//! Little-endian bit packing used by batch decoding.
//!
//! Bit `i` is stored in byte `i / 8` at bit position `i % 8`, matching
//! PyMatching's `bit_packed_shots` and `bit_packed_predictions` format.

/// Returns the number of bytes required to store `bit_count` bits.
#[must_use]
pub fn required_packed_bytes(bit_count: usize) -> usize {
    bit_count.div_ceil(8)
}

/// Packs the least-significant bit of each value in little-endian order.
///
/// ```
/// use pymatching::bit_packing::pack_bits_le;
///
/// assert_eq!(pack_bits_le(&[1, 0, 1, 1, 0, 0, 0, 0, 1]), vec![13, 1]);
/// ```
#[must_use]
pub fn pack_bits_le(bits: &[u8]) -> Vec<u8> {
    let mut packed = vec![0; required_packed_bytes(bits.len())];
    for (index, &bit) in bits.iter().enumerate() {
        if bit & 1 == 1 {
            packed[index / 8] |= 1 << (index % 8);
        }
    }
    packed
}

/// Unpacks `bit_count` little-endian bits into zeros and ones.
///
/// # Panics
///
/// Panics if `bytes` contains fewer than [`required_packed_bytes`] bytes.
///
/// ```
/// use pymatching::bit_packing::unpack_bits_le;
///
/// assert_eq!(unpack_bits_le(&[13], 4), vec![1, 0, 1, 1]);
/// ```
#[must_use]
pub fn unpack_bits_le(bytes: &[u8], bit_count: usize) -> Vec<u8> {
    let mut unpacked = vec![0; bit_count];
    for index in 0..bit_count {
        unpacked[index] = (bytes[index / 8] >> (index % 8)) & 1;
    }
    unpacked
}