zstd-complete 0.3.0

A pure Rust Zstandard compressor and decompressor with bounded streaming I/O
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
//! Optimal-parser price model ported from the no-dictionary path in
//! `zstd_opt.c`.

use super::hash_chain_match::highbit32;
use crate::encoding::blocks::{literal_length_code, match_length_code};

mod weights;

use weights::{
    downscale_stats, literal_length_code_transition, price_delta, scale_stats, sum, weight,
};

const BITCOST_ACCURACY: u32 = 8;
pub(super) const BITCOST_MULTIPLIER: u32 = 1 << BITCOST_ACCURACY;
pub(super) const ZSTD_MAX_PRICE: i32 = 1 << 30;
const ZSTD_BLOCKSIZE_MAX: u32 = 128 * 1024;
const ZSTD_PREDEF_THRESHOLD: usize = 8;
const ZSTD_LITFREQ_ADD: u32 = 2;
const MINMATCH: u32 = 3;

const MAX_LL: usize = 35;
const MAX_ML: usize = 52;
const MAX_OFF: usize = 31;
const MAX_LIT: usize = 255;

const LL_BITS: [u8; MAX_LL + 1] = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11,
    12, 13, 14, 15, 16,
];

const ML_BITS: [u8; MAX_ML + 1] = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
];

const BASE_LL_FREQS: [u32; MAX_LL + 1] = [
    4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1,
];

