Skip to main content

craft_codec/
codec.rs

1use crate::{Config, Error, FrameSizes, FrameSpec, Metadata, Result};
2use crate::{compression::CompressionState, crypto::EncryptionState};
3
4/// Synchronous frame encoder constructed entirely from metadata with reusable codec storage.
5///
6/// The caller owns the frame index and must never encrypt different payloads
7/// with the same key/index. Use a fresh key for each immutable object. This
8/// type performs no I/O, scheduling, implicit indexing, or retries.
9pub struct Encoder {
10    config: Config,
11    compression: CompressionState,
12    encryption: EncryptionState,
13}
14
15impl TryFrom<&Metadata> for Encoder {
16    type Error = Error;
17
18    fn try_from(metadata: &Metadata) -> Result<Self> {
19        let config = metadata.config().clone();
20        Ok(Self {
21            compression: CompressionState::new(config.compression())?,
22            encryption: EncryptionState::new(config.encryption())?,
23            config,
24        })
25    }
26}
27
28impl TryFrom<Metadata> for Encoder {
29    type Error = Error;
30
31    fn try_from(metadata: Metadata) -> Result<Self> {
32        Self::try_from(&metadata)
33    }
34}
35
36impl Encoder {
37    /// Replace raw bytes with stored bytes, returning lengths to append to metadata.
38    /// Empty/oversized frames and out-of-policy indices are refused.
39    /// On any error the buffer is cleared, but its allocation is retained.
40    ///
41    /// This does not append metadata: the caller does that after successful I/O.
42    /// The metadata builder enforces that a short fixed frame is the last frame.
43    pub fn encode_frame(&mut self, index: u64, buffer: &mut Vec<u8>) -> Result<FrameSizes> {
44        let result = self.encode_inner(index, buffer);
45        if result.is_err() {
46            buffer.clear();
47        }
48        result
49    }
50
51    fn encode_inner(&mut self, index: u64, buffer: &mut Vec<u8>) -> Result<FrameSizes> {
52        let raw = buffer.len() as u64;
53        self.config.validate_frame(index, raw, raw)?;
54        self.compression.encode(buffer)?;
55        let payload = buffer.len() as u64;
56        self.encryption.seal(index, buffer)?;
57        Ok(FrameSizes { raw, payload })
58    }
59}
60
61/// Synchronous frame decoder. It knows no logical ranges or I/O offsets.
62/// Authentication precedes decompression. Reuse one instance and the caller's
63/// buffer to amortize allocations. Compression may swap the buffer allocation.
64pub struct Decoder {
65    config: Config,
66    compression: CompressionState,
67    encryption: EncryptionState,
68}
69
70impl TryFrom<&Metadata> for Decoder {
71    type Error = Error;
72
73    fn try_from(metadata: &Metadata) -> Result<Self> {
74        let config = metadata.config().clone();
75        Ok(Self {
76            compression: CompressionState::new(config.compression())?,
77            encryption: EncryptionState::new(config.encryption())?,
78            config,
79        })
80    }
81}
82
83impl TryFrom<Metadata> for Decoder {
84    type Error = Error;
85
86    fn try_from(metadata: Metadata) -> Result<Self> {
87        Self::try_from(&metadata)
88    }
89}
90
91impl Decoder {
92    /// Replace one complete stored frame with its complete decoded bytes.
93    /// On failure the buffer is cleared. No unauthenticated bytes are returned.
94    /// Clearing the buffer is not a promise to zero its allocation or scratch.
95    pub fn decode_frame(&mut self, spec: FrameSpec, buffer: &mut Vec<u8>) -> Result<()> {
96        let result = self.decode_inner(spec, buffer);
97        if result.is_err() {
98            buffer.clear();
99        }
100        result
101    }
102
103    fn decode_inner(&mut self, spec: FrameSpec, buffer: &mut Vec<u8>) -> Result<()> {
104        if spec.config != self.config {
105            return Err(Error::ProfileMismatch);
106        }
107        if buffer.len() != spec.stored_len() {
108            return Err(Error::InvalidStoredLength);
109        }
110        self.encryption.open(spec.index(), buffer)?;
111        if spec.payload_len() < spec.raw_len() {
112            self.compression.decode(buffer, spec.raw_len())?;
113        }
114        if buffer.len() != spec.raw_len() {
115            return Err(Error::DecompressionFailed);
116        }
117        Ok(())
118    }
119}