1use alloc::{boxed::Box, vec::Vec};
4use core::convert::TryInto;
5#[cfg(feature = "hash")]
6use twox_hash::XxHash64;
7
8#[cfg(feature = "hash")]
9use core::hash::Hasher;
10
11use super::{
12 CompressionLevel, Matcher, block_header::BlockHeader, frame_header::FrameHeader, levels::*,
13 match_generator::MatchGeneratorDriver,
14};
15use crate::fse::fse_encoder::{FSETable, default_ll_table, default_ml_table, default_of_table};
16
17use crate::io::{Read, Write};
18
19pub struct FrameCompressor<R: Read, W: Write, M: Matcher> {
39 uncompressed_data: Option<R>,
40 compressed_data: Option<W>,
41 compression_level: CompressionLevel,
42 dictionary: Option<crate::decoding::Dictionary>,
43 dictionary_entropy_cache: Option<CachedDictionaryEntropy>,
44 source_size_hint: Option<u64>,
45 state: CompressState<M>,
46 #[cfg(feature = "hash")]
47 hasher: XxHash64,
48}
49
50#[derive(Clone, Default)]
51struct CachedDictionaryEntropy {
52 huff: Option<crate::huff0::huff0_encoder::HuffmanTable>,
53 ll_previous: Option<PreviousFseTable>,
54 ml_previous: Option<PreviousFseTable>,
55 of_previous: Option<PreviousFseTable>,
56}
57
58#[derive(Clone)]
59pub(crate) enum PreviousFseTable {
60 Default,
63 Custom(Box<FSETable>),
64}
65
66impl PreviousFseTable {
67 pub(crate) fn as_table<'a>(&'a self, default: &'a FSETable) -> &'a FSETable {
68 match self {
69 Self::Default => default,
70 Self::Custom(table) => table,
71 }
72 }
73}
74
75pub(crate) struct FseTables {
76 pub(crate) ll_default: FSETable,
77 pub(crate) ll_previous: Option<PreviousFseTable>,
78 pub(crate) ml_default: FSETable,
79 pub(crate) ml_previous: Option<PreviousFseTable>,
80 pub(crate) of_default: FSETable,
81 pub(crate) of_previous: Option<PreviousFseTable>,
82}
83
84impl FseTables {
85 pub fn new() -> Self {
86 Self {
87 ll_default: default_ll_table(),
88 ll_previous: None,
89 ml_default: default_ml_table(),
90 ml_previous: None,
91 of_default: default_of_table(),
92 of_previous: None,
93 }
94 }
95}
96
97pub(crate) struct CompressState<M: Matcher> {
98 pub(crate) matcher: M,
99 pub(crate) last_huff_table: Option<crate::huff0::huff0_encoder::HuffmanTable>,
100 pub(crate) fse_tables: FseTables,
101 pub(crate) offset_hist: [u32; 3],
104}
105
106impl<R: Read, W: Write> FrameCompressor<R, W, MatchGeneratorDriver> {
107 pub fn new(compression_level: CompressionLevel) -> Self {
109 Self {
110 uncompressed_data: None,
111 compressed_data: None,
112 compression_level,
113 dictionary: None,
114 dictionary_entropy_cache: None,
115 source_size_hint: None,
116 state: CompressState {
117 matcher: MatchGeneratorDriver::new(1024 * 128, 1),
118 last_huff_table: None,
119 fse_tables: FseTables::new(),
120 offset_hist: [1, 4, 8],
121 },
122 #[cfg(feature = "hash")]
123 hasher: XxHash64::with_seed(0),
124 }
125 }
126}
127
128impl<R: Read, W: Write, M: Matcher> FrameCompressor<R, W, M> {
129 pub fn new_with_matcher(matcher: M, compression_level: CompressionLevel) -> Self {
131 Self {
132 uncompressed_data: None,
133 compressed_data: None,
134 dictionary: None,
135 dictionary_entropy_cache: None,
136 source_size_hint: None,
137 state: CompressState {
138 matcher,
139 last_huff_table: None,
140 fse_tables: FseTables::new(),
141 offset_hist: [1, 4, 8],
142 },
143 compression_level,
144 #[cfg(feature = "hash")]
145 hasher: XxHash64::with_seed(0),
146 }
147 }
148
149 pub fn set_source(&mut self, uncompressed_data: R) -> Option<R> {
153 self.uncompressed_data.replace(uncompressed_data)
154 }
155
156 pub fn set_drain(&mut self, compressed_data: W) -> Option<W> {
160 self.compressed_data.replace(compressed_data)
161 }
162
163 pub fn set_source_size_hint(&mut self, size: u64) {
173 self.source_size_hint = Some(size);
174 }
175
176 pub fn compress(&mut self) {
187 let use_dictionary_state =
188 !matches!(self.compression_level, CompressionLevel::Uncompressed)
189 && self.state.matcher.supports_dictionary_priming();
190 if let Some(size_hint) = self.source_size_hint.take() {
191 self.state.matcher.set_source_size_hint(size_hint);
194 }
195 self.state.matcher.reset(self.compression_level);
197 self.state.offset_hist = [1, 4, 8];
198 let cached_entropy = if use_dictionary_state {
199 self.dictionary_entropy_cache.as_ref()
200 } else {
201 None
202 };
203 if use_dictionary_state && let Some(dict) = self.dictionary.as_ref() {
204 self.state.offset_hist = dict.offset_hist;
207 self.state
208 .matcher
209 .prime_with_dictionary(dict.dict_content.as_slice(), dict.offset_hist);
210 }
211 if let Some(cache) = cached_entropy {
212 self.state.last_huff_table.clone_from(&cache.huff);
213 } else {
214 self.state.last_huff_table = None;
215 }
216 if let Some(cache) = cached_entropy {
219 self.state
220 .fse_tables
221 .ll_previous
222 .clone_from(&cache.ll_previous);
223 self.state
224 .fse_tables
225 .ml_previous
226 .clone_from(&cache.ml_previous);
227 self.state
228 .fse_tables
229 .of_previous
230 .clone_from(&cache.of_previous);
231 } else {
232 self.state.fse_tables.ll_previous = None;
233 self.state.fse_tables.ml_previous = None;
234 self.state.fse_tables.of_previous = None;
235 }
236 #[cfg(feature = "hash")]
237 {
238 self.hasher = XxHash64::with_seed(0);
239 }
240 let source = self.uncompressed_data.as_mut().unwrap();
241 let drain = self.compressed_data.as_mut().unwrap();
242 let window_size = self.state.matcher.window_size();
243 assert!(
244 window_size != 0,
245 "matcher reported window_size == 0, which is invalid"
246 );
247 let mut all_blocks: Vec<u8> = Vec::with_capacity(1024 * 130);
250 let mut total_uncompressed: u64 = 0;
251 loop {
253 let mut uncompressed_data = self.state.matcher.get_next_space();
255 let mut read_bytes = 0;
256 let last_block;
257 'read_loop: loop {
258 let new_bytes = source.read(&mut uncompressed_data[read_bytes..]).unwrap();
259 if new_bytes == 0 {
260 last_block = true;
261 break 'read_loop;
262 }
263 read_bytes += new_bytes;
264 if read_bytes == uncompressed_data.len() {
265 last_block = false;
266 break 'read_loop;
267 }
268 }
269 uncompressed_data.resize(read_bytes, 0);
270 total_uncompressed += read_bytes as u64;
271 #[cfg(feature = "hash")]
273 self.hasher.write(&uncompressed_data);
274 if uncompressed_data.is_empty() {
276 let header = BlockHeader {
277 last_block: true,
278 block_type: crate::blocks::block::BlockType::Raw,
279 block_size: 0,
280 };
281 header.serialize(&mut all_blocks);
282 break;
283 }
284
285 match self.compression_level {
286 CompressionLevel::Uncompressed => {
287 let header = BlockHeader {
288 last_block,
289 block_type: crate::blocks::block::BlockType::Raw,
290 block_size: read_bytes.try_into().unwrap(),
291 };
292 header.serialize(&mut all_blocks);
293 all_blocks.extend_from_slice(&uncompressed_data);
294 }
295 CompressionLevel::Fastest
296 | CompressionLevel::Default
297 | CompressionLevel::Better
298 | CompressionLevel::Best
299 | CompressionLevel::Level(_) => compress_block_encoded(
300 &mut self.state,
301 last_block,
302 uncompressed_data,
303 &mut all_blocks,
304 ),
305 }
306 if last_block {
307 break;
308 }
309 }
310
311 let header = FrameHeader {
317 frame_content_size: Some(total_uncompressed),
318 single_segment: false,
319 content_checksum: cfg!(feature = "hash"),
320 dictionary_id: if use_dictionary_state {
321 self.dictionary.as_ref().map(|dict| dict.id as u64)
322 } else {
323 None
324 },
325 window_size: Some(window_size),
326 };
327 let mut header_buf: Vec<u8> = Vec::with_capacity(14);
330 header.serialize(&mut header_buf);
331 drain.write_all(&header_buf).unwrap();
332 drain.write_all(&all_blocks).unwrap();
333
334 #[cfg(feature = "hash")]
337 {
338 let content_checksum = self.hasher.finish();
341 drain
342 .write_all(&(content_checksum as u32).to_le_bytes())
343 .unwrap();
344 }
345 }
346
347 pub fn source_mut(&mut self) -> Option<&mut R> {
349 self.uncompressed_data.as_mut()
350 }
351
352 pub fn drain_mut(&mut self) -> Option<&mut W> {
354 self.compressed_data.as_mut()
355 }
356
357 pub fn source(&self) -> Option<&R> {
359 self.uncompressed_data.as_ref()
360 }
361
362 pub fn drain(&self) -> Option<&W> {
364 self.compressed_data.as_ref()
365 }
366
367 pub fn take_source(&mut self) -> Option<R> {
369 self.uncompressed_data.take()
370 }
371
372 pub fn take_drain(&mut self) -> Option<W> {
374 self.compressed_data.take()
375 }
376
377 pub fn replace_matcher(&mut self, mut match_generator: M) -> M {
379 core::mem::swap(&mut match_generator, &mut self.state.matcher);
380 match_generator
381 }
382
383 pub fn set_compression_level(
385 &mut self,
386 compression_level: CompressionLevel,
387 ) -> CompressionLevel {
388 let old = self.compression_level;
389 self.compression_level = compression_level;
390 old
391 }
392
393 pub fn compression_level(&self) -> CompressionLevel {
395 self.compression_level
396 }
397
398 pub fn set_dictionary(
405 &mut self,
406 dictionary: crate::decoding::Dictionary,
407 ) -> Result<Option<crate::decoding::Dictionary>, crate::decoding::errors::DictionaryDecodeError>
408 {
409 if dictionary.id == 0 {
410 return Err(crate::decoding::errors::DictionaryDecodeError::ZeroDictionaryId);
411 }
412 if let Some(index) = dictionary.offset_hist.iter().position(|&rep| rep == 0) {
413 return Err(
414 crate::decoding::errors::DictionaryDecodeError::ZeroRepeatOffsetInDictionary {
415 index: index as u8,
416 },
417 );
418 }
419 self.dictionary_entropy_cache = Some(CachedDictionaryEntropy {
420 huff: dictionary.huf.table.to_encoder_table(),
421 ll_previous: dictionary
422 .fse
423 .literal_lengths
424 .to_encoder_table()
425 .map(|table| PreviousFseTable::Custom(Box::new(table))),
426 ml_previous: dictionary
427 .fse
428 .match_lengths
429 .to_encoder_table()
430 .map(|table| PreviousFseTable::Custom(Box::new(table))),
431 of_previous: dictionary
432 .fse
433 .offsets
434 .to_encoder_table()
435 .map(|table| PreviousFseTable::Custom(Box::new(table))),
436 });
437 Ok(self.dictionary.replace(dictionary))
438 }
439
440 pub fn set_dictionary_from_bytes(
442 &mut self,
443 raw_dictionary: &[u8],
444 ) -> Result<Option<crate::decoding::Dictionary>, crate::decoding::errors::DictionaryDecodeError>
445 {
446 let dictionary = crate::decoding::Dictionary::decode_dict(raw_dictionary)?;
447 self.set_dictionary(dictionary)
448 }
449
450 pub fn clear_dictionary(&mut self) -> Option<crate::decoding::Dictionary> {
452 self.dictionary_entropy_cache = None;
453 self.dictionary.take()
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 #[cfg(all(feature = "dict_builder", feature = "std"))]
460 use alloc::format;
461 use alloc::vec;
462
463 use super::FrameCompressor;
464 use crate::common::MAGIC_NUM;
465 use crate::decoding::FrameDecoder;
466 use crate::encoding::{Matcher, Sequence};
467 use alloc::vec::Vec;
468
469 #[cfg(feature = "std")]
471 #[test]
472 fn fcs_header_written_and_c_zstd_compatible() {
473 let levels = [
474 crate::encoding::CompressionLevel::Uncompressed,
475 crate::encoding::CompressionLevel::Fastest,
476 crate::encoding::CompressionLevel::Default,
477 crate::encoding::CompressionLevel::Better,
478 crate::encoding::CompressionLevel::Best,
479 ];
480 let fcs_2byte = vec![0xCDu8; 300]; let large = vec![0xABu8; 100_000];
482 let inputs: [&[u8]; 5] = [
483 &[],
484 &[0x00],
485 b"abcdefghijklmnopqrstuvwxy\n",
486 &fcs_2byte,
487 &large,
488 ];
489 for level in levels {
490 for data in &inputs {
491 let compressed = crate::encoding::compress_to_vec(*data, level);
492 let header = crate::decoding::frame::read_frame_header(compressed.as_slice())
494 .unwrap()
495 .0;
496 assert_eq!(
497 header.frame_content_size(),
498 data.len() as u64,
499 "FCS mismatch for len={} level={:?}",
500 data.len(),
501 level,
502 );
503 assert_ne!(
506 header.descriptor.frame_content_size_bytes().unwrap(),
507 0,
508 "FCS field must be present for len={} level={:?}",
509 data.len(),
510 level,
511 );
512 let mut decoded = Vec::new();
514 zstd::stream::copy_decode(compressed.as_slice(), &mut decoded).unwrap();
515 assert_eq!(
516 decoded.as_slice(),
517 *data,
518 "C zstd roundtrip failed for len={}",
519 data.len()
520 );
521 }
522 }
523 }
524
525 struct NoDictionaryMatcher {
526 last_space: Vec<u8>,
527 window_size: u64,
528 }
529
530 impl NoDictionaryMatcher {
531 fn new(window_size: u64) -> Self {
532 Self {
533 last_space: Vec::new(),
534 window_size,
535 }
536 }
537 }
538
539 impl Matcher for NoDictionaryMatcher {
540 fn get_next_space(&mut self) -> Vec<u8> {
541 vec![0; self.window_size as usize]
542 }
543
544 fn get_last_space(&mut self) -> &[u8] {
545 self.last_space.as_slice()
546 }
547
548 fn commit_space(&mut self, space: Vec<u8>) {
549 self.last_space = space;
550 }
551
552 fn skip_matching(&mut self) {}
553
554 fn start_matching(&mut self, mut handle_sequence: impl for<'a> FnMut(Sequence<'a>)) {
555 handle_sequence(Sequence::Literals {
556 literals: self.last_space.as_slice(),
557 });
558 }
559
560 fn reset(&mut self, _level: super::CompressionLevel) {
561 self.last_space.clear();
562 }
563
564 fn window_size(&self) -> u64 {
565 self.window_size
566 }
567 }
568
569 #[test]
570 fn frame_starts_with_magic_num() {
571 let mock_data = [1_u8, 2, 3].as_slice();
572 let mut output: Vec<u8> = Vec::new();
573 let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
574 compressor.set_source(mock_data);
575 compressor.set_drain(&mut output);
576
577 compressor.compress();
578 assert!(output.starts_with(&MAGIC_NUM.to_le_bytes()));
579 }
580
581 #[test]
582 fn very_simple_raw_compress() {
583 let mock_data = [1_u8, 2, 3].as_slice();
584 let mut output: Vec<u8> = Vec::new();
585 let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
586 compressor.set_source(mock_data);
587 compressor.set_drain(&mut output);
588
589 compressor.compress();
590 }
591
592 #[test]
593 fn very_simple_compress() {
594 let mut mock_data = vec![0; 1 << 17];
595 mock_data.extend(vec![1; (1 << 17) - 1]);
596 mock_data.extend(vec![2; (1 << 18) - 1]);
597 mock_data.extend(vec![2; 1 << 17]);
598 mock_data.extend(vec![3; (1 << 17) - 1]);
599 let mut output: Vec<u8> = Vec::new();
600 let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
601 compressor.set_source(mock_data.as_slice());
602 compressor.set_drain(&mut output);
603
604 compressor.compress();
605
606 let mut decoder = FrameDecoder::new();
607 let mut decoded = Vec::with_capacity(mock_data.len());
608 decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
609 assert_eq!(mock_data, decoded);
610
611 let mut decoded = Vec::new();
612 zstd::stream::copy_decode(output.as_slice(), &mut decoded).unwrap();
613 assert_eq!(mock_data, decoded);
614 }
615
616 #[test]
617 fn rle_compress() {
618 let mock_data = vec![0; 1 << 19];
619 let mut output: Vec<u8> = Vec::new();
620 let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
621 compressor.set_source(mock_data.as_slice());
622 compressor.set_drain(&mut output);
623
624 compressor.compress();
625
626 let mut decoder = FrameDecoder::new();
627 let mut decoded = Vec::with_capacity(mock_data.len());
628 decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
629 assert_eq!(mock_data, decoded);
630 }
631
632 #[test]
633 fn aaa_compress() {
634 let mock_data = vec![0, 1, 3, 4, 5];
635 let mut output: Vec<u8> = Vec::new();
636 let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
637 compressor.set_source(mock_data.as_slice());
638 compressor.set_drain(&mut output);
639
640 compressor.compress();
641
642 let mut decoder = FrameDecoder::new();
643 let mut decoded = Vec::with_capacity(mock_data.len());
644 decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
645 assert_eq!(mock_data, decoded);
646
647 let mut decoded = Vec::new();
648 zstd::stream::copy_decode(output.as_slice(), &mut decoded).unwrap();
649 assert_eq!(mock_data, decoded);
650 }
651
652 #[test]
653 fn dictionary_compression_sets_required_dict_id_and_roundtrips() {
654 let dict_raw = include_bytes!("../../dict_tests/dictionary");
655 let dict_for_encoder = crate::decoding::Dictionary::decode_dict(dict_raw).unwrap();
656 let dict_for_decoder = crate::decoding::Dictionary::decode_dict(dict_raw).unwrap();
657
658 let mut data = Vec::new();
659 for _ in 0..8 {
660 data.extend_from_slice(&dict_for_decoder.dict_content[..2048]);
661 }
662
663 let mut with_dict = Vec::new();
664 let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
665 let previous = compressor
666 .set_dictionary_from_bytes(dict_raw)
667 .expect("dictionary bytes should parse");
668 assert!(
669 previous.is_none(),
670 "first dictionary insert should return None"
671 );
672 assert_eq!(
673 compressor
674 .set_dictionary(dict_for_encoder)
675 .expect("valid dictionary should attach")
676 .expect("set_dictionary_from_bytes inserted previous dictionary")
677 .id,
678 dict_for_decoder.id
679 );
680 compressor.set_source(data.as_slice());
681 compressor.set_drain(&mut with_dict);
682 compressor.compress();
683
684 let (frame_header, _) = crate::decoding::frame::read_frame_header(with_dict.as_slice())
685 .expect("encoded stream should have a frame header");
686 assert_eq!(frame_header.dictionary_id(), Some(dict_for_decoder.id));
687
688 let mut decoder = FrameDecoder::new();
689 let mut missing_dict_target = Vec::with_capacity(data.len());
690 let err = decoder
691 .decode_all_to_vec(&with_dict, &mut missing_dict_target)
692 .unwrap_err();
693 assert!(
694 matches!(
695 &err,
696 crate::decoding::errors::FrameDecoderError::DictNotProvided { .. }
697 ),
698 "dict-compressed stream should require dictionary id, got: {err:?}"
699 );
700
701 let mut decoder = FrameDecoder::new();
702 decoder.add_dict(dict_for_decoder).unwrap();
703 let mut decoded = Vec::with_capacity(data.len());
704 decoder.decode_all_to_vec(&with_dict, &mut decoded).unwrap();
705 assert_eq!(decoded, data);
706
707 let mut ffi_decoder = zstd::bulk::Decompressor::with_dictionary(dict_raw).unwrap();
708 let mut ffi_decoded = Vec::with_capacity(data.len());
709 let ffi_written = ffi_decoder
710 .decompress_to_buffer(with_dict.as_slice(), &mut ffi_decoded)
711 .unwrap();
712 assert_eq!(ffi_written, data.len());
713 assert_eq!(ffi_decoded, data);
714 }
715
716 #[cfg(all(feature = "dict_builder", feature = "std"))]
717 #[test]
718 fn dictionary_compression_roundtrips_with_dict_builder_dictionary() {
719 use std::io::Cursor;
720
721 let mut training = Vec::new();
722 for idx in 0..256u32 {
723 training.extend_from_slice(
724 format!("tenant=demo table=orders key={idx} region=eu\n").as_bytes(),
725 );
726 }
727 let mut raw_dict = Vec::new();
728 crate::dictionary::create_raw_dict_from_source(
729 Cursor::new(training.as_slice()),
730 training.len(),
731 &mut raw_dict,
732 4096,
733 )
734 .expect("dict_builder training should succeed");
735 assert!(
736 !raw_dict.is_empty(),
737 "dict_builder produced an empty dictionary"
738 );
739
740 let dict_id = 0xD1C7_0008;
741 let encoder_dict =
742 crate::decoding::Dictionary::from_raw_content(dict_id, raw_dict.clone()).unwrap();
743 let decoder_dict =
744 crate::decoding::Dictionary::from_raw_content(dict_id, raw_dict.clone()).unwrap();
745
746 let mut payload = Vec::new();
747 for idx in 0..96u32 {
748 payload.extend_from_slice(
749 format!(
750 "tenant=demo table=orders op=put key={idx} value=aaaaabbbbbcccccdddddeeeee\n"
751 )
752 .as_bytes(),
753 );
754 }
755
756 let mut without_dict = Vec::new();
757 let mut baseline = FrameCompressor::new(super::CompressionLevel::Fastest);
758 baseline.set_source(payload.as_slice());
759 baseline.set_drain(&mut without_dict);
760 baseline.compress();
761
762 let mut with_dict = Vec::new();
763 let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
764 compressor
765 .set_dictionary(encoder_dict)
766 .expect("valid dict_builder dictionary should attach");
767 compressor.set_source(payload.as_slice());
768 compressor.set_drain(&mut with_dict);
769 compressor.compress();
770
771 let (frame_header, _) = crate::decoding::frame::read_frame_header(with_dict.as_slice())
772 .expect("encoded stream should have a frame header");
773 assert_eq!(frame_header.dictionary_id(), Some(dict_id));
774 let mut decoder = FrameDecoder::new();
775 decoder.add_dict(decoder_dict).unwrap();
776 let mut decoded = Vec::with_capacity(payload.len());
777 decoder.decode_all_to_vec(&with_dict, &mut decoded).unwrap();
778 assert_eq!(decoded, payload);
779 assert!(
780 with_dict.len() < without_dict.len(),
781 "trained dictionary should improve compression for this small payload"
782 );
783 }
784
785 #[test]
786 fn set_dictionary_from_bytes_seeds_entropy_tables_for_first_block() {
787 let dict_raw = include_bytes!("../../dict_tests/dictionary");
788 let mut output = Vec::new();
789 let input = b"";
790
791 let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
792 let previous = compressor
793 .set_dictionary_from_bytes(dict_raw)
794 .expect("dictionary bytes should parse");
795 assert!(previous.is_none());
796
797 compressor.set_source(input.as_slice());
798 compressor.set_drain(&mut output);
799 compressor.compress();
800
801 assert!(
802 compressor.state.last_huff_table.is_some(),
803 "dictionary entropy should seed previous huffman table before first block"
804 );
805 assert!(
806 compressor.state.fse_tables.ll_previous.is_some(),
807 "dictionary entropy should seed previous ll table before first block"
808 );
809 assert!(
810 compressor.state.fse_tables.ml_previous.is_some(),
811 "dictionary entropy should seed previous ml table before first block"
812 );
813 assert!(
814 compressor.state.fse_tables.of_previous.is_some(),
815 "dictionary entropy should seed previous of table before first block"
816 );
817 }
818
819 #[test]
820 fn set_dictionary_rejects_zero_dictionary_id() {
821 let invalid = crate::decoding::Dictionary {
822 id: 0,
823 fse: crate::decoding::scratch::FSEScratch::new(),
824 huf: crate::decoding::scratch::HuffmanScratch::new(),
825 dict_content: vec![1, 2, 3],
826 offset_hist: [1, 4, 8],
827 };
828
829 let mut compressor: FrameCompressor<
830 &[u8],
831 Vec<u8>,
832 crate::encoding::match_generator::MatchGeneratorDriver,
833 > = FrameCompressor::new(super::CompressionLevel::Fastest);
834 let result = compressor.set_dictionary(invalid);
835 assert!(matches!(
836 result,
837 Err(crate::decoding::errors::DictionaryDecodeError::ZeroDictionaryId)
838 ));
839 }
840
841 #[test]
842 fn set_dictionary_rejects_zero_repeat_offsets() {
843 let invalid = crate::decoding::Dictionary {
844 id: 1,
845 fse: crate::decoding::scratch::FSEScratch::new(),
846 huf: crate::decoding::scratch::HuffmanScratch::new(),
847 dict_content: vec![1, 2, 3],
848 offset_hist: [0, 4, 8],
849 };
850
851 let mut compressor: FrameCompressor<
852 &[u8],
853 Vec<u8>,
854 crate::encoding::match_generator::MatchGeneratorDriver,
855 > = FrameCompressor::new(super::CompressionLevel::Fastest);
856 let result = compressor.set_dictionary(invalid);
857 assert!(matches!(
858 result,
859 Err(
860 crate::decoding::errors::DictionaryDecodeError::ZeroRepeatOffsetInDictionary {
861 index: 0
862 }
863 )
864 ));
865 }
866
867 #[test]
868 fn uncompressed_mode_does_not_require_dictionary() {
869 let dict_id = 0xABCD_0001;
870 let dict =
871 crate::decoding::Dictionary::from_raw_content(dict_id, b"shared-history".to_vec())
872 .expect("raw dictionary should be valid");
873
874 let payload = b"plain-bytes-that-should-stay-raw";
875 let mut output = Vec::new();
876 let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
877 compressor
878 .set_dictionary(dict)
879 .expect("dictionary should attach in uncompressed mode");
880 compressor.set_source(payload.as_slice());
881 compressor.set_drain(&mut output);
882 compressor.compress();
883
884 let (frame_header, _) = crate::decoding::frame::read_frame_header(output.as_slice())
885 .expect("encoded frame should have a header");
886 assert_eq!(
887 frame_header.dictionary_id(),
888 None,
889 "raw/uncompressed frames must not advertise dictionary dependency"
890 );
891
892 let mut decoder = FrameDecoder::new();
893 let mut decoded = Vec::with_capacity(payload.len());
894 decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
895 assert_eq!(decoded, payload);
896 }
897
898 #[test]
899 fn dictionary_roundtrip_stays_valid_after_output_exceeds_window() {
900 use crate::encoding::match_generator::MatchGeneratorDriver;
901
902 let dict_id = 0xABCD_0002;
903 let dict = crate::decoding::Dictionary::from_raw_content(dict_id, b"abcdefgh".to_vec())
904 .expect("raw dictionary should be valid");
905 let dict_for_decoder =
906 crate::decoding::Dictionary::from_raw_content(dict_id, b"abcdefgh".to_vec())
907 .expect("raw dictionary should be valid");
908
909 let payload = b"abcdefgh".repeat(128 * 1024 / 8 + 64);
912 let matcher = MatchGeneratorDriver::new(1024, 1);
913
914 let mut no_dict_output = Vec::new();
915 let mut no_dict_compressor =
916 FrameCompressor::new_with_matcher(matcher, super::CompressionLevel::Fastest);
917 no_dict_compressor.set_source(payload.as_slice());
918 no_dict_compressor.set_drain(&mut no_dict_output);
919 no_dict_compressor.compress();
920 let (no_dict_frame_header, _) =
921 crate::decoding::frame::read_frame_header(no_dict_output.as_slice())
922 .expect("baseline frame should have a header");
923 let no_dict_window = no_dict_frame_header
924 .window_size()
925 .expect("window size should be present");
926
927 let mut output = Vec::new();
928 let matcher = MatchGeneratorDriver::new(1024, 1);
929 let mut compressor =
930 FrameCompressor::new_with_matcher(matcher, super::CompressionLevel::Fastest);
931 compressor
932 .set_dictionary(dict)
933 .expect("dictionary should attach");
934 compressor.set_source(payload.as_slice());
935 compressor.set_drain(&mut output);
936 compressor.compress();
937
938 let (frame_header, _) = crate::decoding::frame::read_frame_header(output.as_slice())
939 .expect("encoded frame should have a header");
940 let advertised_window = frame_header
941 .window_size()
942 .expect("window size should be present");
943 assert_eq!(
944 advertised_window, no_dict_window,
945 "dictionary priming must not inflate advertised window size"
946 );
947 assert!(
948 payload.len() > advertised_window as usize,
949 "test must cross the advertised window boundary"
950 );
951
952 let mut decoder = FrameDecoder::new();
953 decoder.add_dict(dict_for_decoder).unwrap();
954 let mut decoded = Vec::with_capacity(payload.len());
955 decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
956 assert_eq!(decoded, payload);
957 }
958
959 #[test]
960 fn source_size_hint_with_dictionary_keeps_roundtrip_and_nonincreasing_window() {
961 let dict_id = 0xABCD_0004;
962 let dict_content = b"abcd".repeat(1024); let dict = crate::decoding::Dictionary::from_raw_content(dict_id, dict_content).unwrap();
964 let dict_for_decoder =
965 crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024)).unwrap();
966 let payload = b"abcdabcdabcdabcd".repeat(128);
967
968 let mut hinted_output = Vec::new();
969 let mut hinted = FrameCompressor::new(super::CompressionLevel::Fastest);
970 hinted.set_dictionary(dict).unwrap();
971 hinted.set_source_size_hint(1);
972 hinted.set_source(payload.as_slice());
973 hinted.set_drain(&mut hinted_output);
974 hinted.compress();
975
976 let mut no_hint_output = Vec::new();
977 let mut no_hint = FrameCompressor::new(super::CompressionLevel::Fastest);
978 no_hint
979 .set_dictionary(
980 crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024))
981 .unwrap(),
982 )
983 .unwrap();
984 no_hint.set_source(payload.as_slice());
985 no_hint.set_drain(&mut no_hint_output);
986 no_hint.compress();
987
988 let hinted_window = crate::decoding::frame::read_frame_header(hinted_output.as_slice())
989 .expect("encoded frame should have a header")
990 .0
991 .window_size()
992 .expect("window size should be present");
993 let no_hint_window = crate::decoding::frame::read_frame_header(no_hint_output.as_slice())
994 .expect("encoded frame should have a header")
995 .0
996 .window_size()
997 .expect("window size should be present");
998 assert!(
999 hinted_window <= no_hint_window,
1000 "source-size hint should not increase advertised window with dictionary priming",
1001 );
1002
1003 let mut decoder = FrameDecoder::new();
1004 decoder.add_dict(dict_for_decoder).unwrap();
1005 let mut decoded = Vec::with_capacity(payload.len());
1006 decoder
1007 .decode_all_to_vec(&hinted_output, &mut decoded)
1008 .unwrap();
1009 assert_eq!(decoded, payload);
1010 }
1011
1012 #[test]
1013 fn source_size_hint_with_dictionary_keeps_roundtrip_for_larger_payload() {
1014 let dict_id = 0xABCD_0005;
1015 let dict_content = b"abcd".repeat(1024); let dict = crate::decoding::Dictionary::from_raw_content(dict_id, dict_content).unwrap();
1017 let dict_for_decoder =
1018 crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024)).unwrap();
1019 let payload = b"abcd".repeat(1024); let payload_len = payload.len() as u64;
1021
1022 let mut hinted_output = Vec::new();
1023 let mut hinted = FrameCompressor::new(super::CompressionLevel::Fastest);
1024 hinted.set_dictionary(dict).unwrap();
1025 hinted.set_source_size_hint(payload_len);
1026 hinted.set_source(payload.as_slice());
1027 hinted.set_drain(&mut hinted_output);
1028 hinted.compress();
1029
1030 let mut no_hint_output = Vec::new();
1031 let mut no_hint = FrameCompressor::new(super::CompressionLevel::Fastest);
1032 no_hint
1033 .set_dictionary(
1034 crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024))
1035 .unwrap(),
1036 )
1037 .unwrap();
1038 no_hint.set_source(payload.as_slice());
1039 no_hint.set_drain(&mut no_hint_output);
1040 no_hint.compress();
1041
1042 let hinted_window = crate::decoding::frame::read_frame_header(hinted_output.as_slice())
1043 .expect("encoded frame should have a header")
1044 .0
1045 .window_size()
1046 .expect("window size should be present");
1047 let no_hint_window = crate::decoding::frame::read_frame_header(no_hint_output.as_slice())
1048 .expect("encoded frame should have a header")
1049 .0
1050 .window_size()
1051 .expect("window size should be present");
1052 assert!(
1053 hinted_window <= no_hint_window,
1054 "source-size hint should not increase advertised window with dictionary priming",
1055 );
1056
1057 let mut decoder = FrameDecoder::new();
1058 decoder.add_dict(dict_for_decoder).unwrap();
1059 let mut decoded = Vec::with_capacity(payload.len());
1060 decoder
1061 .decode_all_to_vec(&hinted_output, &mut decoded)
1062 .unwrap();
1063 assert_eq!(decoded, payload);
1064 }
1065
1066 #[test]
1067 fn custom_matcher_without_dictionary_priming_does_not_advertise_dict_id() {
1068 let dict_id = 0xABCD_0003;
1069 let dict = crate::decoding::Dictionary::from_raw_content(dict_id, b"abcdefgh".to_vec())
1070 .expect("raw dictionary should be valid");
1071 let payload = b"abcdefghabcdefgh";
1072
1073 let mut output = Vec::new();
1074 let matcher = NoDictionaryMatcher::new(64);
1075 let mut compressor =
1076 FrameCompressor::new_with_matcher(matcher, super::CompressionLevel::Fastest);
1077 compressor
1078 .set_dictionary(dict)
1079 .expect("dictionary should attach");
1080 compressor.set_source(payload.as_slice());
1081 compressor.set_drain(&mut output);
1082 compressor.compress();
1083
1084 let (frame_header, _) = crate::decoding::frame::read_frame_header(output.as_slice())
1085 .expect("encoded frame should have a header");
1086 assert_eq!(
1087 frame_header.dictionary_id(),
1088 None,
1089 "matchers that do not support dictionary priming must not advertise dictionary dependency"
1090 );
1091
1092 let mut decoder = FrameDecoder::new();
1093 let mut decoded = Vec::with_capacity(payload.len());
1094 decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
1095 assert_eq!(decoded, payload);
1096 }
1097
1098 #[cfg(feature = "hash")]
1099 #[test]
1100 fn checksum_two_frames_reused_compressor() {
1101 let data: Vec<u8> = (0u8..=255).cycle().take(1024).collect();
1107
1108 let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
1109
1110 let mut compressed1 = Vec::new();
1112 compressor.set_source(data.as_slice());
1113 compressor.set_drain(&mut compressed1);
1114 compressor.compress();
1115
1116 let mut compressed2 = Vec::new();
1118 compressor.set_source(data.as_slice());
1119 compressor.set_drain(&mut compressed2);
1120 compressor.compress();
1121
1122 fn decode_and_collect(compressed: &[u8]) -> (Vec<u8>, Option<u32>, Option<u32>) {
1123 let mut decoder = FrameDecoder::new();
1124 let mut source = compressed;
1125 decoder.reset(&mut source).unwrap();
1126 while !decoder.is_finished() {
1127 decoder
1128 .decode_blocks(&mut source, crate::decoding::BlockDecodingStrategy::All)
1129 .unwrap();
1130 }
1131 let mut decoded = Vec::new();
1132 decoder.collect_to_writer(&mut decoded).unwrap();
1133 (
1134 decoded,
1135 decoder.get_checksum_from_data(),
1136 decoder.get_calculated_checksum(),
1137 )
1138 }
1139
1140 let (decoded1, chksum_from_data1, chksum_calculated1) = decode_and_collect(&compressed1);
1141 assert_eq!(decoded1, data, "frame 1: decoded data mismatch");
1142 assert_eq!(
1143 chksum_from_data1, chksum_calculated1,
1144 "frame 1: checksum mismatch"
1145 );
1146
1147 let (decoded2, chksum_from_data2, chksum_calculated2) = decode_and_collect(&compressed2);
1148 assert_eq!(decoded2, data, "frame 2: decoded data mismatch");
1149 assert_eq!(
1150 chksum_from_data2, chksum_calculated2,
1151 "frame 2: checksum mismatch"
1152 );
1153
1154 assert_eq!(
1157 chksum_from_data1, chksum_from_data2,
1158 "frame 1 and frame 2 should have the same checksum (same data, hash must reset per frame)"
1159 );
1160 }
1161
1162 #[cfg(feature = "std")]
1163 #[test]
1164 fn fuzz_targets() {
1165 use std::io::Read;
1166 fn decode_szstd(data: &mut dyn std::io::Read) -> Vec<u8> {
1167 let mut decoder = crate::decoding::StreamingDecoder::new(data).unwrap();
1168 let mut result: Vec<u8> = Vec::new();
1169 decoder.read_to_end(&mut result).expect("Decoding failed");
1170 result
1171 }
1172
1173 fn decode_szstd_writer(mut data: impl Read) -> Vec<u8> {
1174 let mut decoder = crate::decoding::FrameDecoder::new();
1175 decoder.reset(&mut data).unwrap();
1176 let mut result = vec![];
1177 while !decoder.is_finished() || decoder.can_collect() > 0 {
1178 decoder
1179 .decode_blocks(
1180 &mut data,
1181 crate::decoding::BlockDecodingStrategy::UptoBytes(1024 * 1024),
1182 )
1183 .unwrap();
1184 decoder.collect_to_writer(&mut result).unwrap();
1185 }
1186 result
1187 }
1188
1189 fn encode_zstd(data: &[u8]) -> Result<Vec<u8>, std::io::Error> {
1190 zstd::stream::encode_all(std::io::Cursor::new(data), 3)
1191 }
1192
1193 fn encode_szstd_uncompressed(data: &mut dyn std::io::Read) -> Vec<u8> {
1194 let mut input = Vec::new();
1195 data.read_to_end(&mut input).unwrap();
1196
1197 crate::encoding::compress_to_vec(
1198 input.as_slice(),
1199 crate::encoding::CompressionLevel::Uncompressed,
1200 )
1201 }
1202
1203 fn encode_szstd_compressed(data: &mut dyn std::io::Read) -> Vec<u8> {
1204 let mut input = Vec::new();
1205 data.read_to_end(&mut input).unwrap();
1206
1207 crate::encoding::compress_to_vec(
1208 input.as_slice(),
1209 crate::encoding::CompressionLevel::Fastest,
1210 )
1211 }
1212
1213 fn decode_zstd(data: &[u8]) -> Result<Vec<u8>, std::io::Error> {
1214 let mut output = Vec::new();
1215 zstd::stream::copy_decode(data, &mut output)?;
1216 Ok(output)
1217 }
1218 if std::fs::exists("fuzz/artifacts/interop").unwrap_or(false) {
1219 for file in std::fs::read_dir("fuzz/artifacts/interop").unwrap() {
1220 if file.as_ref().unwrap().file_type().unwrap().is_file() {
1221 let data = std::fs::read(file.unwrap().path()).unwrap();
1222 let data = data.as_slice();
1223 let compressed = encode_zstd(data).unwrap();
1225 let decoded = decode_szstd(&mut compressed.as_slice());
1226 let decoded2 = decode_szstd_writer(&mut compressed.as_slice());
1227 assert!(
1228 decoded == data,
1229 "Decoded data did not match the original input during decompression"
1230 );
1231 assert_eq!(
1232 decoded2, data,
1233 "Decoded data did not match the original input during decompression"
1234 );
1235
1236 let mut input = data;
1239 let compressed = encode_szstd_uncompressed(&mut input);
1240 let decoded = decode_zstd(&compressed).unwrap();
1241 assert_eq!(
1242 decoded, data,
1243 "Decoded data did not match the original input during compression"
1244 );
1245 let mut input = data;
1247 let compressed = encode_szstd_compressed(&mut input);
1248 let decoded = decode_zstd(&compressed).unwrap();
1249 assert_eq!(
1250 decoded, data,
1251 "Decoded data did not match the original input during compression"
1252 );
1253 }
1254 }
1255 }
1256 }
1257}