Skip to main content

lz4rip_encode/
compress.rs

1//! LZ4 block compression.
2
3use core::fmt;
4
5use crate::hashtable::HashTable;
6use crate::verified_sink::VerifiedSliceSink;
7#[allow(unused_imports)]
8use alloc::vec;
9use lz4rip_core::CompressError;
10use lz4rip_core::Sink;
11use lz4rip_core::END_OFFSET;
12use lz4rip_core::LZ4_MIN_LENGTH;
13use lz4rip_core::MAX_DISTANCE;
14use lz4rip_core::MFLIMIT;
15use lz4rip_core::MINMATCH;
16use lz4rip_core::WINDOW_SIZE;
17
18#[allow(unused_imports)]
19use alloc::vec::Vec;
20
21pub(crate) use crate::hashtable::HashTableU32;
22pub(crate) use crate::hashtable::HashTableU32U16;
23
24/// Skip acceleration: step grows by 1 every `1 << N` consecutive non-matches.
25/// C lz4 uses 6; see DESIGN.md for tradeoff analysis.
26const INCREASE_STEPSIZE_BITSHIFT: usize = 3;
27
28#[inline]
29fn token_from_literal(lit_len: usize) -> u8 {
30    if lit_len < 0xF {
31        (lit_len as u8) << 4
32    } else {
33        0xF0
34    }
35}
36
37#[inline]
38fn token_from_literal_and_match_length(lit_len: usize, duplicate_length: usize) -> u8 {
39    let mut token = if lit_len < 0xF {
40        (lit_len as u8) << 4
41    } else {
42        0xF0
43    };
44
45    token |= if duplicate_length < 0xF {
46        duplicate_length as u8
47    } else {
48        0xF
49    };
50
51    token
52}
53
54/// Write a variable-length integer in the LZ4 encoding.
55#[inline]
56pub fn write_integer(output: &mut impl Sink, mut n: usize) {
57    while n >= 0xFF {
58        n -= 0xFF;
59        push_byte(output, 0xFF);
60    }
61    push_byte(output, n as u8);
62}
63
64#[cold]
65fn handle_last_literals(output: &mut impl Sink, input: &[u8], start: usize) {
66    let lit_len = input.len() - start;
67
68    let token = token_from_literal(lit_len);
69    push_byte(output, token);
70    if lit_len >= 0xF {
71        write_integer(output, lit_len - 0xF);
72    }
73    output.extend_from_slice(&input[start..]);
74}
75
76#[inline]
77fn backtrack_match(
78    input: &[u8],
79    cur: &mut usize,
80    literal_start: usize,
81    source: &[u8],
82    candidate: &mut usize,
83) {
84    while *candidate > 0 && *cur > literal_start && input[*cur - 1] == source[*candidate - 1] {
85        *cur -= 1;
86        *candidate -= 1;
87    }
88}
89
90/// Core block compression loop, monomorphized over hash table type and dict mode.
91#[inline(never)]
92pub fn compress_internal<T: HashTable, const USE_DICT: bool, const HAS_OFFSET: bool, S: Sink>(
93    input: &[u8],
94    input_pos: usize,
95    output: &mut S,
96    table: &mut T,
97    ext_dict: &[u8],
98    input_stream_offset: usize,
99) -> Result<usize, CompressError> {
100    assert!(input_pos <= input.len());
101    if USE_DICT {
102        assert!(ext_dict.len() <= WINDOW_SIZE);
103        assert!(ext_dict.len() <= input_stream_offset);
104        assert!(input_stream_offset
105            .checked_add(input.len())
106            .and_then(|i| i.checked_add(ext_dict.len()))
107            .is_some_and(|i| i <= isize::MAX as usize));
108    } else {
109        assert!(ext_dict.is_empty());
110    }
111    if !HAS_OFFSET {
112        debug_assert_eq!(input_stream_offset, 0);
113    }
114    let input_stream_offset = if HAS_OFFSET { input_stream_offset } else { 0 };
115    if output.capacity() - output.pos() < get_maximum_output_size(input.len() - input_pos) {
116        return Err(CompressError::OutputTooSmall);
117    }
118
119    let output_start_pos = output.pos();
120    if input.len() - input_pos < LZ4_MIN_LENGTH {
121        handle_last_literals(output, input, input_pos);
122        return Ok(output.pos() - output_start_pos);
123    }
124
125    let ext_dict_stream_offset = input_stream_offset - ext_dict.len();
126    let end_pos_check = input.len() - MFLIMIT;
127    let mut literal_start = input_pos;
128    let mut cur = input_pos;
129
130    if cur == 0 && input_stream_offset == 0 {
131        let hash = T::get_hash_at_unchecked(input, 0);
132        table.put_at(hash, 0);
133        cur = 1;
134    }
135
136    let mut forward_hash = T::get_hash_at_unchecked(input, cur);
137
138    loop {
139        let mut candidate;
140        let mut candidate_source;
141        let mut offset;
142        let mut non_match_count = 1 << INCREASE_STEPSIZE_BITSHIFT;
143
144        loop {
145            let step = non_match_count >> INCREASE_STEPSIZE_BITSHIFT;
146            non_match_count += 1;
147            let next_cur = cur + step;
148
149            if next_cur > end_pos_check + 1 {
150                handle_last_literals(output, input, literal_start);
151                return Ok(output.pos() - output_start_pos);
152            }
153
154            let hash = forward_hash;
155            candidate = table.get_at(hash);
156            forward_hash = T::get_hash_at_unchecked(input, next_cur);
157            table.put_at(hash, cur + input_stream_offset);
158
159            debug_assert!(candidate <= input_stream_offset + cur);
160
161            if candidate >= input_stream_offset
162                && input_stream_offset + cur - candidate <= MAX_DISTANCE
163            {
164                offset = (input_stream_offset + cur - candidate) as u16;
165                candidate -= input_stream_offset;
166                candidate_source = input;
167            } else if USE_DICT
168                && candidate >= ext_dict_stream_offset
169                && input_stream_offset + cur - candidate <= MAX_DISTANCE
170            {
171                offset = (input_stream_offset + cur - candidate) as u16;
172                candidate -= ext_dict_stream_offset;
173                candidate_source = ext_dict;
174            } else {
175                cur = next_cur;
176                continue;
177            }
178            let cand_bytes: u32 =
179                crate::hashtable::get_batch_unchecked(candidate_source, candidate);
180            let curr_bytes: u32 = crate::hashtable::get_batch_unchecked(input, cur);
181
182            if cand_bytes == curr_bytes {
183                break;
184            }
185            cur = next_cur;
186        }
187
188        loop {
189            backtrack_match(
190                input,
191                &mut cur,
192                literal_start,
193                candidate_source,
194                &mut candidate,
195            );
196
197            let lit_len = cur - literal_start;
198
199            cur += MINMATCH;
200            candidate += MINMATCH;
201            let duplicate_length = crate::hashtable::count_same_bytes_unchecked(
202                input,
203                &mut cur,
204                candidate_source,
205                candidate,
206                END_OFFSET,
207            );
208
209            let hash = T::get_hash_at_unchecked(input, cur - 2);
210            table.put_at(hash, cur - 2 + input_stream_offset);
211
212            let token = token_from_literal_and_match_length(lit_len, duplicate_length);
213            push_byte(output, token);
214            if lit_len >= 0xF {
215                write_integer(output, lit_len - 0xF);
216            }
217            if lit_len > 0 {
218                copy_literals_wild(output, input, literal_start, lit_len);
219            }
220            push_u16(output, offset);
221            if duplicate_length >= 0xF {
222                write_integer(output, duplicate_length - 0xF);
223            }
224            literal_start = cur;
225
226            if !USE_DICT && cur <= end_pos_check {
227                let hash = T::get_hash_at_unchecked(input, cur);
228                let rematch = table.get_at(hash);
229
230                if input_stream_offset + cur - rematch <= MAX_DISTANCE
231                    && rematch >= input_stream_offset
232                {
233                    let rc = rematch - input_stream_offset;
234                    if crate::hashtable::get_batch_unchecked(input, cur)
235                        == crate::hashtable::get_batch_unchecked(input, rc)
236                    {
237                        table.put_at(hash, cur + input_stream_offset);
238                        candidate = rc;
239                        candidate_source = input;
240                        offset = (input_stream_offset + cur - rematch) as u16;
241                        continue;
242                    }
243                }
244                forward_hash = hash;
245            } else if cur <= end_pos_check {
246                forward_hash = T::get_hash_at_unchecked(input, cur);
247            }
248            break;
249        }
250    }
251}
252
253/// Dual-table compression for `Compressor::with_dict`.
254#[inline(never)]
255fn compress_with_dict_table<T: HashTable, S: Sink>(
256    input: &[u8],
257    output: &mut S,
258    table: &mut T,
259    dict_table: &T,
260    ext_dict: &[u8],
261    input_stream_offset: usize,
262) -> Result<usize, CompressError> {
263    assert!(ext_dict.len() <= WINDOW_SIZE);
264    assert!(ext_dict.len() <= input_stream_offset);
265    assert!(input_stream_offset
266        .checked_add(input.len())
267        .and_then(|i| i.checked_add(ext_dict.len()))
268        .is_some_and(|i| i <= isize::MAX as usize));
269    if output.capacity() - output.pos() < get_maximum_output_size(input.len()) {
270        return Err(CompressError::OutputTooSmall);
271    }
272
273    let output_start_pos = output.pos();
274    if input.len() < LZ4_MIN_LENGTH {
275        handle_last_literals(output, input, 0);
276        return Ok(output.pos() - output_start_pos);
277    }
278
279    let ext_dict_stream_offset = input_stream_offset - ext_dict.len();
280    let end_pos_check = input.len() - MFLIMIT;
281    let mut literal_start = 0;
282
283    let hash = T::get_hash_at_unchecked(input, 0);
284    table.put_at(hash, input_stream_offset);
285    let mut cur = 1;
286
287    let mut forward_hash = T::get_hash_at_unchecked(input, cur);
288
289    loop {
290        let mut candidate;
291        let mut candidate_source;
292        let mut offset;
293        let mut non_match_count = 1 << INCREASE_STEPSIZE_BITSHIFT;
294
295        loop {
296            let step = non_match_count >> INCREASE_STEPSIZE_BITSHIFT;
297            non_match_count += 1;
298            let next_cur = cur + step;
299
300            if next_cur > end_pos_check + 1 {
301                handle_last_literals(output, input, literal_start);
302                return Ok(output.pos() - output_start_pos);
303            }
304
305            let hash = forward_hash;
306            candidate = table.get_at(hash);
307            forward_hash = T::get_hash_at_unchecked(input, next_cur);
308            table.put_at(hash, cur + input_stream_offset);
309
310            if candidate >= input_stream_offset
311                && input_stream_offset + cur - candidate <= MAX_DISTANCE
312            {
313                offset = (input_stream_offset + cur - candidate) as u16;
314                candidate -= input_stream_offset;
315                candidate_source = input;
316            } else {
317                candidate = dict_table.get_at(hash);
318                if candidate < input_stream_offset
319                    && input_stream_offset + cur - candidate <= MAX_DISTANCE
320                {
321                    offset = (input_stream_offset + cur - candidate) as u16;
322                    candidate -= ext_dict_stream_offset;
323                    candidate_source = ext_dict;
324                } else {
325                    cur = next_cur;
326                    continue;
327                }
328            }
329            let cand_bytes: u32 =
330                crate::hashtable::get_batch_unchecked(candidate_source, candidate);
331            let curr_bytes: u32 = crate::hashtable::get_batch_unchecked(input, cur);
332
333            if cand_bytes == curr_bytes {
334                break;
335            }
336            cur = next_cur;
337        }
338
339        backtrack_match(
340            input,
341            &mut cur,
342            literal_start,
343            candidate_source,
344            &mut candidate,
345        );
346
347        let lit_len = cur - literal_start;
348
349        cur += MINMATCH;
350        candidate += MINMATCH;
351        let duplicate_length = crate::hashtable::count_same_bytes_unchecked(
352            input,
353            &mut cur,
354            candidate_source,
355            candidate,
356            END_OFFSET,
357        );
358
359        let hash = T::get_hash_at_unchecked(input, cur - 2);
360        table.put_at(hash, cur - 2 + input_stream_offset);
361
362        let token = token_from_literal_and_match_length(lit_len, duplicate_length);
363        push_byte(output, token);
364        if lit_len >= 0xF {
365            write_integer(output, lit_len - 0xF);
366        }
367        if lit_len > 0 {
368            copy_literals_wild(output, input, literal_start, lit_len);
369        }
370        push_u16(output, offset);
371        if duplicate_length >= 0xF {
372            write_integer(output, duplicate_length - 0xF);
373        }
374        literal_start = cur;
375
376        if cur <= end_pos_check {
377            forward_hash = T::get_hash_at_unchecked(input, cur);
378        }
379    }
380}
381
382#[inline]
383fn push_byte(output: &mut impl Sink, el: u8) {
384    output.push(el);
385}
386
387#[inline]
388fn push_u16(output: &mut impl Sink, el: u16) {
389    output.extend_from_slice(&el.to_le_bytes());
390}
391
392#[inline(always)]
393fn copy_literals_wild(output: &mut impl Sink, input: &[u8], input_start: usize, len: usize) {
394    output.extend_from_slice_wild(&input[input_start..input_start + len], len)
395}
396
397/// Compress `input` into `output` with optional dictionary data.
398pub fn compress_into_sink_with_dict<const USE_DICT: bool>(
399    input: &[u8],
400    output: &mut impl Sink,
401    mut dict_data: &[u8],
402) -> Result<usize, CompressError> {
403    if USE_DICT && dict_data.len() < MINMATCH {
404        return compress_into_sink_with_dict::<false>(input, output, b"");
405    }
406    if dict_data.len() + input.len() < u16::MAX as usize {
407        let mut dict = HashTableU32U16::new();
408        init_dict(&mut dict, &mut dict_data);
409        compress_internal::<_, USE_DICT, USE_DICT, _>(
410            input,
411            0,
412            output,
413            &mut dict,
414            dict_data,
415            dict_data.len(),
416        )
417    } else {
418        let mut dict = HashTableU32::new();
419        init_dict(&mut dict, &mut dict_data);
420        compress_internal::<_, USE_DICT, USE_DICT, _>(
421            input,
422            0,
423            output,
424            &mut dict,
425            dict_data,
426            dict_data.len(),
427        )
428    }
429}
430
431#[inline]
432fn init_dict<T: HashTable>(dict: &mut T, dict_data: &mut &[u8]) {
433    if dict_data.len() > WINDOW_SIZE {
434        *dict_data = &dict_data[dict_data.len() - WINDOW_SIZE..];
435    }
436    let mut i = 0usize;
437    while i + core::mem::size_of::<usize>() <= dict_data.len() {
438        let hash = T::get_hash_at(dict_data, i);
439        dict.put_at(hash, i);
440        i += 3;
441    }
442}
443
444/// Returns the maximum output size of the compressed data.
445/// Can be used to preallocate capacity on the output vector
446#[inline]
447pub const fn get_maximum_output_size(input_len: usize) -> usize {
448    16 + 4 + (input_len as u64 * 110 / 100) as usize
449}
450
451/// Compress all bytes of `input` into `output`.
452/// output should be preallocated with a size of
453/// `get_maximum_output_size`.
454///
455/// Returns the number of bytes written (compressed) into `output`.
456#[inline]
457pub fn compress_into(input: &[u8], output: &mut [u8]) -> Result<usize, CompressError> {
458    compress_into_sink_with_dict::<false>(input, &mut VerifiedSliceSink::new(output, 0), b"")
459}
460
461/// Compress all bytes of `input`.
462#[inline]
463pub fn compress(input: &[u8]) -> Vec<u8> {
464    let max_compressed_size = get_maximum_output_size(input.len());
465    let mut compressed: Vec<u8> = vec![0u8; max_compressed_size];
466    let compressed_len = compress_into_sink_with_dict::<false>(
467        input,
468        &mut VerifiedSliceSink::new(&mut compressed, 0),
469        b"",
470    )
471    .unwrap();
472    compressed.truncate(compressed_len);
473    compressed.shrink_to_fit();
474    compressed
475}
476
477/// A reusable block compressor. Pre-allocates the hash table once and reuses
478/// it across calls.
479///
480/// For one-shot compression, use [`compress`] or [`compress_into`] instead.
481///
482/// # Example
483/// ```
484/// use lz4rip_encode::{Compressor, get_maximum_output_size};
485///
486/// let mut comp = Compressor::new();
487/// let input = b"hello world, hello world, hello!";
488/// let mut output = vec![0u8; get_maximum_output_size(input.len())];
489/// let compressed_len = comp.compress_into(input, &mut output).unwrap();
490/// ```
491pub struct Compressor {
492    tables: CompressorTables,
493}
494
495enum CompressorTables {
496    Plain {
497        table: HashTableU32,
498        stream_offset: usize,
499    },
500    Dict {
501        table: HashTableU32U16,
502        pristine: HashTableU32U16,
503        dict: Vec<u8>,
504    },
505}
506
507impl fmt::Debug for Compressor {
508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509        match &self.tables {
510            CompressorTables::Plain { .. } => {
511                f.debug_struct("Compressor").field("dict_len", &0).finish()
512            }
513            CompressorTables::Dict { dict, .. } => f
514                .debug_struct("Compressor")
515                .field("dict_len", &dict.len())
516                .finish(),
517        }
518    }
519}
520
521impl Compressor {
522    /// Create a new compressor without a dictionary.
523    pub fn new() -> Self {
524        Compressor {
525            tables: CompressorTables::Plain {
526                table: HashTableU32::new(),
527                stream_offset: 0,
528            },
529        }
530    }
531
532    /// Create a new compressor seeded with an external dictionary.
533    ///
534    /// If `dict` is shorter than 4 bytes, it is ignored.
535    pub fn with_dict(dict: &[u8]) -> Self {
536        if dict.len() < MINMATCH {
537            return Self::new();
538        }
539        let trimmed = if dict.len() > WINDOW_SIZE {
540            &dict[dict.len() - WINDOW_SIZE..]
541        } else {
542            dict
543        };
544        let mut pristine = HashTableU32U16::new();
545        let mut dict_ref = trimmed;
546        init_dict(&mut pristine, &mut dict_ref);
547        Compressor {
548            tables: CompressorTables::Dict {
549                table: HashTableU32U16::new(),
550                pristine,
551                dict: trimmed.to_vec(),
552            },
553        }
554    }
555
556    const EPOCH_THRESHOLD: usize = 8 * 1024;
557
558    /// Compress `input` into `output`, returning the number of compressed bytes.
559    ///
560    /// `output` must be at least [`get_maximum_output_size`]`(input.len())` bytes.
561    pub fn compress_into(
562        &mut self,
563        input: &[u8],
564        output: &mut [u8],
565    ) -> Result<usize, CompressError> {
566        match &mut self.tables {
567            CompressorTables::Dict {
568                table,
569                pristine,
570                dict,
571            } => {
572                if dict.len() + input.len() < u16::MAX as usize {
573                    table.clear();
574                    compress_with_dict_table(
575                        input,
576                        &mut VerifiedSliceSink::new(output, 0),
577                        table,
578                        pristine,
579                        dict,
580                        dict.len(),
581                    )
582                } else {
583                    compress_into_sink_with_dict::<true>(
584                        input,
585                        &mut VerifiedSliceSink::new(output, 0),
586                        dict,
587                    )
588                }
589            }
590            CompressorTables::Plain {
591                table,
592                stream_offset,
593            } => {
594                let offset = prepare_plain_table(table, stream_offset, input.len());
595                if offset > 0 {
596                    compress_internal::<_, false, true, _>(
597                        input,
598                        0,
599                        &mut VerifiedSliceSink::new(output, 0),
600                        table,
601                        b"",
602                        offset,
603                    )
604                } else {
605                    compress_internal::<_, false, false, _>(
606                        input,
607                        0,
608                        &mut VerifiedSliceSink::new(output, 0),
609                        table,
610                        b"",
611                        0,
612                    )
613                }
614            }
615        }
616    }
617
618    /// Compress `input` into a new `Vec<u8>`.
619    pub fn compress(&mut self, input: &[u8]) -> Vec<u8> {
620        let max_compressed = get_maximum_output_size(input.len());
621        let mut compressed = vec![0u8; max_compressed];
622        let compressed_len = match &mut self.tables {
623            CompressorTables::Dict {
624                table,
625                pristine,
626                dict,
627            } => {
628                if dict.len() + input.len() < u16::MAX as usize {
629                    table.clear();
630                    compress_with_dict_table(
631                        input,
632                        &mut VerifiedSliceSink::new(&mut compressed, 0),
633                        table,
634                        pristine,
635                        dict,
636                        dict.len(),
637                    )
638                } else {
639                    compress_into_sink_with_dict::<true>(
640                        input,
641                        &mut VerifiedSliceSink::new(&mut compressed, 0),
642                        dict,
643                    )
644                }
645            }
646            CompressorTables::Plain {
647                table,
648                stream_offset,
649            } => {
650                let offset = prepare_plain_table(table, stream_offset, input.len());
651                if offset > 0 {
652                    compress_internal::<_, false, true, _>(
653                        input,
654                        0,
655                        &mut VerifiedSliceSink::new(&mut compressed, 0),
656                        table,
657                        b"",
658                        offset,
659                    )
660                } else {
661                    compress_internal::<_, false, false, _>(
662                        input,
663                        0,
664                        &mut VerifiedSliceSink::new(&mut compressed, 0),
665                        table,
666                        b"",
667                        0,
668                    )
669                }
670            }
671        }
672        .unwrap();
673        compressed.truncate(compressed_len);
674        compressed.shrink_to_fit();
675        compressed
676    }
677}
678
679#[inline]
680fn prepare_plain_table(
681    table: &mut HashTableU32,
682    stream_offset: &mut usize,
683    input_len: usize,
684) -> usize {
685    if input_len > Compressor::EPOCH_THRESHOLD {
686        table.clear();
687        *stream_offset = input_len + MAX_DISTANCE + 1;
688        return 0;
689    }
690    let offset = *stream_offset;
691    let next = offset
692        .checked_add(input_len)
693        .and_then(|v| v.checked_add(MAX_DISTANCE + 1));
694    if let Some(next) = next.filter(|&n| n <= u32::MAX as usize) {
695        *stream_offset = next;
696    } else {
697        table.clear();
698        *stream_offset = input_len + MAX_DISTANCE + 1;
699    }
700    offset
701}
702
703impl Default for Compressor {
704    fn default() -> Self {
705        Self::new()
706    }
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712
713    fn count_same_bytes(input: &[u8], cur: &mut usize, source: &[u8], candidate: usize) -> usize {
714        const USIZE_SIZE: usize = core::mem::size_of::<usize>();
715        let cur_slice = &input[*cur..input.len() - END_OFFSET];
716        let cand_slice = &source[candidate..];
717
718        let mut num = 0;
719        for (block1, block2) in cur_slice
720            .chunks_exact(USIZE_SIZE)
721            .zip(cand_slice.chunks_exact(USIZE_SIZE))
722        {
723            let input_block = usize::from_ne_bytes(block1.try_into().unwrap());
724            let match_block = usize::from_ne_bytes(block2.try_into().unwrap());
725
726            if input_block == match_block {
727                num += USIZE_SIZE;
728            } else {
729                let diff = input_block ^ match_block;
730                num += (diff.to_le().trailing_zeros() / 8) as usize;
731                *cur += num;
732                return num;
733            }
734        }
735
736        #[cold]
737        fn count_same_bytes_tail(a: &[u8], b: &[u8], offset: usize) -> usize {
738            a.iter()
739                .zip(b)
740                .skip(offset)
741                .take_while(|(a, b)| a == b)
742                .count()
743        }
744        num += count_same_bytes_tail(cur_slice, cand_slice, num);
745
746        *cur += num;
747        num
748    }
749
750    #[test]
751    fn test_count_same_bytes() {
752        let first: &[u8] = &[
753            1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
754        ];
755        let second: &[u8] = &[
756            1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
757        ];
758        assert_eq!(count_same_bytes(first, &mut 0, second, 0), 16);
759
760        for diff_idx in 8..100 {
761            let first: Vec<u8> = (0u8..255).cycle().take(100 + 12).collect();
762            let mut second = first.clone();
763            second[diff_idx] = 255;
764            for start in 0..=diff_idx {
765                let same_bytes = count_same_bytes(&first, &mut start.clone(), &second, start);
766                assert_eq!(same_bytes, diff_idx - start);
767            }
768        }
769    }
770
771    #[test]
772    fn test_bug() {
773        let input: &[u8] = &[
774            10, 12, 14, 16, 18, 10, 12, 14, 16, 18, 10, 12, 14, 16, 18, 10, 12, 14, 16, 18,
775        ];
776        let _out = compress(input);
777    }
778
779    #[test]
780    fn test_conformant_last_block() {
781        let aaas: &[u8] = b"aaaaaaaaaaaaaaa";
782
783        let out = compress(&aaas[..12]);
784        assert!(out.len() > 12);
785        let out = compress(&aaas[..13]);
786        assert!(out.len() <= 13);
787        let out = compress(&aaas[..14]);
788        assert!(out.len() <= 14);
789        let out = compress(&aaas[..15]);
790        assert!(out.len() <= 15);
791    }
792}