Browse Source

Add buffer-based `to_string` to `uuid` package

Feoramund 1 year ago
parent
commit
9b3a104640
2 changed files with 38 additions and 4 deletions
  1. 30 1
      core/encoding/uuid/writing.odin
  2. 8 3
      tests/core/encoding/uuid/test_core_uuid.odin

+ 30 - 1
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,
+}

+ 8 - 3
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)