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, honoring 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 [`Self::bytein`].
23    ct: i32,
24    /// Whether a byte past the end of `data` has been pulled in.
25    overran: bool,
26}
27
28impl<'a> BitReader<'a> {
29    /// A reader positioned at the first bit of `data`.
30    pub fn new(data: &'a [u8]) -> Self {
31        BitReader {
32            data,
33            pos: 0,
34            buf: 0,
35            ct: 0,
36            overran: false,
37        }
38    }
39
40    /// Pull the next byte into the window. If the byte just shifted into the
41    /// high position is `0xFF`, the incoming byte contributes only seven bits
42    /// (its stuffed MSB is dropped). Past the end the byte reads as `0xFF`.
43    fn bytein(&mut self) {
44        self.buf = (self.buf << 8) & 0xFFFF;
45        self.ct = if self.buf == 0xFF00 { 7 } else { 8 };
46        let byte = self.data.get(self.pos).copied().unwrap_or(0xFF);
47        if self.pos < self.data.len() {
48            self.pos += 1;
49        } else {
50            self.overran = true;
51        }
52        self.buf |= byte as u32;
53    }
54
55    /// Read one bit (MSB-first). Reading past the end of `data` yields `1`.
56    pub fn read_bit(&mut self) -> u32 {
57        if self.ct == 0 {
58            self.bytein();
59        }
60        self.ct -= 1;
61        (self.buf >> self.ct) & 1
62    }
63
64    /// Read `n` bits (`0..=32`) MSB-first into the low bits of the result.
65    pub fn read(&mut self, n: u32) -> u32 {
66        let mut v = 0;
67        for i in (0..n).rev() {
68            v |= self.read_bit() << i;
69        }
70        v
71    }
72
73    /// Byte-align at the end of a packet header (Annex B.10.1, OpenJPEG
74    /// `opj_bio_inalign`): drop any partially-read byte, and if the last whole
75    /// byte was `0xFF` consume the following stuffed byte too (its bits are not
76    /// header content). After this, [`bytes_consumed`](Self::bytes_consumed)
77    /// reports where the packet body begins.
78    pub fn align(&mut self) {
79        if self.buf & 0xFF == 0xFF {
80            self.bytein();
81        }
82        self.ct = 0;
83    }
84
85    /// Whether the reader has pulled in a byte past the end of `data`: the
86    /// header it read does not fit in the bytes there are.
87    pub fn overran(&self) -> bool {
88        self.overran
89    }
90
91    /// Whole bytes consumed from `data` so far. Meaningful at a byte boundary —
92    /// before the first read, or after [`align`](Self::align). A partially-read
93    /// byte (`ct > 0`) counts as not yet consumed.
94    ///
95    /// The subtraction saturates: a reader past the end of an empty `data` has
96    /// `ct > 0` with `pos == 0` (every bit synthesized, none consumed), where
97    /// a plain `pos - 1` would panic on underflow.
98    pub fn bytes_consumed(&self) -> usize {
99        if self.ct == 0 {
100            self.pos
101        } else {
102            self.pos.saturating_sub(1)
103        }
104    }
105
106    /// Where the reader stands: bytes pulled in and bits left in the last.
107    /// Two readers over the same data stand at the same bit when these agree.
108    #[cfg(test)]
109    pub fn position(&self) -> (usize, i32) {
110        (self.pos, self.ct)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::BitReader;
117
118    /// A reader that has only synthesized past-end fill bits (empty input) has
119    /// consumed nothing; `bytes_consumed` must not underflow.
120    #[test]
121    fn bytes_consumed_on_empty_input_is_zero() {
122        let mut b = BitReader::new(&[]);
123        let _ = b.read_bit();
124        assert_eq!(b.bytes_consumed(), 0);
125    }
126
127    /// Bits come out most significant first, byte by byte.
128    #[test]
129    fn reads_msb_first() {
130        let mut b = BitReader::new(&[0b1011_0010, 0b0100_0000]);
131        let bits: Vec<u32> = (0..8).map(|_| b.read_bit()).collect();
132        assert_eq!(bits, [1, 0, 1, 1, 0, 0, 1, 0]);
133        // The first two bits of the next byte continue the stream.
134        assert_eq!(b.read(2), 0b01);
135    }
136
137    /// `read(n)` packs `n` MSB-first bits into the low end of the result.
138    #[test]
139    fn read_multiple_bits() {
140        let mut b = BitReader::new(&[0xA5, 0x3C]);
141        assert_eq!(b.read(4), 0xA); // 1010
142        assert_eq!(b.read(4), 0x5); // 0101
143        assert_eq!(b.read(8), 0x3C);
144    }
145
146    /// After a `0xFF` byte the next byte's most significant bit is stuffed and
147    /// skipped (Annex B.10.1): the byte supplies only seven bits.
148    #[test]
149    fn ff_byte_stuffs_following_msb() {
150        // 0xFF = eight 1s; then 0x80 = 1000_0000, whose stuffed MSB is dropped,
151        // leaving seven 0 bits.
152        let mut b = BitReader::new(&[0xFF, 0x80]);
153        for _ in 0..8 {
154            assert_eq!(b.read_bit(), 1, "first byte is all ones");
155        }
156        for _ in 0..7 {
157            assert_eq!(b.read_bit(), 0, "stuffed byte yields seven zeros");
158        }
159    }
160
161    /// Reading past the end yields `1` bits and never panics or runs `pos` away.
162    #[test]
163    fn past_end_is_bounded() {
164        let mut b = BitReader::new(&[0x00]);
165        // The single byte's eight 0 bits, then the 0xFF fill convention.
166        for _ in 0..8 {
167            assert_eq!(b.read_bit(), 0);
168        }
169        for _ in 0..64 {
170            assert_eq!(b.read_bit(), 1);
171        }
172    }
173
174    /// An empty input is immediately in the fill region; it must not panic.
175    #[test]
176    fn empty_input_is_bounded() {
177        let mut b = BitReader::new(&[]);
178        for _ in 0..16 {
179            let _ = b.read_bit();
180        }
181    }
182
183    /// Aligning after a partial byte discards the remaining bits and counts the
184    /// byte as consumed; the next byte is where a packet body would start.
185    #[test]
186    fn align_rounds_up_partial_byte() {
187        let mut b = BitReader::new(&[0b1011_0000, 0xAB]);
188        assert_eq!(b.read(4), 0b1011);
189        b.align();
190        assert_eq!(b.bytes_consumed(), 1);
191    }
192
193    /// A header byte of `0xFF` stuffs the next byte: aligning must skip that
194    /// whole stuffed byte (Annex B.10.1), so the body begins one byte later.
195    #[test]
196    fn align_skips_stuffed_byte_after_ff() {
197        let mut b = BitReader::new(&[0xFF, 0x80, 0xAB]);
198        for _ in 0..8 {
199            assert_eq!(b.read_bit(), 1);
200        }
201        b.align();
202        // 0xFF consumed, then the stuffed 0x80 skipped: body starts at index 2.
203        assert_eq!(b.bytes_consumed(), 2);
204    }
205
206    /// Aligning when already on a byte boundary (and not after `0xFF`) consumes
207    /// nothing further.
208    #[test]
209    fn align_on_boundary_is_noop() {
210        let mut b = BitReader::new(&[0x3C, 0xAB]);
211        assert_eq!(b.read(8), 0x3C);
212        b.align();
213        assert_eq!(b.bytes_consumed(), 1);
214    }
215
216    /// The stuffing test is on the *most recently loaded* byte, not the last
217    /// whole byte: a header ending part-way through a `0xFF` byte must still skip
218    /// the following stuffed byte (matching OpenJPEG `opj_bio_inalign`).
219    #[test]
220    fn align_skips_stuffed_byte_when_ending_mid_ff() {
221        let mut b = BitReader::new(&[0x2F, 0xFF, 0x00, 0xBB]);
222        assert_eq!(b.read(8), 0x2F);
223        // Read only four bits of the 0xFF byte, ending mid-byte on it.
224        assert_eq!(b.read(4), 0xF);
225        b.align();
226        // The 0xFF byte (index 1) forces the next byte (the 0x00 stuff byte) to
227        // be skipped, so the body starts at index 3.
228        assert_eq!(b.bytes_consumed(), 3);
229    }
230}