use alloc::format;
use alloc::vec;
use super::FrameCompressor;
use crate::common::{MAGIC_NUM, MAX_BLOCK_SIZE};
use crate::decoding::FrameDecoder;
use crate::encoding::{Matcher, Sequence};
use alloc::vec::Vec;
fn generate_data(seed: u64, len: usize) -> Vec<u8> {
let mut state = seed;
let mut data = Vec::with_capacity(len);
for _ in 0..len {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
data.push((state >> 33) as u8);
}
data
}
struct NoDictionaryMatcher {
last_space: Vec<u8>,
window_size: u64,
}
impl NoDictionaryMatcher {
fn new(window_size: u64) -> Self {
Self {
last_space: Vec::new(),
window_size,
}
}
}
impl Matcher for NoDictionaryMatcher {
fn get_next_space(&mut self) -> Vec<u8> {
vec![0; self.window_size as usize]
}
fn get_last_space(&mut self) -> &[u8] {
self.last_space.as_slice()
}
fn commit_space(&mut self, space: Vec<u8>) {
self.last_space = space;
}
fn skip_matching(&mut self) {}
fn start_matching(&mut self, mut handle_sequence: impl for<'a> FnMut(Sequence<'a>)) {
handle_sequence(Sequence::Literals {
literals: self.last_space.as_slice(),
});
}
fn reset(&mut self, _level: super::CompressionLevel) {
self.last_space.clear();
}
fn window_size(&self) -> u64 {
self.window_size
}
}
#[test]
fn frame_starts_with_magic_num() {
let mock_data = [1_u8, 2, 3].as_slice();
let mut output: Vec<u8> = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
compressor.set_source(mock_data);
compressor.set_drain(&mut output);
compressor.compress();
assert!(output.starts_with(&MAGIC_NUM.to_le_bytes()));
}
#[test]
fn very_simple_raw_compress() {
let mock_data = [1_u8, 2, 3].as_slice();
let mut output: Vec<u8> = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
compressor.set_source(mock_data);
compressor.set_drain(&mut output);
compressor.compress();
}
#[test]
fn very_simple_compress() {
let mut mock_data = vec![0; 1 << 17];
mock_data.extend(vec![1; (1 << 17) - 1]);
mock_data.extend(vec![2; (1 << 18) - 1]);
mock_data.extend(vec![2; 1 << 17]);
mock_data.extend(vec![3; (1 << 17) - 1]);
let mut output: Vec<u8> = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
compressor.set_source(mock_data.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(mock_data.len());
decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
assert_eq!(mock_data, decoded);
}
#[test]
fn rle_compress() {
let mock_data = vec![0; 1 << 19];
let mut output: Vec<u8> = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
compressor.set_source(mock_data.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(mock_data.len());
decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
assert_eq!(mock_data, decoded);
}
#[test]
fn aaa_compress() {
let mock_data = vec![0, 1, 3, 4, 5];
let mut output: Vec<u8> = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
compressor.set_source(mock_data.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(mock_data.len());
decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
assert_eq!(mock_data, decoded);
}
#[test]
fn dictionary_compression_sets_required_dict_id_and_roundtrips() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let dict_for_encoder = crate::decoding::Dictionary::decode_dict(dict_raw).unwrap();
let dict_for_decoder = crate::decoding::Dictionary::decode_dict(dict_raw).unwrap();
let mut data = Vec::new();
for _ in 0..8 {
data.extend_from_slice(&dict_for_decoder.dict_content[..2048]);
}
let mut with_dict = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
let previous = compressor
.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
assert!(
previous.is_none(),
"first dictionary insert should return None"
);
assert_eq!(
compressor
.set_dictionary(dict_for_encoder)
.expect("valid dictionary should attach")
.expect("set_dictionary_from_bytes inserted previous dictionary")
.id(),
dict_for_decoder.id
);
compressor.set_source(data.as_slice());
compressor.set_drain(&mut with_dict);
compressor.compress();
let (frame_header, _) = crate::decoding::frame::read_frame_header(with_dict.as_slice())
.expect("encoded stream should have a frame header");
assert_eq!(frame_header.dictionary_id(), Some(dict_for_decoder.id));
let mut decoder = FrameDecoder::new();
let mut missing_dict_target = Vec::with_capacity(data.len());
let err = decoder
.decode_all_to_vec(&with_dict, &mut missing_dict_target)
.unwrap_err();
assert!(
matches!(
&err,
crate::decoding::errors::FrameDecoderError::DictNotProvided { .. }
),
"dict-compressed stream should require dictionary id, got: {err:?}"
);
let mut decoder = FrameDecoder::new();
decoder.add_dict(dict_for_decoder).unwrap();
let mut decoded = Vec::with_capacity(data.len());
decoder.decode_all_to_vec(&with_dict, &mut decoded).unwrap();
assert_eq!(decoded, data);
}
#[cfg(all(feature = "dict_builder", feature = "std"))]
#[test]
fn dictionary_compression_roundtrips_with_dict_builder_dictionary() {
use std::io::Cursor;
let mut training = Vec::new();
for idx in 0..256u32 {
training.extend_from_slice(
format!("tenant=demo table=orders key={idx} region=eu\n").as_bytes(),
);
}
let mut raw_dict = Vec::new();
crate::dictionary::create_raw_dict_from_source(
Cursor::new(training.as_slice()),
training.len(),
&mut raw_dict,
4096,
)
.expect("dict_builder training should succeed");
assert!(
!raw_dict.is_empty(),
"dict_builder produced an empty dictionary"
);
let dict_id = 0xD1C7_0008;
let encoder_dict =
crate::decoding::Dictionary::from_raw_content(dict_id, raw_dict.clone()).unwrap();
let decoder_dict =
crate::decoding::Dictionary::from_raw_content(dict_id, raw_dict.clone()).unwrap();
let mut payload = Vec::new();
for idx in 1000..1096u32 {
payload.extend_from_slice(
format!("tenant=demo table=orders key={idx} region=eu\n").as_bytes(),
);
}
let mut without_dict = Vec::new();
let mut baseline = FrameCompressor::new(super::CompressionLevel::Fastest);
baseline.set_source(payload.as_slice());
baseline.set_drain(&mut without_dict);
baseline.compress();
let mut with_dict = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor
.set_dictionary(encoder_dict)
.expect("valid dict_builder dictionary should attach");
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut with_dict);
compressor.compress();
let (frame_header, _) = crate::decoding::frame::read_frame_header(with_dict.as_slice())
.expect("encoded stream should have a frame header");
assert_eq!(frame_header.dictionary_id(), Some(dict_id));
let mut decoder = FrameDecoder::new();
decoder.add_dict(decoder_dict).unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(&with_dict, &mut decoded).unwrap();
assert_eq!(decoded, payload);
assert!(
with_dict.len() < without_dict.len(),
"trained dictionary should improve compression for this small payload (with_dict={}, without_dict={})",
with_dict.len(),
without_dict.len(),
);
}
#[test]
fn set_dictionary_from_bytes_seeds_entropy_tables_for_first_block() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let mut output = Vec::new();
let input = b"";
let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
let previous = compressor
.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
assert!(previous.is_none());
compressor.set_source(input.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
assert!(
compressor.state.last_huff_table.is_some(),
"dictionary entropy should seed previous huffman table before first block"
);
assert!(
compressor.state.fse_tables.ll_previous.is_some(),
"dictionary entropy should seed previous ll table before first block"
);
assert!(
compressor.state.fse_tables.ml_previous.is_some(),
"dictionary entropy should seed previous ml table before first block"
);
assert!(
compressor.state.fse_tables.of_previous.is_some(),
"dictionary entropy should seed previous of table before first block"
);
}
#[test]
fn content_size_flag_off_omits_fcs_and_roundtrips() {
let payload = alloc::vec![0x42u8; 4096];
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
let mut with_fcs = Vec::new();
compressor.compress_independent_frame_into(&payload, &mut with_fcs);
compressor.set_content_size_flag(false);
let mut without_fcs = Vec::new();
compressor.compress_independent_frame_into(&payload, &mut without_fcs);
let parsed_with = crate::decoding::frame::read_frame_header(with_fcs.as_slice())
.expect("flag-on frame header must parse")
.0;
assert_eq!(parsed_with.frame_content_size(), 4096);
let parsed_without = crate::decoding::frame::read_frame_header(without_fcs.as_slice())
.expect("flag-off frame header must parse")
.0;
assert_eq!(
parsed_without.frame_content_size(),
0,
"FCS must be omitted with the content-size flag off"
);
assert_eq!(
parsed_without
.descriptor
.frame_content_size_bytes()
.expect("descriptor must parse"),
0,
"the FCS field itself must be omitted, not written as zero"
);
let mut decoder = crate::decoding::FrameDecoder::new();
let mut decoded = Vec::with_capacity(payload.len() + 64);
decoder
.decode_all_to_vec(&without_fcs, &mut decoded)
.expect("flag-off frame must decode");
assert_eq!(decoded, payload);
}
#[test]
fn dict_id_flag_off_omits_dictionary_id_and_roundtrips() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let payload = b"dictionary-keyed payload dictionary-keyed payload".repeat(8);
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor
.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
compressor.set_dictionary_id_flag(false);
let mut frame = Vec::new();
compressor.compress_independent_frame_into(&payload, &mut frame);
let parsed = crate::decoding::frame::read_frame_header(frame.as_slice())
.expect("frame header must parse")
.0;
assert_eq!(
parsed.dictionary_id(),
None,
"dictionary id must be omitted with the dict-id flag off"
);
let mut sd =
crate::decoding::StreamingDecoder::new_with_dictionary_bytes(frame.as_slice(), dict_raw)
.expect("decoder must accept the dictionary");
let mut dec = Vec::new();
std::io::Read::read_to_end(&mut sd, &mut dec)
.expect("frame must decode with the dictionary handed explicitly");
assert_eq!(dec, payload);
}
#[test]
fn compressible_stream_output_capacity_stays_at_output_scale() {
let line = b"ts=2026-03-26T21:39:28Z level=INFO msg=\"flush memtable\" tenant=demo\n";
let mut input = Vec::with_capacity(4 << 20);
while input.len() < (4 << 20) {
let take = line.len().min((4 << 20) - input.len());
input.extend_from_slice(&line[..take]);
}
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
let mut out = Vec::new();
compressor.compress_independent_frame_into(&input, &mut out);
assert!(!out.is_empty());
assert!(
out.capacity() < input.len() / 4,
"capacity {} must stay at output scale (input {}, output {})",
out.capacity(),
input.len(),
out.len()
);
let mut decoder = crate::decoding::FrameDecoder::new();
let mut decoded = Vec::with_capacity(input.len() + 64);
decoder
.decode_all_to_vec(&out, &mut decoded)
.expect("frame must decode");
assert_eq!(decoded, input);
}
#[test]
fn dict_frame_with_known_size_is_single_segment() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let payload = b"dictionary-keyed payload dictionary-keyed payload".repeat(64);
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor
.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
let mut frame = Vec::new();
compressor.compress_independent_frame_into(&payload, &mut frame);
let parsed = crate::decoding::frame::read_frame_header(frame.as_slice())
.expect("frame header must parse")
.0;
assert!(
parsed.descriptor.single_segment_flag(),
"dict frame with known size <= window must be single-segment"
);
assert!(parsed.dictionary_id().is_some());
assert_eq!(parsed.frame_content_size(), payload.len() as u64);
let mut decoder = crate::decoding::FrameDecoder::new();
decoder
.add_dict_from_bytes(dict_raw)
.expect("decoder must accept the dictionary");
let mut decoded = Vec::with_capacity(payload.len() + 64);
decoder
.decode_all_to_vec(&frame, &mut decoded)
.expect("single-segment dict frame must decode");
assert_eq!(decoded, payload);
}
#[test]
fn clear_dictionary_then_nodict_frame_roundtrips() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let mut payload_b = Vec::new();
payload_b.extend_from_slice(&dict_raw[..dict_raw.len().min(2048)]);
payload_b.extend_from_slice(
b"no-dictionary tail no-dictionary tail"
.repeat(16)
.as_slice(),
);
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(16));
compressor
.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
let mut frame_a = Vec::new();
compressor.compress_independent_frame_into(
b"dictionary-keyed payload dictionary-keyed payload"
.repeat(8)
.as_slice(),
&mut frame_a,
);
compressor.clear_dictionary();
let mut frame_b = Vec::new();
compressor.compress_independent_frame_into(&payload_b, &mut frame_b);
let mut decoder = crate::decoding::FrameDecoder::new();
let mut decoded = Vec::with_capacity(payload_b.len() + 64);
decoder
.decode_all_to_vec(&frame_b, &mut decoded)
.expect("no-dict frame after clear_dictionary must decode");
assert_eq!(
decoded, payload_b,
"no-dict frame after clear_dictionary must round-trip exactly"
);
}
#[test]
fn heap_size_counts_active_and_spare_huffman_tables() {
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
let base = compressor.heap_size();
let active = crate::huff0::huff0_encoder::HuffmanTable::build_from_data(
b"abacabadabacabaeabacabadabacaba",
);
let active_bytes = active.heap_size();
assert!(active_bytes > 0, "built table must own heap buffers");
compressor.state.last_huff_table = Some(active);
assert_eq!(
compressor.heap_size(),
base + active_bytes,
"heap_size must include the active last_huff_table"
);
let spare = crate::huff0::huff0_encoder::HuffmanTable::build_from_data(
b"the quick brown fox jumps over the lazy dog",
);
let spare_bytes = spare.heap_size();
assert!(spare_bytes > 0, "built table must own heap buffers");
compressor.state.huff_table_spare = Some(spare);
assert_eq!(
compressor.heap_size(),
base + active_bytes + spare_bytes,
"heap_size must include the parked huff_table_spare"
);
}
#[test]
fn set_encoder_dictionary_reattaches_prepared_dict_without_reparse() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let payload = b"tenant=demo table=orders op=put key=1 value=aaaaabbbbbcccccdddddeeeee\n\
tenant=demo table=orders op=put key=2 value=aaaaabbbbbcccccdddddeeeee\n";
let prepared = super::EncoderDictionary::from_bytes(dict_raw).expect("dict bytes should parse");
let dict_id = prepared.id();
let mut with_dict = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
let previous = compressor
.set_encoder_dictionary(prepared)
.expect("prepared dictionary should attach");
assert!(previous.is_none());
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut with_dict);
compressor.compress();
let returned = compressor
.clear_dictionary()
.expect("dictionary was attached");
assert_eq!(returned.id(), dict_id);
let (frame_header, _) = crate::decoding::frame::read_frame_header(with_dict.as_slice())
.expect("encoded stream should have a frame header");
assert_eq!(frame_header.dictionary_id(), Some(dict_id));
let decoder_dict = crate::decoding::Dictionary::decode_dict(dict_raw).unwrap();
let mut decoder = FrameDecoder::new();
decoder.add_dict(decoder_dict).unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(&with_dict, &mut decoded).unwrap();
assert_eq!(decoded.as_slice(), payload.as_slice());
let mut with_dict2 = Vec::new();
let mut compressor2 = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor2
.set_encoder_dictionary(returned)
.expect("returned dictionary should reattach");
compressor2.set_source(payload.as_slice());
compressor2.set_drain(&mut with_dict2);
compressor2.compress();
assert_eq!(
with_dict2, with_dict,
"reattached prepared dict must produce an identical frame"
);
}
#[test]
fn dict_primed_matcher_snapshot_reused_across_frames_is_byte_identical() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let mut payload = Vec::new();
while payload.len() < 16 * 1024 {
payload.extend_from_slice(
b"tenant=demo table=orders op=put key=1 value=aaaaabbbbbcccccdddddeeeee\n",
);
}
let prepared = super::EncoderDictionary::from_bytes(dict_raw).expect("dict bytes should parse");
let dict_id = prepared.id();
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor
.set_encoder_dictionary(prepared)
.expect("prepared dictionary should attach");
let frame1 = compressor.compress_independent_frame(payload.as_slice());
let frame2 = compressor.compress_independent_frame(payload.as_slice());
assert_eq!(
frame1, frame2,
"restored prime snapshot must reproduce the freshly-primed frame byte-for-byte"
);
for frame in [&frame1, &frame2] {
let (hdr, _) =
crate::decoding::frame::read_frame_header(frame.as_slice()).expect("frame header");
assert_eq!(hdr.dictionary_id(), Some(dict_id));
let mut decoder = FrameDecoder::new();
decoder
.add_dict(crate::decoding::Dictionary::decode_dict(dict_raw).unwrap())
.unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(frame, &mut decoded).unwrap();
assert_eq!(decoded.as_slice(), payload.as_slice());
}
}
#[test]
fn dict_primed_matcher_cache_reused_across_small_attach_frames_is_byte_identical() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let mut payload = Vec::new();
while payload.len() < 2 * 1024 {
payload.extend_from_slice(b"tenant=demo op=put key=1 value=aaaaabbbbbcccccddddd\n");
}
let prepared = super::EncoderDictionary::from_bytes(dict_raw).expect("dict bytes should parse");
let dict_id = prepared.id();
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor
.set_encoder_dictionary(prepared)
.expect("prepared dictionary should attach");
let frame1 = compressor.compress_independent_frame(payload.as_slice());
let frame2 = compressor.compress_independent_frame(payload.as_slice());
assert_eq!(
frame1, frame2,
"reused dict table (attach path) must reproduce the freshly-built frame byte-for-byte"
);
let fresh_prepared =
super::EncoderDictionary::from_bytes(dict_raw).expect("dict bytes should parse");
let mut fresh: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
fresh
.set_encoder_dictionary(fresh_prepared)
.expect("prepared dictionary should attach");
let fresh_frame = fresh.compress_independent_frame(payload.as_slice());
assert_eq!(
fresh_frame, frame1,
"cold-cache compressor must match the warm-cache frame byte-for-byte"
);
for frame in [&frame1, &frame2] {
let (hdr, _) =
crate::decoding::frame::read_frame_header(frame.as_slice()).expect("frame header");
assert_eq!(hdr.dictionary_id(), Some(dict_id));
let mut decoder = FrameDecoder::new();
decoder
.add_dict(crate::decoding::Dictionary::decode_dict(dict_raw).unwrap())
.unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(frame, &mut decoded).unwrap();
assert_eq!(decoded.as_slice(), payload.as_slice());
}
}
#[test]
fn dict_reused_across_many_lazy_frames_stays_applied() {
let lines: &[&[u8]] = &[
b"ts=2026 level=INFO msg=\"flush memtable\" tenant=demo table=orders\n",
b"ts=2026 level=INFO msg=\"rotate segment\" tenant=demo table=orders\n",
b"ts=2026 level=INFO msg=\"compact level\" tenant=demo table=orders\n",
b"ts=2026 level=INFO msg=\"write block\" tenant=demo table=orders\n",
];
let fill = |n: usize| -> Vec<u8> {
let mut b = Vec::with_capacity(n);
while b.len() < n {
for l in lines {
if b.len() >= n {
break;
}
let take = (n - b.len()).min(l.len());
b.extend_from_slice(&l[..take]);
}
}
b
};
let dict = fill(8 * 1024);
let payload = fill(16 * 1024);
let dict_obj =
crate::decoding::Dictionary::from_raw_content(1, dict).expect("raw dict should build");
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(6));
compressor.set_dictionary_id_flag(false);
compressor
.set_dictionary(dict_obj)
.expect("dict should attach");
let first = compressor.compress_independent_frame(payload.as_slice());
let mut nodict: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(6));
let no_dict_frame = nodict.compress_independent_frame(payload.as_slice());
assert!(
first.len() < no_dict_frame.len(),
"dict must be load-bearing: dict frame {} should beat the no-dict baseline {}",
first.len(),
no_dict_frame.len(),
);
for i in 1..16 {
let frame = compressor.compress_independent_frame(payload.as_slice());
assert_eq!(
frame, first,
"frame {i} of a reused dict compressor must stay byte-identical to \
the first (dict still applied, no decay or bookkeeping drift)"
);
}
}
#[test]
fn dict_fast_epoch_reset_many_frames_and_attach_copy_alternation_byte_identical() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let mut small = Vec::new();
while small.len() < 2 * 1024 {
small.extend_from_slice(b"tenant=demo op=put key=1 value=aaaaabbbbbcccccddddd\n");
}
let mut large = Vec::new();
while large.len() < 64 * 1024 {
large.extend_from_slice(b"tenant=demo op=scan range=[k0,k9) limit=500 order=asc\n");
}
let mut reused: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
reused
.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict bytes should parse"),
)
.expect("prepared dictionary should attach");
let reference = |payload: &[u8]| -> alloc::vec::Vec<u8> {
let mut fresh: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
fresh
.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict bytes should parse"),
)
.expect("prepared dictionary should attach");
fresh.compress_independent_frame(payload)
};
let small_expected = reference(&small);
let large_expected = reference(&large);
for i in 0..32 {
let frame = reused.compress_independent_frame(small.as_slice());
assert_eq!(
frame, small_expected,
"attach frame {i} diverged from the fresh-compressor reference"
);
}
for i in 0..4 {
let frame = reused.compress_independent_frame(large.as_slice());
assert_eq!(
frame, large_expected,
"copy frame {i} diverged from the fresh-compressor reference"
);
let frame = reused.compress_independent_frame(small.as_slice());
assert_eq!(
frame, small_expected,
"attach frame after copy {i} diverged from the fresh-compressor reference"
);
}
}
#[test]
fn dict_primed_btlazy2_reused_across_attach_and_copy_boundary_is_byte_identical() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let dict_id = super::EncoderDictionary::from_bytes(dict_raw)
.expect("dict bytes should parse")
.id();
let make_payload = |target: usize| {
let mut p = Vec::with_capacity(target);
let mut i = 0u64;
while p.len() < target {
p.extend_from_slice(
format!(
"tenant=demo op=put key={i} value=aaaaabbbbbcccccddddd-{}\n",
i % 97
)
.as_bytes(),
);
i += 1;
}
p
};
for target in [16 * 1024usize, 64 * 1024usize] {
let payload = make_payload(target);
let mut warm: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(15));
warm.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict parse"),
)
.expect("dict attach");
let frame1 = warm.compress_independent_frame(payload.as_slice());
let frame2 = warm.compress_independent_frame(payload.as_slice());
assert_eq!(
frame1, frame2,
"reused dict cache must reproduce the freshly-primed frame byte-for-byte \
(Level 15, target={target})"
);
let mut cold: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(15));
cold.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict parse"),
)
.expect("dict attach");
let cold_frame = cold.compress_independent_frame(payload.as_slice());
assert_eq!(
cold_frame, frame1,
"cold-cache compressor must match warm-cache frame (Level 15, target={target})"
);
for frame in [&frame1, &frame2] {
let (hdr, _) =
crate::decoding::frame::read_frame_header(frame.as_slice()).expect("frame header");
assert_eq!(hdr.dictionary_id(), Some(dict_id));
let mut decoder = FrameDecoder::new();
decoder
.add_dict(crate::decoding::Dictionary::decode_dict(dict_raw).unwrap())
.unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(frame, &mut decoded).unwrap();
assert_eq!(decoded.as_slice(), payload.as_slice());
}
}
}
#[test]
fn dict_primed_btultra2_restore_is_floor_safe_and_byte_identical() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let dict_id = super::EncoderDictionary::from_bytes(dict_raw)
.expect("dict bytes should parse")
.id();
let make_payload = |seed: u64, target: usize| {
let mut p = Vec::with_capacity(target);
let mut i = seed;
while p.len() < target {
p.extend_from_slice(
format!(
"tenant=demo op=put key={i} value=aaaaabbbbbcccccddddd-{}\n",
i % 89
)
.as_bytes(),
);
i = i.wrapping_add(1);
}
p.truncate(target);
p
};
let size = 48 * 1024usize;
let frame_a = make_payload(0, size);
let frame_b = make_payload(1_000_000, size);
let mut warm: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(22));
warm.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict parse"),
)
.expect("dict attach");
let _wa = warm.compress_independent_frame(frame_a.as_slice());
let warm_b = warm.compress_independent_frame(frame_b.as_slice());
let mut cold: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(22));
cold.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict parse"),
)
.expect("dict attach");
let cold_b = cold.compress_independent_frame(frame_b.as_slice());
assert_eq!(
warm_b, cold_b,
"frame B via snapshot restore must be byte-identical to a cold compress \
(a restore that leaks frame-A live-table entries would diverge here)"
);
let (hdr, _) =
crate::decoding::frame::read_frame_header(warm_b.as_slice()).expect("frame header");
assert_eq!(hdr.dictionary_id(), Some(dict_id));
let mut decoder = FrameDecoder::new();
decoder
.add_dict(crate::decoding::Dictionary::decode_dict(dict_raw).unwrap())
.unwrap();
let mut decoded = Vec::with_capacity(frame_b.len());
decoder
.decode_all_to_vec(warm_b.as_slice(), &mut decoded)
.unwrap();
assert_eq!(decoded.as_slice(), frame_b.as_slice());
}
#[test]
fn dict_primed_btultra2_ldm_restore_is_byte_identical() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let dict_id = super::EncoderDictionary::from_bytes(dict_raw)
.expect("dict bytes should parse")
.id();
let make_payload = |seed: u64, target: usize| {
let mut p = Vec::with_capacity(target);
let mut i = seed;
while p.len() < target {
p.extend_from_slice(
format!(
"tenant=demo op=put key={i} value=aaaaabbbbbcccccddddd-{}\n",
i % 89
)
.as_bytes(),
);
i = i.wrapping_add(1);
}
p.truncate(target);
p
};
let ldm_params =
crate::encoding::CompressionParameters::builder(super::CompressionLevel::Level(22))
.enable_long_distance_matching(true)
.build()
.expect("LDM-only params build");
let size = 48 * 1024usize;
let frame_a = make_payload(0, size);
let frame_b = make_payload(1_000_000, size);
let mut warm: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(22));
warm.set_parameters(&ldm_params);
warm.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict parse"),
)
.expect("dict attach");
let _wa = warm.compress_independent_frame(frame_a.as_slice());
let warm_b = warm.compress_independent_frame(frame_b.as_slice());
let mut cold: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Level(22));
cold.set_parameters(&ldm_params);
cold.set_encoder_dictionary(
super::EncoderDictionary::from_bytes(dict_raw).expect("dict parse"),
)
.expect("dict attach");
let cold_b = cold.compress_independent_frame(frame_b.as_slice());
assert_eq!(
warm_b, cold_b,
"LDM-on frame B via snapshot restore must be byte-identical to a cold compress"
);
let (hdr, _) =
crate::decoding::frame::read_frame_header(warm_b.as_slice()).expect("frame header");
assert_eq!(hdr.dictionary_id(), Some(dict_id));
let mut decoder = FrameDecoder::new();
decoder
.add_dict(crate::decoding::Dictionary::decode_dict(dict_raw).unwrap())
.unwrap();
let mut decoded = Vec::with_capacity(frame_b.len());
decoder
.decode_all_to_vec(warm_b.as_slice(), &mut decoded)
.unwrap();
assert_eq!(decoded.as_slice(), frame_b.as_slice());
}
#[test]
fn set_dictionary_from_bytes_matches_full_decode_byte_for_byte() {
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let payload = b"tenant=demo table=orders op=put key=1 value=aaaaabbbbbcccccdddddeeeee\n\
tenant=demo table=orders op=put key=2 value=aaaaabbbbbcccccdddddeeeee\n";
let mut from_bytes_out = Vec::new();
{
let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor
.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut from_bytes_out);
compressor.compress();
}
let full_decode = crate::decoding::Dictionary::decode_dict(dict_raw)
.expect("dictionary bytes should fully decode");
let mut full_decode_out = Vec::new();
{
let mut compressor = FrameCompressor::new(super::CompressionLevel::Fastest);
compressor
.set_dictionary(full_decode)
.expect("full-decode dictionary should attach");
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut full_decode_out);
compressor.compress();
}
assert_eq!(
from_bytes_out, full_decode_out,
"encoder-only dict parse must produce byte-identical output to the full decode"
);
}
#[test]
fn set_dictionary_rejects_zero_dictionary_id() {
let invalid = crate::decoding::Dictionary {
id: 0,
fse: crate::decoding::scratch::FSEScratch::new(),
huf: crate::decoding::scratch::HuffmanScratch::new(),
dict_content: vec![1, 2, 3],
offset_hist: [1, 4, 8],
};
let mut compressor: FrameCompressor<
&[u8],
Vec<u8>,
crate::encoding::match_generator::MatchGeneratorDriver,
> = FrameCompressor::new(super::CompressionLevel::Fastest);
let result = compressor.set_dictionary(invalid);
assert!(matches!(
result,
Err(crate::decoding::errors::DictionaryDecodeError::ZeroDictionaryId)
));
}
#[test]
fn set_dictionary_rejects_zero_repeat_offsets() {
let invalid = crate::decoding::Dictionary {
id: 1,
fse: crate::decoding::scratch::FSEScratch::new(),
huf: crate::decoding::scratch::HuffmanScratch::new(),
dict_content: vec![1, 2, 3],
offset_hist: [0, 4, 8],
};
let mut compressor: FrameCompressor<
&[u8],
Vec<u8>,
crate::encoding::match_generator::MatchGeneratorDriver,
> = FrameCompressor::new(super::CompressionLevel::Fastest);
let result = compressor.set_dictionary(invalid);
assert!(matches!(
result,
Err(
crate::decoding::errors::DictionaryDecodeError::ZeroRepeatOffsetInDictionary {
index: 0
}
)
));
}
#[test]
fn uncompressed_mode_does_not_require_dictionary() {
let dict_id = 0xABCD_0001;
let dict = crate::decoding::Dictionary::from_raw_content(dict_id, b"shared-history".to_vec())
.expect("raw dictionary should be valid");
let payload = b"plain-bytes-that-should-stay-raw";
let mut output = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
compressor
.set_dictionary(dict)
.expect("dictionary should attach in uncompressed mode");
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
let (frame_header, _) = crate::decoding::frame::read_frame_header(output.as_slice())
.expect("encoded frame should have a header");
assert_eq!(
frame_header.dictionary_id(),
None,
"raw/uncompressed frames must not advertise dictionary dependency"
);
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
assert_eq!(decoded, payload);
}
#[test]
fn default_level_tiny_raw_dict_compresses_cleanly() {
let dict_id = 0xABCD_0009;
let dict = crate::decoding::Dictionary::from_raw_content(dict_id, b"abc".to_vec())
.expect("raw dictionary should be valid");
let payload = b"the quick brown fox jumps over the lazy dog, repeatedly and at length";
let mut output = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Default);
compressor
.set_dictionary(dict)
.expect("tiny raw dictionary should attach");
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
assert!(!output.is_empty(), "compression should produce a frame");
let (frame_header, _) = crate::decoding::frame::read_frame_header(output.as_slice())
.expect("encoded frame should have a readable header");
assert_eq!(
frame_header.dictionary_id(),
Some(dict_id),
"tiny raw dict frame should still advertise its dictionary id",
);
let decode_dict = crate::decoding::Dictionary::from_raw_content(dict_id, b"abc".to_vec())
.expect("raw dictionary should be valid");
let mut decoder = FrameDecoder::new();
decoder
.add_dict(decode_dict)
.expect("decoder dict should attach");
let mut decoded = Vec::with_capacity(payload.len());
decoder
.decode_all_to_vec(&output, &mut decoded)
.expect("dict roundtrip should decode");
assert_eq!(decoded, payload, "tiny-dict roundtrip mismatch");
}
#[test]
fn dict_attach_roundtrips_across_backends_with_matching_payload() {
let dict_id = 0xD1C7_0001;
let line = |i: u32| {
alloc::format!(
"ts=2026-03-26T21:{:02}:{:02}Z level=INFO msg=\"event {i:05}\" tenant=t{i} region=eu\n",
i / 60 % 60,
i % 60,
)
.into_bytes()
};
let mut dict_content = Vec::new();
for i in 0..256u32 {
dict_content.extend_from_slice(&line(i));
}
let mut payload = Vec::new();
let mut i = 0u32;
for _ in 0..256u32 {
payload.extend_from_slice(&line(i));
i = (i + 97) % 256; }
let compress_at = |level, dict: Option<Vec<u8>>| -> Vec<u8> {
let mut compressor = FrameCompressor::new(level);
if let Some(bytes) = dict {
let d = crate::decoding::Dictionary::from_raw_content(dict_id, bytes)
.expect("raw dictionary should be valid");
compressor
.set_dictionary(d)
.expect("dictionary should attach");
}
let mut out = Vec::new();
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut out);
compressor.compress();
out
};
for level in [
super::CompressionLevel::Level(-5), super::CompressionLevel::Level(1), super::CompressionLevel::Default, super::CompressionLevel::Level(8), ] {
let out = compress_at(level, Some(dict_content.clone()));
let no_dict = compress_at(level, None);
assert!(
out.len() < no_dict.len(),
"level {level:?}: dict-primed output ({}) must beat no-dict ({}) — dict probe did not fire",
out.len(),
no_dict.len(),
);
let ddict = crate::decoding::Dictionary::from_raw_content(dict_id, dict_content.clone())
.expect("raw dictionary should be valid");
let mut decoder = FrameDecoder::new();
decoder.add_dict(ddict).expect("decoder dict should attach");
let mut decoded = Vec::with_capacity(payload.len());
decoder
.decode_all_to_vec(&out, &mut decoded)
.unwrap_or_else(|e| panic!("level {level:?}: dict roundtrip decode failed: {e:?}"));
assert_eq!(decoded, payload, "level {level:?}: dict roundtrip mismatch");
}
}
#[test]
fn dict_swap_across_reused_compressor_roundtrips() {
let lines = |tag: &str| -> (Vec<u8>, Vec<u8>) {
let line = |i: u32| alloc::format!("{tag} record {i:05} field=value{i} end\n").into_bytes();
let mut dict = Vec::new();
for i in 0..256u32 {
dict.extend_from_slice(&line(i));
}
let mut payload = Vec::new();
let mut i = 0u32;
for _ in 0..256u32 {
payload.extend_from_slice(&line(i));
i = (i + 97) % 256;
}
(dict, payload)
};
let (dict_a, payload_a) = lines("alpha");
let (dict_b, payload_b) = lines("bravo");
for level in [
super::CompressionLevel::Default,
super::CompressionLevel::Level(8),
] {
let no_dict = |payload: &[u8]| -> usize {
let mut c: FrameCompressor = FrameCompressor::new(level);
c.compress_independent_frame(payload).len()
};
let no_dict_a = no_dict(&payload_a);
let no_dict_b = no_dict(&payload_b);
let mut compressor: FrameCompressor = FrameCompressor::new(level);
for (dict_bytes, payload, no_dict_len) in [
(&dict_a, &payload_a, no_dict_a),
(&dict_b, &payload_b, no_dict_b),
] {
let dict =
crate::decoding::Dictionary::from_raw_content(0xD1C7_0002, dict_bytes.clone())
.expect("raw dictionary should be valid");
compressor
.set_dictionary(dict)
.expect("dictionary should attach");
let out = compressor.compress_independent_frame(payload.as_slice());
assert!(
out.len() < no_dict_len,
"level {level:?}: dict frame ({}) must beat no-dict ({}) — dict probe did not fire",
out.len(),
no_dict_len,
);
let ddict =
crate::decoding::Dictionary::from_raw_content(0xD1C7_0002, dict_bytes.clone())
.expect("raw dictionary should be valid");
let mut decoder = FrameDecoder::new();
decoder.add_dict(ddict).expect("decoder dict should attach");
let mut decoded = Vec::with_capacity(payload.len());
decoder
.decode_all_to_vec(&out, &mut decoded)
.unwrap_or_else(|e| panic!("level {level:?}: dict-swap decode failed: {e:?}"));
assert_eq!(
decoded, *payload,
"level {level:?}: dict-swap roundtrip mismatch (stale dict rows?)"
);
}
}
}
#[test]
fn dictionary_roundtrip_stays_valid_after_output_exceeds_window() {
use crate::encoding::match_generator::MatchGeneratorDriver;
let dict_id = 0xABCD_0002;
let dict = crate::decoding::Dictionary::from_raw_content(dict_id, b"abcdefgh".to_vec())
.expect("raw dictionary should be valid");
let dict_for_decoder =
crate::decoding::Dictionary::from_raw_content(dict_id, b"abcdefgh".to_vec())
.expect("raw dictionary should be valid");
let payload = b"abcdefgh".repeat(512 * 1024 / 8 + 64);
let matcher = MatchGeneratorDriver::new(1024, 1);
let mut no_dict_output = Vec::new();
let mut no_dict_compressor =
FrameCompressor::new_with_matcher(matcher, super::CompressionLevel::Fastest);
no_dict_compressor.set_source(payload.as_slice());
no_dict_compressor.set_drain(&mut no_dict_output);
no_dict_compressor.compress();
let (no_dict_frame_header, _) =
crate::decoding::frame::read_frame_header(no_dict_output.as_slice())
.expect("baseline frame should have a header");
let no_dict_window = no_dict_frame_header
.window_size()
.expect("window size should be present");
let mut output = Vec::new();
let matcher = MatchGeneratorDriver::new(1024, 1);
let mut compressor =
FrameCompressor::new_with_matcher(matcher, super::CompressionLevel::Fastest);
compressor
.set_dictionary(dict)
.expect("dictionary should attach");
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
let (frame_header, _) = crate::decoding::frame::read_frame_header(output.as_slice())
.expect("encoded frame should have a header");
let advertised_window = frame_header
.window_size()
.expect("window size should be present");
assert_eq!(
advertised_window, no_dict_window,
"dictionary priming must not inflate advertised window size"
);
assert!(
payload.len() > advertised_window as usize,
"test must cross the advertised window boundary"
);
let mut decoder = FrameDecoder::new();
decoder.add_dict(dict_for_decoder).unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
assert_eq!(decoded, payload);
}
#[test]
fn source_size_hint_with_dictionary_keeps_roundtrip_and_nonincreasing_window() {
let dict_id = 0xABCD_0004;
let dict_content = b"abcd".repeat(1024); let dict = crate::decoding::Dictionary::from_raw_content(dict_id, dict_content).unwrap();
let dict_for_decoder =
crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024)).unwrap();
let payload = b"abcdabcdabcdabcd".repeat(128);
let mut hinted_output = Vec::new();
let mut hinted = FrameCompressor::new(super::CompressionLevel::Fastest);
hinted.set_dictionary(dict).unwrap();
hinted.set_source_size_hint(1);
hinted.set_source(payload.as_slice());
hinted.set_drain(&mut hinted_output);
hinted.compress();
let mut no_hint_output = Vec::new();
let mut no_hint = FrameCompressor::new(super::CompressionLevel::Fastest);
no_hint
.set_dictionary(
crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024)).unwrap(),
)
.unwrap();
no_hint.set_source(payload.as_slice());
no_hint.set_drain(&mut no_hint_output);
no_hint.compress();
let hinted_window = crate::decoding::frame::read_frame_header(hinted_output.as_slice())
.expect("encoded frame should have a header")
.0
.window_size()
.expect("window size should be present");
let no_hint_window = crate::decoding::frame::read_frame_header(no_hint_output.as_slice())
.expect("encoded frame should have a header")
.0
.window_size()
.expect("window size should be present");
assert!(
hinted_window <= no_hint_window,
"source-size hint should not increase advertised window with dictionary priming",
);
let mut decoder = FrameDecoder::new();
decoder.add_dict(dict_for_decoder).unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder
.decode_all_to_vec(&hinted_output, &mut decoded)
.unwrap();
assert_eq!(decoded, payload);
}
#[test]
fn dictionary_segment_in_incompressible_input_is_matched() {
fn lcg(seed: u64, n: usize) -> alloc::vec::Vec<u8> {
let mut s = seed;
(0..n)
.map(|_| {
s = s
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(s >> 56) as u8
})
.collect()
}
let dict_id = 0x00DC_7777;
let r = lcg(1, 512); let mut payload = lcg(2, 2000); payload.extend_from_slice(&r); payload.extend_from_slice(&lcg(3, 1500));
assert!(
crate::encoding::incompressible::block_looks_incompressible(&payload),
"test payload must look incompressible to exercise the raw-fast-path",
);
let compress = |level: super::CompressionLevel, dict: Option<&[u8]>| -> alloc::vec::Vec<u8> {
let mut out = alloc::vec::Vec::new();
let mut c = FrameCompressor::new(level);
if let Some(d) = dict {
c.set_dictionary(
crate::decoding::Dictionary::from_raw_content(dict_id, d.to_vec()).unwrap(),
)
.unwrap();
}
c.set_source(payload.as_slice());
c.set_drain(&mut out);
c.compress();
out
};
for lvl in [
super::CompressionLevel::Level(2),
super::CompressionLevel::Level(6),
super::CompressionLevel::Level(19),
] {
let with_dict = compress(lvl, Some(&r));
let no_dict = compress(lvl, None);
assert!(
with_dict.len() + 300 < no_dict.len(),
"{lvl:?}: dict segment not matched (with_dict={}, no_dict={})",
with_dict.len(),
no_dict.len(),
);
let mut decoder = FrameDecoder::new();
decoder
.add_dict(crate::decoding::Dictionary::from_raw_content(dict_id, r.clone()).unwrap())
.unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(&with_dict, &mut decoded).unwrap();
assert_eq!(decoded, payload, "{lvl:?}: dict round-trip mismatch");
let unrelated = lcg(99, 512);
let with_bad_dict = compress(lvl, Some(&unrelated));
assert!(
with_bad_dict.len() <= no_dict.len() + 16,
"{lvl:?}: unhelpful dict expanded output (with={}, no_dict={})",
with_bad_dict.len(),
no_dict.len(),
);
}
}
#[test]
fn source_size_hint_with_dictionary_keeps_roundtrip_for_larger_payload() {
let dict_id = 0xABCD_0005;
let dict_content = b"abcd".repeat(1024); let dict = crate::decoding::Dictionary::from_raw_content(dict_id, dict_content).unwrap();
let dict_for_decoder =
crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024)).unwrap();
let payload = b"abcd".repeat(1024); let payload_len = payload.len() as u64;
let mut hinted_output = Vec::new();
let mut hinted = FrameCompressor::new(super::CompressionLevel::Fastest);
hinted.set_dictionary(dict).unwrap();
hinted.set_source_size_hint(payload_len);
hinted.set_source(payload.as_slice());
hinted.set_drain(&mut hinted_output);
hinted.compress();
let mut no_hint_output = Vec::new();
let mut no_hint = FrameCompressor::new(super::CompressionLevel::Fastest);
no_hint
.set_dictionary(
crate::decoding::Dictionary::from_raw_content(dict_id, b"abcd".repeat(1024)).unwrap(),
)
.unwrap();
no_hint.set_source(payload.as_slice());
no_hint.set_drain(&mut no_hint_output);
no_hint.compress();
let hinted_window = crate::decoding::frame::read_frame_header(hinted_output.as_slice())
.expect("encoded frame should have a header")
.0
.window_size()
.expect("window size should be present");
let no_hint_window = crate::decoding::frame::read_frame_header(no_hint_output.as_slice())
.expect("encoded frame should have a header")
.0
.window_size()
.expect("window size should be present");
assert!(
hinted_window <= no_hint_window,
"source-size hint should not increase advertised window with dictionary priming",
);
let mut decoder = FrameDecoder::new();
decoder.add_dict(dict_for_decoder).unwrap();
let mut decoded = Vec::with_capacity(payload.len());
decoder
.decode_all_to_vec(&hinted_output, &mut decoded)
.unwrap();
assert_eq!(decoded, payload);
}
#[test]
fn custom_matcher_without_dictionary_priming_does_not_advertise_dict_id() {
let dict_id = 0xABCD_0003;
let dict = crate::decoding::Dictionary::from_raw_content(dict_id, b"abcdefgh".to_vec())
.expect("raw dictionary should be valid");
let payload = b"abcdefghabcdefgh";
let mut output = Vec::new();
let matcher = NoDictionaryMatcher::new(64);
let mut compressor =
FrameCompressor::new_with_matcher(matcher, super::CompressionLevel::Fastest);
compressor
.set_dictionary(dict)
.expect("dictionary should attach");
compressor.set_source(payload.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
let (frame_header, _) = crate::decoding::frame::read_frame_header(output.as_slice())
.expect("encoded frame should have a header");
assert_eq!(
frame_header.dictionary_id(),
None,
"matchers that do not support dictionary priming must not advertise dictionary dependency"
);
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(payload.len());
decoder.decode_all_to_vec(&output, &mut decoded).unwrap();
assert_eq!(decoded, payload);
}
#[cfg(feature = "hash")]
#[test]
fn checksum_two_frames_reused_compressor() {
let data: Vec<u8> = (0u8..=255).cycle().take(1024).collect();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Uncompressed);
let mut compressed1 = Vec::new();
compressor.set_source(data.as_slice());
compressor.set_drain(&mut compressed1);
compressor.compress();
let mut compressed2 = Vec::new();
compressor.set_source(data.as_slice());
compressor.set_drain(&mut compressed2);
compressor.compress();
fn decode_and_collect(compressed: &[u8]) -> (Vec<u8>, Option<u32>, Option<u32>) {
let mut decoder = FrameDecoder::new();
let mut source = compressed;
decoder.reset(&mut source).unwrap();
while !decoder.is_finished() {
decoder
.decode_blocks(&mut source, crate::decoding::BlockDecodingStrategy::All)
.unwrap();
}
let mut decoded = Vec::new();
decoder.collect_to_writer(&mut decoded).unwrap();
(
decoded,
decoder.get_checksum_from_data(),
decoder.get_calculated_checksum(),
)
}
let (decoded1, chksum_from_data1, chksum_calculated1) = decode_and_collect(&compressed1);
assert_eq!(decoded1, data, "frame 1: decoded data mismatch");
assert_eq!(
chksum_from_data1, chksum_calculated1,
"frame 1: checksum mismatch"
);
let (decoded2, chksum_from_data2, chksum_calculated2) = decode_and_collect(&compressed2);
assert_eq!(decoded2, data, "frame 2: decoded data mismatch");
assert_eq!(
chksum_from_data2, chksum_calculated2,
"frame 2: checksum mismatch"
);
assert_eq!(
chksum_from_data1, chksum_from_data2,
"frame 1 and frame 2 should have the same checksum (same data, hash must reset per frame)"
);
}
#[cfg(feature = "lsm")]
#[test]
fn frame_emit_info_decompressed_ranges_match_decoded_output() {
let data = emit_info_fixture_data();
for level in [
super::CompressionLevel::Default,
super::CompressionLevel::Level(22),
] {
let mut compressed = Vec::new();
let mut compressor = FrameCompressor::new(level);
compressor.set_source_size_hint(data.len() as u64);
compressor.set_source(data.as_slice());
compressor.set_drain(&mut compressed);
compressor.compress();
let info = compressor
.last_frame_emit_info()
.expect("emit info populated after compress")
.clone();
let mut decoder = FrameDecoder::new();
let mut source = compressed.as_slice();
decoder.reset(&mut source).unwrap();
while !decoder.is_finished() {
decoder
.decode_blocks(&mut source, crate::decoding::BlockDecodingStrategy::All)
.unwrap();
}
let mut decoded = Vec::new();
decoder.collect_to_writer(&mut decoded).unwrap();
assert_eq!(decoded, data, "sanity: frame must round-trip ({level:?})");
assert!(
info.blocks.len() >= 2,
"fixture must span multiple blocks to exercise the mapping ({level:?}, got {})",
info.blocks.len()
);
assert!(
info.blocks.last().unwrap().last_block,
"final block must carry last_block ({level:?})"
);
if matches!(level, super::CompressionLevel::Level(22)) {
let max_block = crate::common::MAX_BLOCK_SIZE as usize;
let n_chunks = data.len().div_ceil(max_block);
assert!(
info.blocks.len() > n_chunks,
"Level(22) must exercise post-split: {} blocks for {} input chunks",
info.blocks.len(),
n_chunks
);
}
let mut expected_start = 0u64;
for i in 0..info.blocks.len() {
let range = info
.decompressed_byte_range(i)
.expect("in-bounds block has a range");
assert_eq!(
range.start, expected_start,
"block {i} range must start where the previous ended ({level:?})"
);
assert_eq!(
u64::from(info.blocks[i].decompressed_size),
range.end - range.start,
"block {i} decompressed_size must equal its range width ({level:?})"
);
let mut psrc = compressed.as_slice();
let mut pdec = FrameDecoder::new();
pdec.reset(&mut psrc).unwrap();
let pd = pdec
.decode_blocks_partial(&mut psrc, i as u32, i as u32 + 1, None, false)
.unwrap();
assert!(
pd.stopped_at.is_none(),
"block {i} must decode cleanly ({level:?})"
);
assert_eq!(
pd.data.as_slice(),
&decoded[range.start as usize..range.end as usize],
"block {i} partial-decode bytes must equal the full-decode slice ({level:?})"
);
expected_start = range.end;
}
assert_eq!(
expected_start,
decoded.len() as u64,
"block decompressed sizes must sum to the full decoded length ({level:?})"
);
assert_eq!(
info.decompressed_byte_range(info.blocks.len()),
None,
"out-of-range index yields None ({level:?})"
);
}
}
#[cfg(feature = "lsm")]
fn emit_info_fixture_data() -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(400 * 1024);
let mut x = 0x9E37_79B9u32;
while data.len() < 400 * 1024 {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
let run = 16 + (x as usize % 48);
let byte = (x >> 24) as u8;
for _ in 0..run {
data.push(byte);
}
data.extend_from_slice(b"the quick brown fox jumps over the lazy dog\n");
}
data
}
#[cfg(feature = "lsm")]
#[test]
fn frame_emit_info_decompressed_ranges_match_on_borrowed_oneshot_path() {
let data = emit_info_fixture_data();
let mut compressor: FrameCompressor = FrameCompressor::new(super::CompressionLevel::Fastest);
let compressed = compressor.compress_independent_frame(data.as_slice());
let info = compressor
.last_frame_emit_info()
.expect("emit info populated after compress_independent_frame")
.clone();
assert!(
info.blocks
.iter()
.any(|b| matches!(b.block_type, crate::blocks::block::BlockType::Compressed)),
"borrowed-path fixture must emit at least one compressed block"
);
assert!(
info.blocks.len() >= 2,
"borrowed fixture must span multiple blocks (got {})",
info.blocks.len()
);
assert!(info.blocks.last().unwrap().last_block);
let mut decoder = FrameDecoder::new();
let mut source = compressed.as_slice();
decoder.reset(&mut source).unwrap();
while !decoder.is_finished() {
decoder
.decode_blocks(&mut source, crate::decoding::BlockDecodingStrategy::All)
.unwrap();
}
let mut decoded = Vec::new();
decoder.collect_to_writer(&mut decoded).unwrap();
assert_eq!(decoded, data, "borrowed one-shot frame must round-trip");
let mut expected_start = 0u64;
for i in 0..info.blocks.len() {
let range = info.decompressed_byte_range(i).unwrap();
assert_eq!(range.start, expected_start, "block {i} range contiguity");
let mut psrc = compressed.as_slice();
let mut pdec = FrameDecoder::new();
pdec.reset(&mut psrc).unwrap();
let pd = pdec
.decode_blocks_partial(&mut psrc, i as u32, i as u32 + 1, None, false)
.unwrap();
assert!(pd.stopped_at.is_none(), "block {i} must decode cleanly");
assert_eq!(
pd.data.as_slice(),
&decoded[range.start as usize..range.end as usize],
"borrowed block {i} partial-decode bytes must equal the full-decode slice"
);
expected_start = range.end;
}
assert_eq!(
expected_start,
decoded.len() as u64,
"ranges sum to full length"
);
}
#[test]
fn split_block_from_borders_keeps_homogeneous_block() {
let block = vec![0xAAu8; MAX_BLOCK_SIZE as usize];
let split = super::split_block_from_borders(&block);
assert_eq!(split, MAX_BLOCK_SIZE as usize);
}
#[test]
fn split_block_from_borders_returns_midpoint_for_centred_transition() {
let mut block = vec![0u8; MAX_BLOCK_SIZE as usize];
for (i, byte) in block
.iter_mut()
.enumerate()
.skip(MAX_BLOCK_SIZE as usize / 2)
{
*byte = (i % 251 + 1) as u8;
}
let split = super::split_block_from_borders(&block);
assert_eq!(
split,
64 * 1024,
"centred-transition fixture must take the symmetric \
midpoint arm (`abs_diff < min_distance`), got {split}"
);
}
#[test]
fn pre_split_level_dispatches_by_compression_level() {
use crate::encoding::CompressionLevel;
use crate::encoding::levels::config::level_pre_split;
assert_eq!(level_pre_split(CompressionLevel::Uncompressed), None);
assert_eq!(level_pre_split(CompressionLevel::Fastest), Some(0));
assert_eq!(level_pre_split(CompressionLevel::Default), Some(0));
assert_eq!(
level_pre_split(CompressionLevel::Better),
level_pre_split(CompressionLevel::Level(7)),
);
assert_eq!(
level_pre_split(CompressionLevel::Best),
level_pre_split(CompressionLevel::Level(13)),
);
assert_eq!(level_pre_split(CompressionLevel::Level(2)), Some(0)); assert_eq!(level_pre_split(CompressionLevel::Level(4)), Some(0)); assert_eq!(level_pre_split(CompressionLevel::Level(5)), Some(0)); assert_eq!(level_pre_split(CompressionLevel::Level(7)), Some(0)); assert_eq!(level_pre_split(CompressionLevel::Level(8)), Some(1)); assert_eq!(level_pre_split(CompressionLevel::Level(11)), Some(1)); assert_eq!(level_pre_split(CompressionLevel::Level(12)), Some(1)); assert_eq!(level_pre_split(CompressionLevel::Level(13)), Some(1)); assert_eq!(level_pre_split(CompressionLevel::Level(15)), Some(1)); assert_eq!(level_pre_split(CompressionLevel::Level(16)), Some(2)); assert_eq!(level_pre_split(CompressionLevel::Level(22)), Some(2)); }
#[test]
fn periodic_stream_not_oversplit() {
use crate::encoding::{CompressionLevel, compress_slice_to_vec};
const LINES: &[&str] = &[
"ts=2026-03-26T21:39:28Z level=INFO msg=\"flush memtable\" tenant=demo table=orders region=eu-west\n",
"ts=2026-03-26T21:39:29Z level=INFO msg=\"rotate segment\" tenant=demo table=orders region=eu-west\n",
"ts=2026-03-26T21:39:30Z level=INFO msg=\"compact level\" tenant=demo table=orders region=eu-west\n",
"ts=2026-03-26T21:39:31Z level=INFO msg=\"write block\" tenant=demo table=orders region=eu-west\n",
];
let target = 512 * 1024usize;
let mut data = Vec::with_capacity(target);
let mut i = 0;
while data.len() < target {
let line = LINES[i % LINES.len()].as_bytes();
let take = line.len().min(target - data.len());
data.extend_from_slice(&line[..take]);
i += 1;
}
let l7 = compress_slice_to_vec(&data, CompressionLevel::Level(7)); let l8 = compress_slice_to_vec(&data, CompressionLevel::Level(8)); let l15 = compress_slice_to_vec(&data, CompressionLevel::Level(15)); assert!(
l8.len() < l7.len() * 2,
"lazy2 over-split periodic stream: l7={} l8={}",
l7.len(),
l8.len()
);
assert!(
l15.len() < l7.len() * 2,
"btlazy2 over-split periodic stream: l7={} l15={}",
l7.len(),
l15.len()
);
for out in [&l7, &l8, &l15] {
let mut decoder = FrameDecoder::new();
let mut round = Vec::with_capacity(data.len());
decoder
.decode_all_to_vec(out, &mut round)
.expect("decode periodic stream");
assert_eq!(round, data, "periodic stream roundtrip mismatch");
}
}
#[test]
fn greedy_chunk_split_roundtrips_through_own_decoder() {
use crate::encoding::CompressionLevel;
let mut data = vec![0u8; 256 * 1024];
for (i, byte) in data.iter_mut().enumerate() {
*byte = if i < 192 * 1024 {
(i & 0x07) as u8
} else {
(i % 251 + 1) as u8
};
}
let second_block = &data[128 * 1024..];
let split = super::optimal_block_size(
CompressionLevel::Level(5),
second_block,
second_block.len(),
MAX_BLOCK_SIZE as usize,
100,
);
assert!(
split < MAX_BLOCK_SIZE as usize,
"second upstream zstd block must chunk-split at its intra-block transition, got {split}",
);
let mut compressed = Vec::new();
let mut compressor = FrameCompressor::new(CompressionLevel::Level(5));
compressor.set_source(data.as_slice());
compressor.set_drain(&mut compressed);
compressor.compress();
let mut decoder = FrameDecoder::new();
let mut source = compressed.as_slice();
decoder
.reset(&mut source)
.expect("frame header should parse");
while !decoder.is_finished() {
decoder
.decode_blocks(&mut source, crate::decoding::BlockDecodingStrategy::All)
.expect("decode should succeed");
}
let mut decoded = Vec::with_capacity(data.len());
decoder.collect_to_writer(&mut decoded).unwrap();
assert_eq!(decoded, data, "roundtrip must reproduce the input verbatim");
}
#[test]
fn fast_oneshot_borrowed_split_emits_subblock() {
use crate::encoding::CompressionLevel;
let mut data = vec![0u8; 256 * 1024];
for (i, byte) in data.iter_mut().enumerate() {
if i >= 192 * 1024 {
*byte = (i % 251 + 1) as u8;
}
}
let second_block = &data[128 * 1024..];
assert!(
super::optimal_block_size(
CompressionLevel::Fastest,
second_block,
second_block.len(),
MAX_BLOCK_SIZE as usize,
100,
) < MAX_BLOCK_SIZE as usize,
"fixture must resolve to a sub-block split in the second upstream zstd block",
);
let mut compressor: FrameCompressor = FrameCompressor::new(CompressionLevel::Fastest);
let frame = compressor.compress_independent_frame(&data);
let mut decoder = FrameDecoder::new();
let mut source = frame.as_slice();
decoder
.reset(&mut source)
.expect("frame header should parse");
while !decoder.is_finished() {
decoder
.decode_blocks(&mut source, crate::decoding::BlockDecodingStrategy::All)
.expect("decode should succeed");
}
let mut decoded = Vec::with_capacity(data.len());
decoder.collect_to_writer(&mut decoded).unwrap();
assert_eq!(decoded, data, "roundtrip must reproduce the input verbatim");
assert!(
decoder.blocks_decoded() >= 3,
"fast one-shot borrowed path must split the second upstream zstd block \
(256 KiB unsplit = 2 blocks), got {} blocks",
decoder.blocks_decoded(),
);
}
#[cfg(feature = "std")]
#[test]
fn set_parameters_keeps_literals_compressed_under_nonfast_strategy_override() {
use super::CompressionLevel;
use crate::encoding::parameters::{CompressionParameters, Strategy};
let data = vec![0xABu8; 256];
let mut out = Vec::new();
let mut compressor = FrameCompressor::new(CompressionLevel::Level(3));
compressor.set_source(data.as_slice());
compressor.set_drain(&mut out);
let params = CompressionParameters::builder(CompressionLevel::Level(-5))
.strategy(Strategy::Btultra2)
.build()
.expect("valid params");
compressor.set_parameters(¶ms);
assert!(
!compressor.state.literal_compression_disabled,
"a non-fast strategy override on a negative level must keep literals compressed",
);
}
#[cfg(feature = "std")]
#[test]
fn set_compression_level_resyncs_literal_disable_for_negatives() {
use super::CompressionLevel;
let data = vec![0xABu8; 256];
let mut out = Vec::new();
let mut compressor = FrameCompressor::new(CompressionLevel::Level(3));
compressor.set_source(data.as_slice());
compressor.set_drain(&mut out);
assert!(
!compressor.state.literal_compression_disabled,
"L3 construction must leave literal compression enabled",
);
compressor.set_compression_level(CompressionLevel::Level(-5));
assert!(
compressor.state.literal_compression_disabled,
"set_compression_level to a negative level must disable literal compression",
);
}
#[cfg(feature = "std")]
#[test]
fn set_compression_level_then_compress_refreshes_strategy_tag() {
use super::CompressionLevel;
use crate::encoding::strategy::StrategyTag;
let data = vec![0xABu8; 256];
let mut out = Vec::new();
let mut compressor = FrameCompressor::new(CompressionLevel::Fastest);
let initial_tag = compressor.state.strategy_tag;
assert_eq!(
initial_tag,
StrategyTag::for_compression_level(CompressionLevel::Fastest),
"construction-time strategy_tag must reflect initial level",
);
let new_level = CompressionLevel::Level(20);
compressor.set_compression_level(new_level);
compressor.set_source(data.as_slice());
compressor.set_drain(&mut out);
compressor.compress();
let new_tag = compressor.state.strategy_tag;
let expected = StrategyTag::for_compression_level(new_level);
assert_eq!(
new_tag, expected,
"strategy_tag must follow set_compression_level → compress, \
got {new_tag:?} expected {expected:?}",
);
assert_eq!(
expected,
StrategyTag::BtUltra2,
"test fixture invariant: Level(20) must resolve to BtUltra2 \
so the post-switch tag visibly crosses the band boundary",
);
assert_ne!(
new_tag, initial_tag,
"test fixture invariant: chosen levels must resolve to \
different StrategyTag variants",
);
}
#[test]
fn magicless_frame_omits_magic_and_roundtrips() {
use crate::common::MAGIC_NUM;
let input: alloc::vec::Vec<u8> = (0..512u32).map(|i| (i ^ 0xA5) as u8).collect();
let mut output: Vec<u8> = Vec::new();
let mut compressor = FrameCompressor::new(super::CompressionLevel::Default);
compressor.set_magicless(true);
compressor.set_source(input.as_slice());
compressor.set_drain(&mut output);
compressor.compress();
assert!(
!output.starts_with(&MAGIC_NUM.to_le_bytes()),
"magicless frame must omit the 4-byte magic prefix",
);
let mut decoder = crate::decoding::FrameDecoder::new();
decoder.set_magicless(true);
let mut cursor: &[u8] = output.as_slice();
decoder.init(&mut cursor).expect("magicless init");
decoder
.decode_blocks(&mut cursor, crate::decoding::BlockDecodingStrategy::All)
.expect("decode_blocks");
let mut decoded: Vec<u8> = Vec::new();
decoder
.collect_to_writer(&mut decoded)
.expect("collect_to_writer");
assert_eq!(decoded, input, "magicless roundtrip must preserve bytes");
use crate::decoding::errors::{FrameDecoderError, ReadFrameHeaderError};
let mut std_decoder = crate::decoding::FrameDecoder::new();
let std_init = std_decoder.init(output.as_slice());
match std_init {
Err(FrameDecoderError::ReadFrameHeaderError(
ReadFrameHeaderError::BadMagicNumber(_) | ReadFrameHeaderError::SkipFrame { .. },
)) => {}
other => panic!(
"standard decoder must reject a magicless frame with \
ReadFrameHeaderError::BadMagicNumber or SkipFrame, got {other:?}",
),
}
}
#[test]
fn compress_independent_frame_reuse_matches_fresh_and_roundtrips() {
use crate::encoding::{CompressionLevel, compress_slice_to_vec};
let levels = [
CompressionLevel::Uncompressed,
CompressionLevel::Fastest,
CompressionLevel::Default,
CompressionLevel::Better,
CompressionLevel::Best,
CompressionLevel::Level(5),
];
let inputs: Vec<Vec<u8>> = vec![
Vec::new(),
vec![0x00],
b"the quick brown fox jumps over the lazy dog\n".to_vec(),
vec![0x7Eu8; 50_000], generate_data(0xABCD, 70_000), generate_data(0x1234, 200_000),
];
for level in levels {
let mut cctx: FrameCompressor = FrameCompressor::new(level);
for data in &inputs {
let reused = cctx.compress_independent_frame(data);
let fresh = compress_slice_to_vec(data, level);
assert_eq!(
reused,
fresh,
"reused frame != fresh frame for len={} level={:?}",
data.len(),
level,
);
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(data.len());
decoder.decode_all_to_vec(&reused, &mut decoded).unwrap();
assert_eq!(
decoded,
*data,
"roundtrip failed for len={} level={:?}",
data.len(),
level,
);
}
}
}
#[test]
fn compress_independent_frame_into_replaces_buffer_contents() {
use crate::encoding::{CompressionLevel, compress_slice_to_vec};
let large = vec![0x11u8; 40_000];
let small = b"short payload".to_vec();
let mut cctx: FrameCompressor = FrameCompressor::new(CompressionLevel::Default);
let mut out = Vec::new();
cctx.compress_independent_frame_into(&large, &mut out);
let frame_large = out.clone();
cctx.compress_independent_frame_into(&small, &mut out);
assert_eq!(
out,
compress_slice_to_vec(&small, CompressionLevel::Default),
"reused buffer must hold exactly the second frame",
);
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(large.len());
decoder
.decode_all_to_vec(&frame_large, &mut decoded)
.unwrap();
assert_eq!(decoded, large);
}
#[test]
fn compress_independent_frame_reuses_sticky_dictionary() {
use crate::encoding::CompressionLevel;
let dict_raw = include_bytes!("../../../dict_tests/dictionary");
let dict_content = crate::decoding::Dictionary::decode_dict(dict_raw).unwrap();
let mut payload_a = Vec::new();
for _ in 0..8 {
payload_a.extend_from_slice(&dict_content.dict_content[..2048]);
}
let payload_b = b"a different second frame payload, still dict-attached".to_vec();
let inputs = [payload_a, payload_b];
let mut cctx: FrameCompressor = FrameCompressor::new(CompressionLevel::Fastest);
cctx.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
for data in &inputs {
let reused = cctx.compress_independent_frame(data);
let mut fresh_enc: FrameCompressor = FrameCompressor::new(CompressionLevel::Fastest);
fresh_enc
.set_dictionary_from_bytes(dict_raw)
.expect("dictionary bytes should parse");
let fresh = fresh_enc.compress_independent_frame(data);
assert_eq!(
reused,
fresh,
"reused dict frame != fresh dict frame, len={}",
data.len(),
);
let dict_for_decoder = crate::decoding::Dictionary::decode_dict(dict_raw).unwrap();
let mut decoder = FrameDecoder::new();
decoder.add_dict(dict_for_decoder).unwrap();
let mut decoded = Vec::with_capacity(data.len());
decoder.decode_all_to_vec(&reused, &mut decoded).unwrap();
assert_eq!(&decoded, data, "dict roundtrip failed, len={}", data.len());
}
}
fn frame_block_list(frame: &[u8]) -> Vec<(u8, usize, bool)> {
let desc = frame[4];
let fcs_flag = desc >> 6;
let single_segment = (desc >> 5) & 1 == 1;
let checksum = (desc >> 2) & 1 == 1;
let dict_id_bytes = match desc & 3 {
0 => 0,
1 => 1,
2 => 2,
_ => 4,
};
let fcs_bytes = match fcs_flag {
0 => usize::from(single_segment),
1 => 2,
2 => 4,
_ => 8,
};
let mut pos = 4 + 1 + usize::from(!single_segment) + dict_id_bytes + fcs_bytes;
let end = frame.len() - if checksum { 4 } else { 0 };
let mut blocks = Vec::new();
while pos + 3 <= end {
let h =
frame[pos] as usize | (frame[pos + 1] as usize) << 8 | (frame[pos + 2] as usize) << 16;
let last = h & 1 == 1;
let btype = ((h >> 1) & 3) as u8;
let bsize = h >> 3;
let advance = if btype == 1 { 1 } else { bsize };
blocks.push((btype, bsize, last));
pos += 3 + advance;
if last {
break;
}
}
blocks
}
#[test]
fn exact_block_multiple_marks_last_real_block() {
const CUSTOM_CAP: u32 = 16 * 1024;
for &(cap, target) in &[
(MAX_BLOCK_SIZE as usize, None),
(CUSTOM_CAP as usize, Some(CUSTOM_CAP)),
] {
for &nblk in &[1usize, 2, 3] {
for &compressible in &[false, true] {
let input: Vec<u8> = if compressible {
vec![0x7Au8; cap * nblk]
} else {
generate_data(0xC0FF_EE11, cap * nblk)
};
let mut oneshot: FrameCompressor =
FrameCompressor::new(super::CompressionLevel::Default);
oneshot.set_target_block_size(target);
let frame_os = oneshot.compress_independent_frame(&input);
let blocks_os = frame_block_list(&frame_os);
let last_os = *blocks_os.last().expect("at least one block");
assert!(
last_os.2,
"one-shot last block must set last_block (cap={cap}, nblk={nblk}, compressible={compressible}): {blocks_os:?}"
);
assert!(
!(last_os.0 == 0 && last_os.1 == 0),
"one-shot must not emit a trailing empty Raw block (cap={cap}, nblk={nblk}, compressible={compressible}): {blocks_os:?}"
);
let mut output = Vec::new();
let mut streaming = FrameCompressor::new(super::CompressionLevel::Default);
streaming.set_target_block_size(target);
streaming.set_source(input.as_slice());
streaming.set_drain(&mut output);
streaming.compress();
let blocks_st = frame_block_list(&output);
let last_st = *blocks_st.last().expect("at least one block");
assert!(
last_st.2,
"streaming last block must set last_block (cap={cap}, nblk={nblk}, compressible={compressible}): {blocks_st:?}"
);
assert!(
!(last_st.0 == 0 && last_st.1 == 0),
"streaming must not emit a trailing empty Raw block (cap={cap}, nblk={nblk}, compressible={compressible}): {blocks_st:?}"
);
for frame in [&frame_os, &output] {
let mut decoder = FrameDecoder::new();
let mut decoded = Vec::with_capacity(input.len());
decoder.decode_all_to_vec(frame, &mut decoded).unwrap();
assert_eq!(
decoded, input,
"roundtrip mismatch (cap={cap}, nblk={nblk}, compressible={compressible})"
);
}
}
}
}
}
#[test]
fn dict_compress_bt_level_tiny_source_round_trips_through_prime_dms_bt() {
let raw_dict: Vec<u8> = (0..100u32)
.map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8)
.collect();
let dict_id = 1u32;
let dict_for_encoder =
crate::decoding::Dictionary::from_raw_content(dict_id, raw_dict.clone()).unwrap();
let dict_for_decoder =
crate::decoding::Dictionary::from_raw_content(dict_id, raw_dict).unwrap();
let data = b"hello world".to_vec();
let mut compressor: FrameCompressor =
FrameCompressor::new(super::CompressionLevel::from_level(19));
compressor
.set_dictionary(dict_for_encoder)
.expect("raw-content dictionary should attach");
let out = compressor.compress_independent_frame(data.as_slice());
let mut decoder = FrameDecoder::new();
decoder.add_dict(dict_for_decoder).unwrap();
let mut decoded = Vec::with_capacity(data.len());
decoder
.decode_all_to_vec(&out, &mut decoded)
.expect("dict BT-level frame should round-trip");
assert_eq!(decoded, data);
}