subtle_encoding/
error.rs

1//! Error type
2
3#[cfg(all(feature = "alloc", not(feature = "std")))]
4use alloc::string::FromUtf8Error;
5use core::fmt;
6#[cfg(feature = "std")]
7use std::{io, string::FromUtf8Error};
8
9/// Error type
10#[derive(Clone, Eq, PartialEq, Debug)]
11pub enum Error {
12    /// Checksum fdoes not match expected value
13    ChecksumInvalid,
14
15    /// Data is not encoded correctly
16    EncodingInvalid,
17
18    /// Error performing I/O operation
19    IoError,
20
21    /// Input or output buffer is an incorrect length
22    LengthInvalid,
23
24    /// Padding missing/invalid
25    PaddingInvalid,
26
27    /// Trailing whitespace detected
28    // TODO: handle trailing whitespace?
29    TrailingWhitespace,
30}
31
32impl fmt::Display for Error {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        let description = match self {
35            Error::ChecksumInvalid => "checksum mismatch",
36            Error::EncodingInvalid => "bad encoding",
37            Error::IoError => "I/O error",
38            Error::LengthInvalid => "invalid length",
39            Error::PaddingInvalid => "padding invalid",
40            Error::TrailingWhitespace => "trailing whitespace",
41        };
42
43        write!(f, "{}", description)
44    }
45}
46
47#[cfg(feature = "std")]
48impl std::error::Error for Error {}
49
50/// Assert that the provided condition is true, or else return the given error
51macro_rules! ensure {
52    ($condition:expr, $err:path) => {
53        if !($condition) {
54            Err($err)?;
55        }
56    };
57}
58
59#[cfg(feature = "std")]
60impl From<io::Error> for Error {
61    fn from(_err: io::Error) -> Error {
62        // TODO: preserve cause or error message?
63        Error::IoError
64    }
65}
66
67#[cfg(feature = "alloc")]
68impl From<FromUtf8Error> for Error {
69    fn from(_err: FromUtf8Error) -> Error {
70        // TODO: preserve cause or error message?
71        Error::EncodingInvalid
72    }
73}