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) -> Error { Error(::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_receiver_is_total_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::cmp::PartialEq for Error {
    #[inline]
    fn eq(&self, other: &Error) -> 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) -> ErrorKind {
        match self {
            ErrorKind::ParseChar { character: __self_0, index: __self_1 } =>
                ErrorKind::ParseChar {
                    character: ::core::clone::Clone::clone(__self_0),
                    index: ::core::clone::Clone::clone(__self_1),
                },
            ErrorKind::ParseSimpleLength { len: __self_0 } =>
                ErrorKind::ParseSimpleLength {
                    len: ::core::clone::Clone::clone(__self_0),
                },
            ErrorKind::ParseByteLength { len: __self_0 } =>
                ErrorKind::ParseByteLength {
                    len: ::core::clone::Clone::clone(__self_0),
                },
            ErrorKind::ParseGroupCount { count: __self_0 } =>
                ErrorKind::ParseGroupCount {
                    count: ::core::clone::Clone::clone(__self_0),
                },
            ErrorKind::ParseGroupLength {
                group: __self_0, len: __self_1, index: __self_2 } =>
                ErrorKind::ParseGroupLength {
                    group: ::core::clone::Clone::clone(__self_0),
                    len: ::core::clone::Clone::clone(__self_1),
                    index: ::core::clone::Clone::clone(__self_2),
                },
            ErrorKind::ParseInvalidUTF8 => ErrorKind::ParseInvalidUTF8,
            ErrorKind::ParseOther => ErrorKind::ParseOther,
            ErrorKind::Nil => ErrorKind::Nil,
            ErrorKind::InvalidSystemTime(__self_0) =>
                ErrorKind::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 {
            ErrorKind::ParseChar { character: __self_0, index: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ParseChar", "character", __self_0, "index", &__self_1),
            ErrorKind::ParseSimpleLength { len: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseSimpleLength", "len", &__self_0),
            ErrorKind::ParseByteLength { len: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseByteLength", "len", &__self_0),
            ErrorKind::ParseGroupCount { count: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseGroupCount", "count", &__self_0),
            ErrorKind::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),
            ErrorKind::ParseInvalidUTF8 =>
                ::core::fmt::Formatter::write_str(f, "ParseInvalidUTF8"),
            ErrorKind::ParseOther =>
                ::core::fmt::Formatter::write_str(f, "ParseOther"),
            ErrorKind::Nil => ::core::fmt::Formatter::write_str(f, "Nil"),
            ErrorKind::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_receiver_is_total_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) -> () {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            ErrorKind::ParseChar { character: __self_0, index: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            ErrorKind::ParseSimpleLength { len: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            ErrorKind::ParseByteLength { len: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            ErrorKind::ParseGroupCount { count: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            ErrorKind::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)
            }
            ErrorKind::InvalidSystemTime(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash, #[automatically_derived]
impl ::core::cmp::PartialEq for ErrorKind {
    #[inline]
    fn eq(&self, other: &ErrorKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ErrorKind::ParseChar { character: __self_0, index: __self_1
                    }, ErrorKind::ParseChar {
                    character: __arg1_0, index: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (ErrorKind::ParseSimpleLength { len: __self_0 },
                    ErrorKind::ParseSimpleLength { len: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (ErrorKind::ParseByteLength { len: __self_0 },
                    ErrorKind::ParseByteLength { len: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (ErrorKind::ParseGroupCount { count: __self_0 },
                    ErrorKind::ParseGroupCount { count: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (ErrorKind::ParseGroupLength {
                    group: __self_0, len: __self_1, index: __self_2 },
                    ErrorKind::ParseGroupLength {
                    group: __arg1_0, len: __arg1_1, index: __arg1_2 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                        __self_2 == __arg1_2,
                (ErrorKind::InvalidSystemTime(__self_0),
                    ErrorKind::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 simple [`Uuid`] didn't contain 32 characters.
14    ///
15    /// [`Uuid`]: ../struct.Uuid.html
16    ParseSimpleLength { len: usize },
17    /// A byte array didn't contain 16 bytes
18    ParseByteLength { len: usize },
19    /// A hyphenated [`Uuid`] didn't contain 5 groups
20    ///
21    /// [`Uuid`]: ../struct.Uuid.html
22    ParseGroupCount { count: usize },
23    /// A hyphenated [`Uuid`] had a group that wasn't the right length
24    ///
25    /// [`Uuid`]: ../struct.Uuid.html
26    ParseGroupLength {
27        group: usize,
28        len: usize,
29        index: usize,
30    },
31    /// The input was not a valid UTF8 string
32    ParseInvalidUTF8,
33    /// Some other parsing error occurred.
34    ParseOther,
35    /// The UUID is nil.
36    Nil,
37    /// A system time was invalid.
38    #[cfg(feature = "std")]
39    InvalidSystemTime(&'static str),
40}
41
42/// A string that is guaranteed to fail to parse to a [`Uuid`].
43///
44/// This type acts as a lightweight error indicator, suggesting
45/// that the string cannot be parsed but offering no error
46/// details. To get details, use `InvalidUuid::into_err`.
47///
48/// [`Uuid`]: ../struct.Uuid.html
49#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for InvalidUuid<'a> {
    #[inline]
    fn clone(&self) -> InvalidUuid<'a> {
        InvalidUuid(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[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_field1_finish(f, "InvalidUuid",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl<'a> ::core::cmp::Eq for InvalidUuid<'a> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<&'a [u8]>;
    }
}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)
    }
}Hash, #[automatically_derived]
impl<'a> ::core::cmp::PartialEq for InvalidUuid<'a> {
    #[inline]
    fn eq(&self, other: &InvalidUuid<'a>) -> bool { self.0 == other.0 }
}PartialEq)]
50pub struct InvalidUuid<'a>(pub(crate) &'a [u8]);
51
52impl<'a> InvalidUuid<'a> {
53    /// Converts the lightweight error type into detailed diagnostics.
54    pub fn into_err(self) -> Error {
55        // Check whether or not the input was ever actually a valid UTF8 string
56        let input_str = match std::str::from_utf8(self.0) {
57            Ok(s) => s,
58            Err(_) => return Error(ErrorKind::ParseInvalidUTF8),
59        };
60
61        let (uuid_str, offset, simple) = match input_str.as_bytes() {
62            [b'{', s @ .., b'}'] => (s, 1, false),
63            [b'u', b'r', b'n', b':', b'u', b'u', b'i', b'd', b':', s @ ..] => {
64                (s, "urn:uuid:".len(), false)
65            }
66            s => (s, 0, true),
67        };
68
69        let mut hyphen_count = 0;
70        let mut group_bounds = [0; 4];
71
72        // SAFETY: the byte array came from a valid utf8 string,
73        // and is aligned along char boundaries.
74        let uuid_str = unsafe { std::str::from_utf8_unchecked(uuid_str) };
75
76        for (index, character) in uuid_str.char_indices() {
77            let byte = character as u8;
78            if character as u32 - byte as u32 > 0 {
79                // Multibyte char
80                return Error(ErrorKind::ParseChar {
81                    character,
82                    index: index + offset + 1,
83                });
84            } else if byte == b'-' {
85                // While we search, also count group breaks
86                if hyphen_count < 4 {
87                    group_bounds[hyphen_count] = index;
88                }
89                hyphen_count += 1;
90            } else if !byte.is_ascii_hexdigit() {
91                // Non-hex char
92                return Error(ErrorKind::ParseChar {
93                    character: byte as char,
94                    index: index + offset + 1,
95                });
96            }
97        }
98
99        if hyphen_count == 0 && simple {
100            // This means that we tried and failed to parse a simple uuid.
101            // Since we verified that all the characters are valid, this means
102            // that it MUST have an invalid length.
103            Error(ErrorKind::ParseSimpleLength {
104                len: input_str.len(),
105            })
106        } else if hyphen_count != 4 {
107            // We tried to parse a hyphenated variant, but there weren't
108            // 5 groups (4 hyphen splits).
109            Error(ErrorKind::ParseGroupCount {
110                count: hyphen_count + 1,
111            })
112        } else {
113            // There are 5 groups, one of them has an incorrect length
114            const BLOCK_STARTS: [usize; 5] = [0, 9, 14, 19, 24];
115            for i in 0..4 {
116                if group_bounds[i] != BLOCK_STARTS[i + 1] - 1 {
117                    return Error(ErrorKind::ParseGroupLength {
118                        group: i,
119                        len: group_bounds[i] - BLOCK_STARTS[i],
120                        index: offset + BLOCK_STARTS[i] + 1,
121                    });
122                }
123            }
124
125            // The last group must be too long
126            Error(ErrorKind::ParseGroupLength {
127                group: 4,
128                len: input_str.len() - BLOCK_STARTS[4],
129                index: offset + BLOCK_STARTS[4] + 1,
130            })
131        }
132    }
133}
134
135// NOTE: This impl is part of the public API. Breaking changes to it should be carefully considered
136impl fmt::Display for Error {
137    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138        match self.0 {
139            ErrorKind::ParseChar {
140                character, index, ..
141            } => {
142                f.write_fmt(format_args!("invalid character: expected an optional prefix of `urn:uuid:` followed by [0-9a-fA-F-], found `{0}` at {1}",
        character, index))write!(f, "invalid character: expected an optional prefix of `urn:uuid:` followed by [0-9a-fA-F-], found `{}` at {}", character, index)
143            }
144            ErrorKind::ParseSimpleLength { len } => {
145                f.write_fmt(format_args!("invalid length: expected length 32 for simple format, found {0}",
        len))write!(
146                    f,
147                    "invalid length: expected length 32 for simple format, found {}",
148                    len
149                )
150            }
151            ErrorKind::ParseByteLength { len } => {
152                f.write_fmt(format_args!("invalid length: expected 16 bytes, found {0}", len))write!(f, "invalid length: expected 16 bytes, found {}", len)
153            }
154            ErrorKind::ParseGroupCount { count } => {
155                f.write_fmt(format_args!("invalid group count: expected 5, found {0}", count))write!(f, "invalid group count: expected 5, found {}", count)
156            }
157            ErrorKind::ParseGroupLength { group, len, .. } => {
158                let expected = [8, 4, 4, 4, 12][group];
159                f.write_fmt(format_args!("invalid group length in group {0}: expected {1}, found {2}",
        group, expected, len))write!(
160                    f,
161                    "invalid group length in group {}: expected {}, found {}",
162                    group, expected, len
163                )
164            }
165            ErrorKind::ParseInvalidUTF8 => f.write_fmt(format_args!("non-UTF8 input"))write!(f, "non-UTF8 input"),
166            ErrorKind::Nil => f.write_fmt(format_args!("the UUID is nil"))write!(f, "the UUID is nil"),
167            ErrorKind::ParseOther => f.write_fmt(format_args!("failed to parse a UUID"))write!(f, "failed to parse a UUID"),
168            #[cfg(feature = "std")]
169            ErrorKind::InvalidSystemTime(ref e) => f.write_fmt(format_args!("the system timestamp is invalid: {0}", e))write!(f, "the system timestamp is invalid: {e}"),
170        }
171    }
172}
173
174#[cfg(feature = "std")]
175mod std_support {
176    use super::*;
177    use crate::std::error;
178
179    impl error::Error for Error { }
180}