added dupe method

This commit is contained in:
Moritz Gmeiner 2025-04-14 16:34:33 +02:00
commit 19cc6619fa
3 changed files with 43 additions and 2 deletions

View file

@ -1,5 +1,7 @@
const std = @import("std");
const AllocError = std.mem.Allocator.Error;
pub const SmolStr = struct {
pub const max_inline_len: usize = 22;
@ -13,7 +15,7 @@ pub const SmolStr = struct {
inner: Inner,
pub fn init(alloc: std.mem.Allocator, s: []const u8) !SmolStr {
pub fn init(alloc: std.mem.Allocator, s: []const u8) AllocError!SmolStr {
if (s.len <= max_inline_len) {
return initInline(s);
}
@ -73,6 +75,13 @@ pub const SmolStr = struct {
}
}
pub fn dupe(self: SmolStr, alloc: std.mem.Allocator) AllocError!SmolStr {
switch (self.inner) {
.inl => return self, // dupe inlined string by direct copy
.heap => |s| return try SmolStr.init(alloc, s),
}
}
pub fn format(self: SmolStr, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;