Debian Codegraph @

.cargo/vendor/uuid/src/parser.rs

raw
1 // Copyright 2013-2014 The Rust Project Developers.
2 // Copyright 2018 The Uuid Project Developers.
3 //
4 // See the COPYRIGHT file at the top-level directory of this distribution.
5 //
6 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9 // option. This file may not be copied, modified, or distributed
10 // except according to those terms.
11
12 //! [`Uuid`] parsing constructs and utilities.
13 //!
14 //! [`Uuid`]: ../struct.Uuid.html
15
16 use crate::{
17 error::*,
18 std::{convert::TryFrom, str},
19 Uuid,
20 };
21
22 impl str::FromStr for Uuid {
23 type Err = Error;
24
25 fn from_str(uuid_str: &str) -> Result<Self, Self::Err> {
26 Uuid::parse_str(uuid_str)
27 }
28 }
29
30 impl TryFrom<&'_ str> for Uuid {
31 type Error = Error;
32
33 fn try_from(uuid_str: &'_ str) -> Result<Self, Self::Error> {
34 Uuid::parse_str(uuid_str)
35 }
36 }
37
38 impl Uuid {
39 /// Parses a `Uuid` from a string of hexadecimal digits with optional
40 /// hyphens.
41 ///
42 /// Any of the formats generated by this module (simple, hyphenated, urn,
43 /// Microsoft GUID) are supported by this parsing function.
44 ///
45 /// Prefer [`try_parse`] unless you need detailed user-facing diagnostics.
46 /// This method will be eventually deprecated in favor of `try_parse`.
47 ///
48 /// # Examples
49 ///
50 /// Parse a hyphenated UUID:
51 ///
52 /// ```
53 /// # use uuid::{Uuid, Version, Variant};
54 /// # fn main() -> Result<(), uuid::Error> {
55 /// let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?;
56 ///
57 /// assert_eq!(Some(Version::Random), uuid.get_version());
58 /// assert_eq!(Variant::RFC4122, uuid.get_variant());
59 /// # Ok(())
60 /// # }
61 /// ```
62 ///
63 /// [`try_parse`]: #method.try_parse
64 pub fn parse_str(input: &str) -> Result<Uuid, Error> {
65 try_parse(input.as_bytes())
66 .map(Uuid::from_bytes)
67 .map_err(InvalidUuid::into_err)
68 }
69
70 /// Parses a `Uuid` from a string of hexadecimal digits with optional
71 /// hyphens.
72 ///
73 /// This function is similar to [`parse_str`], in fact `parse_str` shares
74 /// the same underlying parser. The difference is that if `try_parse`
75 /// fails, it won't generate very useful error messages. The `parse_str`
76 /// function will eventually be deprecated in favor of `try_parse`.
77 ///
78 /// To parse a UUID from a byte stream instead of a UTF8 string, see
79 /// [`try_parse_ascii`].
80 ///
81 /// # Examples
82 ///
83 /// Parse a hyphenated UUID:
84 ///
85 /// ```
86 /// # use uuid::{Uuid, Version, Variant};
87 /// # fn main() -> Result<(), uuid::Error> {
88 /// let uuid = Uuid::try_parse("550e8400-e29b-41d4-a716-446655440000")?;
89 ///
90 /// assert_eq!(Some(Version::Random), uuid.get_version());
91 /// assert_eq!(Variant::RFC4122, uuid.get_variant());
92 /// # Ok(())
93 /// # }
94 /// ```
95 ///
96 /// [`parse_str`]: #method.parse_str
97 /// [`try_parse_ascii`]: #method.try_parse_ascii
98 pub const fn try_parse(input: &str) -> Result<Uuid, Error> {
99 Self::try_parse_ascii(input.as_bytes())
100 }
101
102 /// Parses a `Uuid` from a string of hexadecimal digits with optional
103 /// hyphens.
104 ///
105 /// The input is expected to be a string of ASCII characters. This method
106 /// can be more convenient than [`try_parse`] if the UUID is being
107 /// parsed from a byte stream instead of from a UTF8 string.
108 ///
109 /// # Examples
110 ///
111 /// Parse a hyphenated UUID:
112 ///
113 /// ```
114 /// # use uuid::{Uuid, Version, Variant};
115 /// # fn main() -> Result<(), uuid::Error> {
116 /// let uuid = Uuid::try_parse_ascii(b"550e8400-e29b-41d4-a716-446655440000")?;
117 ///
118 /// assert_eq!(Some(Version::Random), uuid.get_version());
119 /// assert_eq!(Variant::RFC4122, uuid.get_variant());
120 /// # Ok(())
121 /// # }
122 /// ```
123 ///
124 /// [`try_parse`]: #method.try_parse
125 pub const fn try_parse_ascii(input: &[u8]) -> Result<Uuid, Error> {
126 match try_parse(input) {
127 Ok(bytes) => Ok(Uuid::from_bytes(bytes)),
128 // If parsing fails then we don't know exactly what went wrong
129 // In this case, we just return a generic error
130 Err(_) => Err(Error(ErrorKind::Other)),
131 }
132 }
133 }
134
135 const fn try_parse(input: &[u8]) -> Result<[u8; 16], InvalidUuid> {
136 match (input.len(), input) {
137 // Inputs of 32 bytes must be a non-hyphenated UUID
138 (32, s) => parse_simple(s),
139 // Hyphenated UUIDs may be wrapped in various ways:
140 // - `{UUID}` for braced UUIDs
141 // - `urn:uuid:UUID` for URNs
142 // - `UUID` for a regular hyphenated UUID
143 (36, s)
144 | (38, [b'{', s @ .., b'}'])
145 | (45, [b'u', b'r', b'n', b':', b'u', b'u', b'i', b'd', b':', s @ ..]) => {
146 parse_hyphenated(s)
147 }
148 // Any other shaped input is immediately invalid
149 _ => Err(InvalidUuid(input)),
150 }
151 }
152
153 #[inline]
154 pub(crate) const fn parse_braced(input: &[u8]) -> Result<[u8; 16], InvalidUuid> {
155 if let (38, [b'{', s @ .., b'}']) = (input.len(), input) {
156 parse_hyphenated(s)
157 } else {
158 Err(InvalidUuid(input))
159 }
160 }
161
162 #[inline]
163 pub(crate) const fn parse_urn(input: &[u8]) -> Result<[u8; 16], InvalidUuid> {
164 if let (45, [b'u', b'r', b'n', b':', b'u', b'u', b'i', b'd', b':', s @ ..]) =
165 (input.len(), input)
166 {
167 parse_hyphenated(s)
168 } else {
169 Err(InvalidUuid(input))
170 }
171 }
172
173 #[inline]
174 pub(crate) const fn parse_simple(s: &[u8]) -> Result<[u8; 16], InvalidUuid> {
175 // This length check here removes all other bounds
176 // checks in this function
177 if s.len() != 32 {
178 return Err(InvalidUuid(s));
179 }
180
181 let mut buf: [u8; 16] = [0; 16];
182 let mut i = 0;
183
184 while i < 16 {
185 // Convert a two-char hex value (like `A8`)
186 // into a byte (like `10101000`)
187 let h1 = HEX_TABLE[s[i * 2] as usize];
188 let h2 = HEX_TABLE[s[i * 2 + 1] as usize];
189
190 // We use `0xff` as a sentinel value to indicate
191 // an invalid hex character sequence (like the letter `G`)
192 if h1 | h2 == 0xff {
193 return Err(InvalidUuid(s));
194 }
195
196 // The upper nibble needs to be shifted into position
197 // to produce the final byte value
198 buf[i] = SHL4_TABLE[h1 as usize] | h2;
199 i += 1;
200 }
201
202 Ok(buf)
203 }
204
205 #[inline]
206 const fn parse_hyphenated(s: &[u8]) -> Result<[u8; 16], InvalidUuid> {
207 // This length check here removes all other bounds
208 // checks in this function
209 if s.len() != 36 {
210 return Err(InvalidUuid(s));
211 }
212
213 // We look at two hex-encoded values (4 chars) at a time because
214 // that's the size of the smallest group in a hyphenated UUID.
215 // The indexes we're interested in are:
216 //
217 // uuid : 936da01f-9abd-4d9d-80c7-02af85c822a8
218 // | | || || || || | |
219 // hyphens : | | 8| 13| 18| 23| | |
220 // positions: 0 4 9 14 19 24 28 32
221
222 // First, ensure the hyphens appear in the right places
223 match [s[8], s[13], s[18], s[23]] {
224 [b'-', b'-', b'-', b'-'] => {}
225 _ => return Err(InvalidUuid(s)),
226 }
227
228 let positions: [u8; 8] = [0, 4, 9, 14, 19, 24, 28, 32];
229 let mut buf: [u8; 16] = [0; 16];
230 let mut j = 0;
231
232 while j < 8 {
233 let i = positions[j];
234
235 // The decoding here is the same as the simple case
236 // We're just dealing with two values instead of one
237 let h1 = HEX_TABLE[s[i as usize] as usize];
238 let h2 = HEX_TABLE[s[(i + 1) as usize] as usize];
239 let h3 = HEX_TABLE[s[(i + 2) as usize] as usize];
240 let h4 = HEX_TABLE[s[(i + 3) as usize] as usize];
241
242 if h1 | h2 | h3 | h4 == 0xff {
243 return Err(InvalidUuid(s));
244 }
245
246 buf[j * 2] = SHL4_TABLE[h1 as usize] | h2;
247 buf[j * 2 + 1] = SHL4_TABLE[h3 as usize] | h4;
248 j += 1;
249 }
250
251 Ok(buf)
252 }
253
254 const HEX_TABLE: &[u8; 256] = &{
255 let mut buf = [0; 256];
256 let mut i: u8 = 0;
257
258 loop {
259 buf[i as usize] = match i {
260 b'0'..=b'9' => i - b'0',
261 b'a'..=b'f' => i - b'a' + 10,
262 b'A'..=b'F' => i - b'A' + 10,
263 _ => 0xff,
264 };
265
266 if i == 255 {
267 break buf;
268 }
269
270 i += 1
271 }
272 };
273
274 const SHL4_TABLE: &[u8; 256] = &{
275 let mut buf = [0; 256];
276 let mut i: u8 = 0;
277
278 loop {
279 buf[i as usize] = i.wrapping_shl(4);
280
281 if i == 255 {
282 break buf;
283 }
284
285 i += 1;
286 }
287 };
288
289 #[cfg(test)]
290 mod tests {
291 use super::*;
292 use crate::{std::string::ToString, tests::new};
293
294 #[test]
295 fn test_parse_uuid_v4_valid() {
296 let from_hyphenated = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
297 let from_simple = Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8").unwrap();
298 let from_urn = Uuid::parse_str("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
299 let from_guid = Uuid::parse_str("{67e55044-10b1-426f-9247-bb680e5fe0c8}").unwrap();
300
301 assert_eq!(from_hyphenated, from_simple);
302 assert_eq!(from_hyphenated, from_urn);
303 assert_eq!(from_hyphenated, from_guid);
304
305 assert!(Uuid::parse_str("00000000000000000000000000000000").is_ok());
306 assert!(Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
307 assert!(Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4").is_ok());
308 assert!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8").is_ok());
309 assert!(Uuid::parse_str("01020304-1112-2122-3132-414243444546").is_ok());
310 assert!(Uuid::parse_str("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
311 assert!(Uuid::parse_str("{6d93bade-bd9f-4e13-8914-9474e1e3567b}").is_ok());
312
313 // Nil
314 let nil = Uuid::nil();
315 assert_eq!(
316 Uuid::parse_str("00000000000000000000000000000000").unwrap(),
317 nil
318 );
319 assert_eq!(
320 Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(),
321 nil
322 );
323 }
324
325 #[test]
326 fn test_parse_uuid_v4_invalid() {
327 // Invalid
328 assert_eq!(
329 Uuid::parse_str(""),
330 Err(Error(ErrorKind::SimpleLength { len: 0 }))
331 );
332
333 assert_eq!(
334 Uuid::parse_str("!"),
335 Err(Error(ErrorKind::Char {
336 character: '!',
337 index: 1,
338 }))
339 );
340
341 assert_eq!(
342 Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E45"),
343 Err(Error(ErrorKind::GroupLength {
344 group: 4,
345 len: 13,
346 index: 25,
347 }))
348 );
349
350 assert_eq!(
351 Uuid::parse_str("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4"),
352 Err(Error(ErrorKind::GroupLength {
353 group: 3,
354 len: 3,
355 index: 20,
356 }))
357 );
358
359 assert_eq!(
360 Uuid::parse_str("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4"),
361 Err(Error(ErrorKind::Char {
362 character: 'G',
363 index: 21,
364 }))
365 );
366
367 assert_eq!(
368 Uuid::parse_str("F9168C5E-CEB2F4faaFB6BFF329BF39FA1E4"),
369 Err(Error(ErrorKind::GroupCount { count: 2 }))
370 );
371
372 assert_eq!(
373 Uuid::parse_str("F9168C5E-CEB2-4faaFB6BFF329BF39FA1E4"),
374 Err(Error(ErrorKind::GroupCount { count: 3 }))
375 );
376
377 assert_eq!(
378 Uuid::parse_str("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4"),
379 Err(Error(ErrorKind::GroupCount { count: 4 }))
380 );
381
382 assert_eq!(
383 Uuid::parse_str("F9168C5E-CEB2-4faa"),
384 Err(Error(ErrorKind::GroupCount { count: 3 }))
385 );
386
387 assert_eq!(
388 Uuid::parse_str("F9168C5E-CEB2-4faaXB6BFF329BF39FA1E4"),
389 Err(Error(ErrorKind::Char {
390 character: 'X',
391 index: 19,
392 }))
393 );
394
395 assert_eq!(
396 Uuid::parse_str("{F9168C5E-CEB2-4faa9B6BFF329BF39FA1E41"),
397 Err(Error(ErrorKind::Char {
398 character: '{',
399 index: 1,
400 }))
401 );
402
403 assert_eq!(
404 Uuid::parse_str("{F9168C5E-CEB2-4faa9B6BFF329BF39FA1E41}"),
405 Err(Error(ErrorKind::GroupCount { count: 3 }))
406 );
407
408 assert_eq!(
409 Uuid::parse_str("F9168C5E-CEB-24fa-eB6BFF32-BF39FA1E4"),
410 Err(Error(ErrorKind::GroupLength {
411 group: 1,
412 len: 3,
413 index: 10,
414 }))
415 );
416
417 // // (group, found, expecting)
418 // //
419 assert_eq!(
420 Uuid::parse_str("01020304-1112-2122-3132-41424344"),
421 Err(Error(ErrorKind::GroupLength {
422 group: 4,
423 len: 8,
424 index: 25,
425 }))
426 );
427
428 assert_eq!(
429 Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
430 Err(Error(ErrorKind::SimpleLength { len: 31 }))
431 );
432
433 assert_eq!(
434 Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c88"),
435 Err(Error(ErrorKind::SimpleLength { len: 33 }))
436 );
437
438 assert_eq!(
439 Uuid::parse_str("67e5504410b1426f9247bb680e5fe0cg8"),
440 Err(Error(ErrorKind::Char {
441 character: 'g',
442 index: 32,
443 }))
444 );
445
446 assert_eq!(
447 Uuid::parse_str("67e5504410b1426%9247bb680e5fe0c8"),
448 Err(Error(ErrorKind::Char {
449 character: '%',
450 index: 16,
451 }))
452 );
453
454 assert_eq!(
455 Uuid::parse_str("231231212212423424324323477343246663"),
456 Err(Error(ErrorKind::SimpleLength { len: 36 }))
457 );
458
459 assert_eq!(
460 Uuid::parse_str("{00000000000000000000000000000000}"),
461 Err(Error(ErrorKind::GroupCount { count: 1 }))
462 );
463
464 assert_eq!(
465 Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
466 Err(Error(ErrorKind::SimpleLength { len: 31 }))
467 );
468
469 assert_eq!(
470 Uuid::parse_str("67e550X410b1426f9247bb680e5fe0cd"),
471 Err(Error(ErrorKind::Char {
472 character: 'X',
473 index: 7,
474 }))
475 );
476
477 assert_eq!(
478 Uuid::parse_str("67e550-4105b1426f9247bb680e5fe0c"),
479 Err(Error(ErrorKind::GroupCount { count: 2 }))
480 );
481
482 assert_eq!(
483 Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4"),
484 Err(Error(ErrorKind::GroupLength {
485 group: 3,
486 len: 5,
487 index: 20,
488 }))
489 );
490
491 assert_eq!(
492 Uuid::parse_str("\u{bcf3c}"),
493 Err(Error(ErrorKind::Char {
494 character: '\u{bcf3c}',
495 index: 1
496 }))
497 );
498 }
499
500 #[test]
501 fn test_roundtrip_default() {
502 let uuid_orig = new();
503 let orig_str = uuid_orig.to_string();
504 let uuid_out = Uuid::parse_str(&orig_str).unwrap();
505 assert_eq!(uuid_orig, uuid_out);
506 }
507
508 #[test]
509 fn test_roundtrip_hyphenated() {
510 let uuid_orig = new();
511 let orig_str = uuid_orig.hyphenated().to_string();
512 let uuid_out = Uuid::parse_str(&orig_str).unwrap();
513 assert_eq!(uuid_orig, uuid_out);
514 }
515
516 #[test]
517 fn test_roundtrip_simple() {
518 let uuid_orig = new();
519 let orig_str = uuid_orig.simple().to_string();
520 let uuid_out = Uuid::parse_str(&orig_str).unwrap();
521 assert_eq!(uuid_orig, uuid_out);
522 }
523
524 #[test]
525 fn test_roundtrip_urn() {
526 let uuid_orig = new();
527 let orig_str = uuid_orig.urn().to_string();
528 let uuid_out = Uuid::parse_str(&orig_str).unwrap();
529 assert_eq!(uuid_orig, uuid_out);
530 }
531
532 #[test]
533 fn test_roundtrip_braced() {
534 let uuid_orig = new();
535 let orig_str = uuid_orig.braced().to_string();
536 let uuid_out = Uuid::parse_str(&orig_str).unwrap();
537 assert_eq!(uuid_orig, uuid_out);
538 }
539
540 #[test]
541 fn test_roundtrip_parse_urn() {
542 let uuid_orig = new();
543 let orig_str = uuid_orig.urn().to_string();
544 let uuid_out = Uuid::from_bytes(parse_urn(orig_str.as_bytes()).unwrap());
545 assert_eq!(uuid_orig, uuid_out);
546 }
547
548 #[test]
549 fn test_roundtrip_parse_braced() {
550 let uuid_orig = new();
551 let orig_str = uuid_orig.braced().to_string();
552 let uuid_out = Uuid::from_bytes(parse_braced(orig_str.as_bytes()).unwrap());
553 assert_eq!(uuid_orig, uuid_out);
554 }
555
556 #[test]
557 fn test_try_parse_ascii_non_utf8() {
558 assert!(Uuid::try_parse_ascii(b"67e55044-10b1-426f-9247-bb680e5\0e0c8").is_err());
559 }
560 }