Skip to main content

oxabl_cache_format/
segment_plaintext.rs

1//! `OXSP` plaintext of a segment, after decryption.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::frame::VERSION;
6use crate::padme::padme;
7use crate::writer::Writer;
8
9const MAGIC: [u8; 4] = *b"OXSP";
10const HEADER_LEN: usize = 14;
11
12/// How the compressed bytes were produced.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Codec {
15    None,
16    Zstd,
17    ZstdDictionary,
18}
19
20impl Codec {
21    fn to_u8(self) -> u8 {
22        match self {
23            Self::None => 0,
24            Self::Zstd => 1,
25            Self::ZstdDictionary => 2,
26        }
27    }
28
29    fn from_u8(v: u8) -> Result<Self> {
30        match v {
31            0 => Ok(Self::None),
32            1 => Ok(Self::Zstd),
33            2 => Ok(Self::ZstdDictionary),
34            _ => Err(FormatError::Invalid("codec")),
35        }
36    }
37}
38
39/// The plaintext of a segment: a codec and the compressed stream, then zero padding to the
40/// Padmé length of everything before it.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct SegmentPlaintext<'a> {
43    pub codec: Codec,
44    pub compressed: &'a [u8],
45}
46
47impl<'a> SegmentPlaintext<'a> {
48    fn padded_len(compressed_len: usize) -> Result<usize> {
49        let unpadded = (HEADER_LEN as u64)
50            .checked_add(compressed_len as u64)
51            .ok_or(FormatError::Invalid("plaintext length"))?;
52        padme(unpadded)
53            .and_then(|n| usize::try_from(n).ok())
54            .ok_or(FormatError::Invalid("plaintext length"))
55    }
56
57    pub fn encode(&self) -> Result<Vec<u8>> {
58        let padded = Self::padded_len(self.compressed.len())?;
59        let mut w = Writer::with_capacity(padded);
60        w.bytes(&MAGIC);
61        w.u8(VERSION);
62        w.u8(self.codec.to_u8());
63        w.u64(self.compressed.len() as u64);
64        w.bytes(self.compressed);
65        w.zeros(padded - w.len());
66        Ok(w.into_vec())
67    }
68
69    pub fn decode(bytes: &'a [u8]) -> Result<Self> {
70        let mut c = Cursor::new(bytes);
71        if c.array::<4>()? != MAGIC {
72            return Err(FormatError::BadMagic);
73        }
74        let version = c.u8()?;
75        if version != VERSION {
76            return Err(FormatError::UnsupportedVersion(version));
77        }
78        let codec = Codec::from_u8(c.u8()?)?;
79        let len = c.u64()?;
80        let len = usize::try_from(len)
81            .ok()
82            .filter(|&n| n <= c.remaining())
83            .ok_or(FormatError::Truncated)?;
84        let compressed = c.take(len)?;
85        if bytes.len() != Self::padded_len(len)? {
86            return Err(FormatError::Invalid("padding length"));
87        }
88        let padding = c.take(c.remaining())?;
89        if padding.iter().any(|&b| b != 0) {
90            return Err(FormatError::Invalid("padding is not zero"));
91        }
92        Ok(Self { codec, compressed })
93    }
94}