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
//! Reusable slice-to-slice compression workspaces.

use alloc::vec::Vec;
use core::{fmt, marker::PhantomData, mem::MaybeUninit};

use super::{levels::c_port, CompressionLevel};
use crate::workspace::{Arena, ArenaError, ArenaSize, ReusableVec};

use c_port::{
    WorkspaceCctxParameters as CctxParameters, WorkspaceDFastMatchState as DFastMatchState,
    WorkspaceFastMatchState as FastMatchState, WorkspaceFrameBlockState as FrameBlockState,
    WorkspaceGreedyMatchState as GreedyMatchState, WorkspaceLazyBlockStrategy as LazyBlockStrategy,
    WorkspaceLdmWorkspace as LdmWorkspace, WorkspaceOptBlockState as OptBlockState,
    WorkspaceOptFrameStrategy as OptFrameStrategy, WorkspaceParamSwitch as ParamSwitch,
    WorkspaceStrategy as Strategy,
};

/// Errors reported while creating or using an encoder workspace.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EncoderWorkspaceError {
    Capacity(crate::workspace::CapacityError),
    /// A prior encode did not complete. Recreate the context before reuse.
    ContextPoisoned,
    /// Requested strategy would enter an owned-only entropy path.
    UnsupportedWorkspaceConfiguration,
    InsufficientWorkspace { required: usize, provided: usize },
    InputTooLarge { maximum: usize, provided: usize },
    OutputTooSmall { required: usize, provided: usize },
    SizeOverflow,
}

impl fmt::Display for EncoderWorkspaceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Capacity(error) => write!(formatter, "encoder storage admission failed: {error:?}"),
            Self::UnsupportedWorkspaceConfiguration => formatter.write_str("encoder configuration is not supported by caller-backed storage"),
            Self::ContextPoisoned => formatter.write_str("encoder context must be recreated after an incomplete encode"),
            Self::InsufficientWorkspace { required, provided } => write!(
                formatter,
                "encoder workspace needs {required} bytes but only {provided} were provided"
            ),
            Self::InputTooLarge { maximum, provided } => write!(
                formatter,
                "encoder workspace accepts at most {maximum} input bytes but received {provided}"
            ),
            Self::OutputTooSmall { required, provided } => write!(
                formatter,
                "encoded output needs {required} bytes but only {provided} were provided"
            ),
            Self::SizeOverflow => formatter.write_str("encoder workspace size overflowed"),
        }
    }
}

// Boxing a strategy would add a heap allocation to caller-backed contexts;
// the enum deliberately keeps the selected state inline in the arena owner.
#[allow(clippy::large_enum_variant)]
enum MatchWorkspace {
    Uncompressed,
    Fast(FastMatchState),
    DFast(DFastMatchState),
    Greedy {
        state: GreedyMatchState,
        depth: LazyBlockStrategy,
    },
    Opt {
        state: OptBlockState,
        strategy: OptFrameStrategy,
    },
}

impl From<crate::workspace::CapacityError> for EncoderWorkspaceError {
    fn from(error: crate::workspace::CapacityError) -> Self { Self::Capacity(error) }
}

struct EncoderCore {
    // Set before any codec mutation and cleared only after complete success.
    // This also survives caught unwinds: taken scratch cannot silently become
    // an owned default buffer on a later sensitive operation.
    poisoned: bool,
    level: i32,
    maximum_input: usize,
    base_cctx: CctxParameters,
    frame: FrameBlockState,
    matcher: MatchWorkspace,
    ldm: Option<LdmWorkspace>,
}

