Skip to main content

nautilus_core/
uuid.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! A `UUID4` Universally Unique Identifier (UUID) version 4 (RFC 4122).
17
18use std::{
19    ffi::CStr,
20    fmt::{Debug, Display},
21    hash::Hash,
22    io::{Cursor, Write},
23    str::FromStr,
24};
25
26use rand::Rng;
27use serde::{Deserialize, Deserializer, Serialize, Serializer};
28use uuid::Uuid;
29
30/// The maximum length of ASCII characters for a `UUID4` string value (includes null terminator).
31pub(crate) const UUID4_LEN: usize = 37;
32
33/// Represents a Universally Unique Identifier (UUID)
34/// version 4 based on a 128-bit label as specified in RFC 4122.
35#[repr(C)]
36#[derive(Copy, Clone, Hash, PartialEq, Eq)]
37#[cfg_attr(
38    feature = "python",
39    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.core")
40)]
41pub struct UUID4 {
42    /// The UUID v4 value as a fixed-length C string byte array (includes null terminator).
43    pub(crate) value: [u8; 37], // cbindgen issue using the constant in the array
44}
45
46impl UUID4 {
47    /// Creates a new [`UUID4`] instance.
48    ///
49    /// The UUID value is stored as a fixed-length C string byte array.
50    #[must_use]
51    pub fn new() -> Self {
52        let mut rng = rand::rng();
53        let mut bytes = [0u8; 16];
54        rng.fill_bytes(&mut bytes);
55
56        bytes[6] = (bytes[6] & 0x0F) | 0x40; // Set the version to 4
57        bytes[8] = (bytes[8] & 0x3F) | 0x80; // Set the variant to RFC 4122
58
59        let mut value = [0u8; UUID4_LEN];
60        let mut cursor = Cursor::new(&mut value[..36]);
61
62        write!(
63            cursor,
64            "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
65            u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
66            u16::from_be_bytes([bytes[4], bytes[5]]),
67            u16::from_be_bytes([bytes[6], bytes[7]]),
68            u16::from_be_bytes([bytes[8], bytes[9]]),
69            u64::from_be_bytes([
70                bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15], 0, 0
71            ]) >> 16
72        )
73        .expect("Error writing UUID string to buffer");
74
75        value[36] = 0; // Add the null terminator
76
77        Self { value }
78    }
79
80    /// Converts the [`UUID4`] to a C string reference.
81    ///
82    /// # Panics
83    ///
84    /// Panics if the internal byte array is not a valid C string (does not end with a null terminator).
85    #[must_use]
86    pub fn to_cstr(&self) -> &CStr {
87        // SAFETY: We always store valid C strings
88        CStr::from_bytes_with_nul(&self.value)
89            .expect("UUID byte representation should be a valid C string")
90    }
91
92    /// Returns the UUID as a string slice.
93    #[must_use]
94    pub fn as_str(&self) -> &str {
95        // SAFETY: We always store valid ASCII UUID strings
96        self.to_cstr().to_str().expect("UUID should be valid UTF-8")
97    }
98
99    /// Returns the raw UUID bytes (16 bytes).
100    ///
101    /// This method is optimized for serialization where the UUID bytes
102    /// are needed directly without string conversion overhead.
103    #[must_use]
104    pub fn as_bytes(&self) -> [u8; 16] {
105        // Parse the string representation to extract the raw bytes
106        // This is done once at read time to avoid repeated parsing
107        let uuid_str = self.to_cstr().to_str().expect("Valid UTF-8");
108        let uuid = Uuid::parse_str(uuid_str).expect("Valid UUID4");
109        *uuid.as_bytes()
110    }
111
112    fn validate_v4(uuid: &Uuid) {
113        // Validate this is a v4 UUID
114        assert_eq!(
115            uuid.get_version(),
116            Some(uuid::Version::Random),
117            "UUID is not version 4"
118        );
119
120        // Validate RFC4122 variant
121        assert_eq!(
122            uuid.get_variant(),
123            uuid::Variant::RFC4122,
124            "UUID is not RFC 4122 variant"
125        );
126    }
127
128    fn try_validate_v4(uuid: &Uuid) -> Result<(), String> {
129        if uuid.get_version() != Some(uuid::Version::Random) {
130            return Err("UUID is not version 4".to_string());
131        }
132        if uuid.get_variant() != uuid::Variant::RFC4122 {
133            return Err("UUID is not RFC 4122 variant".to_string());
134        }
135        Ok(())
136    }
137
138    fn from_validated_uuid(uuid: &Uuid) -> Self {
139        let mut value = [0; UUID4_LEN];
140        let uuid_str = uuid.to_string();
141        value[..uuid_str.len()].copy_from_slice(uuid_str.as_bytes());
142        value[uuid_str.len()] = 0; // Add null terminator
143        Self { value }
144    }
145}
146
147impl FromStr for UUID4 {
148    type Err = String;
149
150    /// Attempts to create a [`UUID4`] from a string representation.
151    ///
152    /// The string should be a valid UUID in the standard format (e.g., "2d89666b-1a1e-4a75-b193-4eb3b454c757").
153    ///
154    /// # Errors
155    ///
156    /// Returns an error if the `value` is not a valid UUID version 4 RFC 4122.
157    fn from_str(value: &str) -> Result<Self, Self::Err> {
158        let uuid = Uuid::try_parse(value).map_err(|e| e.to_string())?;
159        Self::try_validate_v4(&uuid)?;
160        Ok(Self::from_validated_uuid(&uuid))
161    }
162}
163
164impl From<&str> for UUID4 {
165    fn from(value: &str) -> Self {
166        Self::from_str(value).expect("Invalid UUID4 string")
167    }
168}
169
170impl From<String> for UUID4 {
171    fn from(value: String) -> Self {
172        Self::from_str(&value).expect("Invalid UUID4 string")
173    }
174}
175
176impl From<uuid::Uuid> for UUID4 {
177    /// Creates a [`UUID4`] from a [`uuid::Uuid`].
178    ///
179    /// # Panics
180    ///
181    /// Panics if the `value` is not a valid UUID version 4 RFC 4122.
182    fn from(value: uuid::Uuid) -> Self {
183        Self::validate_v4(&value);
184        Self::from_validated_uuid(&value)
185    }
186}
187
188impl From<UUID4> for uuid::Uuid {
189    /// Creates a [`uuid::Uuid`] from a [`UUID4`].
190    fn from(value: UUID4) -> Self {
191        Self::from_bytes(value.as_bytes())
192    }
193}
194
195impl Default for UUID4 {
196    /// Creates a new default [`UUID4`] instance.
197    ///
198    /// The default UUID4 is simply a newly generated UUID version 4.
199    fn default() -> Self {
200        Self::new()
201    }
202}
203
204impl Debug for UUID4 {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        write!(f, "{}({})", stringify!(UUID4), self)
207    }
208}
209
210impl Display for UUID4 {
211    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        write!(f, "{}", self.to_cstr().to_string_lossy())
213    }
214}
215
216impl Serialize for UUID4 {
217    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
218    where
219        S: Serializer,
220    {
221        self.to_string().serialize(serializer)
222    }
223}
224
225impl<'de> Deserialize<'de> for UUID4 {
226    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
227    where
228        D: Deserializer<'de>,
229    {
230        let uuid4_str: &str = Deserialize::deserialize(deserializer)?;
231        uuid4_str.parse().map_err(serde::de::Error::custom)
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use std::{
238        collections::hash_map::DefaultHasher,
239        hash::{Hash, Hasher},
240    };
241
242    use rstest::*;
243    use uuid;
244
245    use super::*;
246
247    #[rstest]
248    fn test_new() {
249        let uuid = UUID4::new();
250        let uuid_string = uuid.to_string();
251        let uuid_parsed = Uuid::parse_str(&uuid_string).unwrap();
252        assert_eq!(uuid_parsed.get_version().unwrap(), uuid::Version::Random);
253        assert_eq!(uuid_parsed.to_string().len(), 36);
254
255        // Version 4 requires bits: 0b0100xxxx
256        assert_eq!(&uuid_string[14..15], "4");
257        // RFC4122 variant requires bits: 0b10xxxxxx
258        let variant_char = &uuid_string[19..20];
259        assert!(matches!(variant_char, "8" | "9" | "a" | "b" | "A" | "B"));
260    }
261
262    #[rstest]
263    fn test_uuid_format() {
264        let uuid = UUID4::new();
265        let bytes = uuid.value;
266
267        // Check null termination
268        assert_eq!(bytes[36], 0);
269
270        // Verify dash positions
271        assert_eq!(bytes[8] as char, '-');
272        assert_eq!(bytes[13] as char, '-');
273        assert_eq!(bytes[18] as char, '-');
274        assert_eq!(bytes[23] as char, '-');
275
276        let s = uuid.to_string();
277        assert_eq!(s.chars().nth(14).unwrap(), '4');
278    }
279
280    #[rstest]
281    #[should_panic(expected = "UUID is not version 4")]
282    fn test_from_str_with_non_version_4_uuid_panics() {
283        let uuid_string = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; // v1 UUID
284        let _ = UUID4::from(uuid_string);
285    }
286
287    #[rstest]
288    fn test_case_insensitive_parsing() {
289        let upper = "2D89666B-1A1E-4A75-B193-4EB3B454C757";
290        let lower = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
291        let uuid_upper = UUID4::from(upper);
292        let uuid_lower = UUID4::from(lower);
293
294        assert_eq!(uuid_upper, uuid_lower);
295        assert_eq!(uuid_upper.to_string(), lower);
296    }
297
298    #[rstest]
299    #[case("6ba7b810-9dad-11d1-80b4-00c04fd430c8")] // v1 (time-based)
300    #[case("000001f5-8fa9-21d1-9df3-00e098032b8c")] // v2 (DCE Security)
301    #[case("3d813cbb-47fb-32ba-91df-831e1593ac29")] // v3 (MD5 hash)
302    #[case("fb4f37c1-4ba3-5173-9812-2b90e76a06f7")] // v5 (SHA-1 hash)
303    #[should_panic(expected = "UUID is not version 4")]
304    fn test_invalid_version(#[case] uuid_string: &str) {
305        let _ = UUID4::from(uuid_string);
306    }
307
308    #[rstest]
309    #[should_panic(expected = "UUID is not RFC 4122 variant")]
310    fn test_non_rfc4122_variant() {
311        // Valid v4 but wrong variant
312        let uuid = "550e8400-e29b-41d4-0000-446655440000";
313        let _ = UUID4::from(uuid);
314    }
315
316    #[rstest]
317    #[case("")] // Empty string
318    #[case("not-a-uuid-at-all")] // Invalid format
319    #[case("6ba7b810-9dad-11d1-80b4")] // Too short
320    #[case("6ba7b810-9dad-11d1-80b4-00c04fd430c8-extra")] // Too long
321    #[case("6ba7b810-9dad-11d1-80b4=00c04fd430c8")] // Wrong separator
322    #[case("6ba7b81019dad111d180b400c04fd430c8")] // No separators
323    #[case("6ba7b810-9dad-11d1-80b4-00c04fd430")] // Truncated
324    #[case("6ba7b810-9dad-11d1-80b4-00c04fd430cg")] // Invalid hex character
325    fn test_invalid_uuid_cases(#[case] invalid_uuid: &str) {
326        assert!(UUID4::from_str(invalid_uuid).is_err());
327    }
328
329    #[rstest]
330    fn test_default() {
331        let uuid: UUID4 = UUID4::default();
332        let uuid_string = uuid.to_string();
333        let uuid_parsed = Uuid::parse_str(&uuid_string).unwrap();
334        assert_eq!(uuid_parsed.get_version().unwrap(), uuid::Version::Random);
335    }
336
337    #[rstest]
338    fn test_from_str() {
339        let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
340        let uuid = UUID4::from(uuid_string);
341        let result_string = uuid.to_string();
342        let result_parsed = Uuid::parse_str(&result_string).unwrap();
343        let expected_parsed = Uuid::parse_str(uuid_string).unwrap();
344        assert_eq!(result_parsed, expected_parsed);
345    }
346
347    #[rstest]
348    fn test_from_uuid() {
349        let original = uuid::Uuid::new_v4();
350        let uuid4 = UUID4::from(original);
351        assert_eq!(uuid4.to_string(), original.to_string());
352    }
353
354    #[rstest]
355    fn test_equality() {
356        let uuid1 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
357        let uuid2 = UUID4::from("46922ecb-4324-4e40-a56c-841e0d774cef");
358        assert_eq!(uuid1, uuid1);
359        assert_ne!(uuid1, uuid2);
360    }
361
362    #[rstest]
363    fn test_debug() {
364        let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
365        let uuid = UUID4::from(uuid_string);
366        assert_eq!(format!("{uuid:?}"), format!("UUID4({uuid_string})"));
367    }
368
369    #[rstest]
370    fn test_display() {
371        let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
372        let uuid = UUID4::from(uuid_string);
373        assert_eq!(format!("{uuid}"), uuid_string);
374    }
375
376    #[rstest]
377    fn test_to_cstr() {
378        let uuid = UUID4::new();
379        let cstr = uuid.to_cstr();
380
381        assert_eq!(cstr.to_str().unwrap(), uuid.to_string());
382        assert_eq!(cstr.to_bytes_with_nul()[36], 0);
383    }
384
385    #[rstest]
386    fn test_as_str() {
387        let uuid = UUID4::new();
388        let s = uuid.as_str();
389
390        assert_eq!(s, uuid.to_string());
391        assert_eq!(s.len(), 36);
392    }
393
394    #[rstest]
395    fn test_hash_consistency() {
396        let uuid = UUID4::new();
397
398        let mut hasher1 = DefaultHasher::new();
399        let mut hasher2 = DefaultHasher::new();
400
401        uuid.hash(&mut hasher1);
402        uuid.hash(&mut hasher2);
403
404        assert_eq!(hasher1.finish(), hasher2.finish());
405    }
406
407    #[rstest]
408    fn test_serialize_json() {
409        let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
410        let uuid = UUID4::from(uuid_string);
411
412        let serialized = serde_json::to_string(&uuid).unwrap();
413        let expected_json = format!("\"{uuid_string}\"");
414        assert_eq!(serialized, expected_json);
415    }
416
417    #[rstest]
418    fn test_deserialize_json() {
419        let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
420        let serialized = format!("\"{uuid_string}\"");
421
422        let deserialized: UUID4 = serde_json::from_str(&serialized).unwrap();
423        assert_eq!(deserialized.to_string(), uuid_string);
424    }
425
426    #[rstest]
427    fn test_serialize_deserialize_round_trip() {
428        let uuid = UUID4::new();
429
430        let serialized = serde_json::to_string(&uuid).unwrap();
431        let deserialized: UUID4 = serde_json::from_str(&serialized).unwrap();
432
433        assert_eq!(uuid, deserialized);
434    }
435
436    #[rstest]
437    fn test_as_bytes() {
438        let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
439        let uuid = UUID4::from(uuid_string);
440
441        let bytes = uuid.as_bytes();
442        assert_eq!(bytes.len(), 16);
443
444        // Reconstruct UUID from bytes and verify it matches
445        let reconstructed = Uuid::from_bytes(bytes);
446        assert_eq!(reconstructed.to_string(), uuid_string);
447
448        // Verify version 4
449        assert_eq!(reconstructed.get_version().unwrap(), uuid::Version::Random);
450    }
451
452    #[rstest]
453    fn test_as_bytes_round_trip() {
454        let uuid1 = UUID4::new();
455        let bytes = uuid1.as_bytes();
456        let uuid2 = UUID4::from(Uuid::from_bytes(bytes));
457
458        assert_eq!(uuid1, uuid2);
459    }
460
461    #[rstest]
462    #[case("\"not-a-uuid\"")] // Invalid format
463    #[case("\"6ba7b810-9dad-11d1-80b4-00c04fd430c8\"")] // v1 UUID (wrong version)
464    #[case("\"\"")] // Empty string
465    fn test_deserialize_invalid_uuid_returns_error(#[case] json: &str) {
466        let result: Result<UUID4, _> = serde_json::from_str(json);
467        assert!(result.is_err());
468    }
469}