Fix trackedString.zig a bit

This commit is contained in:
Lys 2024-12-06 08:48:35 +02:00
parent 13cec10439
commit e9b80e659c
Signed by: lyssieth
GPG key ID: 6EE87E973D3AA8F2
2 changed files with 48 additions and 1 deletions

View file

@ -6,7 +6,7 @@ pub const TrackedString = struct {
pub fn initAlloc(value: []const u8, allocator: std.mem.Allocator) !TrackedString { pub fn initAlloc(value: []const u8, allocator: std.mem.Allocator) !TrackedString {
return .{ return .{
.data = try allocator.dupe(value), .data = try allocator.dupe(u8, value),
.kind = .{ .Allocated = allocator }, .kind = .{ .Allocated = allocator },
}; };
} }
@ -40,4 +40,42 @@ pub const AllocKind = union(enum) {
Constant: void, Constant: void,
Allocated: std.mem.Allocator, Allocated: std.mem.Allocator,
Dead: void, Dead: void,
fn eql(self: AllocKind, other: AllocKind) bool {
return switch (self) {
.Constant => switch (other) {
.Constant => true,
else => false,
},
.Allocated => |a| switch (other) {
.Allocated => |b| std.meta.eql(a, b),
else => false,
},
.Dead => switch (other) {
.Dead => true,
else => false,
},
}; };
}
};
const t = std.testing;
test "the different kinds work" {
const a = t.allocator;
var strOne = try TrackedString.initAlloc("hello, world", a);
defer strOne.deinit();
try t.expectEqualStrings("hello, world", strOne.data);
try t.expectEqual(AllocKind{ .Allocated = a }, strOne.kind);
var strTwo = TrackedString.initConst("hello, world");
defer strTwo.deinit();
try t.expectEqualStrings("hello, world", strTwo.data);
try t.expectEqual(AllocKind{ .Constant = {} }, strTwo.kind);
try t.expectEqualStrings(strOne.data, strTwo.data);
try t.expect(!strOne.kind.eql(strTwo.kind));
}

View file

@ -1 +1,10 @@
pub const str = @import("trackedString.zig"); pub const str = @import("trackedString.zig");
comptime {
const std = @import("std");
const builtin = @import("builtin");
if (builtin.is_test) {
std.mem.doNotOptimizeAway(str);
}
}