zrip-encode 0.8.6

zstd encoder for zrip (internal crate)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(unsafe_op_in_unsafe_fn)]
#![cfg_attr(feature = "nightly", feature(optimize_attribute))]
#![cfg_attr(feature = "paranoid", forbid(unsafe_code))]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(not(feature = "paranoid"))]
macro_rules! paranoid_unsafe_call {
    ($e:expr) => {
        unsafe { $e }
    };
}

#[cfg(feature = "paranoid")]
macro_rules! paranoid_unsafe_call {
    ($e:expr) => {
        $e
    };
}

pub(crate) mod block_encoder;
#[cfg(feature = "std")]
pub mod context;
pub(crate) mod dfast;
pub(crate) mod fast;
#[cfg(feature = "ldm")]
pub(crate) mod ldm;
mod output;
pub(crate) mod primitives;
pub mod strategy;
#[cfg(feature = "std")]
pub mod streaming;

#[cfg(feature = "alloc")]
use alloc::vec;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

use crate::output::{OutputSink, SliceSink};
use crate::strategy::Strategy;
use zrip_core::error::CompressError;
use zrip_core::frame::{MAX_BLOCK_SIZE, MAX_WINDOW_SIZE, ZSTD_MAGIC};
use zrip_core::xxhash::xxh64;

pub(crate) fn write_frame_header(
    output: &mut impl OutputSink,
    content_size: usize,
    dict_id: Option<u32>,
    window_log: u32,
) -> Result<(), CompressError> {
    write_frame_header_inner(output, Some(content_size), dict_id, window_log)
}

#[cfg_attr(not(feature = "std"), allow(dead_code))]
pub(crate) fn write_frame_header_without_content_size(
    output: &mut impl OutputSink,
    dict_id: Option<u32>,
    window_log: u32,
) -> Result<(), CompressError> {
    write_frame_header_inner(output, None, dict_id, window_log)
}

fn write_frame_header_inner(
    output: &mut impl OutputSink,
    content_size: Option<usize>,
    dict_id: Option<u32>,
    window_log: u32,
) -> Result<(), CompressError> {
    output.extend_from_slice(&ZSTD_MAGIC.to_le_bytes())?;

    let single_segment =
        dict_id.is_none() && content_size.is_some_and(|size| size as u64 <= MAX_WINDOW_SIZE);
    let fcs_size = content_size.map_or(0, |size| {
        frame_content_size_field_size(size, single_segment)
    });
    let fcs_flag: u8 = match fcs_size {
        0 => 0,
        1 => 0,
        2 => 1,
        4 => 2,
        _ => 3,
    };

    let dict_id_flag: u8 = match dict_id {
        None => 0,
        Some(id) if id <= 0xFF => 1,
        Some(id) if id <= 0xFFFF => 2,
        Some(_) => 3,
    };

    let descriptor = if single_segment { 0x20 } else { 0 } | 0x04 | (fcs_flag << 6) | dict_id_flag;
    output.push(descriptor)?;

    if !single_segment {
        output.push(window_descriptor_for_log(window_log))?;
    }

    match dict_id {
        Some(id) if id <= 0xFF => output.push(id as u8)?,
        Some(id) if id <= 0xFFFF => output.extend_from_slice(&(id as u16).to_le_bytes())?,
        Some(id) => output.extend_from_slice(&id.to_le_bytes())?,
        None => {}
    }

    let Some(content_size) = content_size else {
        return Ok(());
    };
    match fcs_size {
        0 => {}
        1 => output.push(content_size as u8)?,
        2 => {
            let v = (content_size - 256) as u16;
            output.extend_from_slice(&v.to_le_bytes())?;
        }
        4 => output.extend_from_slice(&(content_size as u32).to_le_bytes())?,
        _ => output.extend_from_slice(&(content_size as u64).to_le_bytes())?,
    }
    Ok(())
}

fn frame_content_size_field_size(content_size: usize, single_segment: bool) -> usize {
    if single_segment && content_size <= 255 {
        1
    } else if (256..=0xFFFF + 256).contains(&content_size) {
        2
    } else if content_size <= 0xFFFF_FFFF {
        4
    } else {
        8
    }
}

