Skip to main content

brotli/concat/
mod.rs

1//! Joins brotli streams that were compressed to be concatenated (`-appendable` for the first
2//! stream, `-catable` for the rest) into one stream.
3//!
4//! A brotli stream is a sequence of bits, least significant bit first: a window size, then
5//! meta-blocks. It ends with an empty meta-block, which is just the two bits ISLAST and
6//! ISLASTEMPTY, followed by zero padding to the end of the byte. A catable stream starts with a
7//! meta-block whose header leaves the stream byte aligned (an uncompressed or metadata
8//! meta-block, or the stream's final empty one), and it never refers back to data before itself.
9//!
10//! So appending stream B to output A only takes changing a few bits where they meet:
11//!
12//! ```text
13//!   A:            ... | ISLAST ISLASTEMPTY | padding
14//!   B:                                       window size | header | padding | aligned bytes ...
15//!   A then B:     ... | header | padding | aligned bytes ...
16//! ```
17//!
18//! A's ISLAST/ISLASTEMPTY pair always lies in its last two bytes, so `BroCatli` holds the last two
19//! bytes of the output back (the *tail*) until it knows whether another stream follows, and copies
20//! everything else straight through.
21
22use core::cmp::min;
23
24#[repr(C)]
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub enum BroCatliResult {
27    Success = 0,
28    NeedsMoreInput = 1,
29    NeedsMoreOutput = 2,
30    BrotliFileNotCraftedForAppend = 124,
31    InvalidWindowSize = 125,
32    WindowSizeLargerThanPreviousFile = 126,
33    BrotliFileNotCraftedForConcatenation = 127,
34}
35
36/// How many bytes of a new stream are buffered to find where it becomes byte aligned.
37const NUM_STREAM_HEADER_BYTES: usize = 5;
38
39/// The most bytes of a new stream that are read before giving up on finding where it becomes
40/// byte aligned: 4, or 5 for a large window size. That fits an uncompressed first meta-block of up
41/// to 1 MiB (five length nibbles), or metadata with up to two length bytes.
42fn max_header_bytes(header: &[u8]) -> usize {
43    match header.first() {
44        Some(byte) if byte & 0x7f == 0x11 => 5, // large window size marker
45        _ => 4,
46    }
47}
48
49/// The value of bits `start..end` of `bytes`, least significant bit first.
50fn bit_range(bytes: &[u8], start: usize, end: usize) -> u64 {
51    let all = bytes
52        .iter()
53        .rev()
54        .fold(0u64, |value, byte| (value << 8) | u64::from(*byte));
55    (all >> start) & ((1u64 << (end - start)) - 1)
56}
57
58enum ParseError {
59    /// More bytes of the stream are needed.
60    Incomplete,
61    Invalid(BroCatliResult),
62}
63
64/// Reads bits from the buffered start of a stream.
65struct BitReader<'a> {
66    bytes: &'a [u8],
67    position: usize,
68}
69
70impl<'a> BitReader<'a> {
71    fn read(&mut self, num_bits: usize) -> Result<u64, ParseError> {
72        let end = self.position + num_bits;
73        if end > self.bytes.len() * 8 {
74            return Err(ParseError::Incomplete);
75        }
76        let value = bit_range(self.bytes, self.position, end);
77        self.position = end;
78        Ok(value)
79    }
80
81    /// Reads the window size (log2 of the window in bytes) that starts every stream.
82    fn read_window_size(&mut self) -> Result<u8, ParseError> {
83        let invalid = ParseError::Invalid(BroCatliResult::InvalidWindowSize);
84        if self.read(1)? == 0 {
85            return Ok(16);
86        }
87        let size = self.read(3)? as u8;
88        if size != 0 {
89            return Ok(17 + size);
90        }
91        match self.read(3)? as u8 {
92            0 => Ok(17),
93            1 => {
94                // large window size: a zero bit, then six bits of size
95                if self.read(1)? != 0 {
96                    return Err(invalid);
97                }
98                let size = self.read(6)? as u8;
99                if (10..=30).contains(&size) {
100                    Ok(size)
101                } else {
102                    Err(invalid)
103                }
104            }
105            size => Ok(8 + size),
106        }
107    }
108
109    /// Reads the header of a catable stream's first meta-block, after which the stream is byte
110    /// aligned.
111    fn read_first_metablock_header(&mut self) -> Result<(), ParseError> {
112        let not_catable = ParseError::Invalid(BroCatliResult::BrotliFileNotCraftedForConcatenation);
113        let is_last = self.read(1)? == 1;
114        if is_last && self.read(1)? == 1 {
115            return Ok(()); // ISLASTEMPTY: the stream is empty
116        }
117        let mlen_nibbles = self.read(2)?;
118        if mlen_nibbles == 3 {
119            // metadata: a reserved zero bit, then the byte count of its length, then its length
120            if self.read(1)? != 0 {
121                return Err(not_catable);
122            }
123            let length_bytes = self.read(2)? as usize;
124            self.read(8 * length_bytes)?;
125            return Ok(());
126        }
127        self.read(4 * (4 + mlen_nibbles as usize))?;
128        // only a meta-block that is not the last has an ISUNCOMPRESSED bit; a compressed one is
129        // not byte aligned
130        if is_last || self.read(1)? == 0 {
131            return Err(not_catable);
132        }
133        Ok(())
134    }
135}
136
137/// Assembles bits into bytes, least significant bit first.
138#[derive(Default)]
139struct BitWriter {
140    bits: u64,
141    num_bits: usize,
142}
143
144impl BitWriter {
145    fn write(&mut self, value: u64, num_bits: usize) {
146        assert!(self.num_bits + num_bits <= 64);
147        self.bits |= value << self.num_bits;
148        self.num_bits += num_bits;
149    }
150
151    fn write_bytes(&mut self, bytes: &[u8]) {
152        for byte in bytes {
153            self.write(u64::from(*byte), 8);
154        }
155    }
156
157    /// Writes zero bits up to the next byte boundary.
158    fn pad_to_byte(&mut self) {
159        self.num_bits = (self.num_bits + 7) / 8 * 8;
160    }
161
162    /// Pads the bits to a whole byte, returning the bytes and their count.
163    fn finish(mut self) -> ([u8; 8], usize) {
164        self.pad_to_byte();
165        (self.bits.to_le_bytes(), self.num_bits / 8)
166    }
167}
168
169/// Splits the final bytes of a stream into the bits before its closing ISLAST + ISLASTEMPTY pair,
170/// returning them with their count, or `None` if the bytes don't end that way.
171fn remove_final_empty_metablock(final_bytes: &[u8]) -> Option<(u64, usize)> {
172    let bits = bit_range(final_bytes, 0, final_bytes.len() * 8);
173    if bits == 0 {
174        return None;
175    }
176    let islastempty = 63 - bits.leading_zeros() as usize; // the highest set bit
177    if islastempty == 0 || (bits >> (islastempty - 1)) != 0b11 {
178        return None;
179    }
180    let num_bits = islastempty - 1;
181    Some((bit_range(final_bytes, 0, num_bits), num_bits))
182}
183
184/// A few buffered bytes.
185#[derive(Clone, Copy, Default)]
186#[cfg_attr(test, derive(Debug, PartialEq))]
187struct ByteBuf {
188    bytes: [u8; NUM_STREAM_HEADER_BYTES],
189    len: u8,
190}
191
192impl ByteBuf {
193    fn from_slice(bytes: &[u8]) -> ByteBuf {
194        let mut buf = ByteBuf::default();
195        buf.bytes[..bytes.len()].copy_from_slice(bytes);
196        buf.len = bytes.len() as u8;
197        buf
198    }
199
200    fn as_slice(&self) -> &[u8] {
201        &self.bytes[..usize::from(self.len)]
202    }
203}
204
205#[derive(Clone, Copy)]
206#[cfg_attr(test, derive(Debug, PartialEq))]
207enum Phase {
208    /// Copying the current stream through to the output.
209    PassThrough,
210    /// Buffering the start of a new stream until it can be spliced onto the output.
211    ReadHeader(ByteBuf),
212    /// The new stream has been spliced on; these bytes of the splice are waiting for output space.
213    WriteSplice { bytes: ByteBuf, written: u8 },
214    /// The new stream ended before its first meta-block header did.
215    Truncated,
216}
217
218impl Default for Phase {
219    fn default() -> Phase {
220        Phase::PassThrough
221    }
222}
223
224// eat your vegetables
225#[derive(Default)]
226#[cfg_attr(test, derive(Debug, PartialEq))]
227pub struct BroCatli {
228    /// The last bytes of the output (at most two), held back because they hold the ISLAST and
229    /// ISLASTEMPTY bits that end the stream, which have to go if another stream is appended.
230    tail: [u8; 2],
231    tail_len: u8,
232    /// The first stream's window size, or 0 before it is known; later streams may not exceed it.
233    window_size: u8,
234    /// Whether any bytes were written; if none are, `finish` writes an empty stream.
235    any_bytes_emitted: bool,
236    phase: Phase,
237}
238
239// Serialized layout, which the FFI also uses to hold its state:
240//   [0..2]    tail                      [8]   tail_len
241//   [9]       flags (below)             [10]  open tail bit offset (old versions only)
242//   [11]      window_size               [12]  number of buffered bytes
243//   [13]      buffered bytes written    [16..16 + NUM_STREAM_HEADER_BYTES]  buffered bytes
244const FLAG_OPEN_TAIL: u8 = 1 << 0; // old versions only: the tail's final empty meta-block is removed
245const FLAG_TRUNCATED: u8 = 1 << 1;
246const FLAG_ANY_BYTES_EMITTED: u8 = 1 << 5;
247const FLAG_NEW_STREAM: u8 = 1 << 6; // the phase is not PassThrough
248const FLAG_WRITE_SPLICE: u8 = 1 << 7;
249
250impl BroCatli {
251    pub fn new() -> Self {
252        Self::default()
253    }
254
255    pub fn deserialize_from_buffer(buffer: &[u8]) -> Result<BroCatli, ()> {
256        if 16 + NUM_STREAM_HEADER_BYTES > buffer.len() {
257            return Err(());
258        }
259        let tail_len = buffer[8];
260        let flags = buffer[9];
261        let open_tail_bit_offset = buffer[10];
262        let window_size = buffer[11];
263        if tail_len > 2 || open_tail_bit_offset >= 8 {
264            return Err(());
265        }
266        if window_size != 0 && BroCatli::try_new_with_window_size(window_size).is_err() {
267            return Err(());
268        }
269        let mut buffered = ByteBuf::default();
270        buffered
271            .bytes
272            .copy_from_slice(&buffer[16..16 + NUM_STREAM_HEADER_BYTES]);
273        buffered.len = buffer[12];
274        let written = buffer[13];
275        let phase = if flags & FLAG_NEW_STREAM == 0 {
276            Phase::PassThrough
277        } else if usize::from(buffered.len) > NUM_STREAM_HEADER_BYTES {
278            return Err(());
279        } else if flags & FLAG_WRITE_SPLICE != 0 {
280            if written > buffered.len {
281                return Err(());
282            }
283            Phase::WriteSplice {
284                bytes: buffered,
285                written,
286            }
287        } else if flags & FLAG_TRUNCATED != 0 {
288            Phase::Truncated
289        } else {
290            Phase::ReadHeader(buffered)
291        };
292        let mut ret = BroCatli {
293            tail: [buffer[0], buffer[1]],
294            tail_len,
295            window_size,
296            any_bytes_emitted: flags & FLAG_ANY_BYTES_EMITTED != 0,
297            phase,
298        };
299        if flags & FLAG_OPEN_TAIL != 0 && tail_len != 0 {
300            // Old versions removed the tail's final empty meta-block as soon as a new stream
301            // started. Put it back; it is removed again when the new stream is spliced on.
302            let num_bits = usize::from(tail_len - 1) * 8 + usize::from(open_tail_bit_offset);
303            let mut tail = BitWriter::default();
304            tail.write(bit_range(&ret.tail, 0, num_bits), num_bits);
305            tail.write(0b11, 2);
306            let (bytes, len) = tail.finish();
307            if len > 2 {
308                return Err(());
309            }
310            ret.set_tail(&bytes[..len]);
311        }
312        Ok(ret)
313    }
314
315    #[inline(always)]
316    pub fn serialize_to_buffer(&self, buffer: &mut [u8]) -> Result<(), ()> {
317        if 16 + NUM_STREAM_HEADER_BYTES > buffer.len() {
318            return Err(());
319        }
320        let mut flags = 0;
321        if self.any_bytes_emitted {
322            flags |= FLAG_ANY_BYTES_EMITTED;
323        }
324        let (buffered, written) = match self.phase {
325            Phase::PassThrough => (None, 0),
326            Phase::ReadHeader(header) => (Some(header), 0),
327            Phase::WriteSplice { bytes, written } => {
328                flags |= FLAG_WRITE_SPLICE;
329                (Some(bytes), written)
330            }
331            Phase::Truncated => {
332                flags |= FLAG_TRUNCATED;
333                (Some(ByteBuf::default()), 0)
334            }
335        };
336        buffer[..2].copy_from_slice(&self.tail);
337        buffer[8] = self.tail_len;
338        buffer[10] = 0;
339        buffer[11] = self.window_size;
340        if let Some(buffered) = buffered {
341            flags |= FLAG_NEW_STREAM;
342            buffer[12] = buffered.len;
343            buffer[13] = written;
344            // 14, 15 reserved
345            buffer[16..16 + NUM_STREAM_HEADER_BYTES].copy_from_slice(&buffered.bytes);
346        }
347        buffer[9] = flags;
348        Ok(())
349    }
350
351    /// Creates a `BroCatli` with an initial window size.
352    ///
353    /// Panics for invalid window sizes. Use `try_new_with_window_size` to detect
354    /// invalid input without panicking.
355    pub fn new_with_window_size(log_window_size: u8) -> BroCatli {
356        Self::try_new_with_window_size(log_window_size).expect("invalid brotli window size")
357    }
358
359    /// Creates a `BroCatli` with an initial window size, or returns an error for invalid sizes.
360    pub fn try_new_with_window_size(log_window_size: u8) -> Result<BroCatli, BroCatliResult> {
361        // Start as if an empty stream with this window size had already been written: the first
362        // stream is then spliced onto it, checking its window size like any later stream's.
363        let mut empty_stream = BitWriter::default();
364        let window_size = u64::from(log_window_size);
365        match log_window_size {
366            16 => empty_stream.write(0, 1),
367            17 => empty_stream.write(0b0000001, 7),
368            18..=24 => empty_stream.write(1 | ((window_size - 17) << 1), 4),
369            10..=15 => empty_stream.write(1 | ((window_size - 8) << 4), 7),
370            25..=30 => {
371                empty_stream.write(0x11, 8);
372                empty_stream.write(window_size, 6);
373            }
374            _ => return Err(BroCatliResult::InvalidWindowSize),
375        }
376        empty_stream.write(0b11, 2); // ISLAST, ISLASTEMPTY
377        let (bytes, len) = empty_stream.finish();
378        let mut ret = BroCatli {
379            window_size: log_window_size,
380            ..BroCatli::default()
381        };
382        ret.set_tail(&bytes[..len]);
383        Ok(ret)
384    }
385
386    pub fn new_brotli_file(&mut self) {
387        self.phase = match self.phase {
388            // a stream is spliced as soon as its header is complete, so this one was cut short
389            Phase::ReadHeader(header) if header.len != 0 => Phase::Truncated,
390            Phase::Truncated => Phase::Truncated,
391            _ => Phase::ReadHeader(ByteBuf::default()),
392        };
393    }
394
395    pub fn stream(
396        &mut self,
397        in_bytes: &[u8],
398        in_offset: &mut usize,
399        out_bytes: &mut [u8],
400        out_offset: &mut usize,
401    ) -> BroCatliResult {
402        loop {
403            match self.phase {
404                Phase::PassThrough => {
405                    return self.pass_through(in_bytes, in_offset, out_bytes, out_offset)
406                }
407                Phase::Truncated => return BroCatliResult::BrotliFileNotCraftedForConcatenation,
408                Phase::ReadHeader(mut header) => {
409                    while usize::from(header.len) < max_header_bytes(header.as_slice())
410                        && *in_offset < in_bytes.len()
411                    {
412                        header.bytes[usize::from(header.len)] = in_bytes[*in_offset];
413                        header.len += 1;
414                        *in_offset += 1;
415                    }
416                    self.phase = Phase::ReadHeader(header);
417                    match self.splice(header.as_slice()) {
418                        Ok(Some(bytes)) => self.phase = Phase::WriteSplice { bytes, written: 0 },
419                        Ok(None) => return BroCatliResult::NeedsMoreInput,
420                        Err(err) => return err,
421                    }
422                }
423                Phase::WriteSplice { bytes, written } => {
424                    let unwritten = &bytes.as_slice()[usize::from(written)..];
425                    let written = written + self.write_out(unwritten, out_bytes, out_offset) as u8;
426                    if written != bytes.len {
427                        self.phase = Phase::WriteSplice { bytes, written };
428                        return BroCatliResult::NeedsMoreOutput;
429                    }
430                    self.phase = Phase::PassThrough;
431                }
432            }
433        }
434    }
435
436    pub fn finish(&mut self, out_bytes: &mut [u8], out_offset: &mut usize) -> BroCatliResult {
437        // Write out whatever of the last stream is still pending.
438        if let Phase::ReadHeader(header) = self.phase {
439            if header.len != 0 {
440                self.phase = Phase::Truncated;
441            }
442        }
443        match self.stream(&[], &mut 0, out_bytes, out_offset) {
444            BroCatliResult::NeedsMoreInput => {}
445            result => return result,
446        }
447        // The tail holds the final empty meta-block, which now does end the stream.
448        while self.tail_len != 0 {
449            let byte = self.tail[0];
450            if self.write_out(&[byte], out_bytes, out_offset) == 0 {
451                return BroCatliResult::NeedsMoreOutput;
452            }
453            self.tail = [self.tail[1], 0];
454            self.tail_len -= 1;
455        }
456        if !self.any_bytes_emitted {
457            // No streams at all: write an empty one.
458            if self.write_out(b";", out_bytes, out_offset) == 0 {
459                return BroCatliResult::NeedsMoreOutput;
460            }
461        }
462        BroCatliResult::Success
463    }
464
465    /// Reads as much of a new stream as splicing it on takes: its window size and, unless it is the
466    /// first stream, its first meta-block header. Returns the window size and where that header
467    /// starts and ends, in bits.
468    fn read_stream_start(&self, header: &[u8]) -> Result<(u8, usize, usize), ParseError> {
469        let mut reader = BitReader {
470            bytes: header,
471            position: 0,
472        };
473        let window_size = reader.read_window_size()?;
474        let metablock_header_start = reader.position;
475        if self.window_size != 0 {
476            if window_size > self.window_size {
477                return Err(ParseError::Invalid(
478                    BroCatliResult::WindowSizeLargerThanPreviousFile,
479                ));
480            }
481            reader.read_first_metablock_header()?;
482        }
483        Ok((window_size, metablock_header_start, reader.position))
484    }
485
486    /// Splices the stream that starts with `header` onto the output: the output loses its final
487    /// empty meta-block, the stream loses its window size, and the two are joined bit by bit. The
488    /// last two bytes of the result become the new tail; the rest is returned, ready to write.
489    /// Returns `Ok(None)` if more of the stream is needed to find where it becomes byte aligned.
490    fn splice(&mut self, header: &[u8]) -> Result<Option<ByteBuf>, BroCatliResult> {
491        let (window_size, start, end) = match self.read_stream_start(header) {
492            Ok(parsed) => parsed,
493            Err(ParseError::Incomplete) if header.len() < max_header_bytes(header) => {
494                return Ok(None)
495            }
496            Err(ParseError::Incomplete) => {
497                return Err(BroCatliResult::BrotliFileNotCraftedForConcatenation)
498            }
499            Err(ParseError::Invalid(err)) => return Err(err),
500        };
501        let mut spliced = BitWriter::default();
502        if self.window_size == 0 {
503            // The first stream is copied as is.
504            self.window_size = window_size;
505            spliced.write_bytes(header);
506        } else {
507            let tail = &self.tail[..usize::from(self.tail_len)];
508            let (output_bits, num_output_bits) = remove_final_empty_metablock(tail)
509                .ok_or(BroCatliResult::BrotliFileNotCraftedForAppend)?;
510            spliced.write(output_bits, num_output_bits);
511            spliced.write(bit_range(header, start, end), end - start);
512            // the stream is padded to a byte boundary after this header, so the rest of it can be
513            // copied byte by byte
514            spliced.pad_to_byte();
515            spliced.write_bytes(&header[(end + 7) / 8..]);
516        }
517        let (bytes, len) = spliced.finish();
518        let tail_len = min(2, len);
519        self.set_tail(&bytes[len - tail_len..len]);
520        Ok(Some(ByteBuf::from_slice(&bytes[..len - tail_len])))
521    }
522
523    /// Copies the current stream through to the output, keeping its last two bytes in the tail.
524    fn pass_through(
525        &mut self,
526        in_bytes: &[u8],
527        in_offset: &mut usize,
528        out_bytes: &mut [u8],
529        out_offset: &mut usize,
530    ) -> BroCatliResult {
531        loop {
532            let input = &in_bytes[*in_offset..];
533            if input.is_empty() {
534                return BroCatliResult::NeedsMoreInput;
535            }
536            if self.tail_len < 2 {
537                self.tail[usize::from(self.tail_len)] = input[0];
538                self.tail_len += 1;
539                *in_offset += 1;
540                continue;
541            }
542            if *out_offset == out_bytes.len() {
543                return BroCatliResult::NeedsMoreOutput;
544            }
545            // Of the tail followed by the next `count` input bytes, the first `count` go out and
546            // the last two become the tail.
547            let count = min(input.len(), out_bytes.len() - *out_offset);
548            let output = &mut out_bytes[*out_offset..*out_offset + count];
549            if count == 1 {
550                output[0] = self.tail[0];
551                self.tail = [self.tail[1], input[0]];
552            } else {
553                output[..2].copy_from_slice(&self.tail);
554                output[2..].copy_from_slice(&input[..count - 2]);
555                self.tail.copy_from_slice(&input[count - 2..count]);
556            }
557            *in_offset += count;
558            *out_offset += count;
559            self.any_bytes_emitted = true;
560        }
561    }
562
563    /// Writes as much of `bytes` as fits, returning how many bytes that was.
564    fn write_out(&mut self, bytes: &[u8], out_bytes: &mut [u8], out_offset: &mut usize) -> usize {
565        let count = min(bytes.len(), out_bytes.len() - *out_offset);
566        out_bytes[*out_offset..*out_offset + count].copy_from_slice(&bytes[..count]);
567        *out_offset += count;
568        if count != 0 {
569            self.any_bytes_emitted = true;
570        }
571        count
572    }
573
574    fn set_tail(&mut self, bytes: &[u8]) {
575        self.tail = [0, 0];
576        self.tail[..bytes.len()].copy_from_slice(bytes);
577        self.tail_len = bytes.len() as u8;
578    }
579}
580
581#[cfg(test)]
582mod test {
583    use super::BroCatli;
584    use core::cmp::min;
585
586    fn make_valid_serialized_buffer(buffer: &mut [u8]) {
587        buffer[8] = 2;
588        buffer[9] = (1 << 6) | (1 << 7);
589        buffer[10] = 7;
590        buffer[11] = 22;
591        buffer[12] = super::NUM_STREAM_HEADER_BYTES as u8;
592        buffer[13] = 3;
593    }
594
595    #[test]
596    fn test_deserialization() {
597        let broccoli = BroCatli {
598            tail: [0x45, 0x46],
599            tail_len: 1,
600            window_size: 22,
601            any_bytes_emitted: false,
602            phase: super::Phase::WriteSplice {
603                bytes: super::ByteBuf {
604                    bytes: [0x33; super::NUM_STREAM_HEADER_BYTES],
605                    len: super::NUM_STREAM_HEADER_BYTES as u8,
606                },
607                written: 3,
608            },
609        };
610        let mut buffer = [0u8; 248];
611        broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
612        let bc = BroCatli::deserialize_from_buffer(&buffer[..]).unwrap();
613        assert_eq!(broccoli, bc);
614    }
615    #[test]
616    fn test_deserialization_any_written() {
617        let broccoli = BroCatli {
618            tail: [0x45, 0x46],
619            tail_len: 1,
620            window_size: 22,
621            any_bytes_emitted: true,
622            phase: super::Phase::WriteSplice {
623                bytes: super::ByteBuf {
624                    bytes: [0x33; super::NUM_STREAM_HEADER_BYTES],
625                    len: super::NUM_STREAM_HEADER_BYTES as u8,
626                },
627                written: 3,
628            },
629        };
630        let mut buffer = [0u8; 248];
631        broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
632        let bc = BroCatli::deserialize_from_buffer(&buffer[..]).unwrap();
633        assert_eq!(broccoli, bc);
634    }
635    #[test]
636    fn test_serialization() {
637        let mut buffer = [0u8; 248];
638        let mut broccoli = BroCatli::deserialize_from_buffer(&buffer).unwrap();
639        let mut buffer2 = [0u8; 248];
640        broccoli.serialize_to_buffer(&mut buffer2[..]).unwrap();
641        assert_eq!(&buffer[..], &buffer2[..]);
642        for (index, item) in buffer.iter_mut().enumerate() {
643            *item = index as u8;
644        }
645        make_valid_serialized_buffer(&mut buffer[..]);
646        broccoli = BroCatli::deserialize_from_buffer(&buffer).unwrap();
647        broccoli.serialize_to_buffer(&mut buffer2[..]).unwrap();
648        broccoli = BroCatli::deserialize_from_buffer(&buffer2).unwrap();
649        for (_index, item) in buffer.iter_mut().enumerate() {
650            *item = 0;
651        }
652        broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
653        assert_eq!(&buffer[..], &buffer2[..]);
654        for (index, item) in buffer.iter_mut().enumerate() {
655            *item = 0xff ^ index as u8;
656        }
657        make_valid_serialized_buffer(&mut buffer[..]);
658        broccoli = BroCatli::deserialize_from_buffer(&buffer).unwrap();
659        broccoli.serialize_to_buffer(&mut buffer2[..]).unwrap();
660        broccoli = BroCatli::deserialize_from_buffer(&buffer2).unwrap();
661        for (_index, item) in buffer.iter_mut().enumerate() {
662            *item = 0;
663        }
664        broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
665        assert_eq!(&buffer[..], &buffer2[..]);
666    }
667    #[test]
668    fn test_deserialization_rejects_invalid_state_fields() {
669        let mut buffer = [0u8; 248];
670        make_valid_serialized_buffer(&mut buffer[..]);
671
672        let mut invalid = buffer;
673        invalid[8] = 3;
674        assert!(BroCatli::deserialize_from_buffer(&invalid[..]).is_err());
675
676        invalid = buffer;
677        invalid[10] = 8;
678        assert!(BroCatli::deserialize_from_buffer(&invalid[..]).is_err());
679
680        invalid = buffer;
681        invalid[11] = 9;
682        assert!(BroCatli::deserialize_from_buffer(&invalid[..]).is_err());
683
684        invalid = buffer;
685        invalid[12] = super::NUM_STREAM_HEADER_BYTES as u8 + 1;
686        assert!(BroCatli::deserialize_from_buffer(&invalid[..]).is_err());
687
688        invalid = buffer;
689        invalid[13] = buffer[12] + 1;
690        assert!(BroCatli::deserialize_from_buffer(&invalid[..]).is_err());
691    }
692    #[test]
693    fn test_cat_empty_stream() {
694        let empty_catable = [b';'];
695        let mut bcat = super::BroCatli::default();
696        let mut in_offset = 0usize;
697        let mut out_bytes = [0u8; 32];
698        let mut out_offset = 0usize;
699        bcat.new_brotli_file();
700        let mut res = bcat.stream(
701            &empty_catable[..],
702            &mut in_offset,
703            &mut out_bytes[..],
704            &mut out_offset,
705        );
706        assert_eq!(res, super::BroCatliResult::NeedsMoreInput);
707        bcat.new_brotli_file();
708        in_offset = 0;
709        res = bcat.stream(
710            &empty_catable[..],
711            &mut in_offset,
712            &mut out_bytes[..],
713            &mut out_offset,
714        );
715        assert_eq!(res, super::BroCatliResult::NeedsMoreInput);
716        res = bcat.finish(&mut out_bytes[..], &mut out_offset);
717        assert_eq!(res, super::BroCatliResult::Success);
718        assert_ne!(out_offset, 0);
719        assert_eq!(&out_bytes[..out_offset], &[b';']);
720    }
721    fn canonical_empty_stream(window: u8) -> ([u8; 2], usize) {
722        // window bits followed by ISLAST + ISLASTEMPTY
723        match window {
724            16 => ([0x06, 0], 1),
725            17 => ([0x81, 0x01], 2),
726            10..=15 => ([0x01 | ((window - 8) << 4) | 0x80, 0x01], 2),
727            18..=24 => ([(3 + (window - 18) * 2) | 0x30, 0], 1),
728            _ => ([0x11, window | 0xc0], 2),
729        }
730    }
731
732    fn concat_chunked(
733        mut bcat: BroCatli,
734        streams: &[&[u8]],
735        in_chunk: usize,
736        out_chunk: usize,
737        output: &mut [u8],
738    ) -> usize {
739        let mut output_offset = 0;
740        for stream in streams {
741            bcat.new_brotli_file();
742            for chunk in stream.chunks(in_chunk) {
743                let mut input_offset = 0;
744                loop {
745                    let out_end = min(output.len(), output_offset + out_chunk);
746                    match bcat.stream(
747                        chunk,
748                        &mut input_offset,
749                        &mut output[..out_end],
750                        &mut output_offset,
751                    ) {
752                        super::BroCatliResult::NeedsMoreOutput => {}
753                        super::BroCatliResult::NeedsMoreInput => break,
754                        res => panic!("unexpected {:?}", res),
755                    }
756                }
757                assert_eq!(input_offset, chunk.len());
758            }
759        }
760        loop {
761            let out_end = min(output.len(), output_offset + out_chunk);
762            match bcat.finish(&mut output[..out_end], &mut output_offset) {
763                super::BroCatliResult::NeedsMoreOutput => {}
764                super::BroCatliResult::Success => return output_offset,
765                res => panic!("unexpected {:?}", res),
766            }
767        }
768    }
769
770    #[test]
771    fn test_cat_empty_streams_every_window_and_buffer_size() {
772        // An empty stream's ISLAST/ISLASTEMPTY pair straddles a byte boundary whenever it is
773        // realigned onto bit offset 7 (windows 10..=15 and 17, and large windows, at offset 14).
774        // Concatenating empty streams must reproduce the empty stream regardless of how the
775        // caller chunks its input and output buffers.
776        for window in 10u8..=30 {
777            let (empty, empty_len) = canonical_empty_stream(window);
778            let empty = &empty[..empty_len];
779            for in_chunk in 1..=3 {
780                for out_chunk in 1..=3 {
781                    for count in 1..=3 {
782                        let streams = [empty; 3];
783                        for preseeded in [false, true] {
784                            let bcat = if preseeded {
785                                BroCatli::new_with_window_size(window)
786                            } else {
787                                BroCatli::new()
788                            };
789                            let mut output = [0u8; 32];
790                            let len = concat_chunked(
791                                bcat,
792                                &streams[..count],
793                                in_chunk,
794                                out_chunk,
795                                &mut output,
796                            );
797                            assert_eq!(
798                                &output[..len],
799                                empty,
800                                "window {window} in_chunk {in_chunk} out_chunk {out_chunk} \
801                                 count {count} preseeded {preseeded}",
802                            );
803                        }
804                    }
805                }
806            }
807        }
808    }
809
810    #[test]
811    fn test_cat_empty_stream_between_streams_with_straddled_final_bits() {
812        // window 15 puts an empty stream's ISLAST/ISLASTEMPTY pair at bits 7 and 8, and
813        // new_with_window_size(15) realigns the next stream onto bit offset 7
814        let empty_w15 = [0x71u8 | 0x80, 1];
815        let mut bcat = super::BroCatli::new_with_window_size(15);
816        let mut out_bytes = [0u8; 32];
817        let mut out_offset = 0usize;
818        for _ in 0..3 {
819            let mut in_offset = 0usize;
820            bcat.new_brotli_file();
821            let res = bcat.stream(
822                &empty_w15[..],
823                &mut in_offset,
824                &mut out_bytes[..],
825                &mut out_offset,
826            );
827            assert_eq!(res, super::BroCatliResult::NeedsMoreInput);
828        }
829        let res = bcat.finish(&mut out_bytes[..], &mut out_offset);
830        assert_eq!(res, super::BroCatliResult::Success);
831        assert_eq!(&out_bytes[..out_offset], &empty_w15[..]);
832    }
833    #[test]
834    fn test_cat_truncated_metadata_header_fails() {
835        let empty_catable = [b';'];
836        let mut bcat = super::BroCatli::new_with_window_size(22);
837        let mut in_offset = 0usize;
838        let mut out_bytes = [0u8; 32];
839        let mut out_offset = 0usize;
840        let mut res = bcat.stream(
841            &empty_catable[..],
842            &mut in_offset,
843            &mut out_bytes[..],
844            &mut out_offset,
845        );
846        assert_eq!(res, super::BroCatliResult::NeedsMoreInput);
847
848        let truncated_metadata = [0x71, 0x1b, 0, 0];
849        bcat.new_brotli_file();
850        in_offset = 0;
851        out_offset = 0;
852        res = bcat.stream(
853            &truncated_metadata[..],
854            &mut in_offset,
855            &mut out_bytes[..],
856            &mut out_offset,
857        );
858        assert_eq!(
859            res,
860            super::BroCatliResult::BrotliFileNotCraftedForConcatenation
861        );
862    }
863    #[test]
864    fn test_try_new_with_window_size_invalid_returns_error() {
865        use super::BroCatliResult;
866        // Values 0..=9 are invalid window sizes and must return an error, not panic.
867        for ws in 0u8..=9 {
868            match BroCatli::try_new_with_window_size(ws) {
869                Err(BroCatliResult::InvalidWindowSize) => {}
870                Err(_) => panic!("window_size {} returned wrong error variant", ws),
871                Ok(_) => panic!("window_size {} should be rejected", ws),
872            }
873            #[cfg(feature = "std")]
874            assert!(
875                std::panic::catch_unwind(|| BroCatli::new_with_window_size(ws)).is_err(),
876                "window_size {} should panic through the legacy constructor",
877                ws
878            );
879        }
880    }
881    #[test]
882    fn test_new_with_window_size_valid() {
883        // Values 10..=24 and >24 are valid window sizes.
884        for ws in 10u8..=30 {
885            let _ = BroCatli::new_with_window_size(ws);
886            assert!(
887                BroCatli::try_new_with_window_size(ws).is_ok(),
888                "window_size {} should be accepted",
889                ws
890            );
891        }
892    }
893
894    #[test]
895    fn test_cat_empty_stream_after_quality_one_stream() {
896        // The first stream is the quality-1 reproduction from #258; the second is empty.
897        let first_catable = [
898            131, 0, 128, 48, 48, 152, 0, 0, 0, 10, 38, 6, 14, 224, 250, 125, 73, 137, 13, 224, 2,
899            28, 94, 161, 1,
900        ];
901        let empty_catable = [161, 1];
902        let mut bcat = BroCatli::new();
903        let mut output = [0u8; 32];
904        let mut output_offset = 0;
905
906        for stream in [&first_catable[..], &empty_catable[..]] {
907            bcat.new_brotli_file();
908            let mut input_offset = 0;
909            let result = bcat.stream(stream, &mut input_offset, &mut output, &mut output_offset);
910            assert_eq!(result, super::BroCatliResult::NeedsMoreInput);
911            assert_eq!(input_offset, stream.len());
912        }
913
914        let result = bcat.finish(&mut output, &mut output_offset);
915        assert_eq!(result, super::BroCatliResult::Success);
916        assert_eq!(&output[..output_offset], &first_catable[..]);
917    }
918
919    fn concat_single_stream_with_window(window: u8, stream: &[u8], output: &mut [u8; 32]) -> usize {
920        let mut bcat = BroCatli::new_with_window_size(window);
921        let mut output_offset = 0;
922        bcat.new_brotli_file();
923        let mut input_offset = 0;
924        let result = bcat.stream(stream, &mut input_offset, output, &mut output_offset);
925        assert_eq!(result, super::BroCatliResult::NeedsMoreInput);
926        assert_eq!(input_offset, stream.len());
927        let result = bcat.finish(output, &mut output_offset);
928        assert_eq!(result, super::BroCatliResult::Success);
929        output_offset
930    }
931
932    #[test]
933    fn test_cat_empty_stream_with_small_window_size() {
934        // Regression test: `new_with_window_size` for windows 10..=17 used to turn a valid
935        // empty brotli stream into an undecodable one (reporting Success while doing so).
936        //
937        // Each `stream` below is an empty brotli stream for the given window as produced by
938        // this crate's own encoder with -bytealign -appendable (a metadata block, then an empty
939        // last block). It is shorter than a sufficient() header, so it passes through as is.
940        // A zero-byte file instead leaves the pre-seed in place, which `finish` closes into the
941        // canonical short empty stream (window bits followed by ISLAST + ISLASTEMPTY). All
942        // expected outputs decode to zero bytes with a conformant brotli decoder.
943        //
944        // Windows 10/17 exercise the two-byte pre-seeded `last_bytes` path (the length was
945        // left at 2, so `append_eof_metablock_to_last_bytes` overflowed `3u16 << 15`).
946        // Window 16 exercises its own pre-seed, whose window bit was incorrectly set.
947        let cases: [(u8, &[u8], &[u8]); 3] = [
948            (10, &[0x21, 0x03, 0x03], &[0xa1, 0x01]),
949            (16, &[0x0c, 0x03], &[0x06]),
950            (17, &[0x01, 0x03, 0x03], &[0x81, 0x01]),
951        ];
952        for (window, stream, canonical) in cases {
953            let mut output = [0u8; 32];
954            let len = concat_single_stream_with_window(window, stream, &mut output);
955            assert_eq!(
956                &output[..len],
957                stream,
958                "unexpected concatenation output for window {window}",
959            );
960            let len = concat_single_stream_with_window(window, &[], &mut output);
961            assert_eq!(
962                &output[..len],
963                canonical,
964                "unexpected zero-byte file output for window {window}",
965            );
966        }
967    }
968}