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