Skip to main content

oxabl_cache_crypto/
dictionary.rs

1//! Trained zstd dictionaries.
2
3use oxabl_cache_format::SegmentId;
4use zeroize::Zeroizing;
5use zstd::dict::{DecoderDictionary, EncoderDictionary};
6
7use crate::error::{Error, Result};
8
9/// Size of a dictionary that `train` produces unless told otherwise.
10pub const DEFAULT_DICTIONARY_BYTES: usize = 112 * 1024;
11/// Largest dictionary a reader accepts.
12pub const MAX_DICTIONARY_BYTES: usize = 8 * 1024 * 1024;
13
14/// A dictionary ready for compression and decompression, named by the id of the sealed
15/// dictionary segment that carries it.
16pub struct Dictionary {
17    id: SegmentId,
18    bytes: Zeroizing<Vec<u8>>,
19    encoder: EncoderDictionary<'static>,
20    decoder: DecoderDictionary<'static>,
21}
22
23impl Dictionary {
24    /// Prepares `bytes` for compression at `level` and for decompression.
25    pub fn new(id: SegmentId, bytes: Vec<u8>, level: i32) -> Result<Self> {
26        let bytes = Zeroizing::new(bytes);
27        if bytes.is_empty() || bytes.len() > MAX_DICTIONARY_BYTES {
28            return Err(Error::Limit("dictionary size"));
29        }
30        Ok(Self {
31            id,
32            encoder: EncoderDictionary::copy(&bytes, level),
33            decoder: DecoderDictionary::copy(&bytes),
34            bytes,
35        })
36    }
37
38    /// Id of the sealed segment that carries this dictionary.
39    pub fn id(&self) -> SegmentId {
40        self.id
41    }
42
43    /// The raw dictionary.
44    pub fn as_bytes(&self) -> &[u8] {
45        &self.bytes
46    }
47
48    pub(crate) fn encoder(&self) -> &EncoderDictionary<'static> {
49        &self.encoder
50    }
51
52    pub(crate) fn decoder(&self) -> &DecoderDictionary<'static> {
53        &self.decoder
54    }
55}
56
57impl std::fmt::Debug for Dictionary {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        write!(f, "Dictionary({})", self.id)
60    }
61}
62
63/// Trains a dictionary of at most `max_size` bytes from sample artifact sets.
64pub fn train<S: AsRef<[u8]>>(samples: &[S], max_size: usize) -> Result<Vec<u8>> {
65    if max_size == 0 || max_size > MAX_DICTIONARY_BYTES {
66        return Err(Error::Limit("dictionary size"));
67    }
68    zstd::dict::from_samples(samples, max_size)
69        .map_err(|_| Error::Compression("dictionary training failed"))
70}