fn window_descriptor_for_log(window_log: u32) -> u8 {
    let window_log = window_log.clamp(strategy::WINDOW_LOG_MIN, strategy::WINDOW_LOG_MAX);
    ((window_log - 10) as u8) << 3
}

pub(crate) fn block_looks_incompressible(data: &[u8]) -> bool {
    const SAMPLE: usize = 1024;
    const DISTINCT_THRESHOLD: u32 = 200;
    const MAX_FREQ_DENOM: u32 = 24;
    if data.len() < SAMPLE {
        return false;
    }
    let mut counts = [0u16; 256];
    for &b in &data[..SAMPLE] {
        counts[b as usize] += 1;
    }
    let mut distinct: u32 = 0;
    let mut max_freq: u16 = 0;
    for &c in &counts {
        distinct += (c > 0) as u32;
        max_freq = max_freq.max(c);
    }
    distinct >= DISTINCT_THRESHOLD && (max_freq as u32) <= SAMPLE as u32 / MAX_FREQ_DENOM
}

pub(crate) fn clamp_params_to_src_size(params: &mut strategy::LevelParams, src_len: usize) {
    params.hash_log = params
        .hash_log
        .clamp(strategy::HASH_LOG_MIN, strategy::HASH_LOG_MAX);
    params.chain_log = params
        .chain_log
        .clamp(strategy::HASH_LOG_MIN, strategy::HASH_LOG_MAX);
    params.window_log = params
        .window_log
        .clamp(strategy::WINDOW_LOG_MIN, strategy::WINDOW_LOG_MAX);
    if src_len >= 2 {
        let src_log = 32 - ((src_len as u32) - 1).leading_zeros();
        params.hash_log = params.hash_log.min(src_log).max(strategy::HASH_LOG_MIN);
        params.chain_log = params.chain_log.min(src_log).max(strategy::HASH_LOG_MIN);
        params.window_log = params.window_log.min(src_log);
    }
}

pub fn compress_with_params(
    input: &[u8],
    params: &strategy::LevelParams,
) -> Result<Vec<u8>, CompressError> {
    let mut params = *params;
    clamp_params_to_src_size(&mut params, input.len());
    compress_inner(input, &params)
}

pub fn compress(input: &[u8], level: i32) -> Result<Vec<u8>, CompressError> {
    let params = strategy::level_params_for_size(level, input.len())
        .ok_or(CompressError::InvalidLevel(level))?;
    compress_inner(input, &params)
}

pub fn compress_opts(
    input: &[u8],
    level: i32,
    opts: &strategy::Options,
) -> Result<Vec<u8>, CompressError> {
    let mut params = strategy::level_params_for_size(level, input.len())
        .ok_or(CompressError::InvalidLevel(level))?;
    strategy::apply_options(&mut params, opts);
    clamp_params_to_src_size(&mut params, input.len());
    compress_inner(input, &params)
}

#[allow(clippy::unnecessary_wraps)]
fn compress_inner(input: &[u8], params: &strategy::LevelParams) -> Result<Vec<u8>, CompressError> {
    let mut params = *params;
    strategy::apply_raw_literals_size_override(&mut params, input.len());
    let mut output = Vec::with_capacity(input.len() + 32);
    compress_frame(input, &params, &mut output)?;
    Ok(output)
}

