1use 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
30pub(crate) const UUID4_LEN: usize = 37;
32
33#[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 pub(crate) value: [u8; 37], }
45
46impl UUID4 {
47 #[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; bytes[8] = (bytes[8] & 0x3F) | 0x80; 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; Self { value }
78 }
79
80 #[must_use]
86 pub fn to_cstr(&self) -> &CStr {
87 CStr::from_bytes_with_nul(&self.value)
89 .expect("UUID byte representation should be a valid C string")
90 }
91
92 #[must_use]
94 pub fn as_str(&self) -> &str {
95 self.to_cstr().to_str().expect("UUID should be valid UTF-8")
97 }
98
99 #[must_use]
104 pub fn as_bytes(&self) -> [u8; 16] {
105 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 assert_eq!(
115 uuid.get_version(),
116 Some(uuid::Version::Random),
117 "UUID is not version 4"
118 );
119
120 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; Self { value }
144 }
145}
146
147impl FromStr for UUID4 {
148 type Err = String;
149
150 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 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 fn from(value: UUID4) -> Self {
191 Self::from_bytes(value.as_bytes())
192 }
193}
194
195impl Default for UUID4 {
196 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 assert_eq!(&uuid_string[14..15], "4");
257 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 assert_eq!(bytes[36], 0);
269
270 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"; 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")] #[case("000001f5-8fa9-21d1-9df3-00e098032b8c")] #[case("3d813cbb-47fb-32ba-91df-831e1593ac29")] #[case("fb4f37c1-4ba3-5173-9812-2b90e76a06f7")] #[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 let uuid = "550e8400-e29b-41d4-0000-446655440000";
313 let _ = UUID4::from(uuid);
314 }
315
316 #[rstest]
317 #[case("")] #[case("not-a-uuid-at-all")] #[case("6ba7b810-9dad-11d1-80b4")] #[case("6ba7b810-9dad-11d1-80b4-00c04fd430c8-extra")] #[case("6ba7b810-9dad-11d1-80b4=00c04fd430c8")] #[case("6ba7b81019dad111d180b400c04fd430c8")] #[case("6ba7b810-9dad-11d1-80b4-00c04fd430")] #[case("6ba7b810-9dad-11d1-80b4-00c04fd430cg")] 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 let reconstructed = Uuid::from_bytes(bytes);
446 assert_eq!(reconstructed.to_string(), uuid_string);
447
448 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\"")] #[case("\"6ba7b810-9dad-11d1-80b4-00c04fd430c8\"")] #[case("\"\"")] 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}