impl EncoderCore {
    fn add_size(
        size: &mut ArenaSize,
        level: i32,
        maximum_input: usize,
    ) -> Result<CctxParameters, EncoderWorkspaceError> {
        let cctx = CctxParameters::for_level(level, maximum_input as u64, 0);
        FrameBlockState::add_workspace_size(size).map_err(map_arena)?;
        let block_size = crate::common::MAX_BLOCK_SIZE as usize;
        if level == 0 {
            return Ok(cctx);
        }
        match cctx.compression.strategy {
            Strategy::Fast => {
                FastMatchState::add_workspace_size(size, cctx.compression, block_size)
                    .map_err(map_arena)?;
            }
            Strategy::DFast => {
                DFastMatchState::add_workspace_size(size, cctx.compression, block_size)
                    .map_err(map_arena)?;
            }
            Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 | Strategy::BtLazy2 => {
                GreedyMatchState::add_workspace_size(size, cctx.compression, block_size)
                    .map_err(map_arena)?;
            }
            Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
                OptBlockState::add_workspace_size(size, cctx.compression, block_size)
                    .map_err(map_arena)?;
            }
        }
        if cctx.ldm.enable_ldm == ParamSwitch::Enable {
            LdmWorkspace::add_workspace_size(size, cctx.ldm, maximum_input).map_err(map_arena)?;
        }
        Ok(cctx)
    }

    fn new_in(
        arena: &mut Arena<'_>,
        level: i32,
        maximum_input: usize,
        cctx: CctxParameters,
    ) -> Result<Self, EncoderWorkspaceError> {
        let block_size = crate::common::MAX_BLOCK_SIZE as usize;
        let frame = FrameBlockState::new_in(arena, cctx.compression, cctx.max_block_size)
            .map_err(map_arena)?;
        let matcher = if level == 0 {
            MatchWorkspace::Uncompressed
        } else {
            match cctx.compression.strategy {
                Strategy::Fast => MatchWorkspace::Fast(
                    FastMatchState::new_in(arena, cctx.compression, block_size)
                        .map_err(map_arena)?,
                ),
                Strategy::DFast => MatchWorkspace::DFast(
                    DFastMatchState::new_in(arena, cctx.compression, block_size)
                        .map_err(map_arena)?,
                ),
                strategy @ (Strategy::Greedy
                | Strategy::Lazy
                | Strategy::Lazy2
                | Strategy::BtLazy2) => MatchWorkspace::Greedy {
                    state: GreedyMatchState::new_in(arena, cctx.compression, block_size)
                        .map_err(map_arena)?,
                    depth: match strategy {
                        Strategy::Greedy => LazyBlockStrategy::Greedy,
                        Strategy::Lazy => LazyBlockStrategy::Lazy,
                        Strategy::Lazy2 => LazyBlockStrategy::Lazy2,
                        Strategy::BtLazy2 => LazyBlockStrategy::BtLazy2,
                        _ => unreachable!(),
                    },
                },
                strategy @ (Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2) => {
                    MatchWorkspace::Opt {
                        state: OptBlockState::new_in(arena, cctx.compression, block_size)
                            .map_err(map_arena)?,
                        strategy: match strategy {
                            Strategy::BtOpt => OptFrameStrategy::BtOpt,
                            Strategy::BtUltra => OptFrameStrategy::BtUltra,
                            Strategy::BtUltra2 => OptFrameStrategy::BtUltra2,
                            _ => unreachable!(),
                        },
                    }
                }
            }
        };
        let ldm = if cctx.ldm.enable_ldm == ParamSwitch::Enable {
            Some(LdmWorkspace::new_in(arena, cctx.ldm, maximum_input).map_err(map_arena)?)
        } else {
            None
        };
        Ok(Self {
            poisoned: false,
            level,
            maximum_input,
            base_cctx: cctx,
            frame,
            matcher,
            ldm,
        })
    }

    fn encode_into<'output>(
        &mut self,
        input: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output [u8], EncoderWorkspaceError> {
        if self.poisoned { return Err(EncoderWorkspaceError::ContextPoisoned); }
        if input.len() > self.maximum_input {
            return Err(EncoderWorkspaceError::InputTooLarge {
                maximum: self.maximum_input,
                provided: input.len(),
            });
        }
        let required = checked_output_size(input.len())?;
        if output.len() < required {
            return Err(EncoderWorkspaceError::OutputTooSmall {
                required,
                provided: output.len(),
            });
        }
        self.poisoned = true;
        let cctx = CctxParameters::from_compression_parameters(
            self.level,
            self.base_cctx.compression,
            input.len() as u64,
        );
        // Target mode uses owned clone-based alternatives. Static encoding
        // currently never requests it; refuse a future accidental routing change.
        if cctx.target_c_block_size != 0
            || !FrameBlockState::supports_workspace_entropy(cctx.compression)
        {
            return Err(EncoderWorkspaceError::UnsupportedWorkspaceConfiguration);
        }
        // SAFETY: the guarded facade never owns caller storage, including on
        // early exit. Every growth is admitted before writes by the fixed-capacity
        // facade; caller storage cannot be reallocated even if sizing is wrong.
        let reusable = unsafe { ReusableVec::from_static_parts(output.as_mut_ptr(), output.len()) };
        let (mut output_vec, lease) = reusable.lease_vec();
        let ldm = &mut self.ldm;
        match &mut self.matcher {
            MatchWorkspace::Uncompressed => encode_uncompressed(input, &mut output_vec),
            MatchWorkspace::Fast(state) => {
                c_port::workspace_encode_fast(input, cctx, &mut self.frame, state, &mut output_vec)
            }
            MatchWorkspace::DFast(state) => {
                c_port::workspace_encode_dfast(input, cctx, &mut self.frame, state, &mut output_vec)
            }
            MatchWorkspace::Greedy { state, depth } => c_port::workspace_encode_greedy(
                input,
                cctx,
                *depth,
                &mut self.frame,
                state,
                &mut output_vec,
            ),
            MatchWorkspace::Opt { state, strategy } => c_port::workspace_encode_opt(
                input,
                cctx,
                *strategy,
                &mut self.frame,
                state,
                ldm.as_mut(),
                &mut output_vec,
            ),
        }?;
        let length = output_vec.len();
        let reusable = ReusableVec::recover_vec(output_vec, lease);
        drop(reusable);
        self.poisoned = false;
        Ok(&output[..length])
    }
}

