Skip to main content

embark_format/
error.rs

1/// Everything that can go wrong decoding an entry, shared by every crate in
2/// the toolkit.
3#[non_exhaustive]
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum Error {
6    /// The input ended in the middle of a header or payload. Distinct from
7    /// [`Corrupt`](Error::Corrupt): the bytes present were well formed,
8    /// there were simply not enough of them.
9    Truncated,
10    /// The entry's tag byte names a codec id that is either unassigned or
11    /// not compiled into this build. Carries the id as read.
12    UnknownCodec(u8),
13    /// The entry's tag byte names a cipher id that is either unassigned or
14    /// not compiled into this build. Carries the id as read.
15    ///
16    /// Also returned for [`CryptoId::None`](crate::CryptoId::None) where a
17    /// real cipher was required, since nothing is ever sealed under it.
18    UnknownCrypto(u8),
19    /// The bytes are structurally invalid: a payload the named codec cannot
20    /// decode, a varint longer than ten bytes, or output whose length
21    /// disagrees with the length the header declared.
22    ///
23    /// A decoder also reports this rather than aborting when the header
24    /// claims a length too large to allocate, so a hostile entry costs a
25    /// failed reservation rather than the process.
26    Corrupt,
27    /// The AEAD tag does not authenticate the payload under the key and
28    /// nonce supplied: a wrong key, a tampered entry, or both. The
29    /// plaintext is never returned in this case, even partially.
30    Auth,
31    /// The decoded bytes were requested as a string but are not valid
32    /// UTF-8.
33    Utf8 {
34        /// How many leading bytes were valid UTF-8 before the bad sequence,
35        /// as reported by `core::str::Utf8Error::valid_up_to`.
36        valid_up_to: usize,
37    },
38}
39
40/// The toolkit's `Result`, defaulting its error type to [`Error`].
41pub type Result<T, E = Error> = core::result::Result<T, E>;
42
43impl core::fmt::Display for Error {
44    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
45        match self {
46            Error::Truncated => f.write_str("input ended before a complete entry"),
47            Error::UnknownCodec(v) => write!(f, "unknown codec id {v}"),
48            Error::UnknownCrypto(v) => write!(f, "unknown crypto id {v}"),
49            Error::Corrupt => f.write_str("malformed compressed or encoded data"),
50            Error::Auth => f.write_str("authentication tag mismatch"),
51            Error::Utf8 { valid_up_to } => {
52                write!(f, "decoded bytes are not valid UTF-8 at byte {valid_up_to}")
53            }
54        }
55    }
56}
57
58// `core::error::Error` is `std::error::Error` -- std re-exports it -- so this
59// one impl covers both, no_std builds included.
60impl core::error::Error for Error {}