Skip to main content

embark_format/
ids.rs

1use crate::{Error, Result};
2
3/// Names the compression applied to an entry's payload.
4///
5/// Stored in the low nibble of an entry's first byte, so the format admits
6/// at most sixteen codecs and every id below is permanently assigned. Which
7/// of them a given build can actually *use* is a separate question, decided
8/// by `embark-codec`'s cargo features: an id naming a codec that was not
9/// compiled in parses fine here and fails at decompression time with
10/// [`Error::UnknownCodec`].
11///
12/// `#[non_exhaustive]`: this list has already grown from two variants to
13/// six and the format has room for ten more, so match it with a wildcard
14/// arm that reports [`Error::UnknownCodec`] rather than one that silently
15/// picks a default.
16#[non_exhaustive]
17#[repr(u8)]
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum CodecId {
20    /// No compression: the payload is the original bytes verbatim.
21    ///
22    /// Also the fallback the build-time encoders pick whenever the chosen
23    /// codec would have made the file larger.
24    Store = 0,
25    /// Raw DEFLATE (RFC 1951), with no zlib or gzip wrapper.
26    Deflate = 1,
27    /// LZ4 block format, without the frame header.
28    Lz4 = 2,
29    /// Snappy block format, including its length preamble.
30    Snappy = 3,
31    /// Zstandard, as a complete single-frame stream.
32    Zstd = 4,
33    /// LZMA1 in the `.lzma` "alone" container, header included.
34    Lzma = 5,
35}
36
37impl CodecId {
38    /// The byte written to the low nibble of an entry's tag byte.
39    #[must_use]
40    pub fn as_u8(self) -> u8 {
41        self as u8
42    }
43
44    /// Reads a codec id back out of an entry's tag byte.
45    ///
46    /// # Errors
47    ///
48    /// Returns [`Error::UnknownCodec`] if `v` is not an assigned id. Entry
49    /// bytes are untrusted input, so this is an ordinary runtime outcome
50    /// rather than a sign of a bug.
51    pub fn from_u8(v: u8) -> Result<CodecId> {
52        match v {
53            0 => Ok(CodecId::Store),
54            1 => Ok(CodecId::Deflate),
55            2 => Ok(CodecId::Lz4),
56            3 => Ok(CodecId::Snappy),
57            4 => Ok(CodecId::Zstd),
58            5 => Ok(CodecId::Lzma),
59            other => Err(Error::UnknownCodec(other)),
60        }
61    }
62}
63
64/// Names the AEAD cipher an entry's payload was sealed with, if any.
65///
66/// Stored in the high nibble of an entry's first byte. Any id other than
67/// [`None`](CryptoId::None) also means the header carries a 12-byte nonce
68/// and a 16-byte authentication tag between the length varint and the
69/// payload; both built-in ciphers share that shape.
70///
71/// `#[non_exhaustive]`: this list has already grown from two variants to
72/// three, so match it with a wildcard arm that reports
73/// [`Error::UnknownCrypto`] rather than one that treats an unrecognized
74/// cipher as no cipher at all.
75#[non_exhaustive]
76#[repr(u8)]
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum CryptoId {
79    /// The payload is not encrypted, and the header carries no nonce or tag.
80    None = 0,
81    /// ChaCha20-Poly1305 (RFC 8439), the default cipher.
82    ChaCha20Poly1305 = 1,
83    /// AES-256-GCM, available where hardware acceleration makes it the
84    /// faster choice.
85    Aes256Gcm = 2,
86}
87
88impl CryptoId {
89    /// The byte written to the high nibble of an entry's tag byte.
90    #[must_use]
91    pub fn as_u8(self) -> u8 {
92        self as u8
93    }
94
95    /// Reads a crypto id back out of an entry's tag byte.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`Error::UnknownCrypto`] if `v` is not an assigned id. Entry
100    /// bytes are untrusted input, so this is an ordinary runtime outcome
101    /// rather than a sign of a bug.
102    pub fn from_u8(v: u8) -> Result<CryptoId> {
103        match v {
104            0 => Ok(CryptoId::None),
105            1 => Ok(CryptoId::ChaCha20Poly1305),
106            2 => Ok(CryptoId::Aes256Gcm),
107            other => Err(Error::UnknownCrypto(other)),
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn codec_roundtrip() {
118        for id in [
119            CodecId::Store,
120            CodecId::Deflate,
121            CodecId::Lz4,
122            CodecId::Snappy,
123            CodecId::Zstd,
124            CodecId::Lzma,
125        ] {
126            assert_eq!(CodecId::from_u8(id.as_u8()).unwrap(), id);
127        }
128        assert!(matches!(
129            CodecId::from_u8(9),
130            Err(crate::Error::UnknownCodec(9))
131        ));
132    }
133
134    #[test]
135    fn crypto_roundtrip() {
136        assert_eq!(CryptoId::from_u8(1).unwrap(), CryptoId::ChaCha20Poly1305);
137        assert_eq!(CryptoId::from_u8(2).unwrap(), CryptoId::Aes256Gcm);
138        assert!(matches!(
139            CryptoId::from_u8(7),
140            Err(crate::Error::UnknownCrypto(7))
141        ));
142    }
143}