oxabl_cache_crypto/
dictionary.rs1use oxabl_cache_format::SegmentId;
4use zeroize::Zeroizing;
5use zstd::dict::{DecoderDictionary, EncoderDictionary};
6
7use crate::error::{Error, Result};
8
9pub const DEFAULT_DICTIONARY_BYTES: usize = 112 * 1024;
11pub const MAX_DICTIONARY_BYTES: usize = 8 * 1024 * 1024;
13
14pub struct Dictionary {
17 id: SegmentId,
18 bytes: Zeroizing<Vec<u8>>,
19 encoder: EncoderDictionary<'static>,
20 decoder: DecoderDictionary<'static>,
21}
22
23impl Dictionary {
24 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 pub fn id(&self) -> SegmentId {
40 self.id
41 }
42
43 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
63pub 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}