Skip to main content

zrip_encode/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![cfg_attr(feature = "nightly", feature(optimize_attribute))]
3#![cfg_attr(feature = "paranoid", forbid(unsafe_code))]
4
5#[cfg(feature = "alloc")]
6extern crate alloc;
7
8pub(crate) mod block_encoder;
9#[cfg(feature = "std")]
10pub mod context;
11pub(crate) mod dfast;
12pub(crate) mod fast;
13#[cfg(feature = "ldm")]
14pub(crate) mod ldm;
15pub(crate) mod primitives;
16pub(crate) mod sequences;
17pub mod strategy;
18#[cfg(feature = "std")]
19pub mod streaming;
20
21#[cfg(feature = "alloc")]
22use alloc::vec;
23#[cfg(feature = "alloc")]
24use alloc::vec::Vec;
25
26use crate::strategy::Strategy;
27use zrip_core::error::CompressError;
28use zrip_core::frame::{MAX_BLOCK_SIZE, ZSTD_MAGIC};
29use zrip_core::xxhash::xxh64;
30
31pub(crate) fn write_frame_header(output: &mut Vec<u8>, content_size: usize, dict_id: Option<u32>) {
32    output.extend_from_slice(&ZSTD_MAGIC.to_le_bytes());
33
34    let fcs_size = if content_size <= 255 {
35        1
36    } else if content_size <= 0xFFFF + 256 {
37        2
38    } else if content_size <= 0xFFFF_FFFF {
39        4
40    } else {
41        8
42    };
43    let fcs_flag: u8 = match fcs_size {
44        1 => 0,
45        2 => 1,
46        4 => 2,
47        _ => 3,
48    };
49
50    let dict_id_flag: u8 = match dict_id {
51        None => 0,
52        Some(id) if id <= 0xFF => 1,
53        Some(id) if id <= 0xFFFF => 2,
54        Some(_) => 3,
55    };
56
57    let descriptor = 0x20 | 0x04 | (fcs_flag << 6) | dict_id_flag;
58    output.push(descriptor);
59
60    match dict_id {
61        Some(id) if id <= 0xFF => output.push(id as u8),
62        Some(id) if id <= 0xFFFF => output.extend_from_slice(&(id as u16).to_le_bytes()),
63        Some(id) => output.extend_from_slice(&id.to_le_bytes()),
64        None => {}
65    }
66
67    match fcs_size {
68        1 => output.push(content_size as u8),
69        2 => {
70            let v = (content_size - 256) as u16;
71            output.extend_from_slice(&v.to_le_bytes());
72        }
73        4 => output.extend_from_slice(&(content_size as u32).to_le_bytes()),
74        _ => output.extend_from_slice(&(content_size as u64).to_le_bytes()),
75    }
76}
77
78pub(crate) fn block_looks_incompressible(data: &[u8]) -> bool {
79    const SAMPLE: usize = 1024;
80    const DISTINCT_THRESHOLD: u32 = 200;
81    const MAX_FREQ_DENOM: u32 = 24;
82    if data.len() < SAMPLE {
83        return false;
84    }
85    let mut counts = [0u16; 256];
86    for &b in &data[..SAMPLE] {
87        counts[b as usize] += 1;
88    }
89    let mut distinct: u32 = 0;
90    let mut max_freq: u16 = 0;
91    for &c in &counts {
92        distinct += (c > 0) as u32;
93        max_freq = max_freq.max(c);
94    }
95    distinct >= DISTINCT_THRESHOLD && (max_freq as u32) <= SAMPLE as u32 / MAX_FREQ_DENOM
96}
97
98pub(crate) fn clamp_params_to_src_size(params: &mut strategy::LevelParams, src_len: usize) {
99    params.hash_log = params
100        .hash_log
101        .clamp(strategy::HASH_LOG_MIN, strategy::HASH_LOG_MAX);
102    params.chain_log = params
103        .chain_log
104        .clamp(strategy::HASH_LOG_MIN, strategy::HASH_LOG_MAX);
105    if src_len >= 2 {
106        let src_log = 32 - ((src_len as u32) - 1).leading_zeros();
107        params.hash_log = params.hash_log.min(src_log).max(strategy::HASH_LOG_MIN);
108        params.chain_log = params.chain_log.min(src_log).max(strategy::HASH_LOG_MIN);
109        params.window_log = params.window_log.min(src_log);
110    }
111}
112
113pub fn compress_with_params(
114    input: &[u8],
115    params: &strategy::LevelParams,
116) -> Result<Vec<u8>, CompressError> {
117    let mut params = *params;
118    clamp_params_to_src_size(&mut params, input.len());
119    compress_inner(input, &params)
120}
121
122pub fn compress(input: &[u8], level: i32) -> Result<Vec<u8>, CompressError> {
123    let params = strategy::level_params_for_size(level, input.len())
124        .ok_or(CompressError::InvalidLevel(level))?;
125    compress_inner(input, &params)
126}
127
128pub fn compress_opts(
129    input: &[u8],
130    level: i32,
131    opts: &strategy::Options,
132) -> Result<Vec<u8>, CompressError> {
133    let mut params = strategy::level_params_for_size(level, input.len())
134        .ok_or(CompressError::InvalidLevel(level))?;
135    strategy::apply_options(&mut params, opts);
136    compress_inner(input, &params)
137}
138
139#[allow(clippy::unnecessary_wraps)]
140fn compress_inner(input: &[u8], params: &strategy::LevelParams) -> Result<Vec<u8>, CompressError> {
141    let mut params = *params;
142    strategy::apply_raw_literals_size_override(&mut params, input.len());
143    let mut output = Vec::with_capacity(input.len() + 32);
144    compress_frame(input, &params, &mut output);
145    Ok(output)
146}
147
148fn compress_frame(input: &[u8], params: &strategy::LevelParams, output: &mut Vec<u8>) {
149    write_frame_header(output, input.len(), None);
150
151    if input.is_empty() {
152        block_encoder::encode_raw_block(&[], true, output);
153    } else {
154        let mut rep_offsets = [1u32, 4, 8];
155        let mut offset = 0;
156        let mut sequences = Vec::with_capacity(MAX_BLOCK_SIZE / 8);
157        let mut workspace = block_encoder::BlockEncodeWorkspace::new();
158
159        #[cfg(feature = "ldm")]
160        let mut ldm_state = params.ldm_params.as_ref().map(ldm::LdmState::new);
161
162        match params.strategy {
163            Strategy::Fast => {
164                let hash_size = 1usize << params.hash_log;
165                let mut hash_table = vec![0u32; hash_size];
166                while offset < input.len() {
167                    let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
168                    let block_end = offset + chunk_size;
169                    let is_last = block_end >= input.len();
170
171                    if block_looks_incompressible(&input[offset..block_end]) {
172                        block_encoder::encode_raw_block(&input[offset..block_end], is_last, output);
173                    } else {
174                        #[cfg(feature = "ldm")]
175                        let used_ldm = if let Some(ref mut ldm) = ldm_state {
176                            let mut empty = Vec::new();
177                            ldm.compress_block(
178                                input,
179                                offset,
180                                block_end,
181                                params,
182                                &rep_offsets,
183                                &mut hash_table,
184                                &mut empty,
185                                &mut sequences,
186                            );
187                            true
188                        } else {
189                            false
190                        };
191                        #[cfg(not(feature = "ldm"))]
192                        let used_ldm = false;
193
194                        if !used_ldm {
195                            fast::compress_fast_block(
196                                input,
197                                offset,
198                                block_end,
199                                params,
200                                &rep_offsets,
201                                &mut hash_table,
202                                &mut sequences,
203                            );
204                        }
205                        if params.force_raw_literals {
206                            block_encoder::encode_compressed_block_raw(
207                                &input[offset..block_end],
208                                &sequences,
209                                &mut rep_offsets,
210                                is_last,
211                                output,
212                                &mut workspace,
213                            );
214                        } else {
215                            block_encoder::encode_compressed_block(
216                                &input[offset..block_end],
217                                &sequences,
218                                &mut rep_offsets,
219                                is_last,
220                                output,
221                                &mut workspace,
222                            );
223                        }
224                    }
225                    offset = block_end;
226                }
227            }
228            Strategy::DFast => {
229                let short_size = 1usize << params.chain_log;
230                let long_size = 1usize << params.hash_log;
231                let mut hash_short = vec![0u32; short_size];
232                let mut hash_long = vec![0u32; long_size];
233                while offset < input.len() {
234                    let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
235                    let block_end = offset + chunk_size;
236                    let is_last = block_end >= input.len();
237
238                    if block_looks_incompressible(&input[offset..block_end]) {
239                        block_encoder::encode_raw_block(&input[offset..block_end], is_last, output);
240                    } else {
241                        #[cfg(feature = "ldm")]
242                        let used_ldm = if let Some(ref mut ldm) = ldm_state {
243                            ldm.compress_block(
244                                input,
245                                offset,
246                                block_end,
247                                params,
248                                &rep_offsets,
249                                &mut hash_short,
250                                &mut hash_long,
251                                &mut sequences,
252                            );
253                            true
254                        } else {
255                            false
256                        };
257                        #[cfg(not(feature = "ldm"))]
258                        let used_ldm = false;
259
260                        if !used_ldm {
261                            dfast::compress_dfast_block(
262                                input,
263                                offset,
264                                block_end,
265                                params,
266                                &rep_offsets,
267                                &mut hash_short,
268                                &mut hash_long,
269                                &mut sequences,
270                            );
271                        }
272                        block_encoder::encode_compressed_block(
273                            &input[offset..block_end],
274                            &sequences,
275                            &mut rep_offsets,
276                            is_last,
277                            output,
278                            &mut workspace,
279                        );
280                    }
281                    offset = block_end;
282                }
283            }
284        }
285    }
286
287    let hash = xxh64(input, 0);
288    let checksum = (hash & 0xFFFF_FFFF) as u32;
289    output.extend_from_slice(&checksum.to_le_bytes());
290}
291
292pub fn compress_with_dict(
293    input: &[u8],
294    level: i32,
295    dict: &zrip_core::dict::Dictionary,
296) -> Result<Vec<u8>, CompressError> {
297    let total_window = dict.content().len() + input.len();
298    let mut params = strategy::level_params_for_size(level, total_window)
299        .ok_or(CompressError::InvalidLevel(level))?;
300    strategy::apply_raw_literals_size_override(&mut params, input.len());
301
302    let mut output = Vec::with_capacity(input.len() + 32);
303    write_frame_header(&mut output, input.len(), Some(dict.id()));
304
305    if input.is_empty() {
306        block_encoder::encode_raw_block(&[], true, &mut output);
307    } else {
308        let prefix = dict.content();
309        let mut rep_offsets = *dict.rep_offsets();
310        let mut workspace = block_encoder::BlockEncodeWorkspace::new();
311
312        workspace.prev_ll = dict
313            .ll_table()
314            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 35));
315        workspace.prev_of = dict
316            .of_table()
317            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 31));
318        workspace.prev_ml = dict
319            .ml_table()
320            .map(|(dt, al)| block_encoder::FseEncodeTable::from_decode_table(dt, al, 52));
321        workspace.prev_huffman = dict.huf_table().and_then(|(dt, tl)| {
322            zrip_core::huffman::encode::HuffmanEncodeTable::from_decode_table(dt, tl)
323        });
324
325        if input.len() <= MAX_BLOCK_SIZE {
326            let sequences = match params.strategy {
327                Strategy::Fast => {
328                    fast::compress_fast_with_prefix(input, &params, &rep_offsets, prefix)
329                }
330                Strategy::DFast => {
331                    dfast::compress_dfast_with_prefix(input, &params, &rep_offsets, prefix)
332                }
333            };
334            if params.force_raw_literals {
335                block_encoder::encode_compressed_block_raw(
336                    input,
337                    &sequences,
338                    &mut rep_offsets,
339                    true,
340                    &mut output,
341                    &mut workspace,
342                );
343            } else {
344                block_encoder::encode_compressed_block(
345                    input,
346                    &sequences,
347                    &mut rep_offsets,
348                    true,
349                    &mut output,
350                    &mut workspace,
351                );
352            }
353        } else {
354            let mut combined = Vec::with_capacity(prefix.len() + input.len());
355            combined.extend_from_slice(prefix);
356            combined.extend_from_slice(input);
357            let plen = prefix.len();
358            let hash_size = 1usize << params.hash_log;
359            let mut sequences = Vec::new();
360
361            match params.strategy {
362                Strategy::Fast => {
363                    let mut hash_table = vec![0u32; hash_size];
364                    fast::prefill_hash_table(&combined, plen, params.hash_log, &mut hash_table);
365                    let mut offset = 0;
366                    while offset < input.len() {
367                        let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
368                        let is_last = offset + chunk_size >= input.len();
369                        fast::compress_fast_block(
370                            &combined,
371                            plen + offset,
372                            plen + offset + chunk_size,
373                            &params,
374                            &rep_offsets,
375                            &mut hash_table,
376                            &mut sequences,
377                        );
378                        if params.force_raw_literals {
379                            block_encoder::encode_compressed_block_raw(
380                                &input[offset..offset + chunk_size],
381                                &sequences,
382                                &mut rep_offsets,
383                                is_last,
384                                &mut output,
385                                &mut workspace,
386                            );
387                        } else {
388                            block_encoder::encode_compressed_block(
389                                &input[offset..offset + chunk_size],
390                                &sequences,
391                                &mut rep_offsets,
392                                is_last,
393                                &mut output,
394                                &mut workspace,
395                            );
396                        }
397                        offset += chunk_size;
398                    }
399                }
400                Strategy::DFast => {
401                    let short_size = 1usize << params.chain_log;
402                    let long_size = 1usize << params.hash_log;
403                    let mut hash_short = vec![0u32; short_size];
404                    let mut hash_long = vec![0u32; long_size];
405                    dfast::prefill_hash_tables(
406                        &combined,
407                        plen,
408                        params.hash_log,
409                        params.chain_log,
410                        params.min_match,
411                        &mut hash_short,
412                        &mut hash_long,
413                    );
414                    let mut offset = 0;
415                    while offset < input.len() {
416                        let chunk_size = (input.len() - offset).min(MAX_BLOCK_SIZE);
417                        let is_last = offset + chunk_size >= input.len();
418                        dfast::compress_dfast_block(
419                            &combined,
420                            plen + offset,
421                            plen + offset + chunk_size,
422                            &params,
423                            &rep_offsets,
424                            &mut hash_short,
425                            &mut hash_long,
426                            &mut sequences,
427                        );
428                        block_encoder::encode_compressed_block(
429                            &input[offset..offset + chunk_size],
430                            &sequences,
431                            &mut rep_offsets,
432                            is_last,
433                            &mut output,
434                            &mut workspace,
435                        );
436                        offset += chunk_size;
437                    }
438                }
439            }
440        }
441    }
442
443    let hash = xxh64(input, 0);
444    let checksum = (hash & 0xFFFF_FFFF) as u32;
445    output.extend_from_slice(&checksum.to_le_bytes());
446
447    Ok(output)
448}
449
450pub fn compress_into(input: &[u8], output: &mut [u8], level: i32) -> Result<usize, CompressError> {
451    let mut params = strategy::level_params_for_size(level, input.len())
452        .ok_or(CompressError::InvalidLevel(level))?;
453    strategy::apply_raw_literals_size_override(&mut params, input.len());
454    let mut buf = Vec::with_capacity(output.len());
455    compress_frame(input, &params, &mut buf);
456    if buf.len() > output.len() {
457        return Err(CompressError::OutputTooSmall);
458    }
459    output[..buf.len()].copy_from_slice(&buf);
460    Ok(buf.len())
461}
462
463#[cfg(all(test, miri, not(feature = "paranoid")))]
464mod ub_tests {
465    use super::*;
466
467    #[test]
468    fn public_compress_with_params_accepts_zero_hash_log() {
469        // Issue: LevelParams is public and compress_with_params only clamps log
470        // values downward for the input size. A caller can pass hash_log = 0,
471        // which allocates a one-entry hash table, while release-mode hash shifts
472        // produce indexes derived from the input bytes. The first hash_load then
473        // reaches get_unchecked with an out-of-bounds index.
474        let mut params = strategy::level_params(1).unwrap();
475        params.hash_log = 0;
476        params.chain_log = 0;
477        let _ = compress_with_params(b"abcdefghijklmnop", &params);
478    }
479}