1use crate::std::fmt;
2
3#[derive(Clone, Debug, Eq, Hash, PartialEq)]
5pub struct Error(pub(crate) ErrorKind);
6
7#[derive(Clone, Debug, Eq, Hash, PartialEq)]
8pub(crate) enum ErrorKind {
9 ParseChar { character: char, index: usize },
13 ParseByteLength { len: usize },
15 ParseGroupCount { count: usize },
19 ParseGroupLength {
23 group: usize,
24 len: usize,
25 index: usize,
26 },
27 ParseInvalidUTF8,
29 ParseLength { len: usize },
31 ParseOther,
33 Nil,
35 #[cfg(feature = "std")]
37 InvalidSystemTime(&'static str),
38}
39
40#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
48pub(crate) struct InvalidUuid<'a>(pub(crate) &'a [u8], pub(crate) RequestedUuid);
49
50#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
51pub(crate) enum RequestedUuid {
52 Any,
53 Simple,
54 Hyphenated,
55 Braced,
56 Urn,
57}
58
59impl<'a> InvalidUuid<'a> {
60 pub fn into_err(self) -> Error {
62 if self.0.len() == 0 || self.0.len() > 45 {
63 return Error(ErrorKind::ParseLength { len: self.0.len() });
65 }
66
67 let input_str = match std::str::from_utf8(self.0) {
69 Ok(s) => s,
70 Err(_) => return Error(ErrorKind::ParseInvalidUTF8),
71 };
72
73 let (bounds, mut format) = match (self.1, self.0) {
74 (RequestedUuid::Any | RequestedUuid::Braced, [b'{', .., b'}']) => {
75 (1..self.0.len() - 1, RequestedUuid::Braced)
76 }
77 (RequestedUuid::Braced, _) => {
78 if self.0[0] != b'{' {
79 let (index, character) = input_str.char_indices().next().unwrap();
81
82 return Error(ErrorKind::ParseChar { character, index });
83 } else {
84 let (index, character) = input_str.char_indices().last().unwrap();
86
87 return Error(ErrorKind::ParseChar { character, index });
88 }
89 }
90 (RequestedUuid::Any | RequestedUuid::Urn, bytes)
91 if bytes.len() >= 9 && bytes[..9].eq_ignore_ascii_case(b"urn:uuid:") =>
92 {
93 ("urn:uuid:".len()..self.0.len(), RequestedUuid::Urn)
94 }
95 (RequestedUuid::Urn, _) => {
96 return Error(ErrorKind::ParseChar {
97 character: input_str.chars().next().unwrap(),
98 index: 0,
99 })
100 }
101 (r, s) => (0..s.len(), r),
102 };
103
104 let mut hyphen_count = 0;
105 let mut group_bounds = [0; 4];
106
107 for (index, character) in input_str[bounds.clone()].char_indices() {
108 match (format, character) {
109 (_, character) if character.is_ascii_hexdigit() => (),
110 (RequestedUuid::Simple, '-') => {
111 return Error(ErrorKind::ParseChar {
112 character: '-',
113 index: index + bounds.start,
114 })
115 }
116 (_, '-') => {
117 if format == RequestedUuid::Any {
118 format = RequestedUuid::Hyphenated;
119 }
120
121 if hyphen_count < 4 {
122 group_bounds[hyphen_count] = index;
124 }
125 hyphen_count += 1;
126 }
127 _ => {
128 return Error(ErrorKind::ParseChar {
129 character,
130 index: index + bounds.start,
131 })
132 }
133 }
134 }
135
136 if format == RequestedUuid::Any || format == RequestedUuid::Simple {
137 Error(ErrorKind::ParseLength {
141 len: input_str.len(),
142 })
143 } else if hyphen_count != 4 {
144 Error(ErrorKind::ParseGroupCount {
147 count: hyphen_count + 1,
148 })
149 } else {
150 const BLOCK_STARTS: [usize; 5] = [0, 9, 14, 19, 24];
152 for i in 0..4 {
153 if group_bounds[i] != BLOCK_STARTS[i + 1] - 1 {
154 return Error(ErrorKind::ParseGroupLength {
155 group: i,
156 len: group_bounds[i] - BLOCK_STARTS[i],
157 index: bounds.start + BLOCK_STARTS[i] + 1,
158 });
159 }
160 }
161
162 Error(ErrorKind::ParseGroupLength {
164 group: 4,
165 len: input_str.len() - BLOCK_STARTS[4],
166 index: bounds.start + BLOCK_STARTS[4] + 1,
167 })
168 }
169 }
170}
171
172impl fmt::Display for Error {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175 match self.0 {
176 ErrorKind::ParseChar {
177 character, index, ..
178 } => {
179 write!(f, "invalid character: found `{}` at {}", character, index)
180 }
181 ErrorKind::ParseByteLength { len } => {
182 write!(f, "invalid length: expected 16 bytes, found {}", len)
183 }
184 ErrorKind::ParseGroupCount { count } => {
185 write!(f, "invalid group count: expected 5, found {}", count)
186 }
187 ErrorKind::ParseGroupLength { group, len, .. } => {
188 let expected = [8, 4, 4, 4, 12][group];
189 write!(
190 f,
191 "invalid group length in group {}: expected {}, found {}",
192 group, expected, len
193 )
194 }
195 ErrorKind::ParseInvalidUTF8 => write!(f, "non-UTF8 input"),
196 ErrorKind::Nil => write!(f, "the UUID is nil"),
197 ErrorKind::ParseLength { len } => write!(f, "invalid length: found {}", len),
198 ErrorKind::ParseOther => write!(f, "failed to parse a UUID"),
199 #[cfg(feature = "std")]
200 ErrorKind::InvalidSystemTime(ref e) => {
201 write!(f, "the system timestamp is invalid: {e}")
202 }
203 }
204 }
205}
206
207impl crate::std::error::Error for Error {}