1//! Modified from `hex::error`.
23use core::fmt;
45/// 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)]
12InvalidHexCharacter { c: char, index: usize },
1314/// A hex string's length needs to be even, as two digits correspond to
15 /// one byte.
16OddLength,
1718/// 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.
21InvalidStringLength,
22}
2324#[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 {}
2829impl fmt::Display for FromHexError {
30#[inline]
31fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32match *self {
33Self::InvalidHexCharacter { c, index } => {
34write!(f, "invalid character {c:?} at position {index}")
35 }
36Self::OddLength => f.write_str("odd number of digits"),
37Self::InvalidStringLength => f.write_str("invalid string length"),
38 }
39 }
40}
4142#[cfg(all(test, feature = "alloc"))]
43mod tests {
44use super::*;
45use alloc::string::ToString;
4647#[test]
48fn test_display() {
49assert_eq!(
50 FromHexError::InvalidHexCharacter { c: '\n', index: 5 }.to_string(),
51"invalid character '\\n' at position 5"
52);
5354assert_eq!(FromHexError::OddLength.to_string(), "odd number of digits");
55assert_eq!(
56 FromHexError::InvalidStringLength.to_string(),
57"invalid string length"
58);
59 }
60}