Skip to main content

oxabl_cache_crypto/
dictionary_seal.rs

1//! A dictionary travels as a segment whose plaintext is the raw dictionary with codec none.
2
3use std::io::Write;
4
5use oxabl_cache_format::{Codec, SegmentId, SegmentPlaintext};
6
7use crate::dictionary::{Dictionary, MAX_DICTIONARY_BYTES};
8use crate::error::{Error, Result};
9use crate::keys::SegmentKey;
10use crate::segment_info::SegmentSeal;
11use crate::segment_open::{decrypt_segment, verify_id};
12use crate::segment_seal::seal_compressed;
13
14/// Seals a raw dictionary as a dictionary-kind segment.
15pub fn seal_dictionary(
16    key: &SegmentKey,
17    dictionary: &[u8],
18    out: impl Write,
19) -> Result<SegmentSeal> {
20    if dictionary.is_empty() || dictionary.len() > MAX_DICTIONARY_BYTES {
21        return Err(Error::Limit("dictionary size"));
22    }
23    seal_compressed(key, Codec::None, dictionary, out)
24}
25
26/// Verifies `sealed` against the signed dictionary id, opens it and prepares the dictionary
27/// for compression at `level`.
28pub fn open_dictionary(
29    key: &SegmentKey,
30    sealed: &[u8],
31    id: &SegmentId,
32    level: i32,
33) -> Result<Dictionary> {
34    verify_id(sealed, id)?;
35    let plaintext = decrypt_segment(key, sealed)?;
36    let body = SegmentPlaintext::decode(&plaintext)?;
37    if body.codec != Codec::None {
38        return Err(Error::Mismatch("not a dictionary segment"));
39    }
40    Dictionary::new(*id, body.compressed.to_vec(), level)
41}