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 = "std")]
25impl std::error::Error for FromHexError {}
26
27impl fmt::Display for FromHexError {
28    #[inline]
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match *self {
31            Self::InvalidHexCharacter { c, index } => {
32                write!(f, "invalid character {c:?} at position {index}")
33            }
34            Self::OddLength => f.write_str("odd number of digits"),
35            Self::InvalidStringLength => f.write_str("invalid string length"),
36        }
37    }
38}
39
40#[cfg(all(test, feature = "alloc"))]
41mod tests {
42    use super::*;
43    use alloc::string::ToString;
44
45    #[test]
46    fn test_display() {
47        assert_eq!(
48            FromHexError::InvalidHexCharacter { c: '\n', index: 5 }.to_string(),
49            "invalid character '\\n' at position 5"
50        );
51
52        assert_eq!(FromHexError::OddLength.to_string(), "odd number of digits");
53        assert_eq!(
54            FromHexError::InvalidStringLength.to_string(),
55            "invalid string length"
56        );
57    }
58}