fn compress_frame(
    input: &[u8],
    params: &strategy::LevelParams,
    output: &mut impl OutputSink,
) -> Result<(), CompressError> {
    write_frame_header(output, input.len(), None, params.window_log)?;

    if input.is_empty() {
        block_encoder::encode_raw_block(&[], true, output)?;
    } else {
        let mut rep_offsets = [1u32, 4, 8];
        let mut offset = 0;
        let mut sequences = Vec::with_capacity(MAX_BLOCK_SIZE / 8);
        let mut workspace = block_encoder::BlockEncodeWorkspace::new();

        #[cfg(feature = "ldm")]
        let mut ldm_state = params.ldm_params.as_ref().map(ldm::LdmState::new);

        match params.strategy {
            Strategy::Fast => {
                let hash_size = 1usize << params.hash_log;
                let mut hash_table = vec![0u32; hash_size];
                while offset < input.len() {
                    let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
                    let block_end = offset + chunk_size;
                    let is_last = block_end >= input.len();
                    let block = &input[offset..block_end];

                    if block_looks_incompressible(block) {
                        block_encoder::encode_raw_block(block, is_last, output)?;
                    } else {
                        #[cfg(feature = "ldm")]
                        let used_ldm = if let Some(ref mut ldm) = ldm_state {
                            let mut empty = Vec::new();
                            ldm.compress_block(
                                input,
                                offset,
                                block_end,
                                params,
                                &rep_offsets,
                                &mut hash_table,
                                &mut empty,
                                &mut sequences,
                            );
                            true
                        } else {
                            false
                        };
                        #[cfg(not(feature = "ldm"))]
                        let used_ldm = false;

                        if !used_ldm {
                            fast::compress_fast_block(
                                input,
                                offset,
                                block_end,
                                params,
                                &rep_offsets,
                                &mut hash_table,
                                &mut sequences,
                            );
                        }
                        if params.force_raw_literals {
                            block_encoder::encode_compressed_block_raw(
                                block,
                                &sequences,
                                &mut rep_offsets,
                                is_last,
                                output,
                                &mut workspace,
                            )?;
                        } else {
                            block_encoder::encode_compressed_block(
                                block,
                                &sequences,
                                &mut rep_offsets,
                                is_last,
                                output,
                                &mut workspace,
                                strategy::use_custom_sequence_tables(params, input.len()),
                            )?;
                        }
                    }
                    offset = block_end;
                }
            }
            Strategy::DFast => {
                let short_size = 1usize << params.chain_log;
                let long_size = 1usize << params.hash_log;
                let mut hash_short = vec![0u32; short_size];
                let mut hash_long = vec![0u32; long_size];
                while offset < input.len() {
                    let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
                    let block_end = offset + chunk_size;
                    let is_last = block_end >= input.len();
                    let block = &input[offset..block_end];

                    if block_looks_incompressible(block) {
                        block_encoder::encode_raw_block(block, is_last, output)?;
                    } else {
                        #[cfg(feature = "ldm")]
                        let used_ldm = if let Some(ref mut ldm) = ldm_state {
                            ldm.compress_block(
                                input,
                                offset,
                                block_end,
                                params,
                                &rep_offsets,
                                &mut hash_short,
                                &mut hash_long,
                                &mut sequences,
                            );
                            true
                        } else {
                            false
                        };
                        #[cfg(not(feature = "ldm"))]
                        let used_ldm = false;

                        if !used_ldm {
                            dfast::compress_dfast_block(
                                input,
                                offset,
                                block_end,
                                params,
                                &rep_offsets,
                                &mut hash_short,
                                &mut hash_long,
                                &mut sequences,
                            );
                        }
                        block_encoder::encode_compressed_block(
                            block,
                            &sequences,
                            &mut rep_offsets,
                            is_last,
                            output,
                            &mut workspace,
                            strategy::use_custom_sequence_tables(params, input.len()),
                        )?;
                    }
                    offset = block_end;
                }
            }
        }
    }

    let hash = xxh64(input, 0);
    let checksum = (hash & 0xFFFF_FFFF) as u32;
    output.extend_from_slice(&checksum.to_le_bytes())?;
    Ok(())
}

