const_hex/
error.rs

1//! Modified from `hex::error`.
2
3use core::fmt;
4
5/// The error type for decoding a hex string into `Vec<u8>` or `[u8; N]`.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7#[allow(clippy::module_name_repetitions)]
8pub enum FromHexError {
9    /// An invalid character was found. Valid ones are: `0...9`, `a...f`
10    /// or `A...F`.
11    #[allow(missing_docs)]
12    InvalidHexCharacter { c: char, index: usize },
13
14    /// A hex string's length needs to be even, as two digits correspond to
15    /// one byte.
16    OddLength,
17
18    /// If the hex string is decoded into a fixed sized container, such as an
19    /// array, the hex string's length * 2 has to match the container's
20    /// length.
21    InvalidStringLength,
22}
23
24#[cfg(feature = "core-error")]
25impl core::error::Error for FromHexError {}
26#[cfg(all(feature = "std", not(feature = "core-error")))]
27impl std::error::Error for FromHexError {}
28
29impl fmt::Display for FromHexError {
30    #[inline]
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match *self {
33            Self::InvalidHexCharacter { c, index } => {
34                write!(f, "invalid character {c:?} at position {index}")
35            }
36            Self::OddLength => f.write_str("odd number of digits"),
37            Self::InvalidStringLength => f.write_str("invalid string length"),
38        }
39    }
40}
41
42#[cfg(all(test, feature = "alloc"))]
43mod tests {
44    use super::*;
45    use alloc::string::ToString;
46
47    #[test]
48    fn test_display() {
49        assert_eq!(
50            FromHexError::InvalidHexCharacter { c: '\n', index: 5 }.to_string(),
51            "invalid character '\\n' at position 5"
52        );
53
54        assert_eq!(FromHexError::OddLength.to_string(), "odd number of digits");
55        assert_eq!(
56            FromHexError::InvalidStringLength.to_string(),
57            "invalid string length"
58        );
59    }
60}