sql_values/postgres/uuid.rs
1//! PostgreSQL 18's `uuid`, read as `uuid_in` reads it and printed as `uuid_out` prints it.
2
3use core::fmt;
4
5/// Why `uuid_in` refuses a text, one variant per message it raises.
6///
7/// ```
8/// use sql_values::postgres::{PgUuid, UuidError};
9///
10/// let error = PgUuid::parse("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a1").unwrap_err();
11/// assert_eq!(error, UuidError::InvalidInputSyntax);
12/// assert_eq!(error.to_string(), "invalid input syntax for type uuid");
13/// ```
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
15pub enum UuidError {
16 /// Text other than 32 hexadecimal digits, with at most one hyphen after each group of four
17 /// but the last, optionally between `{` and `}`, and with nothing around them.
18 #[error("invalid input syntax for type uuid")]
19 InvalidInputSyntax,
20}
21
22/// A PostgreSQL `uuid`, ordered as `uuid_cmp` orders it, byte by byte, and printed as `uuid_out`
23/// prints it, in lowercase 8-4-4-4-12 form.
24///
25/// ```
26/// use sql_values::postgres::PgUuid;
27///
28/// let uuid = |text| PgUuid::parse(text).unwrap();
29/// let canonical = "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11";
30/// for spelling in [
31/// "A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11",
32/// "{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}",
33/// "a0eebc999c0b4ef8bb6d6bb9bd380a11",
34/// "a0ee-bc99-9c0b4ef8-bb6d-6bb9-bd38-0a11",
35/// ] {
36/// assert_eq!(uuid(spelling).to_string(), canonical);
37/// }
38/// for refused in [
39/// " a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11",
40/// "a0eebc9-99c0b-4ef8-bb6d-6bb9bd380a11",
41/// "a0eebc99--9c0b-4ef8-bb6d-6bb9bd380a11",
42/// "{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11",
43/// "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11-",
44/// ] {
45/// assert!(PgUuid::parse(refused).is_err());
46/// }
47///
48/// let bytes = [
49/// 0xa0, 0xee, 0xbc, 0x99, 0x9c, 0x0b, 0x4e, 0xf8, 0xbb, 0x6d, 0x6b, 0xb9, 0xbd, 0x38, 0x0a, 0x11,
50/// ];
51/// assert_eq!(PgUuid::from(bytes), uuid(canonical));
52/// assert_eq!(uuid(canonical).as_bytes(), &bytes);
53/// let low = uuid("00000000-0000-0000-0000-0000000000ff");
54/// assert!(low < uuid("01000000-0000-0000-0000-000000000000"));
55/// ```
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
57pub struct PgUuid([u8; 16]);
58
59impl PgUuid {
60 /// Read `text` as `string_to_uuid` reads it.
61 ///
62 /// # Errors
63 ///
64 /// [`UuidError::InvalidInputSyntax`] for text `uuid_in` refuses.
65 pub fn parse(text: &str) -> Result<Self, UuidError> {
66 let (mut rest, braced) = match text.as_bytes() {
67 [b'{', rest @ ..] => (rest, true),
68 rest => (rest, false),
69 };
70 let mut uuid = [0; 16];
71 for (at, byte) in uuid.iter_mut().enumerate() {
72 let [high, low, tail @ ..] = rest else {
73 return Err(UuidError::InvalidInputSyntax);
74 };
75 let digit = |digit| crate::hex_digit(digit).ok_or(UuidError::InvalidInputSyntax);
76 *byte = (digit(*high)? << 4) | digit(*low)?;
77 rest = match tail {
78 [b'-', after @ ..] if at % 2 == 1 && at < 15 => after,
79 _ => tail,
80 };
81 }
82 let rest = match (braced, rest) {
83 (true, [b'}', rest @ ..]) => rest,
84 (true, _) => return Err(UuidError::InvalidInputSyntax),
85 (false, rest) => rest,
86 };
87 if rest.is_empty() {
88 Ok(Self(uuid))
89 } else {
90 Err(UuidError::InvalidInputSyntax)
91 }
92 }
93
94 /// The 16 bytes, in the order PostgreSQL stores and compares them.
95 #[must_use]
96 pub const fn as_bytes(&self) -> &[u8; 16] {
97 &self.0
98 }
99}
100
101impl From<[u8; 16]> for PgUuid {
102 fn from(bytes: [u8; 16]) -> Self {
103 Self(bytes)
104 }
105}
106
107impl fmt::Display for PgUuid {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 self.0.iter().enumerate().try_for_each(|(at, byte)| {
110 if matches!(at, 4 | 6 | 8 | 10) {
111 f.write_str("-")?;
112 }
113 write!(f, "{byte:02x}")
114 })
115 }
116}