pub fn compress_with_dict(
    input: &[u8],
    level: i32,
    dict: &zrip_core::dict::Dictionary,
) -> Result<Vec<u8>, CompressError> {
    let total_window = dict.content().len() + input.len();
    let mut params = strategy::level_params_for_size(level, total_window)
        .ok_or(CompressError::InvalidLevel(level))?;
    strategy::apply_raw_literals_size_override(&mut params, input.len());

    let mut output = Vec::with_capacity(input.len() + 32);
    write_frame_header(&mut output, input.len(), Some(dict.id()), params.window_log)?;

    if input.is_empty() {
        block_encoder::encode_raw_block(&[], true, &mut output)?;
    } else {
        let prefix = dict.content();
        let mut rep_offsets = *dict.rep_offsets();
        let mut workspace = block_encoder::BlockEncodeWorkspace::new();

        workspace.prev_ll = dict
            .ll_table()
            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 35));
        workspace.prev_of = dict
            .of_table()
            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 31));
        workspace.prev_ml = dict
            .ml_table()
            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 52));
        workspace.prev_huffman = dict.huf_table().and_then(|(dt, tl)| {
            zrip_core::huffman::encode::HuffmanEncodeTable::from_decode_table(dt, tl)
        });

        if input.len() <= MAX_BLOCK_SIZE {
            let sequences = match params.strategy {
                Strategy::Fast => {
                    fast::compress_fast_with_prefix(input, &params, &rep_offsets, prefix)
                }
                Strategy::DFast => {
                    dfast::compress_dfast_with_prefix(input, &params, &rep_offsets, prefix)
                }
            };
            if params.force_raw_literals {
                block_encoder::encode_compressed_block_raw(
                    input,
                    &sequences,
                    &mut rep_offsets,
                    true,
                    &mut output,
                    &mut workspace,
                )?;
            } else {
                block_encoder::encode_compressed_block(
                    input,
                    &sequences,
                    &mut rep_offsets,
                    true,
                    &mut output,
                    &mut workspace,
                    strategy::use_custom_sequence_tables(&params, input.len()),
                )?;
            }
        } else {
            let mut combined = Vec::with_capacity(prefix.len() + input.len());
            combined.extend_from_slice(prefix);
            combined.extend_from_slice(input);
            let plen = prefix.len();
            let hash_size = 1usize << params.hash_log;
            let mut sequences = Vec::new();

            match params.strategy {
                Strategy::Fast => {
                    let mut hash_table = vec![0u32; hash_size];
                    fast::prefill_hash_table(&combined, plen, params.hash_log, &mut hash_table);
                    let mut offset = 0;
                    while offset < input.len() {
                        let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
                        let is_last = offset + chunk_size >= input.len();
                        fast::compress_fast_block(
                            &combined,
                            plen + offset,
                            plen + offset + chunk_size,
                            &params,
                            &rep_offsets,
                            &mut hash_table,
                            &mut sequences,
                        );
                        if params.force_raw_literals {
                            block_encoder::encode_compressed_block_raw(
                                &input[offset..offset + chunk_size],
                                &sequences,
                                &mut rep_offsets,
                                is_last,
                                &mut output,
                                &mut workspace,
                            )?;
                        } else {
                            block_encoder::encode_compressed_block(
                                &input[offset..offset + chunk_size],
                                &sequences,
                                &mut rep_offsets,
                                is_last,
                                &mut output,
                                &mut workspace,
                                strategy::use_custom_sequence_tables(&params, input.len()),
                            )?;
                        }
                        offset += chunk_size;
                    }
                }
                Strategy::DFast => {
                    let short_size = 1usize << params.chain_log;
                    let long_size = 1usize << params.hash_log;
                    let mut hash_short = vec![0u32; short_size];
                    let mut hash_long = vec![0u32; long_size];
                    dfast::prefill_hash_tables(
                        &combined,
                        plen,
                        params.hash_log,
                        params.chain_log,
                        params.min_match,
                        &mut hash_short,
                        &mut hash_long,
                    );
                    let mut offset = 0;
                    while offset < input.len() {
                        let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
                        let is_last = offset + chunk_size >= input.len();
                        dfast::compress_dfast_block(
                            &combined,
                            plen + offset,
                            plen + offset + chunk_size,
                            &params,
                            &rep_offsets,
                            &mut hash_short,
                            &mut hash_long,
                            &mut sequences,
                        );
                        block_encoder::encode_compressed_block(
                            &input[offset..offset + chunk_size],
                            &sequences,
                            &mut rep_offsets,
                            is_last,
                            &mut output,
                            &mut workspace,
                            strategy::use_custom_sequence_tables(&params, input.len()),
                        )?;
                        offset += chunk_size;
                    }
                }
            }
        }
    }

    let hash = xxh64(input, 0);
    let checksum = (hash & 0xFFFF_FFFF) as u32;
    output.extend_from_slice(&checksum.to_le_bytes());

    Ok(output)
}

