Skip to main content

uuid/
error.rs

1use crate::std::fmt;
2
3/// A general error that can occur when working with UUIDs.
4#[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    /// Invalid character in the [`Uuid`] string.
10    ///
11    /// [`Uuid`]: ../struct.Uuid.html
12    ParseChar { character: char, index: usize },
13    /// A byte array didn't contain 16 bytes.
14    ParseByteLength { len: usize },
15    /// A hyphenated [`Uuid`] didn't contain 5 groups
16    ///
17    /// [`Uuid`]: ../struct.Uuid.html
18    ParseGroupCount { count: usize },
19    /// A hyphenated [`Uuid`] had a group that wasn't the right length.
20    ///
21    /// [`Uuid`]: ../struct.Uuid.html
22    ParseGroupLength {
23        group: usize,
24        len: usize,
25        index: usize,
26    },
27    /// The input was not a valid UTF8 string.
28    ParseInvalidUTF8,
29    /// The input has an invalid length.
30    ParseLength { len: usize },
31    /// Some other parsing error occurred.
32    ParseOther,
33    /// The UUID is nil.
34    Nil,
35    /// A system time was invalid.
36    #[cfg(feature = "std")]
37    InvalidSystemTime(&'static str),
38}
39
40/// A string that is guaranteed to fail to parse to a [`Uuid`].
41///
42/// This type acts as a lightweight error indicator, suggesting
43/// that the string cannot be parsed but offering no error
44/// details. To get details, use `InvalidUuid::into_err`.
45///
46/// [`Uuid`]: ../struct.Uuid.html
47#[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    /// Converts the lightweight error type into detailed diagnostics.
61    pub fn into_err(self) -> Error {
62        if self.0.len() == 0 || self.0.len() > 45 {
63            // Don't waste time looking at strings that may be enormous
64            return Error(ErrorKind::ParseLength { len: self.0.len() });
65        }
66
67        // Check whether or not the input was ever actually a valid UTF8 string
68        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                    // The first character is invalid
80                    let (index, character) = input_str.char_indices().next().unwrap();
81
82                    return Error(ErrorKind::ParseChar { character, index });
83                } else {
84                    // The last character is invalid
85                    let (index, character) = input_str.char_indices().last().unwrap();
86
87                    return Error(ErrorKind::ParseChar { character, index });
88                }
89            }
90            (
91                RequestedUuid::Any | RequestedUuid::Urn,
92                [b'u', b'r', b'n', b':', b'u', b'u', b'i', b'd', b':', ..],
93            ) => ("urn:uuid:".len()..self.0.len(), RequestedUuid::Urn),
94            (RequestedUuid::Urn, _) => {
95                return Error(ErrorKind::ParseChar {
96                    character: input_str.chars().next().unwrap(),
97                    index: 0,
98                })
99            }
100            (r, s) => (0..s.len(), r),
101        };
102
103        let mut hyphen_count = 0;
104        let mut group_bounds = [0; 4];
105
106        for (index, character) in input_str[bounds.clone()].char_indices() {
107            match (format, character) {
108                (_, character) if character.is_ascii_hexdigit() => (),
109                (RequestedUuid::Simple, '-') => {
110                    return Error(ErrorKind::ParseChar {
111                        character: '-',
112                        index: index + bounds.start,
113                    })
114                }
115                (_, '-') => {
116                    if format == RequestedUuid::Any {
117                        format = RequestedUuid::Hyphenated;
118                    }
119
120                    if hyphen_count < 4 {
121                        // While we search, also count group breaks
122                        group_bounds[hyphen_count] = index;
123                    }
124                    hyphen_count += 1;
125                }
126                _ => {
127                    return Error(ErrorKind::ParseChar {
128                        character,
129                        index: index + bounds.start,
130                    })
131                }
132            }
133        }
134
135        if format == RequestedUuid::Any || format == RequestedUuid::Simple {
136            // This means that we tried and failed to parse a simple uuid.
137            // Since we verified that all the characters are valid, this means
138            // that it MUST have an invalid length.
139            Error(ErrorKind::ParseLength {
140                len: input_str.len(),
141            })
142        } else if hyphen_count != 4 {
143            // We tried to parse a hyphenated variant, but there weren't
144            // 5 groups (4 hyphen splits).
145            Error(ErrorKind::ParseGroupCount {
146                count: hyphen_count + 1,
147            })
148        } else {
149            // There are 5 groups, one of them has an incorrect length
150            const BLOCK_STARTS: [usize; 5] = [0, 9, 14, 19, 24];
151            for i in 0..4 {
152                if group_bounds[i] != BLOCK_STARTS[i + 1] - 1 {
153                    return Error(ErrorKind::ParseGroupLength {
154                        group: i,
155                        len: group_bounds[i] - BLOCK_STARTS[i],
156                        index: bounds.start + BLOCK_STARTS[i] + 1,
157                    });
158                }
159            }
160
161            // The last group must be too long
162            Error(ErrorKind::ParseGroupLength {
163                group: 4,
164                len: input_str.len() - BLOCK_STARTS[4],
165                index: bounds.start + BLOCK_STARTS[4] + 1,
166            })
167        }
168    }
169}
170
171// NOTE: This impl is part of the public API. Breaking changes to it should be carefully considered
172impl fmt::Display for Error {
173    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174        match self.0 {
175            ErrorKind::ParseChar {
176                character, index, ..
177            } => {
178                write!(f, "invalid character: found `{}` at {}", character, index)
179            }
180            ErrorKind::ParseByteLength { len } => {
181                write!(f, "invalid length: expected 16 bytes, found {}", len)
182            }
183            ErrorKind::ParseGroupCount { count } => {
184                write!(f, "invalid group count: expected 5, found {}", count)
185            }
186            ErrorKind::ParseGroupLength { group, len, .. } => {
187                let expected = [8, 4, 4, 4, 12][group];
188                write!(
189                    f,
190                    "invalid group length in group {}: expected {}, found {}",
191                    group, expected, len
192                )
193            }
194            ErrorKind::ParseInvalidUTF8 => write!(f, "non-UTF8 input"),
195            ErrorKind::Nil => write!(f, "the UUID is nil"),
196            ErrorKind::ParseLength { len } => write!(f, "invalid length: found {}", len),
197            ErrorKind::ParseOther => write!(f, "failed to parse a UUID"),
198            #[cfg(feature = "std")]
199            ErrorKind::InvalidSystemTime(ref e) => {
200                write!(f, "the system timestamp is invalid: {e}")
201            }
202        }
203    }
204}
205
206impl crate::std::error::Error for Error {}