Skip to main content

gtars_refget/digest/
streaming_decoder.rs

1//! Streaming decoder for bit-packed encoded sequences - WASM-safe.
2//!
3//! Unlike [`decode_substring_from_bytes`](super::encoder::decode_substring_from_bytes),
4//! which requires the entire encoded byte slice to be buffered in memory,
5//! [`StreamingDecoder`] consumes an [`std::io::Read`] source incrementally and
6//! emits decoded ASCII bases via its own `Read` implementation. Only a tiny
7//! bit buffer (`u64`) of internal state is used, so memory is bounded regardless
8//! of sequence length.
9//!
10//! The decoder relies on the supplied [`Alphabet`]'s `decoding_array`, so `N`
11//! and other ambiguity codes are handled identically to the in-memory path.
12//!
13//! # Bit ordering
14//!
15//! Matches the encoder: MSB-first within each byte (see
16//! [`encode_sequence`](super::encoder::encode_sequence)).
17//!
18//! # Non-byte-aligned windows
19//!
20//! For alphabets where `bits_per_symbol` does not divide 8 (2-bit, 3-bit, 5-bit),
21//! a requested `[start, end)` base window typically does not land on byte
22//! boundaries. Callers should:
23//!
24//! 1. Feed the decoder the exact byte range
25//!    `[floor(start * bps / 8), ceil(end * bps / 8))`.
26//! 2. Pass `leading_skip_bits = (start * bps) mod 8` — the number of *bits* at
27//!    the very front of the byte window that precede the requested base window
28//!    (0..=7). The decoder consumes and discards them before emitting.
29//! 3. Pass `bases_to_emit = end - start`.
30//!
31//! For the Raw / ASCII case (`bits_per_symbol == 8`), byte and base boundaries
32//! coincide; pass `leading_skip = 0`.
33
34use std::io::{self, Read};
35
36use super::alphabet::Alphabet;
37
38/// Streaming decoder for bit-packed encoded sequences.
39///
40/// Wraps any `impl Read` source and implements `Read` itself, emitting
41/// decoded ASCII bases. Internal state is O(bits_per_symbol) — just a
42/// 64-bit bit buffer plus a handful of counters.
43pub struct StreamingDecoder<R: Read> {
44    inner: R,
45    alphabet: &'static Alphabet,
46    bits_per_symbol: u8,
47    bases_remaining: u64,
48    /// Number of bits to discard at the front of the byte stream (0..=7).
49    /// Consumed on the first `read` call.
50    leading_skip_bits: u8,
51    bit_buffer: u64,
52    bit_buffer_len: u8,
53}
54
55impl<R: Read> StreamingDecoder<R> {
56    /// Construct a new streaming decoder.
57    ///
58    /// - `inner` - Byte source providing the bit-packed encoded sequence.
59    /// - `alphabet` - Alphabet whose `bits_per_symbol` and `decoding_array` drive decoding.
60    /// - `leading_skip_bits` - Number of bits at the very start of the byte
61    ///   stream to discard before the first emitted symbol. Must be `< 8`.
62    ///   Should be `0` when `bits_per_symbol == 8`.
63    /// - `bases_to_emit` - Total number of bases the decoder will emit via `Read`.
64    pub fn new(
65        inner: R,
66        alphabet: &'static Alphabet,
67        leading_skip_bits: u8,
68        bases_to_emit: u64,
69    ) -> Self {
70        let bits_per_symbol = alphabet.bits_per_symbol as u8;
71        debug_assert!(
72            bits_per_symbol > 0 && bits_per_symbol <= 8,
73            "StreamingDecoder supports 1..=8 bits per symbol, got {}",
74            bits_per_symbol
75        );
76        debug_assert!(
77            leading_skip_bits < 8,
78            "leading_skip_bits must be < 8, got {}",
79            leading_skip_bits
80        );
81        StreamingDecoder {
82            inner,
83            alphabet,
84            bits_per_symbol,
85            bases_remaining: bases_to_emit,
86            leading_skip_bits,
87            bit_buffer: 0,
88            bit_buffer_len: 0,
89        }
90    }
91
92    /// Ensure `bit_buffer` contains at least `min_bits` valid bits, reading
93    /// more bytes from `inner` if needed. Returns `UnexpectedEof` if the
94    /// source is exhausted before the requirement is met.
95    fn refill(&mut self, min_bits: u8) -> io::Result<()> {
96        while self.bit_buffer_len < min_bits {
97            // Pull up to 6 bytes at a time when the bit buffer has room.
98            // `bit_buffer` is u64 = 64 bits; keep headroom so we never
99            // overflow when shifting in a full byte.
100            let headroom_bits = 64u8.saturating_sub(self.bit_buffer_len);
101            let max_bytes = (headroom_bits / 8) as usize;
102            let want = max_bytes.clamp(1, 6);
103            let mut tmp = [0u8; 6];
104            let n = loop {
105                match self.inner.read(&mut tmp[..want]) {
106                    Ok(0) => {
107                        return Err(io::Error::new(
108                            io::ErrorKind::UnexpectedEof,
109                            "StreamingDecoder: source ended before all bases were decoded",
110                        ));
111                    }
112                    Ok(n) => break n,
113                    Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
114                    Err(e) => return Err(e),
115                }
116            };
117            for &b in &tmp[..n] {
118                self.bit_buffer = (self.bit_buffer << 8) | (b as u64);
119                self.bit_buffer_len += 8;
120            }
121        }
122        Ok(())
123    }
124
125    /// Pull the next decoded base from the stream, or `Ok(None)` if the
126    /// configured base budget has been exhausted.
127    fn next_symbol(&mut self) -> io::Result<Option<u8>> {
128        if self.bases_remaining == 0 {
129            return Ok(None);
130        }
131        self.refill(self.bits_per_symbol)?;
132
133        let shift = self.bit_buffer_len - self.bits_per_symbol;
134        let mask: u64 = if self.bits_per_symbol == 64 {
135            u64::MAX
136        } else {
137            (1u64 << self.bits_per_symbol) - 1
138        };
139        let code = ((self.bit_buffer >> shift) & mask) as u8;
140        self.bit_buffer_len -= self.bits_per_symbol;
141        // Mask off consumed bits so they don't leak into later symbols.
142        let keep_mask: u64 = if self.bit_buffer_len == 0 {
143            0
144        } else {
145            (1u64 << self.bit_buffer_len) - 1
146        };
147        self.bit_buffer &= keep_mask;
148
149        self.bases_remaining -= 1;
150        Ok(Some(self.alphabet.decoding_array[code as usize]))
151    }
152}
153
154impl<R: Read> Read for StreamingDecoder<R> {
155    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
156        // Discard any leading bits from the start of the byte stream (the
157        // bits that preceded the requested base window within the first byte).
158        if self.leading_skip_bits > 0 {
159            self.refill(self.leading_skip_bits)?;
160            // Consume (discard) the top `leading_skip_bits` of the buffer.
161            self.bit_buffer_len -= self.leading_skip_bits;
162            let keep_mask: u64 = if self.bit_buffer_len == 0 {
163                0
164            } else {
165                (1u64 << self.bit_buffer_len) - 1
166            };
167            self.bit_buffer &= keep_mask;
168            self.leading_skip_bits = 0;
169        }
170
171        let mut written = 0;
172        while written < buf.len() {
173            match self.next_symbol()? {
174                Some(base) => {
175                    buf[written] = base;
176                    written += 1;
177                }
178                None => break,
179            }
180        }
181        Ok(written)
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::digest::alphabet::{
189        ASCII_ALPHABET, AlphabetType, DNA_2BIT_ALPHABET, DNA_3BIT_ALPHABET, DNA_IUPAC_ALPHABET,
190        PROTEIN_ALPHABET, guess_alphabet,
191    };
192    use crate::digest::encoder::{decode_substring_from_bytes, encode_sequence};
193    use std::io::Cursor;
194
195    /// Compute the tight byte window and leading-skip for a `[start, end)`
196    /// base range, matching what `RefgetStore::stream_sequence` will do.
197    fn byte_window(
198        start: usize,
199        end: usize,
200        bits_per_symbol: usize,
201    ) -> (usize, usize, u8) {
202        let start_bit = start * bits_per_symbol;
203        let end_bit = end * bits_per_symbol;
204        let byte_start = start_bit / 8;
205        let byte_end = end_bit.div_ceil(8);
206        let leading_skip_bits = (start_bit - byte_start * 8) as u8;
207        (byte_start, byte_end, leading_skip_bits)
208    }
209
210    fn run_range_test(
211        sequence: &[u8],
212        alphabet: &'static Alphabet,
213        start: usize,
214        end: usize,
215    ) {
216        let encoded = encode_sequence(sequence, alphabet).unwrap();
217        let (byte_start, byte_end, leading_skip) =
218            byte_window(start, end, alphabet.bits_per_symbol);
219        let slice = &encoded[byte_start..byte_end.min(encoded.len())];
220
221        let mut decoder = StreamingDecoder::new(
222            Cursor::new(slice.to_vec()),
223            alphabet,
224            leading_skip,
225            (end - start) as u64,
226        );
227        let mut out = Vec::new();
228        decoder.read_to_end(&mut out).expect("streaming read failed");
229
230        // Main assertion: streamed output must equal the ORIGINAL INPUT
231        // slice, not just agree with another decoder reading the same
232        // (possibly wrong) table.
233        assert_eq!(
234            out,
235            &sequence[start..end],
236            "streamed output does not match source input: alphabet bps={} range [{}, {}) sequence={:?}",
237            alphabet.bits_per_symbol,
238            start,
239            end,
240            std::str::from_utf8(sequence).unwrap_or("<non-utf8>")
241        );
242
243        // Secondary cross-check against the other decode path.
244        let expected = decode_substring_from_bytes(&encoded, start, end, alphabet);
245        assert_eq!(
246            out, expected,
247            "streaming decoder disagrees with decode_substring_from_bytes: bps={} range [{}, {})",
248            alphabet.bits_per_symbol, start, end
249        );
250    }
251
252    /// The Protein fixture, factored out so `test_protein_5bit_unaligned`
253    /// uses the exact same bytes as `fixtures()` and the two cannot drift
254    /// apart. Covers every Protein symbol, including U/B/Z/O/J, which the
255    /// guesser now sends to Protein (see `fixtures_match_guesser` below).
256    fn protein_fixture() -> &'static [u8] {
257        b"ACDEFGHIKLMNPQRSTVWY*X-.UBZOJ"
258    }
259
260    // Test inputs per alphabet. Each sequence is chosen to exercise the
261    // decoder across the full symbol set where possible, and must be an
262    // input the real pipeline would actually send to that alphabet (see
263    // `fixtures_match_guesser`).
264    fn fixtures() -> Vec<(&'static Alphabet, &'static [u8])> {
265        vec![
266            (&DNA_2BIT_ALPHABET, b"ACGTACGTACGTACGT" as &[u8]),
267            // All 8 Dna3bit symbols, including U (RNA fits in 3 bits).
268            (&DNA_3BIT_ALPHABET, b"ACGTNRYUACGTNRYC" as &[u8]),
269            // All 16 DnaIupac symbols including U; 17 symbols long so the
270            // half-byte tail of the 4-bit packing is exercised. `-` dropped:
271            // it is not a DnaIupac member (encodes to 0b0000, decodes 'N'),
272            // so it could never round-trip and the real pipeline would send
273            // it to Protein/Ascii, not DnaIupac.
274            (&DNA_IUPAC_ALPHABET, b"ACGTURYSWKMBDHVNA" as &[u8]),
275            (&PROTEIN_ALPHABET, protein_fixture()),
276            // Standard-alphabet passthrough: digits, punctuation, spaces and
277            // lowercase force Ascii.
278            (&ASCII_ALPHABET, b"Hello, World! 1234" as &[u8]),
279        ]
280    }
281
282    /// Every fixture must be an input the real pipeline would actually send
283    /// to that alphabet -- otherwise the fixture tests a case that never
284    /// happens. Ascii is exempt: it is the catch-all, so any guess of Ascii
285    /// is fine for that fixture regardless of what forced it there.
286    #[test]
287    fn fixtures_match_guesser() {
288        for (alphabet, seq) in fixtures() {
289            let guessed = guess_alphabet(seq);
290            if alphabet.alphabet_type == AlphabetType::Ascii {
291                continue;
292            }
293            assert_eq!(
294                guessed,
295                alphabet.alphabet_type,
296                "fixture for {:?} is actually guessed as {:?}: {:?}",
297                alphabet.alphabet_type,
298                guessed,
299                std::str::from_utf8(seq).unwrap_or("<non-utf8>")
300            );
301        }
302    }
303
304    #[test]
305    fn test_full_sequence() {
306        for (alphabet, seq) in fixtures() {
307            run_range_test(seq, alphabet, 0, seq.len());
308        }
309    }
310
311    #[test]
312    fn test_aligned_start_aligned_end() {
313        // For 2-bit, 4 symbols per byte — [4, 12) is byte-aligned.
314        run_range_test(
315            b"ACGTACGTACGTACGT",
316            &DNA_2BIT_ALPHABET,
317            4,
318            12,
319        );
320    }
321
322    #[test]
323    fn test_unaligned_start() {
324        run_range_test(
325            b"ACGTACGTACGTACGT",
326            &DNA_2BIT_ALPHABET,
327            1,
328            16,
329        );
330    }
331
332    #[test]
333    fn test_unaligned_end() {
334        run_range_test(
335            b"ACGTACGTACGTACGT",
336            &DNA_2BIT_ALPHABET,
337            0,
338            15,
339        );
340    }
341
342    #[test]
343    fn test_unaligned_both_3bit() {
344        run_range_test(
345            b"ACGTNRYUACGTNRYU",
346            &DNA_3BIT_ALPHABET,
347            1,
348            7,
349        );
350    }
351
352    #[test]
353    fn test_zero_length() {
354        // Zero-length windows should emit nothing regardless of alphabet or
355        // leading_skip_bits — the bit-buffer never needs refilling.
356        for (alphabet, seq) in fixtures() {
357            let encoded = encode_sequence(seq, alphabet).unwrap();
358            // A zero-length window at offset 5 — the decoder should read
359            // zero bytes and produce an empty output.
360            let mut decoder = StreamingDecoder::new(
361                Cursor::new(encoded.clone()),
362                alphabet,
363                0,
364                0,
365            );
366            let mut out = Vec::new();
367            decoder.read_to_end(&mut out).expect("zero-length read");
368            assert!(out.is_empty());
369        }
370    }
371
372    #[test]
373    fn test_single_base() {
374        for (alphabet, seq) in fixtures() {
375            for start in 0..seq.len() {
376                run_range_test(seq, alphabet, start, start + 1);
377            }
378        }
379    }
380
381    #[test]
382    fn test_start_at_end_minus_one() {
383        for (alphabet, seq) in fixtures() {
384            run_range_test(seq, alphabet, seq.len() - 1, seq.len());
385        }
386    }
387
388    #[test]
389    fn test_read_small_buf() {
390        let sequence = b"ACGTACGTACGTACGT";
391        let alphabet = &DNA_2BIT_ALPHABET;
392        let encoded = encode_sequence(sequence, alphabet).unwrap();
393        let (byte_start, byte_end, leading_skip) =
394            byte_window(1, 15, alphabet.bits_per_symbol);
395        let slice = &encoded[byte_start..byte_end];
396
397        let mut decoder = StreamingDecoder::new(
398            Cursor::new(slice.to_vec()),
399            alphabet,
400            leading_skip,
401            (15 - 1) as u64,
402        );
403
404        // Read into a 3-byte buffer repeatedly.
405        let mut small_buf = [0u8; 3];
406        let mut collected = Vec::new();
407        loop {
408            let n = decoder.read(&mut small_buf).unwrap();
409            if n == 0 {
410                break;
411            }
412            collected.extend_from_slice(&small_buf[..n]);
413        }
414
415        let expected = decode_substring_from_bytes(&encoded, 1, 15, alphabet);
416        assert_eq!(collected, expected);
417        assert_eq!(collected, &sequence[1..15]);
418    }
419
420    #[test]
421    fn test_protein_5bit_unaligned() {
422        let sequence = protein_fixture();
423        let alphabet = &PROTEIN_ALPHABET;
424        // Test starts that are non-byte-aligned at 5 bits per symbol.
425        for start in 0..sequence.len() {
426            for end in (start + 1)..=sequence.len() {
427                run_range_test(sequence, alphabet, start, end);
428            }
429        }
430    }
431
432    #[test]
433    fn test_ascii_passthrough() {
434        let sequence = b"The quick brown fox";
435        let alphabet = &ASCII_ALPHABET;
436        run_range_test(sequence, alphabet, 0, sequence.len());
437        run_range_test(sequence, alphabet, 4, 9);
438    }
439
440    #[test]
441    fn test_unexpected_eof() {
442        // Provide a truncated source and ask for more bases than fit.
443        let sequence = b"ACGTACGT";
444        let alphabet = &DNA_2BIT_ALPHABET;
445        let encoded = encode_sequence(sequence, alphabet).unwrap();
446        // Only feed 1 byte (4 bases worth) but ask for 8 bases.
447        let mut decoder = StreamingDecoder::new(
448            Cursor::new(encoded[..1].to_vec()),
449            alphabet,
450            0,
451            8,
452        );
453        let mut buf = [0u8; 16];
454        let err = decoder.read(&mut buf).unwrap_err();
455        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
456    }
457
458    /// A reader that yields at most 1 byte per `read` call, simulating the
459    /// worst-case partial-read behaviour of an unbuffered network source.
460    struct TrickleReader<R: Read> {
461        inner: R,
462    }
463
464    impl<R: Read> TrickleReader<R> {
465        fn new(inner: R) -> Self {
466            Self { inner }
467        }
468    }
469
470    impl<R: Read> Read for TrickleReader<R> {
471        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
472            if buf.is_empty() {
473                return Ok(0);
474            }
475            // Only ever read 1 byte even when buf is larger.
476            self.inner.read(&mut buf[..1])
477        }
478    }
479
480    #[test]
481    fn test_multi_byte_refill_with_trickle_reader() {
482        // Verifies the multi-byte refill path handles partial reads (1 byte
483        // per call) correctly — the decoder should produce identical output
484        // whether the inner reader yields 1 byte or many at a time.
485        for (alphabet, seq) in fixtures() {
486            let encoded = encode_sequence(seq, alphabet).unwrap();
487            for start in 0..seq.len() {
488                for end in (start + 1)..=seq.len() {
489                    let (byte_start, byte_end, leading_skip) =
490                        byte_window(start, end, alphabet.bits_per_symbol);
491                    let slice = &encoded[byte_start..byte_end.min(encoded.len())];
492                    let expected = decode_substring_from_bytes(&encoded, start, end, alphabet);
493
494                    let trickle = TrickleReader::new(Cursor::new(slice.to_vec()));
495                    let mut decoder = StreamingDecoder::new(
496                        trickle,
497                        alphabet,
498                        leading_skip,
499                        (end - start) as u64,
500                    );
501                    let mut out = Vec::new();
502                    decoder
503                        .read_to_end(&mut out)
504                        .expect("trickle read failed");
505                    assert_eq!(
506                        out, expected,
507                        "TrickleReader: bps={} range [{}, {}) alphabet",
508                        alphabet.bits_per_symbol, start, end
509                    );
510                }
511            }
512        }
513    }
514}