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