From 2eca868540b4aeb617c8ab3de7542c0fa2d5eda3 Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Sat, 28 Sep 2024 20:58:03 +0200 Subject: [PATCH] Add UUID generation. --- lib/std/math/math_random.c3 | 3 ++- lib/std/math/uuid.c3 | 41 +++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 lib/std/math/uuid.c3 diff --git a/lib/std/math/math_random.c3 b/lib/std/math/math_random.c3 index c4579e983..fc6ff98dd 100644 --- a/lib/std/math/math_random.c3 +++ b/lib/std/math/math_random.c3 @@ -173,7 +173,8 @@ interface Random fn void next_bytes(char[] buffer); } -macro init_default_random() @local + +macro init_default_random() @private { if (!default_random_initialized) { diff --git a/lib/std/math/uuid.c3 b/lib/std/math/uuid.c3 new file mode 100644 index 000000000..564d1eeee --- /dev/null +++ b/lib/std/math/uuid.c3 @@ -0,0 +1,41 @@ +module std::math::uuid; +import std::math::random @public; +import std::io; + +distinct Uuid (Printable) = char[16]; + +/** + * Generate a version 4 UUID from the default random. + **/ +fn Uuid generate() +{ + random::init_default_random(); + return generate_from_random(&random::default_random); +} + +/** + * Generate a version 4 UUID from the given random. + **/ +fn Uuid generate_from_random(Random random) +{ + Uuid uuid; + random.next_bytes(&(char[16])uuid); + uuid[6] = (uuid[6] & 0b0000_1111) | 0b0100_0000; + uuid[8] = (uuid[8] & 0b0011_1111) | 0b1000_0000; + return uuid; +} + +fn usz! Uuid.to_format(&self, Formatter* formatter) @dynamic +{ + return formatter.printf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + (*self)[0], (*self)[1], (*self)[2], (*self)[3], + (*self)[4], (*self)[5], + (*self)[6], (*self)[7], + (*self)[8], (*self)[9], + (*self)[10], (*self)[11], (*self)[12], (*self)[13], (*self)[14], (*self)[15]); +} + +fn String Uuid.to_string(&self, Allocator allocator) @dynamic +{ + return string::new_format("%s", *self, allocator: allocator); +} \ No newline at end of file