fn encode_uncompressed(input: &[u8], output: &mut impl crate::workspace::Growable<u8>) -> Result<(), crate::workspace::CapacityError> {
    use crate::{
        blocks::block::BlockType,
        encoding::{block_header::BlockHeader, frame_header::FrameHeader},
    };
    output.clear();
    FrameHeader {
        frame_content_size: Some(input.len() as u64),
        single_segment: true,
        content_checksum: false,
        dictionary_id: None,
        window_size: None,
    }
    .serialize(output)?;
    if input.is_empty() {
        BlockHeader {
            last_block: true,
            block_type: BlockType::Raw,
            block_size: 0,
        }
        .serialize(output)?;
        return Ok(());
    }
    let block_size = crate::common::MAX_BLOCK_SIZE as usize;
    for (index, block) in input.chunks(block_size).enumerate() {
        BlockHeader {
            last_block: (index + 1) * block_size >= input.len(),
            block_type: BlockType::Raw,
            block_size: block.len() as u32,
        }
        .serialize(output)?;
        output.extend_from_slice(block)?;
    }
    Ok(())
}

/// An owned compression workspace reusable without further allocation.
pub struct EncoderWorkspace {
    core: EncoderCore,
    storage: Vec<MaybeUninit<u8>>,
}

impl EncoderWorkspace {
    pub fn new(
        level: CompressionLevel,
        maximum_input: usize,
    ) -> Result<Self, EncoderWorkspaceError> {
        let required = Self::required_size(level, maximum_input)?;
        let mut storage = Vec::with_capacity(required);
        storage.resize_with(required, MaybeUninit::uninit);
        let mut arena = Arena::new(&mut storage);
        let mut size = ArenaSize::new();
        let cctx = EncoderCore::add_size(&mut size, level.get(), maximum_input)?;
        let core = EncoderCore::new_in(&mut arena, level.get(), maximum_input, cctx)?;
        Ok(Self { core, storage })
    }

