From 9b3a104640f518f21a83ae2c9784cd8601589880 Mon Sep 17 00:00:00 2001 From: Feoramund <161657516+Feoramund@users.noreply.github.com> Date: Sat, 22 Jun 2024 14:38:45 -0400 Subject: [PATCH] Add buffer-based `to_string` to `uuid` package --- core/encoding/uuid/writing.odin | 31 +++++++++++++++++++- tests/core/encoding/uuid/test_core_uuid.odin | 11 +++++-- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/core/encoding/uuid/writing.odin b/core/encoding/uuid/writing.odin index 45096e84f..27dc789c2 100644 --- a/core/encoding/uuid/writing.odin +++ b/core/encoding/uuid/writing.odin @@ -46,7 +46,7 @@ Returns: - str: The allocated and converted string. - error: An optional allocator error if one occured, `nil` otherwise. */ -to_string :: proc( +to_string_allocated :: proc( id: Identifier, allocator := context.allocator, loc := #caller_location, @@ -59,3 +59,32 @@ to_string :: proc( write(strings.to_writer(&builder), id) return strings.to_string(builder), nil } + +/* +Convert a UUID to a string in the 8-4-4-4-12 format. + +Inputs: +- id: The identifier to convert. +- buffer: A byte buffer to store the result. Must be at least 32 bytes large. +- loc: The caller location for debugging purposes (default: #caller_location) + +Returns: +- str: The converted string which will be stored in `buffer`. +*/ +to_string_buffer :: proc( + id: Identifier, + buffer: []byte, + loc := #caller_location, +) -> ( + str: string, +) { + assert(len(buffer) >= EXPECTED_LENGTH, "The buffer provided is not at least 32 bytes large.", loc) + builder := strings.builder_from_bytes(buffer) + write(strings.to_writer(&builder), id) + return strings.to_string(builder) +} + +to_string :: proc { + to_string_allocated, + to_string_buffer, +} diff --git a/tests/core/encoding/uuid/test_core_uuid.odin b/tests/core/encoding/uuid/test_core_uuid.odin index c7beb67d3..460e4259b 100644 --- a/tests/core/encoding/uuid/test_core_uuid.odin +++ b/tests/core/encoding/uuid/test_core_uuid.odin @@ -157,10 +157,15 @@ test_writing :: proc(t: ^testing.T) { b = u8(i) } - s := uuid.to_string(id) - defer delete(s) + buf: [uuid.EXPECTED_LENGTH]u8 - testing.expect_value(t, s, "00010203-0405-0607-0809-0a0b0c0d0e0f") + s_alloc := uuid.to_string(id) + defer delete(s_alloc) + + s_buf := uuid.to_string(id, buf[:]) + + testing.expect_value(t, s_alloc, "00010203-0405-0607-0809-0a0b0c0d0e0f") + testing.expect_value(t, s_buf, "00010203-0405-0607-0809-0a0b0c0d0e0f") } @(test)