#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use crate::error::{Error, Result};
pub const RAW_GROUP: usize = 7;
pub const PACKED_GROUP: usize = 8;
#[must_use]
pub const fn packed_len(raw_len: usize) -> usize {
raw_len.div_ceil(RAW_GROUP) * PACKED_GROUP
}
pub const fn unpacked_len(packed_len: usize) -> Result<usize> {
let rest = packed_len % PACKED_GROUP;
if rest == 1 {
return Err(Error::PackedRunLength(packed_len));
}
Ok(packed_len / PACKED_GROUP * RAW_GROUP + rest.saturating_sub(1))
}
pub fn pack_into(raw: &[u8], out: &mut [u8]) -> Result<usize> {
let needed = packed_len(raw.len());
let available = out.len();
let out = out
.get_mut(..needed)
.ok_or(Error::BufferTooSmall { needed, available })?;
for (group, packed) in raw.chunks(RAW_GROUP).zip(out.chunks_mut(PACKED_GROUP)) {
let high = group
.iter()
.enumerate()
.fold(0u8, |bits, (index, byte)| bits | ((byte >> 7) << index));
if let Some(slot) = packed.first_mut() {
*slot = high;
}
let data = group
.iter()
.map(|byte| byte & 0x7F)
.chain(core::iter::repeat(0));
for (slot, byte) in packed.iter_mut().skip(1).zip(data) {
*slot = byte;
}
}
Ok(needed)
}
pub fn unpack_into(packed: &[u8], out: &mut [u8]) -> Result<usize> {
let needed = unpacked_len(packed.len())?;
let available = out.len();
let out = out
.get_mut(..needed)
.ok_or(Error::BufferTooSmall { needed, available })?;
for (group, raw) in packed.chunks(PACKED_GROUP).zip(out.chunks_mut(RAW_GROUP)) {
let Some((high, data)) = group.split_first() else {
continue;
};
for (index, (slot, byte)) in raw.iter_mut().zip(data).enumerate() {
*slot = (byte & 0x7F) | (((high >> index) & 1) << 7);
}
}
Ok(needed)
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[must_use]
pub fn pack(raw: &[u8]) -> Vec<u8> {
let mut out = alloc::vec![0; packed_len(raw.len())];
let written = pack_into(raw, &mut out).unwrap_or(0);
out.truncate(written);
out
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn unpack(packed: &[u8]) -> Result<Vec<u8>> {
let mut out = alloc::vec![0; unpacked_len(packed.len())?];
unpack_into(packed, &mut out)?;
Ok(out)
}
#[cfg(all(test, feature = "alloc"))]
#[expect(
clippy::expect_used,
reason = "a failed expectation is the test failure"
)]
mod tests {
use super::*;
fn sample(len: usize) -> Vec<u8> {
let mut state = 0x1234_5678_9ABC_DEF0_u64;
(0..len)
.map(|_| {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
#[expect(
clippy::cast_possible_truncation,
reason = "the low byte is the sample"
)]
{
(state >> 33) as u8
}
})
.collect()
}
#[test]
fn packing_round_trips_for_every_length_up_to_four_groups() {
for len in 0..=28 {
let raw = sample(len);
let packed = pack(&raw);
assert_eq!(packed.len(), packed_len(len));
assert!(
packed.iter().all(|byte| byte < &0x80),
"packed data must fit seven bits"
);
let back = unpack(&packed).expect("a packed run unpacks");
assert_eq!(
back.get(..len),
Some(raw.as_slice()),
"{len} bytes did not survive"
);
assert!(
back.get(len..)
.is_some_and(|tail| tail.iter().all(|b| *b == 0))
);
}
}
#[test]
fn a_group_carries_the_high_bits_in_its_first_byte() {
let packed = pack(&[0x80, 0x00, 0xFF, 0x7F]);
assert_eq!(packed, [0b0000_0101, 0x00, 0x00, 0x7F, 0x7F, 0, 0, 0]);
}
#[test]
fn the_manual_tabulates_the_padded_length_everywhere_but_the_program_dump() {
for (raw, packed) in [
(45, 56),
(65, 80),
(2048, 2344),
(16, 24),
(26, 32),
(512, 592),
] {
assert_eq!(packed_len(raw), packed, "{raw} raw bytes");
}
assert_eq!(packed_len(242), 280);
assert_ne!(packed_len(242), 278);
}
#[test]
fn a_short_last_group_unpacks_as_readily_as_a_padded_one() {
let raw = sample(242);
let padded = pack(&raw);
assert_eq!(padded.len(), 280);
let short = padded.get(..277).expect("280 bytes to cut down").to_vec();
let back = unpack(&short).expect("a short run unpacks");
assert_eq!(back.len(), 242);
assert_eq!(back, raw);
}
#[test]
fn a_run_ending_in_a_lone_high_bit_byte_is_rejected() {
assert_eq!(unpacked_len(1), Err(Error::PackedRunLength(1)));
assert_eq!(unpacked_len(9), Err(Error::PackedRunLength(9)));
assert_eq!(unpack(&[0x00]), Err(Error::PackedRunLength(1)));
assert_eq!(unpacked_len(0), Ok(0));
assert_eq!(unpacked_len(8), Ok(7));
assert_eq!(unpacked_len(2), Ok(1));
}
#[test]
fn a_buffer_that_cannot_hold_the_result_is_reported_rather_than_filled() {
let mut small = [0u8; 4];
assert_eq!(
pack_into(&[1, 2, 3, 4], &mut small),
Err(Error::BufferTooSmall {
needed: 8,
available: 4
})
);
assert_eq!(small, [0; 4]);
assert_eq!(
unpack_into(&[0, 1, 2, 3, 4, 5, 6, 7], &mut small),
Err(Error::BufferTooSmall {
needed: 7,
available: 4
})
);
}
#[test]
fn bit_seven_of_an_input_byte_is_ignored() {
let mut out = [0u8; 7];
unpack_into(&[0xFF, 0xFF, 0, 0, 0, 0, 0, 0], &mut out).expect("buffer fits");
assert_eq!(out, [0xFF, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]);
}
}