Skip to main content

zrip_encode/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![deny(unsafe_op_in_unsafe_fn)]
3#![cfg_attr(feature = "nightly", feature(optimize_attribute))]
4#![cfg_attr(feature = "paranoid", forbid(unsafe_code))]
5
6#[cfg(feature = "alloc")]
7extern crate alloc;
8
9#[cfg(not(feature = "paranoid"))]
10macro_rules! paranoid_unsafe_call {
11    ($e:expr) => {
12        unsafe { $e }
13    };
14}
15
16#[cfg(feature = "paranoid")]
17macro_rules! paranoid_unsafe_call {
18    ($e:expr) => {
19        $e
20    };
21}
22
23/// Evaluates `$body` compiled for x86-64-v3 (AVX2, BMI1/2, LZCNT) when the CPU
24/// supports it, and compiled for the build target otherwise.
25///
26/// Use it as a whole function body around a call to an `#[inline(always)]`
27/// implementation, so the implementation is duplicated into both contexts.
28/// `fearless_simd` selects the level at runtime and provides the safe
29/// target-feature entry point.
30#[cfg(all(feature = "simd", target_arch = "x86_64", not(target_feature = "avx2")))]
31macro_rules! simd_body {
32    ($body:expr) => {
33        match fearless_simd::Level::new().as_avx2() {
34            Some(avx2) => fearless_simd::Simd::vectorize(
35                avx2,
36                #[inline(always)]
37                || $body,
38            ),
39            None => $body,
40        }
41    };
42}
43
44#[cfg(not(all(feature = "simd", target_arch = "x86_64", not(target_feature = "avx2"))))]
45macro_rules! simd_body {
46    ($body:expr) => {
47        $body
48    };
49}
50
51pub(crate) mod block_encoder;
52#[cfg(feature = "std")]
53pub mod context;
54pub(crate) mod dfast;
55pub(crate) mod fast;
56#[cfg(feature = "ldm")]
57pub(crate) mod ldm;
58mod output;
59pub(crate) mod primitives;
60pub mod strategy;
61#[cfg(feature = "std")]
62pub mod streaming;
63
64#[cfg(feature = "alloc")]
65use alloc::vec;
66#[cfg(feature = "alloc")]
67use alloc::vec::Vec;
68
69use crate::output::{OutputSink, SliceSink};
70use crate::strategy::Strategy;
71use zrip_core::error::CompressError;
72use zrip_core::frame::{MAX_BLOCK_SIZE, MAX_WINDOW_SIZE, ZSTD_MAGIC};
73use zrip_core::xxhash::xxh64;
74
75pub(crate) fn write_frame_header(
76    output: &mut impl OutputSink,
77    content_size: usize,
78    dict_id: Option<u32>,
79    window_log: u32,
80) -> Result<(), CompressError> {
81    write_frame_header_inner(output, Some(content_size), dict_id, window_log, true)
82}
83
84#[cfg_attr(not(feature = "std"), allow(dead_code))]
85pub(crate) fn write_frame_header_with_checksum(
86    output: &mut impl OutputSink,
87    content_size: usize,
88    dict_id: Option<u32>,
89    window_log: u32,
90    content_checksum: bool,
91) -> Result<(), CompressError> {
92    write_frame_header_inner(
93        output,
94        Some(content_size),
95        dict_id,
96        window_log,
97        content_checksum,
98    )
99}
100
101#[cfg_attr(not(feature = "std"), allow(dead_code))]
102pub(crate) fn write_frame_header_without_content_size(
103    output: &mut impl OutputSink,
104    dict_id: Option<u32>,
105    window_log: u32,
106) -> Result<(), CompressError> {
107    write_frame_header_inner(output, None, dict_id, window_log, true)
108}
109
110fn write_frame_header_inner(
111    output: &mut impl OutputSink,
112    content_size: Option<usize>,
113    dict_id: Option<u32>,
114    window_log: u32,
115    content_checksum: bool,
116) -> Result<(), CompressError> {
117    output.extend_from_slice(&ZSTD_MAGIC.to_le_bytes())?;
118
119    let single_segment =
120        dict_id.is_none() && content_size.is_some_and(|size| size as u64 <= MAX_WINDOW_SIZE);
121    let fcs_size = content_size.map_or(0, |size| {
122        frame_content_size_field_size(size, single_segment)
123    });
124    let fcs_flag: u8 = match fcs_size {
125        0 => 0,
126        1 => 0,
127        2 => 1,
128        4 => 2,
129        _ => 3,
130    };
131
132    let dict_id_flag: u8 = match dict_id {
133        None => 0,
134        Some(id) if id <= 0xFF => 1,
135        Some(id) if id <= 0xFFFF => 2,
136        Some(_) => 3,
137    };
138
139    let descriptor = if single_segment { 0x20 } else { 0 }
140        | if content_checksum { 0x04 } else { 0 }
141        | (fcs_flag << 6)
142        | dict_id_flag;
143    output.push(descriptor)?;
144
145    if !single_segment {
146        output.push(window_descriptor_for_log(window_log))?;
147    }
148
149    match dict_id {
150        Some(id) if id <= 0xFF => output.push(id as u8)?,
151        Some(id) if id <= 0xFFFF => output.extend_from_slice(&(id as u16).to_le_bytes())?,
152        Some(id) => output.extend_from_slice(&id.to_le_bytes())?,
153        None => {}
154    }
155
156    let Some(content_size) = content_size else {
157        return Ok(());
158    };
159    match fcs_size {
160        0 => {}
161        1 => output.push(content_size as u8)?,
162        2 => {
163            let v = (content_size - 256) as u16;
164            output.extend_from_slice(&v.to_le_bytes())?;
165        }
166        4 => output.extend_from_slice(&(content_size as u32).to_le_bytes())?,
167        _ => output.extend_from_slice(&(content_size as u64).to_le_bytes())?,
168    }
169    Ok(())
170}
171
172fn frame_content_size_field_size(content_size: usize, single_segment: bool) -> usize {
173    if single_segment && content_size <= 255 {
174        1
175    } else if (256..=0xFFFF + 256).contains(&content_size) {
176        2
177    } else if content_size <= 0xFFFF_FFFF {
178        4
179    } else {
180        8
181    }
182}
183
184fn window_descriptor_for_log(window_log: u32) -> u8 {
185    let window_log = window_log.clamp(strategy::WINDOW_LOG_MIN, strategy::WINDOW_LOG_MAX);
186    ((window_log - 10) as u8) << 3
187}
188
189/// Whether to store `data`, a block of an `input_len`-byte input, raw without
190/// a match search.
191///
192/// Inputs that keep raw literals skip the sampling: it costs about as much as
193/// their match search, and a block without matches is stored raw anyway.
194pub(crate) fn skip_match_search(
195    params: &strategy::LevelParams,
196    input_len: usize,
197    data: &[u8],
198) -> bool {
199    !strategy::keeps_raw_literals(params, input_len) && block_looks_incompressible(data)
200}
201
202fn block_looks_incompressible(data: &[u8]) -> bool {
203    const SAMPLE: usize = 1024;
204    const DISTINCT_THRESHOLD: u32 = 200;
205    const MAX_FREQ_DENOM: u32 = 24;
206    if data.len() < SAMPLE {
207        return false;
208    }
209    let mut counts = [0u16; 256];
210    for &b in &data[..SAMPLE] {
211        counts[b as usize] += 1;
212    }
213    let mut distinct: u32 = 0;
214    let mut max_freq: u16 = 0;
215    for &c in &counts {
216        distinct += (c > 0) as u32;
217        max_freq = max_freq.max(c);
218    }
219    distinct >= DISTINCT_THRESHOLD && (max_freq as u32) <= SAMPLE as u32 / MAX_FREQ_DENOM
220}
221
222pub(crate) fn clamp_params_to_src_size(params: &mut strategy::LevelParams, src_len: usize) {
223    params.hash_log = params
224        .hash_log
225        .clamp(strategy::HASH_LOG_MIN, strategy::HASH_LOG_MAX);
226    params.chain_log = params
227        .chain_log
228        .clamp(strategy::HASH_LOG_MIN, strategy::HASH_LOG_MAX);
229    params.window_log = params
230        .window_log
231        .clamp(strategy::WINDOW_LOG_MIN, strategy::WINDOW_LOG_MAX);
232    if src_len >= 2 {
233        let src_log = 32 - ((src_len as u32) - 1).leading_zeros();
234        params.hash_log = params.hash_log.min(src_log).max(strategy::HASH_LOG_MIN);
235        params.chain_log = params.chain_log.min(src_log).max(strategy::HASH_LOG_MIN);
236        params.window_log = params.window_log.min(src_log);
237    }
238}
239
240pub fn compress_with_params(
241    input: &[u8],
242    params: &strategy::LevelParams,
243) -> Result<Vec<u8>, CompressError> {
244    let mut params = *params;
245    clamp_params_to_src_size(&mut params, input.len());
246    compress_inner(input, &params)
247}
248
249pub fn compress(input: &[u8], level: i32) -> Result<Vec<u8>, CompressError> {
250    let params = strategy::level_params_for_size(level, input.len())
251        .ok_or(CompressError::InvalidLevel(level))?;
252    compress_inner(input, &params)
253}
254
255pub fn compress_opts(
256    input: &[u8],
257    level: i32,
258    opts: &strategy::Options,
259) -> Result<Vec<u8>, CompressError> {
260    let mut params = strategy::level_params_for_size(level, input.len())
261        .ok_or(CompressError::InvalidLevel(level))?;
262    strategy::apply_options(&mut params, opts);
263    clamp_params_to_src_size(&mut params, input.len());
264    compress_inner(input, &params)
265}
266
267#[allow(clippy::unnecessary_wraps)]
268fn compress_inner(input: &[u8], params: &strategy::LevelParams) -> Result<Vec<u8>, CompressError> {
269    let mut output = Vec::with_capacity(input.len() + 32);
270    compress_frame(input, params, &mut output)?;
271    Ok(output)
272}
273
274fn compress_frame(
275    input: &[u8],
276    params: &strategy::LevelParams,
277    output: &mut impl OutputSink,
278) -> Result<(), CompressError> {
279    write_frame_header(output, input.len(), None, params.window_log)?;
280
281    if input.is_empty() {
282        block_encoder::encode_raw_block(&[], true, output)?;
283    } else {
284        let mut rep_offsets = [1u32, 4, 8];
285        let mut offset = 0;
286        let mut sequences = Vec::with_capacity(MAX_BLOCK_SIZE / 8);
287        let mut workspace = block_encoder::BlockEncodeWorkspace::new();
288
289        #[cfg(feature = "ldm")]
290        let mut ldm_state = params.ldm_params.as_ref().map(ldm::LdmState::new);
291
292        match params.strategy {
293            Strategy::Fast => {
294                let hash_size = 1usize << params.hash_log;
295                let mut hash_table = vec![0u32; hash_size];
296                while offset < input.len() {
297                    let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
298                    let block_end = offset + chunk_size;
299                    let is_last = block_end >= input.len();
300                    let block = &input[offset..block_end];
301
302                    if skip_match_search(params, input.len(), block) {
303                        block_encoder::encode_raw_block(block, is_last, output)?;
304                    } else {
305                        #[cfg(feature = "ldm")]
306                        let used_ldm = if let Some(ref mut ldm) = ldm_state {
307                            let mut empty = Vec::new();
308                            ldm.compress_block(
309                                input,
310                                offset,
311                                block_end,
312                                params,
313                                &rep_offsets,
314                                &mut hash_table,
315                                &mut empty,
316                                &mut sequences,
317                            );
318                            true
319                        } else {
320                            false
321                        };
322                        #[cfg(not(feature = "ldm"))]
323                        let used_ldm = false;
324
325                        if !used_ldm {
326                            fast::compress_fast_block(
327                                input,
328                                offset,
329                                block_end,
330                                params,
331                                &rep_offsets,
332                                &mut hash_table,
333                                &mut sequences,
334                            );
335                        }
336                        if params.force_raw_literals {
337                            block_encoder::encode_compressed_block_raw(
338                                block,
339                                &sequences,
340                                &mut rep_offsets,
341                                is_last,
342                                output,
343                                &mut workspace,
344                            )?;
345                        } else {
346                            block_encoder::encode_compressed_block(
347                                block,
348                                &sequences,
349                                &mut rep_offsets,
350                                is_last,
351                                output,
352                                &mut workspace,
353                                strategy::block_policy(params, input.len()),
354                            )?;
355                        }
356                    }
357                    offset = block_end;
358                }
359            }
360            Strategy::DFast => {
361                let short_size = 1usize << params.chain_log;
362                let long_size = 1usize << params.hash_log;
363                let mut hash_short = vec![0u32; short_size];
364                let mut hash_long = vec![0u32; long_size];
365                while offset < input.len() {
366                    let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
367                    let block_end = offset + chunk_size;
368                    let is_last = block_end >= input.len();
369                    let block = &input[offset..block_end];
370
371                    if skip_match_search(params, input.len(), block) {
372                        block_encoder::encode_raw_block(block, is_last, output)?;
373                    } else {
374                        #[cfg(feature = "ldm")]
375                        let used_ldm = if let Some(ref mut ldm) = ldm_state {
376                            ldm.compress_block(
377                                input,
378                                offset,
379                                block_end,
380                                params,
381                                &rep_offsets,
382                                &mut hash_short,
383                                &mut hash_long,
384                                &mut sequences,
385                            );
386                            true
387                        } else {
388                            false
389                        };
390                        #[cfg(not(feature = "ldm"))]
391                        let used_ldm = false;
392
393                        if !used_ldm {
394                            dfast::compress_dfast_block(
395                                input,
396                                offset,
397                                block_end,
398                                params,
399                                &rep_offsets,
400                                &mut hash_short,
401                                &mut hash_long,
402                                &mut sequences,
403                            );
404                        }
405                        block_encoder::encode_compressed_block(
406                            block,
407                            &sequences,
408                            &mut rep_offsets,
409                            is_last,
410                            output,
411                            &mut workspace,
412                            strategy::block_policy(params, input.len()),
413                        )?;
414                    }
415                    offset = block_end;
416                }
417            }
418        }
419    }
420
421    let hash = xxh64(input, 0);
422    let checksum = (hash & 0xFFFF_FFFF) as u32;
423    output.extend_from_slice(&checksum.to_le_bytes())?;
424    Ok(())
425}
426
427pub fn compress_with_dict(
428    input: &[u8],
429    level: i32,
430    dict: &zrip_core::dict::Dictionary,
431) -> Result<Vec<u8>, CompressError> {
432    let total_window = dict.content().len() + input.len();
433    let params = strategy::level_params_for_size(level, total_window)
434        .ok_or(CompressError::InvalidLevel(level))?;
435
436    let mut output = Vec::with_capacity(input.len() + 32);
437    write_frame_header(&mut output, input.len(), Some(dict.id()), params.window_log)?;
438
439    if input.is_empty() {
440        block_encoder::encode_raw_block(&[], true, &mut output)?;
441    } else {
442        let prefix = dict.content();
443        let mut rep_offsets = *dict.rep_offsets();
444        let mut workspace = block_encoder::BlockEncodeWorkspace::new();
445
446        workspace.prev_ll = dict
447            .ll_table()
448            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 35));
449        workspace.prev_of = dict
450            .of_table()
451            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 31));
452        workspace.prev_ml = dict
453            .ml_table()
454            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 52));
455        workspace.prev_huffman = dict.huf_table().and_then(|(dt, tl)| {
456            zrip_core::huffman::encode::HuffmanEncodeTable::from_decode_table(dt, tl)
457        });
458
459        if input.len() <= MAX_BLOCK_SIZE {
460            let sequences = match params.strategy {
461                Strategy::Fast => {
462                    fast::compress_fast_with_prefix(input, &params, &rep_offsets, prefix)
463                }
464                Strategy::DFast => {
465                    dfast::compress_dfast_with_prefix(input, &params, &rep_offsets, prefix)
466                }
467            };
468            if params.force_raw_literals {
469                block_encoder::encode_compressed_block_raw(
470                    input,
471                    &sequences,
472                    &mut rep_offsets,
473                    true,
474                    &mut output,
475                    &mut workspace,
476                )?;
477            } else {
478                block_encoder::encode_compressed_block(
479                    input,
480                    &sequences,
481                    &mut rep_offsets,
482                    true,
483                    &mut output,
484                    &mut workspace,
485                    strategy::block_policy(&params, input.len()),
486                )?;
487            }
488        } else {
489            let mut combined = Vec::with_capacity(prefix.len() + input.len());
490            combined.extend_from_slice(prefix);
491            combined.extend_from_slice(input);
492            let plen = prefix.len();
493            let hash_size = 1usize << params.hash_log;
494            let mut sequences = Vec::new();
495
496            match params.strategy {
497                Strategy::Fast => {
498                    let mut hash_table = vec![0u32; hash_size];
499                    fast::prefill_hash_table(&combined, plen, params.hash_log, &mut hash_table);
500                    let mut offset = 0;
501                    while offset < input.len() {
502                        let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
503                        let is_last = offset + chunk_size >= input.len();
504                        fast::compress_fast_block(
505                            &combined,
506                            plen + offset,
507                            plen + offset + chunk_size,
508                            &params,
509                            &rep_offsets,
510                            &mut hash_table,
511                            &mut sequences,
512                        );
513                        if params.force_raw_literals {
514                            block_encoder::encode_compressed_block_raw(
515                                &input[offset..offset + chunk_size],
516                                &sequences,
517                                &mut rep_offsets,
518                                is_last,
519                                &mut output,
520                                &mut workspace,
521                            )?;
522                        } else {
523                            block_encoder::encode_compressed_block(
524                                &input[offset..offset + chunk_size],
525                                &sequences,
526                                &mut rep_offsets,
527                                is_last,
528                                &mut output,
529                                &mut workspace,
530                                strategy::block_policy(&params, input.len()),
531                            )?;
532                        }
533                        offset += chunk_size;
534                    }
535                }
536                Strategy::DFast => {
537                    let short_size = 1usize << params.chain_log;
538                    let long_size = 1usize << params.hash_log;
539                    let mut hash_short = vec![0u32; short_size];
540                    let mut hash_long = vec![0u32; long_size];
541                    dfast::prefill_hash_tables(
542                        &combined,
543                        plen,
544                        params.hash_log,
545                        params.chain_log,
546                        params.min_match,
547                        &mut hash_short,
548                        &mut hash_long,
549                    );
550                    let mut offset = 0;
551                    while offset < input.len() {
552                        let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
553                        let is_last = offset + chunk_size >= input.len();
554                        dfast::compress_dfast_block(
555                            &combined,
556                            plen + offset,
557                            plen + offset + chunk_size,
558                            &params,
559                            &rep_offsets,
560                            &mut hash_short,
561                            &mut hash_long,
562                            &mut sequences,
563                        );
564                        block_encoder::encode_compressed_block(
565                            &input[offset..offset + chunk_size],
566                            &sequences,
567                            &mut rep_offsets,
568                            is_last,
569                            &mut output,
570                            &mut workspace,
571                            strategy::block_policy(&params, input.len()),
572                        )?;
573                        offset += chunk_size;
574                    }
575                }
576            }
577        }
578    }
579
580    let hash = xxh64(input, 0);
581    let checksum = (hash & 0xFFFF_FFFF) as u32;
582    output.extend_from_slice(&checksum.to_le_bytes());
583
584    Ok(output)
585}
586
587pub fn compress_into(input: &[u8], output: &mut [u8], level: i32) -> Result<usize, CompressError> {
588    let params = strategy::level_params_for_size(level, input.len())
589        .ok_or(CompressError::InvalidLevel(level))?;
590    let mut sink = SliceSink::new(output);
591    compress_frame(input, &params, &mut sink)?;
592    Ok(sink.pos())
593}
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598    use zrip_core::frame::header::parse_frame_header;
599
600    #[test]
601    fn clamp_params_normalizes_public_log_values() {
602        let mut params = strategy::level_params(1).unwrap();
603        params.hash_log = 0;
604        params.chain_log = 40;
605        params.window_log = 40;
606
607        clamp_params_to_src_size(&mut params, usize::MAX);
608
609        assert_eq!(params.hash_log, strategy::HASH_LOG_MIN);
610        assert_eq!(params.chain_log, strategy::HASH_LOG_MAX);
611        assert_eq!(params.window_log, strategy::WINDOW_LOG_MAX);
612    }
613
614    #[test]
615    fn options_clamp_window_log_before_ldm_defaults() {
616        let mut params = strategy::level_params(1).unwrap();
617        let opts = strategy::Options::default().window_log(0);
618
619        strategy::apply_options(&mut params, &opts);
620
621        assert_eq!(params.window_log, strategy::WINDOW_LOG_MIN);
622        #[cfg(feature = "ldm")]
623        {
624            let mut params = strategy::level_params(1).unwrap();
625            let opts = strategy::Options::default().window_log(0).ldm(true);
626            strategy::apply_options(&mut params, &opts);
627
628            let ldm = params.ldm_params.unwrap();
629            assert!(ldm.hash_log >= ldm.bucket_size_log);
630        }
631    }
632
633    /// Bytes from a skewed alphabet: about 3.5 bits of order-0 entropy per
634    /// byte and few repeated 6-byte strings.
635    fn skewed_bytes(len: usize) -> Vec<u8> {
636        let mut x = 0x2545_F491_4F6C_DD1Du64;
637        (0..len)
638            .map(|_| {
639                x ^= x << 13;
640                x ^= x >> 7;
641                x ^= x << 17;
642                let r = (x >> 32) as u32;
643                b"eeeeeeettttaaoonnissshhrdl  "[(r % 28) as usize] + (r >> 30) as u8
644            })
645            .collect()
646    }
647
648    /// Words from a 64-word vocabulary. Repeats are short and sparse, so a
649    /// sparse match search misses most of them.
650    fn wordy_bytes(len: usize) -> Vec<u8> {
651        const WORDS: &str = "the of and to in is was for on that with as by at \
652            from his her they this have had were which their are but not one \
653            all been when there she would what so if will more no out up into \
654            could them than then some other time very about only upon over \
655            such said great before after little";
656        let words: Vec<&str> = WORDS.split_whitespace().collect();
657        let mut x = 0x9E37_79B9_7F4A_7C15u64;
658        let mut out = Vec::with_capacity(len + 16);
659        while out.len() < len {
660            x ^= x << 13;
661            x ^= x >> 7;
662            x ^= x << 17;
663            out.extend_from_slice(words[(x >> 58) as usize % words.len()].as_bytes());
664            out.push(b' ');
665        }
666        out.truncate(len);
667        out
668    }
669
670    #[test]
671    fn negative_levels_skip_huffman_on_tiny_inputs() {
672        // No usable matches: only Huffman could shrink these bytes.
673        let data = skewed_bytes(2048);
674        for level in -8..=-1 {
675            let out = compress(&data, level).unwrap();
676            assert!(out.len() > data.len(), "L{level}: {} compressed", out.len());
677        }
678        for level in 1..=4 {
679            let out = compress(&data, level).unwrap();
680            assert!(out.len() * 5 < data.len() * 4, "L{level}: {}", out.len());
681        }
682    }
683
684    #[test]
685    fn negative_levels_still_match_tiny_inputs() {
686        let data = wordy_bytes(2048);
687        let sizes: Vec<usize> = (-8..=-1)
688            .map(|level| compress(&data, level).unwrap().len())
689            .collect();
690        // At least 10% smaller, and no smaller output at a faster level.
691        assert!(sizes.iter().all(|&n| n * 11 < data.len() * 10), "{sizes:?}");
692        assert!(sizes.windows(2).all(|w| w[0] >= w[1]), "{sizes:?}");
693    }
694
695    #[test]
696    fn negative_levels_huffman_code_above_their_raw_limit() {
697        let data = skewed_bytes(32 * 1024);
698        for level in -8..=-1 {
699            let out = compress(&data, level).unwrap();
700            assert!(out.len() * 5 < data.len() * 4, "L{level}: {}", out.len());
701        }
702    }
703
704    #[test]
705    fn faster_levels_keep_raw_literals_longer() {
706        let limits: Vec<usize> = (-8..=-1)
707            .map(|level| strategy::raw_literals_limit(level).unwrap())
708            .collect();
709        assert_eq!(limits.last(), Some(&2048));
710        assert!(limits.windows(2).all(|w| w[0] > w[1]), "{limits:?}");
711        assert_eq!(strategy::raw_literals_limit(1), None);
712    }
713
714    #[test]
715    fn small_plain_frame_uses_single_segment_header() {
716        let mut output = Vec::new();
717
718        write_frame_header(&mut output, 12, None, 19).unwrap();
719        let header = parse_frame_header(&output).unwrap();
720
721        assert!(header.single_segment);
722        assert_eq!(header.frame_content_size, Some(12));
723        assert_eq!(header.window_size, 12);
724        assert_eq!(header.dict_id, None);
725        assert!(header.content_checksum);
726        assert_eq!(header.header_size, 6);
727    }
728
729    #[test]
730    fn large_plain_frame_uses_bounded_window_descriptor() {
731        let mut output = Vec::new();
732        let content_size = MAX_WINDOW_SIZE as usize + 1;
733
734        write_frame_header(&mut output, content_size, None, 19).unwrap();
735        let header = parse_frame_header(&output).unwrap();
736
737        assert!(!header.single_segment);
738        assert_eq!(header.frame_content_size, Some(content_size as u64));
739        assert_eq!(header.window_size, 1 << 19);
740        assert_eq!(header.dict_id, None);
741        assert!(header.content_checksum);
742        assert_eq!(header.header_size, 10);
743    }
744
745    #[test]
746    fn dict_frame_uses_window_descriptor_even_when_small() {
747        let mut output = Vec::new();
748
749        write_frame_header(&mut output, 12, Some(0x1234), 10).unwrap();
750        let header = parse_frame_header(&output).unwrap();
751
752        assert!(!header.single_segment);
753        assert_eq!(header.frame_content_size, Some(12));
754        assert_eq!(header.window_size, 1 << 10);
755        assert_eq!(header.dict_id, Some(0x1234));
756        assert!(header.content_checksum);
757        assert_eq!(header.header_size, 12);
758    }
759
760    #[test]
761    fn no_fcs_frame_uses_window_descriptor() {
762        let mut output = Vec::new();
763
764        write_frame_header_without_content_size(&mut output, None, 19).unwrap();
765        let header = parse_frame_header(&output).unwrap();
766
767        assert!(!header.single_segment);
768        assert_eq!(header.frame_content_size, None);
769        assert_eq!(header.window_size, 1 << 19);
770        assert_eq!(header.dict_id, None);
771        assert!(header.content_checksum);
772        assert_eq!(header.header_size, 6);
773    }
774}