Skip to main content

rust_j2k/tier2/
bio.rs

1//! The packet-header bit reader (ISO/IEC 15444-1 Annex B.10.1).
2//!
3//! Packet-header values — the tag-tree bits, inclusion bits, coding-pass and
4//! length fields — are packed MSB-first into bytes with a stuffing rule: once a
5//! byte equals `0xFF`, the most significant bit of the following byte is a
6//! stuffed `0` and is skipped, so the header can never accidentally spell a
7//! marker (`0xFF90`–`0xFFFF`). This reader is the decode side of that packing;
8//! the Tier-2 packet parser drives it, and the [tag tree](super::tagtree) reads
9//! one bit at a time through it.
10
11/// An MSB-first bit reader over a packet header's bytes, honouring the Annex
12/// B.10.1 `0xFF` bit-stuffing. Past the end of `data` it yields `1` bits (the
13/// `0xFF` fill convention), which also bounds every read so a truncated header
14/// can never index out of range or panic.
15#[derive(Debug)]
16pub struct BitReader<'a> {
17    data: &'a [u8],
18    pos: usize,
19    /// A 16-bit window: the previously consumed byte in bits 8..=15, the current
20    /// byte in bits 0..=7 (matching OpenJPEG's `opj_bio` convention).
21    buf: u32,
22    /// Bits left to read from `buf`'s low byte before the next [`bytein`].
23    ct: i32,
24}
25
26impl<'a> BitReader<'a> {
27    /// A reader positioned at the first bit of `data`.
28    pub fn new(data: &'a [u8]) -> Self {
29        BitReader {
30            data,
31            pos: 0,
32            buf: 0,
33            ct: 0,
34        }
35    }
36
37    /// Pull the next byte into the window. If the byte just shifted into the
38    /// high position is `0xFF`, the incoming byte contributes only seven bits
39    /// (its stuffed MSB is dropped). Past the end the byte reads as `0xFF`.
40    fn bytein(&mut self) {
41        self.buf = (self.buf << 8) & 0xFFFF;
42        self.ct = if self.buf == 0xFF00 { 7 } else { 8 };
43        let byte = self.data.get(self.pos).copied().unwrap_or(0xFF);
44        if self.pos < self.data.len() {
45            self.pos += 1;
46        }
47        self.buf |= byte as u32;
48    }
49
50    /// Read one bit (MSB-first). Reading past the end of `data` yields `1`.
51    pub fn read_bit(&mut self) -> u32 {
52        if self.ct == 0 {
53            self.bytein();
54        }
55        self.ct -= 1;
56        (self.buf >> self.ct) & 1
57    }
58
59    /// Read `n` bits (`0..=32`) MSB-first into the low bits of the result.
60    pub fn read(&mut self, n: u32) -> u32 {
61        let mut v = 0;
62        for i in (0..n).rev() {
63            v |= self.read_bit() << i;
64        }
65        v
66    }
67
68    /// Byte-align at the end of a packet header (Annex B.10.1, OpenJPEG
69    /// `opj_bio_inalign`): drop any partially-read byte, and if the last whole
70    /// byte was `0xFF` consume the following stuffed byte too (its bits are not
71    /// header content). After this, [`bytes_consumed`](Self::bytes_consumed)
72    /// reports where the packet body begins.
73    pub fn align(&mut self) {
74        if self.buf & 0xFF == 0xFF {
75            self.bytein();
76        }
77        self.ct = 0;
78    }
79
80    /// Whole bytes consumed from `data` so far. Meaningful at a byte boundary —
81    /// before the first read, or after [`align`](Self::align). A partially-read
82    /// byte (`ct > 0`) counts as not yet consumed.
83    pub fn bytes_consumed(&self) -> usize {
84        if self.ct == 0 { self.pos } else { self.pos - 1 }
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use super::BitReader;
91
92    /// Bits come out most significant first, byte by byte.
93    #[test]
94    fn reads_msb_first() {
95        let mut b = BitReader::new(&[0b1011_0010, 0b0100_0000]);
96        let bits: Vec<u32> = (0..8).map(|_| b.read_bit()).collect();
97        assert_eq!(bits, [1, 0, 1, 1, 0, 0, 1, 0]);
98        // The first two bits of the next byte continue the stream.
99        assert_eq!(b.read(2), 0b01);
100    }
101
102    /// `read(n)` packs `n` MSB-first bits into the low end of the result.
103    #[test]
104    fn read_multiple_bits() {
105        let mut b = BitReader::new(&[0xA5, 0x3C]);
106        assert_eq!(b.read(4), 0xA); // 1010
107        assert_eq!(b.read(4), 0x5); // 0101
108        assert_eq!(b.read(8), 0x3C);
109    }
110
111    /// After a `0xFF` byte the next byte's most significant bit is stuffed and
112    /// skipped (Annex B.10.1): the byte supplies only seven bits.
113    #[test]
114    fn ff_byte_stuffs_following_msb() {
115        // 0xFF = eight 1s; then 0x80 = 1000_0000, whose stuffed MSB is dropped,
116        // leaving seven 0 bits.
117        let mut b = BitReader::new(&[0xFF, 0x80]);
118        for _ in 0..8 {
119            assert_eq!(b.read_bit(), 1, "first byte is all ones");
120        }
121        for _ in 0..7 {
122            assert_eq!(b.read_bit(), 0, "stuffed byte yields seven zeros");
123        }
124    }
125
126    /// Reading past the end yields `1` bits and never panics or runs `pos` away.
127    #[test]
128    fn past_end_is_bounded() {
129        let mut b = BitReader::new(&[0x00]);
130        // The single byte's eight 0 bits, then the 0xFF fill convention.
131        for _ in 0..8 {
132            assert_eq!(b.read_bit(), 0);
133        }
134        for _ in 0..64 {
135            assert_eq!(b.read_bit(), 1);
136        }
137    }
138
139    /// An empty input is immediately in the fill region; it must not panic.
140    #[test]
141    fn empty_input_is_bounded() {
142        let mut b = BitReader::new(&[]);
143        for _ in 0..16 {
144            let _ = b.read_bit();
145        }
146    }
147
148    /// Aligning after a partial byte discards the remaining bits and counts the
149    /// byte as consumed; the next byte is where a packet body would start.
150    #[test]
151    fn align_rounds_up_partial_byte() {
152        let mut b = BitReader::new(&[0b1011_0000, 0xAB]);
153        assert_eq!(b.read(4), 0b1011);
154        b.align();
155        assert_eq!(b.bytes_consumed(), 1);
156    }
157
158    /// A header byte of `0xFF` stuffs the next byte: aligning must skip that
159    /// whole stuffed byte (Annex B.10.1), so the body begins one byte later.
160    #[test]
161    fn align_skips_stuffed_byte_after_ff() {
162        let mut b = BitReader::new(&[0xFF, 0x80, 0xAB]);
163        for _ in 0..8 {
164            assert_eq!(b.read_bit(), 1);
165        }
166        b.align();
167        // 0xFF consumed, then the stuffed 0x80 skipped: body starts at index 2.
168        assert_eq!(b.bytes_consumed(), 2);
169    }
170
171    /// Aligning when already on a byte boundary (and not after `0xFF`) consumes
172    /// nothing further.
173    #[test]
174    fn align_on_boundary_is_noop() {
175        let mut b = BitReader::new(&[0x3C, 0xAB]);
176        assert_eq!(b.read(8), 0x3C);
177        b.align();
178        assert_eq!(b.bytes_consumed(), 1);
179    }
180
181    /// The stuffing test is on the *most recently loaded* byte, not the last
182    /// whole byte: a header ending part-way through a `0xFF` byte must still skip
183    /// the following stuffed byte (matching OpenJPEG `opj_bio_inalign`).
184    #[test]
185    fn align_skips_stuffed_byte_when_ending_mid_ff() {
186        let mut b = BitReader::new(&[0x2F, 0xFF, 0x00, 0xBB]);
187        assert_eq!(b.read(8), 0x2F);
188        // Read only four bits of the 0xFF byte, ending mid-byte on it.
189        assert_eq!(b.read(4), 0xF);
190        b.align();
191        // The 0xFF byte (index 1) forces the next byte (the 0x00 stuff byte) to
192        // be skipped, so the body starts at index 3.
193        assert_eq!(b.bytes_consumed(), 3);
194    }
195}