pub fn compress_into(input: &[u8], output: &mut [u8], level: i32) -> Result<usize, CompressError> {
    let mut params = strategy::level_params_for_size(level, input.len())
        .ok_or(CompressError::InvalidLevel(level))?;
    strategy::apply_raw_literals_size_override(&mut params, input.len());
    let mut sink = SliceSink::new(output);
    compress_frame(input, &params, &mut sink)?;
    Ok(sink.pos())
}

#[cfg(test)]
mod tests {
    use super::*;
    use zrip_core::frame::header::parse_frame_header;

    #[test]
    fn clamp_params_normalizes_public_log_values() {
        let mut params = strategy::level_params(1).unwrap();
        params.hash_log = 0;
        params.chain_log = 40;
        params.window_log = 40;

        clamp_params_to_src_size(&mut params, usize::MAX);

        assert_eq!(params.hash_log, strategy::HASH_LOG_MIN);
        assert_eq!(params.chain_log, strategy::HASH_LOG_MAX);
        assert_eq!(params.window_log, strategy::WINDOW_LOG_MAX);
    }

    #[test]
    fn options_clamp_window_log_before_ldm_defaults() {
        let mut params = strategy::level_params(1).unwrap();
        let opts = strategy::Options::default().window_log(0);

        strategy::apply_options(&mut params, &opts);

        assert_eq!(params.window_log, strategy::WINDOW_LOG_MIN);
        #[cfg(feature = "ldm")]
        {
            let mut params = strategy::level_params(1).unwrap();
            let opts = strategy::Options::default().window_log(0).ldm(true);
            strategy::apply_options(&mut params, &opts);

            let ldm = params.ldm_params.unwrap();
            assert!(ldm.hash_log >= ldm.bucket_size_log);
        }
    }

    #[test]
    fn small_plain_frame_uses_single_segment_header() {
        let mut output = Vec::new();

        write_frame_header(&mut output, 12, None, 19).unwrap();
        let header = parse_frame_header(&output).unwrap();

        assert!(header.single_segment);
        assert_eq!(header.frame_content_size, Some(12));
        assert_eq!(header.window_size, 12);
        assert_eq!(header.dict_id, None);
        assert!(header.content_checksum);
        assert_eq!(header.header_size, 6);
    }

    #[test]
    fn large_plain_frame_uses_bounded_window_descriptor() {
        let mut output = Vec::new();
        let content_size = MAX_WINDOW_SIZE as usize + 1;

        write_frame_header(&mut output, content_size, None, 19).unwrap();
        let header = parse_frame_header(&output).unwrap();

        assert!(!header.single_segment);
        assert_eq!(header.frame_content_size, Some(content_size as u64));
        assert_eq!(header.window_size, 1 << 19);
        assert_eq!(header.dict_id, None);
        assert!(header.content_checksum);
        assert_eq!(header.header_size, 10);
    }

    #[test]
    fn dict_frame_uses_window_descriptor_even_when_small() {
        let mut output = Vec::new();

        write_frame_header(&mut output, 12, Some(0x1234), 10).unwrap();
        let header = parse_frame_header(&output).unwrap();

        assert!(!header.single_segment);
        assert_eq!(header.frame_content_size, Some(12));
        assert_eq!(header.window_size, 1 << 10);
        assert_eq!(header.dict_id, Some(0x1234));
        assert!(header.content_checksum);
        assert_eq!(header.header_size, 12);
    }

    #[test]
    fn no_fcs_frame_uses_window_descriptor() {
        let mut output = Vec::new();

        write_frame_header_without_content_size(&mut output, None, 19).unwrap();
        let header = parse_frame_header(&output).unwrap();

        assert!(!header.single_segment);
        assert_eq!(header.frame_content_size, None);
        assert_eq!(header.window_size, 1 << 19);
        assert_eq!(header.dict_id, None);
        assert!(header.content_checksum);
        assert_eq!(header.header_size, 6);
    }
}