const BASE_OFF_FREQS: [u32; MAX_OFF + 1] = [
    6, 2, 1, 1, 2, 3, 4, 4, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
];

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum OptLevel {
    BtOpt,
    BtUltra,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PriceType {
    Predefined,
    Dynamic,
}

#[derive(Clone, Debug)]
pub(crate) struct DictionaryPriceSeeds {
    lit_freq: [u32; MAX_LIT + 1],
    lit_length_freq: [u32; MAX_LL + 1],
    match_length_freq: [u32; MAX_ML + 1],
    off_code_freq: [u32; MAX_OFF + 1],
}

impl DictionaryPriceSeeds {
    pub(crate) const LITERAL_COUNT: usize = MAX_LIT + 1;
    pub(crate) const LIT_LENGTH_COUNT: usize = MAX_LL + 1;
    pub(crate) const MATCH_LENGTH_COUNT: usize = MAX_ML + 1;
    pub(crate) const OFF_CODE_COUNT: usize = MAX_OFF + 1;

    pub(crate) fn new() -> Self {
        Self {
            lit_freq: [0; MAX_LIT + 1],
            lit_length_freq: [0; MAX_LL + 1],
            match_length_freq: [0; MAX_ML + 1],
            off_code_freq: [0; MAX_OFF + 1],
        }
    }

    pub(crate) fn set_literal_freq(&mut self, symbol: usize, freq: u32) {
        self.lit_freq[symbol] = freq;
    }

    pub(crate) fn set_lit_length_freq(&mut self, symbol: usize, freq: u32) {
        self.lit_length_freq[symbol] = freq;
    }

    pub(crate) fn set_match_length_freq(&mut self, symbol: usize, freq: u32) {
        self.match_length_freq[symbol] = freq;
    }

    pub(crate) fn set_off_code_freq(&mut self, symbol: usize, freq: u32) {
        self.off_code_freq[symbol] = freq;
    }
}

#[derive(Clone, Debug)]
pub(super) struct OptPriceState {
    lit_freq: [u32; MAX_LIT + 1],
    lit_length_freq: [u32; MAX_LL + 1],
    match_length_freq: [u32; MAX_ML + 1],
    off_code_freq: [u32; MAX_OFF + 1],
    lit_sum: u32,
    lit_length_sum: u32,
    match_length_sum: u32,
    off_code_sum: u32,
    lit_sum_base_price: u32,
    lit_price_max: u32,
    lit_length_sum_base_price: u32,
    match_length_sum_base_price: u32,
    off_code_sum_base_price: u32,
    price_type: PriceType,
    compressed_literals: bool,
    dictionary_seeds: Option<DictionaryPriceSeeds>,
}

impl OptPriceState {
    pub(super) fn new() -> Self {
        Self {
            lit_freq: [0; MAX_LIT + 1],
            lit_length_freq: [0; MAX_LL + 1],
            match_length_freq: [0; MAX_ML + 1],
            off_code_freq: [0; MAX_OFF + 1],
            lit_sum: 0,
            lit_length_sum: 0,
            match_length_sum: 0,
            off_code_sum: 0,
            lit_sum_base_price: 0,
            lit_price_max: 0,
            lit_length_sum_base_price: 0,
            match_length_sum_base_price: 0,
            off_code_sum_base_price: 0,
            price_type: PriceType::Dynamic,
            compressed_literals: true,
            dictionary_seeds: None,
        }
    }

    pub(super) fn set_dictionary_seeds(&mut self, seeds: DictionaryPriceSeeds) {
        self.dictionary_seeds = Some(seeds);
    }

    pub(super) fn reset_for_frame(&mut self) {
        self.lit_sum = 0;
        self.lit_length_sum = 0;
        self.match_length_sum = 0;
        self.off_code_sum = 0;
        self.lit_sum_base_price = 0;
        self.lit_price_max = 0;
        self.lit_length_sum_base_price = 0;
        self.match_length_sum_base_price = 0;
        self.off_code_sum_base_price = 0;
        self.price_type = PriceType::Dynamic;
        self.compressed_literals = true;
    }

    pub(super) fn rescale_freqs(&mut self, src: &[u8], opt_level: OptLevel) {
        self.price_type = PriceType::Dynamic;

        if self.lit_length_sum == 0 {
            if src.len() <= ZSTD_PREDEF_THRESHOLD {
                self.price_type = PriceType::Predefined;
            }

            if let Some(seeds) = self.dictionary_seeds.take() {
                self.price_type = PriceType::Dynamic;
                self.apply_dictionary_seeds(&seeds);
            } else {
                if self.compressed_literals {
                    self.lit_freq = [0; MAX_LIT + 1];
                    for &literal in src {
                        self.lit_freq[literal as usize] += 1;
                    }
                    self.lit_sum = downscale_stats(&mut self.lit_freq, 8, false);
                }

                self.lit_length_freq = BASE_LL_FREQS;
                self.lit_length_sum = sum(&self.lit_length_freq);
                self.match_length_freq = [1; MAX_ML + 1];
                self.match_length_sum = (MAX_ML + 1) as u32;
                self.off_code_freq = BASE_OFF_FREQS;
                self.off_code_sum = sum(&self.off_code_freq);
            }
        } else {
            if self.compressed_literals {
                self.lit_sum = scale_stats(&mut self.lit_freq, 12);
            }
            self.lit_length_sum = scale_stats(&mut self.lit_length_freq, 11);
            self.match_length_sum = scale_stats(&mut self.match_length_freq, 11);
            self.off_code_sum = scale_stats(&mut self.off_code_freq, 11);
        }

        self.set_base_prices(opt_level);
    }

    fn apply_dictionary_seeds(&mut self, seeds: &DictionaryPriceSeeds) {
        if self.compressed_literals {
            self.lit_freq = seeds.lit_freq;
            self.lit_sum = sum(&self.lit_freq);
        }
        self.lit_length_freq = seeds.lit_length_freq;
        self.lit_length_sum = sum(&self.lit_length_freq);
        self.match_length_freq = seeds.match_length_freq;
        self.match_length_sum = sum(&self.match_length_freq);
        self.off_code_freq = seeds.off_code_freq;
        self.off_code_sum = sum(&self.off_code_freq);
    }

    pub(super) fn raw_literals_cost(&self, literals: &[u8], opt_level: OptLevel) -> u32 {
        if literals.is_empty() {
            return 0;
        }

        if !self.compressed_literals {
            return ((literals.len() as u32) << 3) * BITCOST_MULTIPLIER;
        }

        if self.price_type == PriceType::Predefined {
            return (literals.len() as u32 * 6) * BITCOST_MULTIPLIER;
        }

        let mut price = self.lit_sum_base_price * literals.len() as u32;
        for &literal in literals {
            let lit_price =
                weight(self.lit_freq[literal as usize], opt_level).min(self.lit_price_max);
            price -= lit_price;
        }
        price
    }

    #[inline(always)]
    pub(super) fn raw_literal_cost(&self, literal: u8, opt_level: OptLevel) -> u32 {
        if !self.compressed_literals {
            return 8 * BITCOST_MULTIPLIER;
        }

        if self.price_type == PriceType::Predefined {
            return 6 * BITCOST_MULTIPLIER;
        }

        self.lit_sum_base_price
            - weight(self.lit_freq[literal as usize], opt_level).min(self.lit_price_max)
    }

    #[inline(always)]
    pub(super) fn dynamic_raw_literal_cost(&self, literal: u8, opt_level: OptLevel) -> u32 {
        debug_assert!(self.compressed_literals);
        debug_assert_eq!(self.price_type, PriceType::Dynamic);

        self.lit_sum_base_price
            - weight(self.lit_freq[literal as usize], opt_level).min(self.lit_price_max)
    }

    #[inline(always)]
    pub(super) fn lit_length_price(&self, lit_length: u32, opt_level: OptLevel) -> u32 {
        debug_assert!(lit_length <= ZSTD_BLOCKSIZE_MAX);
        if self.price_type == PriceType::Predefined {
            return weight(lit_length, opt_level);
        }

        self.dynamic_lit_length_price(lit_length, opt_level)
    }

    #[inline(always)]
    pub(super) fn dynamic_lit_length_price(&self, lit_length: u32, opt_level: OptLevel) -> u32 {
        debug_assert!(lit_length <= ZSTD_BLOCKSIZE_MAX);
        debug_assert_eq!(self.price_type, PriceType::Dynamic);

        if lit_length == ZSTD_BLOCKSIZE_MAX {
            return BITCOST_MULTIPLIER
                + self.dynamic_lit_length_price(ZSTD_BLOCKSIZE_MAX - 1, opt_level);
        }

        let ll_code = literal_length_code(lit_length) as usize;
        u32::from(LL_BITS[ll_code]) * BITCOST_MULTIPLIER + self.lit_length_sum_base_price
            - weight(self.lit_length_freq[ll_code], opt_level)
    }

    #[inline(always)]
    pub(super) fn lit_length_increment_price(&self, lit_length: u32, opt_level: OptLevel) -> i32 {
        debug_assert!(lit_length > 0);
        debug_assert!(lit_length <= ZSTD_BLOCKSIZE_MAX);

        if self.price_type == PriceType::Predefined {
            return price_delta(
                weight(lit_length, opt_level),
                weight(lit_length - 1, opt_level),
            );
        }

        self.dynamic_lit_length_increment_price(lit_length, opt_level)
    }

    #[inline(always)]
    pub(super) fn dynamic_lit_length_increment_price(
        &self,
        lit_length: u32,
        opt_level: OptLevel,
    ) -> i32 {
        debug_assert!(lit_length > 0);
        debug_assert!(lit_length <= ZSTD_BLOCKSIZE_MAX);
        debug_assert_eq!(self.price_type, PriceType::Dynamic);

        self.dynamic_lit_length_increment_price_unchecked(lit_length, opt_level)
    }

    #[inline(always)]
    fn dynamic_lit_length_increment_price_unchecked(
        &self,
        lit_length: u32,
        opt_level: OptLevel,
    ) -> i32 {
        if lit_length == ZSTD_BLOCKSIZE_MAX {
            return BITCOST_MULTIPLIER as i32;
        }

        if lit_length <= 15 {
            let ll_code = lit_length as usize;
            return price_delta(
                weight(self.lit_length_freq[ll_code - 1], opt_level),
                weight(self.lit_length_freq[ll_code], opt_level),
            );
        }

        if lit_length == 16 {
            return self.dynamic_lit_length_code_delta(15, 16, opt_level);
        }

        let Some((previous_code, ll_code)) = literal_length_code_transition(lit_length) else {
            return 0;
        };

        self.dynamic_lit_length_code_delta(previous_code, ll_code, opt_level)
    }

    #[inline(always)]
    fn dynamic_lit_length_code_delta(
        &self,
        previous_code: usize,
        ll_code: usize,
        opt_level: OptLevel,
    ) -> i32 {
        let price = u32::from(LL_BITS[ll_code]) * BITCOST_MULTIPLIER
            + self.lit_length_sum_base_price
            - weight(self.lit_length_freq[ll_code], opt_level);
        let previous_price = u32::from(LL_BITS[previous_code]) * BITCOST_MULTIPLIER
            + self.lit_length_sum_base_price
            - weight(self.lit_length_freq[previous_code], opt_level);
        price_delta(price, previous_price)
    }

    #[inline(always)]
    pub(super) fn match_price(&self, off_base: u32, match_length: u32, opt_level: OptLevel) -> u32 {
        self.match_offset_price(off_base, opt_level)
            + self.match_length_price(match_length, opt_level)
    }

    #[inline(always)]
    pub(super) fn match_offset_price(&self, off_base: u32, opt_level: OptLevel) -> u32 {
        let off_code = highbit32(off_base);

        if self.price_type == PriceType::Predefined {
            return (16 + off_code) * BITCOST_MULTIPLIER;
        }

        self.dynamic_match_offset_price_from_code(off_code, opt_level)
    }

    #[inline(always)]
    pub(super) fn dynamic_match_offset_price(&self, off_base: u32, opt_level: OptLevel) -> u32 {
        debug_assert_eq!(self.price_type, PriceType::Dynamic);
        let off_code = highbit32(off_base);
        self.dynamic_match_offset_price_from_code(off_code, opt_level)
    }

    #[inline(always)]
    fn dynamic_match_offset_price_from_code(&self, off_code: u32, opt_level: OptLevel) -> u32 {
        let mut price = off_code * BITCOST_MULTIPLIER + self.off_code_sum_base_price
            - weight(self.off_code_freq[off_code as usize], opt_level);
        if opt_level.favors_small_offsets() && off_code >= 20 {
            price += (off_code - 19) * 2 * BITCOST_MULTIPLIER;
        }

        price
    }

    #[inline(always)]
    pub(super) fn match_length_price(&self, match_length: u32, opt_level: OptLevel) -> u32 {
        debug_assert!(match_length >= MINMATCH);
        let ml_base = match_length - MINMATCH;

        if self.price_type == PriceType::Predefined {
            return weight(ml_base, opt_level);
        }

        self.dynamic_match_length_price_from_base(ml_base, opt_level)
    }

    #[inline(always)]
    pub(super) fn dynamic_match_length_price(&self, match_length: u32, opt_level: OptLevel) -> u32 {
        debug_assert!(match_length >= MINMATCH);
        debug_assert_eq!(self.price_type, PriceType::Dynamic);
        let ml_base = match_length - MINMATCH;
        self.dynamic_match_length_price_from_base(ml_base, opt_level)
    }

    #[inline(always)]
    fn dynamic_match_length_price_from_base(&self, ml_base: u32, opt_level: OptLevel) -> u32 {
        let match_length = ml_base + MINMATCH;
        let ml_code = match_length_code(match_length) as usize;
        u32::from(ML_BITS[ml_code]) * BITCOST_MULTIPLIER + self.match_length_sum_base_price
            - weight(self.match_length_freq[ml_code], opt_level)
            + BITCOST_MULTIPLIER / 5
    }

    pub(super) fn update_stats(
        &mut self,
        lit_length: u32,
        literals: &[u8],
        off_base: u32,
        match_length: u32,
    ) {
        debug_assert!(literals.len() >= lit_length as usize);

        if self.compressed_literals && lit_length != 0 {
            for &literal in &literals[..lit_length as usize] {
                self.lit_freq[literal as usize] += ZSTD_LITFREQ_ADD;
            }
            self.lit_sum += lit_length * ZSTD_LITFREQ_ADD;
        }

        let ll_code = literal_length_code(lit_length) as usize;
        self.lit_length_freq[ll_code] += 1;
        self.lit_length_sum += 1;

        let off_code = highbit32(off_base) as usize;
        self.off_code_freq[off_code] += 1;
        self.off_code_sum += 1;

        let ml_code = match_length_code(match_length) as usize;
        self.match_length_freq[ml_code] += 1;
        self.match_length_sum += 1;
    }

    #[inline(always)]
    pub(super) fn refresh_base_prices(&mut self, opt_level: OptLevel) {
        self.set_base_prices(opt_level);
    }

    #[cfg(test)]
    pub(super) fn frequency_snapshot(
        &self,
        ll_code: usize,
        ml_code: usize,
        off_code: usize,
    ) -> (u32, u32, u32) {
        (
            self.lit_length_freq[ll_code],
            self.match_length_freq[ml_code],
            self.off_code_freq[off_code],
        )
    }

    #[inline(always)]
    fn set_base_prices(&mut self, opt_level: OptLevel) {
        if self.compressed_literals {
            self.lit_sum_base_price = weight(self.lit_sum, opt_level);
            self.lit_price_max = self.lit_sum_base_price - BITCOST_MULTIPLIER;
        }
        self.lit_length_sum_base_price = weight(self.lit_length_sum, opt_level);
        self.match_length_sum_base_price = weight(self.match_length_sum, opt_level);
        self.off_code_sum_base_price = weight(self.off_code_sum, opt_level);
    }
}