up_rust/
uuid.rs

1/********************************************************************************
2 * Copyright (c) 2023 Contributors to the Eclipse Foundation
3 *
4 * See the NOTICE file(s) distributed with this work for additional
5 * information regarding copyright ownership.
6 *
7 * This program and the accompanying materials are made available under the
8 * terms of the Apache License Version 2.0 which is available at
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * SPDX-License-Identifier: Apache-2.0
12 ********************************************************************************/
13
14use rand::RngCore;
15use std::time::{Duration, SystemTime};
16use std::{hash::Hash, str::FromStr};
17
18pub use crate::up_core_api::uuid::UUID;
19
20use uuid_simd::{AsciiCase, Out};
21
22const BITMASK_VERSION: u64 = 0b1111 << 12;
23const VERSION_7: u64 = 0b0111 << 12;
24const BITMASK_VARIANT: u64 = 0b11 << 62;
25const VARIANT_RFC4122: u64 = 0b10 << 62;
26
27fn is_correct_version(msb: u64) -> bool {
28    msb & BITMASK_VERSION == VERSION_7
29}
30
31fn is_correct_variant(lsb: u64) -> bool {
32    lsb & BITMASK_VARIANT == VARIANT_RFC4122
33}
34
35#[derive(Debug)]
36pub struct UuidConversionError {
37    message: String,
38}
39
40impl UuidConversionError {
41    pub fn new<T: Into<String>>(message: T) -> UuidConversionError {
42        UuidConversionError {
43            message: message.into(),
44        }
45    }
46}
47
48impl std::fmt::Display for UuidConversionError {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(f, "Error converting Uuid: {}", self.message)
51    }
52}
53
54impl std::error::Error for UuidConversionError {}
55
56impl UUID {
57    /// Creates a new UUID from a byte array.
58    ///
59    /// # Arguments
60    ///
61    /// `bytes` - the byte array
62    ///
63    /// # Returns
64    ///
65    /// a uProtocol [`UUID`] with the given timestamp and random values.
66    ///
67    /// # Errors
68    ///
69    /// Returns an error if the given bytes contain an invalid version and/or variant identifier.
70    pub(crate) fn from_bytes(bytes: &[u8; 16]) -> Result<Self, UuidConversionError> {
71        let mut msb = [0_u8; 8];
72        let mut lsb = [0_u8; 8];
73        msb.copy_from_slice(&bytes[..8]);
74        lsb.copy_from_slice(&bytes[8..]);
75        Self::from_u64_pair(u64::from_be_bytes(msb), u64::from_be_bytes(lsb))
76    }
77
78    /// Creates a new UUID from a high/low value pair.
79    ///
80    /// NOTE: This function does *not* check if the given bytes represent a [valid uProtocol UUID](Self::is_uprotocol_uuid).
81    ///       It should therefore only be used in cases where the bytes passed in are known to be valid.
82    ///
83    /// # Arguments
84    ///
85    /// `msb` - the most significant 8 bytes
86    /// `lsb` - the least significant 8 bytes
87    ///
88    /// # Returns
89    ///
90    /// a uProtocol [`UUID`] with the given timestamp and random values.
91    pub(crate) fn from_bytes_unchecked(msb: [u8; 8], lsb: [u8; 8]) -> Self {
92        UUID {
93            msb: u64::from_be_bytes(msb),
94            lsb: u64::from_be_bytes(lsb),
95            ..Default::default()
96        }
97    }
98
99    /// Creates a new UUID from a high/low value pair.
100    ///
101    /// # Arguments
102    ///
103    /// `msb` - the most significant 8 bytes
104    /// `lsb` - the least significant 8 bytes
105    ///
106    /// # Returns
107    ///
108    /// a uProtocol [`UUID`] with the given timestamp and random values.
109    ///
110    /// # Errors
111    ///
112    /// Returns an error if the given bytes contain an invalid version and/or variant identifier.
113    // [impl->dsn~uuid-spec~1]
114    pub(crate) fn from_u64_pair(msb: u64, lsb: u64) -> Result<Self, UuidConversionError> {
115        if !is_correct_version(msb) {
116            return Err(UuidConversionError::new("not a v7 UUID"));
117        }
118        if !is_correct_variant(lsb) {
119            return Err(UuidConversionError::new("not an RFC4122 UUID"));
120        }
121        Ok(UUID {
122            msb,
123            lsb,
124            ..Default::default()
125        })
126    }
127
128    // [impl->dsn~uuid-spec~1]
129    pub(crate) fn build_for_timestamp(duration_since_unix_epoch: Duration) -> UUID {
130        let timestamp_millis = u64::try_from(duration_since_unix_epoch.as_millis())
131            .expect("system time is set to a time too far in the future");
132        // fill upper 48 bits with timestamp
133        let mut msb = (timestamp_millis << 16).to_be_bytes();
134        // fill remaining bits with random bits
135        rand::rng().fill_bytes(&mut msb[6..]);
136        // set version (7)
137        msb[6] = msb[6] & 0b00001111 | 0b01110000;
138
139        let mut lsb = [0u8; 8];
140        // fill lsb with random bits
141        rand::rng().fill_bytes(&mut lsb);
142        // set variant (RFC4122)
143        lsb[0] = lsb[0] & 0b00111111 | 0b10000000;
144        Self::from_bytes_unchecked(msb, lsb)
145    }
146
147    /// Creates a new UUID that can be used for uProtocol messages.
148    ///
149    /// # Panics
150    ///
151    /// if the system clock is set to an instant before the UNIX Epoch.
152    ///
153    /// # Examples
154    ///
155    /// ```
156    /// use up_rust::UUID;
157    ///
158    /// let uuid = UUID::build();
159    /// assert!(uuid.is_uprotocol_uuid());
160    /// ```
161    // [impl->dsn~uuid-spec~1]
162    // [utest->dsn~uuid-spec~1]
163    pub fn build() -> UUID {
164        let duration_since_unix_epoch = SystemTime::UNIX_EPOCH
165            .elapsed()
166            .expect("current system time is set to a point in time before UNIX Epoch");
167        Self::build_for_timestamp(duration_since_unix_epoch)
168    }
169
170    /// Serializes this UUID to a hyphenated string as defined by
171    /// [RFC 4122, Section 3](https://www.rfc-editor.org/rfc/rfc4122.html#section-3)
172    /// using lower case characters.
173    ///
174    /// # Examples
175    ///
176    /// ```rust
177    /// use up_rust::UUID;
178    ///
179    /// // timestamp = 1, ver = 0b0111
180    /// let msb = 0x0000000000017000_u64;
181    /// // variant = 0b10, random = 0x0010101010101a1a
182    /// let lsb = 0x8010101010101a1a_u64;
183    /// let uuid = UUID { msb, lsb, ..Default::default() };
184    /// assert_eq!(uuid.to_hyphenated_string(), "00000000-0001-7000-8010-101010101a1a");
185    /// ```
186    // [impl->req~uuid-hex-and-dash~1]
187    pub fn to_hyphenated_string(&self) -> String {
188        let mut bytes = [0_u8; 16];
189        bytes[..8].clone_from_slice(self.msb.to_be_bytes().as_slice());
190        bytes[8..].clone_from_slice(self.lsb.to_be_bytes().as_slice());
191        let mut out_bytes = [0_u8; 36];
192        let out =
193            uuid_simd::format_hyphenated(&bytes, Out::from_mut(&mut out_bytes), AsciiCase::Lower);
194        String::from_utf8(out.to_vec()).unwrap()
195    }
196
197    /// Returns the point in time that this UUID has been created at.
198    ///
199    /// # Returns
200    ///
201    /// The number of milliseconds since UNIX EPOCH if this UUID is a uProtocol UUID,
202    /// or [`Option::None`] otherwise.
203    ///
204    /// # Examples
205    ///
206    /// ```rust
207    /// use up_rust::UUID;
208    ///
209    /// // timestamp = 0x018D548EA8E0 (Monday, 29 January 2024, 9:30:52 AM GMT)
210    /// // ver = 0b0111
211    /// let msb = 0x018D548EA8E07000u64;
212    /// // variant = 0b10
213    /// let lsb = 0x8000000000000000u64;
214    /// let creation_time = UUID { msb, lsb, ..Default::default() }.get_time();
215    /// assert_eq!(creation_time.unwrap(), 0x018D548EA8E0_u64);
216    ///
217    /// // timestamp = 1, (invalid) ver = 0b1100
218    /// let msb = 0x000000000001C000u64;
219    /// // variant = 0b10
220    /// let lsb = 0x8000000000000000u64;
221    /// let creation_time = UUID { msb, lsb, ..Default::default() }.get_time();
222    /// assert!(creation_time.is_none());
223    /// ```
224    // [impl->dsn~uuid-spec~1]
225    // [utest->dsn~uuid-spec~1]
226    pub fn get_time(&self) -> Option<u64> {
227        if self.is_uprotocol_uuid() {
228            // the timestamp is contained in the 48 most significant bits
229            Some(self.msb >> 16)
230        } else {
231            None
232        }
233    }
234
235    /// Checks if this is a valid uProtocol UUID.
236    ///
237    /// # Returns
238    ///
239    /// `true` if this UUID meets the formal requirements defined by the
240    /// [uProtocol spec](https://github.com/eclipse-uprotocol/uprotocol-spec).
241    ///
242    /// # Examples
243    ///
244    /// ```rust
245    /// use up_rust::UUID;
246    ///
247    /// // timestamp = 1, ver = 0b0111
248    /// let msb = 0x0000000000017000u64;
249    /// // variant = 0b10
250    /// let lsb = 0x8000000000000000u64;
251    /// assert!(UUID { msb, lsb, ..Default::default() }.is_uprotocol_uuid());
252    ///
253    /// // timestamp = 1, (invalid) ver = 0b1100
254    /// let msb = 0x000000000001C000u64;
255    /// // variant = 0b10
256    /// let lsb = 0x8000000000000000u64;
257    /// assert!(!UUID { msb, lsb, ..Default::default() }.is_uprotocol_uuid());
258    ///
259    /// // timestamp = 1, ver = 0b0111
260    /// let msb = 0x0000000000017000u64;
261    /// // (invalid) variant = 0b01
262    /// let lsb = 0x4000000000000000u64;
263    /// assert!(!UUID { msb, lsb, ..Default::default() }.is_uprotocol_uuid());
264    /// ```
265    // [impl->dsn~uuid-spec~1]
266    // [utest->dsn~uuid-spec~1]
267    pub fn is_uprotocol_uuid(&self) -> bool {
268        is_correct_version(self.msb) && is_correct_variant(self.lsb)
269    }
270}
271
272impl Eq for UUID {}
273
274impl Hash for UUID {
275    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
276        let bytes = (self.msb, self.lsb);
277        bytes.hash(state)
278    }
279}
280
281impl From<UUID> for String {
282    fn from(value: UUID) -> Self {
283        Self::from(&value)
284    }
285}
286
287impl From<&UUID> for String {
288    fn from(value: &UUID) -> Self {
289        value.to_hyphenated_string()
290    }
291}
292
293impl FromStr for UUID {
294    type Err = UuidConversionError;
295
296    /// Parses a string into a UUID.
297    ///
298    /// # Returns
299    ///
300    /// a uProtocol [`UUID`] based on the bytes encoded in the string.
301    ///
302    /// # Errors
303    ///
304    /// Returns an error
305    /// * if the given string does not represent a UUID as defined by
306    ///   [RFC 4122, Section 3](https://www.rfc-editor.org/rfc/rfc4122.html#section-3), or
307    /// * if the bytes encoded in the string contain an invalid version and/or variant identifier.
308    ///
309    /// # Examples
310    ///
311    /// ```rust
312    /// use up_rust::UUID;
313    ///
314    /// // parsing a valid uProtocol UUID succeeds
315    /// let parsing_attempt = "00000000-0001-7000-8010-101010101a1A".parse::<UUID>();
316    /// assert!(parsing_attempt.is_ok());
317    /// let uuid = parsing_attempt.unwrap();
318    /// assert!(uuid.is_uprotocol_uuid());
319    /// assert_eq!(uuid.msb, 0x0000000000017000_u64);
320    /// assert_eq!(uuid.lsb, 0x8010101010101a1a_u64);
321    ///
322    /// // parsing an invalid UUID fails
323    /// assert!("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8"
324    ///     .parse::<UUID>()
325    ///     .is_err());
326    ///
327    /// // parsing a string that is not a UUID fails
328    /// assert!("this-is-not-a-UUID"
329    ///     .parse::<UUID>()
330    ///     .is_err());
331    /// ```
332    // [impl->req~uuid-hex-and-dash~1]
333    fn from_str(uuid_str: &str) -> Result<Self, Self::Err> {
334        let mut uuid = [0u8; 16];
335        uuid_simd::parse_hyphenated(uuid_str.as_bytes(), Out::from_mut(&mut uuid))
336            .map_err(|err| UuidConversionError::new(err.to_string()))
337            .and_then(|bytes| UUID::from_bytes(bytes))
338    }
339}
340
341#[cfg(test)]
342mod tests {
343
344    use super::*;
345
346    // [utest->dsn~uuid-spec~1]
347    // [utest->req~uuid-type~1]
348    #[test]
349    fn test_from_u64_pair() {
350        // timestamp = 1, ver = 0b0111
351        let msb = 0x0000000000017000_u64;
352        // variant = 0b10
353        let lsb = 0x8000000000000000_u64;
354        let conversion_attempt = UUID::from_u64_pair(msb, lsb);
355        assert!(conversion_attempt.is_ok_and(|uuid| {
356            uuid.is_uprotocol_uuid()
357                && uuid.get_time() == Some(0x1_u64)
358                && uuid.msb == msb
359                && uuid.lsb == lsb
360        }));
361
362        // timestamp = 1, (invalid) ver = 0b0000
363        let msb = 0x0000000000010000_u64;
364        // variant= 0b10
365        let lsb = 0x80000000000000ab_u64;
366        assert!(UUID::from_u64_pair(msb, lsb).is_err());
367
368        // timestamp = 1, ver = 0b0111
369        let msb = 0x0000000000017000_u64;
370        // (invalid) variant= 0b00
371        let lsb = 0x00000000000000ab_u64;
372        assert!(UUID::from_u64_pair(msb, lsb).is_err());
373    }
374
375    // [utest->dsn~uuid-spec~1]
376    #[test]
377    fn test_from_bytes() {
378        // timestamp = 1, ver = 0b0111, variant = 0b10
379        let bytes: [u8; 16] = [
380            0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x70, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
381            0x00, 0x00,
382        ];
383        let conversion_attempt = UUID::from_bytes(&bytes);
384        assert!(conversion_attempt.is_ok());
385        let uuid = conversion_attempt.unwrap();
386        assert!(uuid.is_uprotocol_uuid());
387        assert_eq!(uuid.get_time(), Some(0x1_u64));
388    }
389
390    #[test]
391    // [utest->req~uuid-hex-and-dash~1]
392    fn test_into_string() {
393        // timestamp = 1, ver = 0b0111
394        let msb = 0x0000000000017000_u64;
395        // variant = 0b10, random = 0x0010101010101a1a
396        let lsb = 0x8010101010101a1a_u64;
397        let uuid = UUID {
398            msb,
399            lsb,
400            ..Default::default()
401        };
402
403        assert_eq!(String::from(&uuid), "00000000-0001-7000-8010-101010101a1a");
404        assert_eq!(String::from(uuid), "00000000-0001-7000-8010-101010101a1a");
405    }
406}