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(#[automatically_derived]
impl ::core::clone::Clone for Error {
    #[inline]
    fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Error {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Error",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Error {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ErrorKind>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Error {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Error { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Error {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq)]
5pub struct Error(pub(crate) ErrorKind);
6
7#[derive(#[automatically_derived]
impl ::core::clone::Clone for ErrorKind {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::ParseChar { character: __self_0, index: __self_1 } =>
                Self::ParseChar {
                    character: ::core::clone::Clone::clone(__self_0),
                    index: ::core::clone::Clone::clone(__self_1),
                },
            Self::ParseByteLength { len: __self_0 } =>
                Self::ParseByteLength {
                    len: ::core::clone::Clone::clone(__self_0),
                },
            Self::ParseGroupCount { count: __self_0 } =>
                Self::ParseGroupCount {
                    count: ::core::clone::Clone::clone(__self_0),
                },
            Self::ParseGroupLength {
                group: __self_0, len: __self_1, index: __self_2 } =>
                Self::ParseGroupLength {
                    group: ::core::clone::Clone::clone(__self_0),
                    len: ::core::clone::Clone::clone(__self_1),
                    index: ::core::clone::Clone::clone(__self_2),
                },
            Self::ParseInvalidUTF8 => Self::ParseInvalidUTF8,
            Self::ParseLength { len: __self_0 } =>
                Self::ParseLength {
                    len: ::core::clone::Clone::clone(__self_0),
                },
            Self::ParseOther => Self::ParseOther,
            Self::Nil => Self::Nil,
            Self::InvalidSystemTime(__self_0) =>
                Self::InvalidSystemTime(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ErrorKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ParseChar { character: __self_0, index: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ParseChar", "character", __self_0, "index", &__self_1),
            Self::ParseByteLength { len: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseByteLength", "len", &__self_0),
            Self::ParseGroupCount { count: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseGroupCount", "count", &__self_0),
            Self::ParseGroupLength {
                group: __self_0, len: __self_1, index: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "ParseGroupLength", "group", __self_0, "len", __self_1,
                    "index", &__self_2),
            Self::ParseInvalidUTF8 =>
                ::core::fmt::Formatter::write_str(f, "ParseInvalidUTF8"),
            Self::ParseLength { len: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseLength", "len", &__self_0),
            Self::ParseOther =>
                ::core::fmt::Formatter::write_str(f, "ParseOther"),
            Self::Nil => ::core::fmt::Formatter::write_str(f, "Nil"),
            Self::InvalidSystemTime(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "InvalidSystemTime", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ErrorKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<char>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
        let _: ::core::cmp::AssertParamIsEq<&'static str>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ErrorKind {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::ParseChar { character: __self_0, index: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            Self::ParseByteLength { len: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::ParseGroupCount { count: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::ParseGroupLength {
                group: __self_0, len: __self_1, index: __self_2 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state);
                ::core::hash::Hash::hash(__self_2, state)
            }
            Self::ParseLength { len: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::InvalidSystemTime(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ErrorKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ErrorKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::ParseChar { character: __self_0, index: __self_1 },
                    Self::ParseChar { character: __arg1_0, index: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (Self::ParseByteLength { len: __self_0 },
                    Self::ParseByteLength { len: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (Self::ParseGroupCount { count: __self_0 },
                    Self::ParseGroupCount { count: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (Self::ParseGroupLength {
                    group: __self_0, len: __self_1, index: __self_2 },
                    Self::ParseGroupLength {
                    group: __arg1_0, len: __arg1_1, index: __arg1_2 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                        __self_2 == __arg1_2,
                (Self::ParseLength { len: __self_0 }, Self::ParseLength {
                    len: __arg1_0 }) => __self_0 == __arg1_0,
                (Self::InvalidSystemTime(__self_0),
                    Self::InvalidSystemTime(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}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(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'a> ::core::clone::TrivialClone for InvalidUuid<'a> { }
#[automatically_derived]
impl<'a> ::core::clone::Clone for InvalidUuid<'a> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<&'a [u8]>;
        let _: ::core::clone::AssertParamIsClone<RequestedUuid>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for InvalidUuid<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::fmt::Debug for InvalidUuid<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field2_finish(f, "InvalidUuid",
            &self.0, &&self.1)
    }
}Debug, #[automatically_derived]
impl<'a> ::core::cmp::Eq for InvalidUuid<'a> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<&'a [u8]>;
        let _: ::core::cmp::AssertParamIsEq<RequestedUuid>;
    }
}Eq, #[automatically_derived]
impl<'a> ::core::hash::Hash for InvalidUuid<'a> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state);
        ::core::hash::Hash::hash(&self.1, state)
    }
}Hash, #[automatically_derived]
impl<'a> ::core::marker::StructuralPartialEq for InvalidUuid<'a> { }
#[automatically_derived]
impl<'a> ::core::cmp::PartialEq for InvalidUuid<'a> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0 && self.1 == other.1
    }
}PartialEq)]
48pub(crate) struct InvalidUuid<'a>(pub(crate) &'a [u8], pub(crate) RequestedUuid);
49
50#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RequestedUuid { }
#[automatically_derived]
impl ::core::clone::Clone for RequestedUuid {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RequestedUuid { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for RequestedUuid {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RequestedUuid::Any => "Any",
                RequestedUuid::Simple => "Simple",
                RequestedUuid::Hyphenated => "Hyphenated",
                RequestedUuid::Braced => "Braced",
                RequestedUuid::Urn => "Urn",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for RequestedUuid { }Eq, #[automatically_derived]
impl ::core::hash::Hash for RequestedUuid {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RequestedUuid { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RequestedUuid {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}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            (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                        // While we search, also count group breaks
123                        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            // This means that we tried and failed to parse a simple uuid.
138            // Since we verified that all the characters are valid, this means
139            // that it MUST have an invalid length.
140            Error(ErrorKind::ParseLength {
141                len: input_str.len(),
142            })
143        } else if hyphen_count != 4 {
144            // We tried to parse a hyphenated variant, but there weren't
145            // 5 groups (4 hyphen splits).
146            Error(ErrorKind::ParseGroupCount {
147                count: hyphen_count + 1,
148            })
149        } else {
150            // There are 5 groups, one of them has an incorrect length
151            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            // The last group must be too long
163            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
172// NOTE: This impl is part of the public API. Breaking changes to it should be carefully considered
173impl 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                f.write_fmt(format_args!("invalid character: found `{0}` at {1}", character,
        index))write!(f, "invalid character: found `{}` at {}", character, index)
180            }
181            ErrorKind::ParseByteLength { len } => {
182                f.write_fmt(format_args!("invalid length: expected 16 bytes, found {0}", len))write!(f, "invalid length: expected 16 bytes, found {}", len)
183            }
184            ErrorKind::ParseGroupCount { count } => {
185                f.write_fmt(format_args!("invalid group count: expected 5, found {0}", count))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                f.write_fmt(format_args!("invalid group length in group {0}: expected {1}, found {2}",
        group, expected, len))write!(
190                    f,
191                    "invalid group length in group {}: expected {}, found {}",
192                    group, expected, len
193                )
194            }
195            ErrorKind::ParseInvalidUTF8 => f.write_fmt(format_args!("non-UTF8 input"))write!(f, "non-UTF8 input"),
196            ErrorKind::Nil => f.write_fmt(format_args!("the UUID is nil"))write!(f, "the UUID is nil"),
197            ErrorKind::ParseLength { len } => f.write_fmt(format_args!("invalid length: found {0}", len))write!(f, "invalid length: found {}", len),
198            ErrorKind::ParseOther => f.write_fmt(format_args!("failed to parse a UUID"))write!(f, "failed to parse a UUID"),
199            #[cfg(feature = "std")]
200            ErrorKind::InvalidSystemTime(ref e) => {
201                f.write_fmt(format_args!("the system timestamp is invalid: {0}", e))write!(f, "the system timestamp is invalid: {e}")
202            }
203        }
204    }
205}
206
207impl crate::std::error::Error for Error {}