Skip to main content

oscyl_driver/
pack.rs

1//! KORG 7-in-8 packing: each group of up to 7 data bytes is sent as one byte
2//! holding their MSBs (bit i = MSB of byte i) followed by their low 7 bits.
3
4/// A byte that must be 7-bit had its high bit set.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
6#[error("byte {0:#04x} is not 7-bit")]
7pub struct NotSevenBit(pub u8);
8
9/// Packed length of `n` data bytes.
10pub fn packed_len(n: usize) -> usize {
11    n + n.div_ceil(7)
12}
13
14/// Pack 8-bit data into 7-bit-safe SysEx payload bytes.
15pub fn pack(data: &[u8]) -> Vec<u8> {
16    let mut out = Vec::with_capacity(packed_len(data.len()));
17    for group in data.chunks(7) {
18        let msbs = group
19            .iter()
20            .enumerate()
21            .fold(0u8, |m, (i, b)| m | ((b >> 7) << i));
22        out.push(msbs);
23        out.extend(group.iter().map(|b| b & 0x7F));
24    }
25    out
26}
27
28/// Unpack 7-bit SysEx payload bytes into 8-bit data.
29pub fn unpack(data: &[u8]) -> Result<Vec<u8>, NotSevenBit> {
30    if let Some(&b) = data.iter().find(|&&b| b >= 0x80) {
31        return Err(NotSevenBit(b));
32    }
33    let mut out = Vec::with_capacity(data.len());
34    for group in data.chunks(8) {
35        let (msbs, rest) = group.split_first().expect("chunks are non-empty");
36        out.extend(
37            rest.iter()
38                .enumerate()
39                .map(|(i, b)| b | (((msbs >> i) & 1) << 7)),
40        );
41    }
42    Ok(out)
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn packed_lengths_match_device_sizes() {
51        assert_eq!(packed_len(1024), 1171); // program
52        assert_eq!(packed_len(80), 92); // global
53    }
54
55    #[test]
56    fn known_vector() {
57        assert_eq!(pack(&[0x80, 0x01]), [0x01, 0x00, 0x01]);
58    }
59
60    #[test]
61    fn round_trip() {
62        for n in [0, 1, 7, 8, 1024] {
63            let data: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
64            let packed = pack(&data);
65            assert_eq!(packed.len(), packed_len(n));
66            assert!(packed.iter().all(|&b| b < 0x80));
67            assert_eq!(unpack(&packed).unwrap(), data);
68        }
69    }
70
71    #[test]
72    fn rejects_eight_bit_input() {
73        assert_eq!(unpack(&[0x00, 0x80]), Err(NotSevenBit(0x80)));
74    }
75}