base64ct/
errors.rs

1//! Error types
2
3use core::fmt;
4
5const INVALID_ENCODING_MSG: &str = "invalid Base64 encoding";
6const INVALID_LENGTH_MSG: &str = "invalid Base64 length";
7
8/// Insufficient output buffer length.
9#[derive(Copy, Clone, Debug, Eq, PartialEq)]
10pub struct InvalidLengthError;
11
12impl fmt::Display for InvalidLengthError {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
14        f.write_str(INVALID_LENGTH_MSG)
15    }
16}
17
18#[cfg(feature = "std")]
19impl std::error::Error for InvalidLengthError {}
20
21/// Invalid encoding of provided Base64 string.
22#[derive(Copy, Clone, Debug, Eq, PartialEq)]
23pub struct InvalidEncodingError;
24
25impl fmt::Display for InvalidEncodingError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
27        f.write_str(INVALID_ENCODING_MSG)
28    }
29}
30
31#[cfg(feature = "std")]
32impl std::error::Error for InvalidEncodingError {}
33
34/// Generic error, union of [`InvalidLengthError`] and [`InvalidEncodingError`].
35#[derive(Copy, Clone, Debug, Eq, PartialEq)]
36pub enum Error {
37    /// Invalid encoding of provided Base64 string.
38    InvalidEncoding,
39
40    /// Insufficient output buffer length.
41    InvalidLength,
42}
43
44impl fmt::Display for Error {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
46        let s = match self {
47            Self::InvalidEncoding => INVALID_ENCODING_MSG,
48            Self::InvalidLength => INVALID_LENGTH_MSG,
49        };
50        f.write_str(s)
51    }
52}
53
54impl From<InvalidEncodingError> for Error {
55    #[inline]
56    fn from(_: InvalidEncodingError) -> Error {
57        Error::InvalidEncoding
58    }
59}
60
61impl From<InvalidLengthError> for Error {
62    #[inline]
63    fn from(_: InvalidLengthError) -> Error {
64        Error::InvalidLength
65    }
66}
67
68impl From<core::str::Utf8Error> for Error {
69    #[inline]
70    fn from(_: core::str::Utf8Error) -> Error {
71        Error::InvalidEncoding
72    }
73}
74
75#[cfg(feature = "std")]
76impl From<Error> for std::io::Error {
77    fn from(err: Error) -> std::io::Error {
78        // TODO(tarcieri): better customize `ErrorKind`?
79        std::io::Error::new(std::io::ErrorKind::InvalidData, err)
80    }
81}
82
83#[cfg(feature = "std")]
84impl std::error::Error for Error {}