Skip to main content

lz4rip_encode/
compressor.rs

1use core::fmt;
2
3use alloc::vec::Vec;
4
5use crate::compress::CompressorRef;
6use lz4rip_core::CompressError;
7
8/// A reusable block compressor that owns its dictionary.
9///
10/// This is the ergonomic API for use with `alloc`. For a no-alloc variant that
11/// borrows the dictionary, see [`CompressorRef`].
12///
13/// For one-shot compression, use [`compress`](crate::compress) or
14/// [`compress_into`](crate::compress_into) instead.
15///
16/// # Example
17/// ```
18/// use lz4rip_encode::{Compressor, get_maximum_output_size};
19///
20/// let mut comp = Compressor::new();
21/// let input = b"hello world, hello world, hello!";
22/// let mut output = vec![0u8; get_maximum_output_size(input.len())];
23/// let compressed_len = comp.compress_into(input, &mut output).unwrap();
24/// ```
25pub struct Compressor {
26    // SAFETY invariants (self-referential struct):
27    //   `inner` may hold a `&[u8]` fabricated via `from_raw_parts` pointing
28    //   into `dict`'s heap buffer. Sound because:
29    //   1. `inner` is declared before `dict` → dropped first (Rust field order).
30    //   2. `dict` is private and never reallocated after construction.
31    //   3. `CompressorRef` has no Drop impl that accesses the slice.
32    //   4. No Clone/Copy impl exists. Cloning would copy the Vec (new alloc)
33    //      but `inner` would still point at the original buffer → UB on drop.
34    //   5. No method exposes `inner` by value or mutates `dict`.
35    inner: CompressorRef<'static>,
36    #[allow(dead_code)]
37    dict: Vec<u8>,
38}
39
40impl fmt::Debug for Compressor {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        f.debug_struct("Compressor")
43            .field("dict_len", &self.dict.len())
44            .finish()
45    }
46}
47
48impl Compressor {
49    /// Create a new compressor without a dictionary.
50    pub fn new() -> Self {
51        Compressor {
52            inner: CompressorRef::new(),
53            dict: Vec::new(),
54        }
55    }
56
57    /// Create a new compressor seeded with an external dictionary.
58    ///
59    /// The dictionary is cloned into owned storage.
60    /// If `dict` is shorter than 4 bytes, it is ignored.
61    pub fn with_dict(dict: &[u8]) -> Self {
62        let dict = dict.to_vec();
63        // SAFETY: We create a &'static [u8] pointing into `dict`'s heap buffer.
64        // Sound because `dict` is stored in self, never reallocated, and `inner`
65        // (which holds the reference) is dropped before `dict` per field order.
66        let dict_ref: &'static [u8] =
67            unsafe { core::slice::from_raw_parts(dict.as_ptr(), dict.len()) };
68        Compressor {
69            inner: CompressorRef::with_dict(dict_ref),
70            dict,
71        }
72    }
73
74    /// Compress `input` into `output`, returning the number of compressed bytes.
75    ///
76    /// `output` must be at least [`get_maximum_output_size`]`(input.len())` bytes.
77    pub fn compress_into(
78        &mut self,
79        input: &[u8],
80        output: &mut [u8],
81    ) -> Result<usize, CompressError> {
82        self.inner.compress_into(input, output)
83    }
84
85    /// Compress `input` into a new `Vec<u8>`.
86    pub fn compress(&mut self, input: &[u8]) -> Vec<u8> {
87        self.inner.compress(input)
88    }
89}
90
91impl Default for Compressor {
92    fn default() -> Self {
93        Self::new()
94    }
95}