Skip to main content

embark_codec/
codec.rs

1//! Named, zero-sized handles for the built-in codecs.
2//!
3//! Each codec compiled into the build (gated by its own cargo feature) has a
4//! unit struct here — [`Store`], [`Deflate`], [`Lz4`], [`Snappy`], [`Zstd`],
5//! [`Lzma`] — carrying inherent `compress`/`decompress` methods and an
6//! [`Codec::ID`] naming its on-binary [`CodecId`]. They are a direct-call
7//! entry point into the same code [`crate::compress`] and
8//! [`crate::decompress`] reach through `CodecId` dispatch, for callers who
9//! already know which codec they want.
10//!
11//! [`Codec`] is sealed: it exists to associate a type with its on-binary id,
12//! not as an extension point. The on-binary format spends four bits on the
13//! codec id and `embark-format` assigns every accepted value to a built-in,
14//! so a third-party codec has no id it could occupy, nothing would ever
15//! decode it, and `#[derive(Embed)]` / `embed_bytes!` select a codec by
16//! `CodecId` at compile time and so can never name one.
17
18extern crate alloc;
19#[cfg(any(feature = "enc", feature = "dec"))]
20use alloc::vec::Vec;
21use embark_format::CodecId;
22#[cfg(feature = "dec")]
23use embark_format::Error;
24
25mod sealed {
26    pub trait Sealed {}
27}
28
29/// Associates a built-in codec type with its on-binary [`CodecId`].
30///
31/// This trait is sealed and cannot be implemented outside this crate. The
32/// codec id is a fixed four-bit field of the embedded entry header with no
33/// values left over, so there is no id a downstream codec could claim and no
34/// path by which the derive macros or [`crate::decompress`] could reach one.
35/// Compression itself lives on inherent methods of each codec type, so
36/// calling `Deflate.compress(..)` does not require this trait in scope.
37pub trait Codec: sealed::Sealed {
38    /// The on-binary [`CodecId`] this codec corresponds to.
39    const ID: CodecId;
40}
41
42/// The identity codec: stores bytes unchanged.
43#[derive(Debug)]
44pub struct Store;
45
46impl sealed::Sealed for Store {}
47
48impl Codec for Store {
49    const ID: CodecId = CodecId::Store;
50}
51
52impl Store {
53    /// Compress `input`.
54    #[cfg(feature = "enc")]
55    #[must_use]
56    pub fn compress(&self, input: &[u8]) -> Vec<u8> {
57        crate::store::compress(input)
58    }
59
60    /// Decompress `input`, which must expand to exactly `orig_len` bytes.
61    ///
62    /// # Errors
63    ///
64    /// Returns [`Error::Corrupt`] if `input` is not exactly `orig_len`
65    /// bytes long. Nothing else can go wrong: there is no encoding to
66    /// misparse.
67    #[cfg(feature = "dec")]
68    pub fn decompress(&self, input: &[u8], orig_len: usize) -> Result<Vec<u8>, Error> {
69        crate::store::decompress(input, orig_len)
70    }
71}
72
73/// The DEFLATE codec (via `miniz_oxide`).
74#[cfg(feature = "deflate")]
75#[derive(Debug)]
76pub struct Deflate;
77
78#[cfg(feature = "deflate")]
79impl sealed::Sealed for Deflate {}
80
81#[cfg(feature = "deflate")]
82impl Codec for Deflate {
83    const ID: CodecId = CodecId::Deflate;
84}
85
86#[cfg(feature = "deflate")]
87impl Deflate {
88    /// Compress `input`.
89    #[cfg(feature = "enc")]
90    #[must_use]
91    pub fn compress(&self, input: &[u8]) -> Vec<u8> {
92        crate::deflate::compress(input)
93    }
94
95    /// Decompress `input`, which must expand to exactly `orig_len` bytes.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`Error::Corrupt`] if `input` is not a valid raw DEFLATE
100    /// stream, if it expands to a length other than `orig_len`, or if
101    /// `orig_len` is more than this target can allocate.
102    #[cfg(feature = "dec")]
103    pub fn decompress(&self, input: &[u8], orig_len: usize) -> Result<Vec<u8>, Error> {
104        crate::deflate::decompress(input, orig_len)
105    }
106}
107
108/// The LZ4 codec (via `lz4_flex`).
109#[cfg(feature = "lz4")]
110#[derive(Debug)]
111pub struct Lz4;
112
113#[cfg(feature = "lz4")]
114impl sealed::Sealed for Lz4 {}
115
116#[cfg(feature = "lz4")]
117impl Codec for Lz4 {
118    const ID: CodecId = CodecId::Lz4;
119}
120
121#[cfg(feature = "lz4")]
122impl Lz4 {
123    /// Compress `input`.
124    #[cfg(feature = "enc")]
125    #[must_use]
126    pub fn compress(&self, input: &[u8]) -> Vec<u8> {
127        crate::lz4::compress(input)
128    }
129
130    /// Decompress `input`, which must expand to exactly `orig_len` bytes.
131    ///
132    /// # Errors
133    ///
134    /// Returns [`Error::Corrupt`] if `input` is not a valid LZ4 block, if it
135    /// expands to a length other than `orig_len`, or if `orig_len` is more
136    /// than this target can allocate.
137    #[cfg(feature = "dec")]
138    pub fn decompress(&self, input: &[u8], orig_len: usize) -> Result<Vec<u8>, Error> {
139        crate::lz4::decompress(input, orig_len)
140    }
141}
142
143/// The Snappy codec (self-implemented).
144#[cfg(feature = "snappy")]
145#[derive(Debug)]
146pub struct Snappy;
147
148#[cfg(feature = "snappy")]
149impl sealed::Sealed for Snappy {}
150
151#[cfg(feature = "snappy")]
152impl Codec for Snappy {
153    const ID: CodecId = CodecId::Snappy;
154}
155
156#[cfg(feature = "snappy")]
157impl Snappy {
158    /// Compress `input`.
159    #[cfg(feature = "enc")]
160    #[must_use]
161    pub fn compress(&self, input: &[u8]) -> Vec<u8> {
162        crate::snappy::compress(input)
163    }
164
165    /// Decompress `input`, which must expand to exactly `orig_len` bytes.
166    ///
167    /// # Errors
168    ///
169    /// Returns [`Error::Truncated`] if the block ends mid-tag, and
170    /// [`Error::Corrupt`] if a tag is malformed, if the length preamble or
171    /// the decoded output disagrees with `orig_len`, or if `orig_len` is
172    /// more than this target can allocate.
173    #[cfg(feature = "dec")]
174    pub fn decompress(&self, input: &[u8], orig_len: usize) -> Result<Vec<u8>, Error> {
175        crate::snappy::decompress(input, orig_len)
176    }
177}
178
179/// The Zstd codec: a self-written encoder, decoding via `ruzstd`.
180#[cfg(feature = "zstd")]
181#[derive(Debug)]
182pub struct Zstd;
183
184#[cfg(feature = "zstd")]
185impl sealed::Sealed for Zstd {}
186
187#[cfg(feature = "zstd")]
188impl Codec for Zstd {
189    const ID: CodecId = CodecId::Zstd;
190}
191
192#[cfg(feature = "zstd")]
193impl Zstd {
194    /// Compress `input`.
195    #[cfg(feature = "enc")]
196    #[must_use]
197    pub fn compress(&self, input: &[u8]) -> Vec<u8> {
198        crate::zstd::compress(input)
199    }
200
201    /// Decompress `input`, which must expand to exactly `orig_len` bytes.
202    ///
203    /// # Errors
204    ///
205    /// Returns [`Error::Corrupt`] if `input` is not a valid zstd frame, if it
206    /// expands to a length other than `orig_len`, or if `orig_len` is more
207    /// than this target can allocate.
208    #[cfg(feature = "dec")]
209    pub fn decompress(&self, input: &[u8], orig_len: usize) -> Result<Vec<u8>, Error> {
210        crate::zstd::decompress(input, orig_len)
211    }
212}
213
214/// The LZMA1 codec (self-implemented `.lzma` alone format).
215#[cfg(feature = "lzma")]
216#[derive(Debug)]
217pub struct Lzma;
218
219#[cfg(feature = "lzma")]
220impl sealed::Sealed for Lzma {}
221
222#[cfg(feature = "lzma")]
223impl Codec for Lzma {
224    const ID: CodecId = CodecId::Lzma;
225}
226
227#[cfg(feature = "lzma")]
228impl Lzma {
229    /// Compress `input`.
230    #[cfg(feature = "enc")]
231    #[must_use]
232    pub fn compress(&self, input: &[u8]) -> Vec<u8> {
233        crate::lzma::compress(input)
234    }
235
236    /// Decompress `input`, which must expand to exactly `orig_len` bytes.
237    ///
238    /// # Errors
239    ///
240    /// Returns [`Error::Truncated`] if the stream ends mid-symbol, and
241    /// [`Error::Corrupt`] if the `.lzma` header is malformed, if the size it
242    /// records or the decoded output disagrees with `orig_len`, or if
243    /// `orig_len` is more than this target can allocate.
244    #[cfg(feature = "dec")]
245    pub fn decompress(&self, input: &[u8], orig_len: usize) -> Result<Vec<u8>, Error> {
246        crate::lzma::decompress(input, orig_len)
247    }
248}
249
250#[cfg(all(test, feature = "enc", feature = "dec"))]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn store_roundtrips_via_handle() {
256        let data = b"handle roundtrip via Store";
257        let c = Store.compress(data);
258        assert_eq!(Store.decompress(&c, data.len()).unwrap(), data);
259        assert_eq!(Store::ID, CodecId::Store);
260    }
261
262    #[cfg(feature = "deflate")]
263    #[test]
264    fn deflate_roundtrips_via_handle() {
265        let data = b"handle roundtrip via Deflate handle roundtrip via Deflate".repeat(4);
266        let c = Deflate.compress(&data);
267        assert_eq!(Deflate.decompress(&c, data.len()).unwrap(), data);
268        assert_eq!(Deflate::ID, CodecId::Deflate);
269    }
270}