    pub fn required_size(
        level: CompressionLevel,
        maximum_input: usize,
    ) -> Result<usize, EncoderWorkspaceError> {
        let mut size = ArenaSize::new();
        EncoderCore::add_size(&mut size, level.get(), maximum_input)?;
        Ok(size.finish())
    }

    pub fn required_output_size(maximum_input: usize) -> Result<usize, EncoderWorkspaceError> {
        checked_output_size(maximum_input)
    }

    pub fn encode_into<'output>(
        &mut self,
        input: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output [u8], EncoderWorkspaceError> {
        self.core.encode_into(input, output)
    }

    pub fn workspace_bytes(&self) -> usize {
        self.storage.len()
    }

    pub const fn maximum_input(&self) -> usize {
        self.core.maximum_input
    }
}

#[cfg(feature = "std")]
impl std::error::Error for EncoderWorkspaceError {}

/// A compression context whose working state lives entirely in caller storage.
pub struct StaticEncoderWorkspace<'storage> {
    core: EncoderCore,
    workspace_bytes: usize,
    marker: PhantomData<&'storage mut [MaybeUninit<u8>]>,
}

impl<'storage> StaticEncoderWorkspace<'storage> {
    pub fn new(
        storage: &'storage mut [u8],
        level: CompressionLevel,
        maximum_input: usize,
    ) -> Result<Self, EncoderWorkspaceError> {
        Self::new_uninit(initialized_bytes_as_uninit(storage), level, maximum_input)
    }

    /// Constructs a workspace without initializing caller-provided bytes.
    pub fn new_uninit(
        storage: &'storage mut [MaybeUninit<u8>],
        level: CompressionLevel,
        maximum_input: usize,
    ) -> Result<Self, EncoderWorkspaceError> {
        let required = EncoderWorkspace::required_size(level, maximum_input)?;
        if storage.len() < required {
            return Err(EncoderWorkspaceError::InsufficientWorkspace {
                required,
                provided: storage.len(),
            });
        }
        let mut size = ArenaSize::new();
        let cctx = EncoderCore::add_size(&mut size, level.get(), maximum_input)?;
        let mut arena = Arena::new(storage);
        let core = EncoderCore::new_in(&mut arena, level.get(), maximum_input, cctx)?;
        Ok(Self {
            core,
            workspace_bytes: storage.len(),
            marker: PhantomData,
        })
    }

    pub fn encode_into<'output>(
        &mut self,
        input: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output [u8], EncoderWorkspaceError> {
        self.core.encode_into(input, output)
    }

    pub const fn maximum_input(&self) -> usize {
        self.core.maximum_input
    }

    pub const fn workspace_bytes(&self) -> usize {
        self.workspace_bytes
    }
}

fn initialized_bytes_as_uninit(storage: &mut [u8]) -> &mut [MaybeUninit<u8>] {
    // SAFETY: `MaybeUninit<u8>` has the same layout as `u8`, and treating
    // initialized bytes as possibly uninitialized only weakens the invariant.
    unsafe { core::slice::from_raw_parts_mut(storage.as_mut_ptr().cast(), storage.len()) }
}

fn map_arena(error: ArenaError) -> EncoderWorkspaceError {
    match error {
        ArenaError::Capacity(error) => EncoderWorkspaceError::Capacity(error),
        ArenaError::InsufficientStorage { required, provided } => {
            EncoderWorkspaceError::InsufficientWorkspace { required, provided }
        }
        ArenaError::CapacityExceeded { .. } | ArenaError::SizeOverflow => {
            EncoderWorkspaceError::SizeOverflow
        }
    }
}

fn checked_output_size(input_size: usize) -> Result<usize, EncoderWorkspaceError> {
    let bound = c_port::workspace_compress_bound(input_size);
    if bound == 0 {
        Err(EncoderWorkspaceError::SizeOverflow)
    } else {
        Ok(bound)
    }
}