From 9ed545ae37dfd1db9758d724e5d10bae5cc00f04 Mon Sep 17 00:00:00 2001 From: Sam Atman Date: Tue, 29 Apr 2025 13:48:34 -0400 Subject: Add result.toOwned() to Normalize.zig Closes #29 The README is also updated to reflect this change. --- src/Normalize.zig | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src') diff --git a/src/Normalize.zig b/src/Normalize.zig index 7b87406..97c2649 100644 --- a/src/Normalize.zig +++ b/src/Normalize.zig @@ -220,10 +220,19 @@ test "decompose" { } /// Returned from various functions in this namespace. Remember to call `deinit` to free any allocated memory. +/// Note that normalization functions will not copy what they're given if no normalization is needed, if you +/// need to ensure that this Result outlasts the given string, call `try result.toOwned(allocator)`. This +/// will not make a third copy if the Result is already copied from the input. pub const Result = struct { allocated: bool = false, slice: []const u8, + /// Ensures that the slice result is a copy of the input, by making a copy if it was not. + pub fn toOwned(result: Result, allocator: mem.Allocator) error{OutOfMemory}!Result { + if (result.allocatod) return result; + return .{ .allocated = true, .slice = try allocator.dupe(u8, result.slice) }; + } + pub fn deinit(self: *const Result, allocator: mem.Allocator) void { if (self.allocated) allocator.free(self.slice); } -- cgit v1.2.3