Coverage Report

Created: 2025-12-20 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/uuid-1.19.0/src/error.rs
Line
Count
Source
1
use crate::std::fmt;
2
3
/// A general error that can occur when working with UUIDs.
4
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
5
pub struct Error(pub(crate) ErrorKind);
6
7
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
8
pub(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(Clone, Debug, Eq, Hash, PartialEq)]
50
pub struct InvalidUuid<'a>(pub(crate) &'a [u8]);
51
52
impl<'a> InvalidUuid<'a> {
53
    /// Converts the lightweight error type into detailed diagnostics.
54
553
    pub fn into_err(self) -> Error {
55
        // Check whether or not the input was ever actually a valid UTF8 string
56
553
        let input_str = match std::str::from_utf8(self.0) {
57
553
            Ok(s) => s,
58
0
            Err(_) => return Error(ErrorKind::ParseInvalidUTF8),
59
        };
60
61
553
        let (uuid_str, offset, simple) = match input_str.as_bytes() {
62
4
            [b'{', s @ .., b'}'] => (s, 1, false),
63
2
            [b'u', b'r', b'n', b':', b'u', b'u', b'i', b'd', b':', s @ ..] => {
64
2
                (s, "urn:uuid:".len(), false)
65
            }
66
547
            s => (s, 0, true),
67
        };
68
69
553
        let mut hyphen_count = 0;
70
553
        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
553
        let uuid_str = unsafe { std::str::from_utf8_unchecked(uuid_str) };
75
76
3.29k
        for (index, character) in uuid_str.char_indices() {
77
3.29k
            let byte = character as u8;
78
3.29k
            if character as u32 - byte as u32 > 0 {
79
                // Multibyte char
80
109
                return Error(ErrorKind::ParseChar {
81
109
                    character,
82
109
                    index: index + offset + 1,
83
109
                });
84
3.18k
            } else if byte == b'-' {
85
                // While we search, also count group breaks
86
412
                if hyphen_count < 4 {
87
295
                    group_bounds[hyphen_count] = index;
88
295
                }
89
412
                hyphen_count += 1;
90
2.77k
            } else if !byte.is_ascii_hexdigit() {
91
                // Non-hex char
92
383
                return Error(ErrorKind::ParseChar {
93
383
                    character: byte as char,
94
383
                    index: index + offset + 1,
95
383
                });
96
2.39k
            }
97
        }
98
99
61
        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
20
            Error(ErrorKind::ParseSimpleLength {
104
20
                len: input_str.len(),
105
20
            })
106
41
        } else if hyphen_count != 4 {
107
            // We tried to parse a hyphenated variant, but there weren't
108
            // 5 groups (4 hyphen splits).
109
21
            Error(ErrorKind::ParseGroupCount {
110
21
                count: hyphen_count + 1,
111
21
            })
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
62
            for i in 0..4 {
116
60
                if group_bounds[i] != BLOCK_STARTS[i + 1] - 1 {
117
18
                    return Error(ErrorKind::ParseGroupLength {
118
18
                        group: i,
119
18
                        len: group_bounds[i] - BLOCK_STARTS[i],
120
18
                        index: offset + BLOCK_STARTS[i] + 1,
121
18
                    });
122
42
                }
123
            }
124
125
            // The last group must be too long
126
2
            Error(ErrorKind::ParseGroupLength {
127
2
                group: 4,
128
2
                len: input_str.len() - BLOCK_STARTS[4],
129
2
                index: offset + BLOCK_STARTS[4] + 1,
130
2
            })
131
        }
132
553
    }
133
}
134
135
// NOTE: This impl is part of the public API. Breaking changes to it should be carefully considered
136
impl fmt::Display for Error {
137
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138
0
        match self.0 {
139
            ErrorKind::ParseChar {
140
0
                character, index, ..
141
            } => {
142
0
                write!(f, "invalid character: expected an optional prefix of `urn:uuid:` followed by [0-9a-fA-F-], found `{}` at {}", character, index)
143
            }
144
0
            ErrorKind::ParseSimpleLength { len } => {
145
0
                write!(
146
0
                    f,
147
0
                    "invalid length: expected length 32 for simple format, found {}",
148
                    len
149
                )
150
            }
151
0
            ErrorKind::ParseByteLength { len } => {
152
0
                write!(f, "invalid length: expected 16 bytes, found {}", len)
153
            }
154
0
            ErrorKind::ParseGroupCount { count } => {
155
0
                write!(f, "invalid group count: expected 5, found {}", count)
156
            }
157
0
            ErrorKind::ParseGroupLength { group, len, .. } => {
158
0
                let expected = [8, 4, 4, 4, 12][group];
159
0
                write!(
160
0
                    f,
161
0
                    "invalid group length in group {}: expected {}, found {}",
162
                    group, expected, len
163
                )
164
            }
165
0
            ErrorKind::ParseInvalidUTF8 => write!(f, "non-UTF8 input"),
166
0
            ErrorKind::Nil => write!(f, "the UUID is nil"),
167
0
            ErrorKind::ParseOther => write!(f, "failed to parse a UUID"),
168
            #[cfg(feature = "std")]
169
0
            ErrorKind::InvalidSystemTime(ref e) => {
170
0
                write!(f, "the system timestamp is invalid: {e}")
171
            }
172
        }
173
0
    }
174
}
175
176
#[cfg(feature = "std")]
177
mod std_support {
178
    use super::*;
179
    use crate::std::error;
180
181
    impl error::Error for Error {}
182
}