From 519c09aef6e3e1aedb037c7f0d4fcaa84dcfd6a0 Mon Sep 17 00:00:00 2001 From: Lyssieth Date: Fri, 6 Dec 2024 08:28:27 +0200 Subject: [PATCH] Add new functionality --- src/root.zig | 3 +++ src/util/trackedString.zig | 43 ++++++++++++++++++++++++++++++++++++++ src/util/utils.zig | 1 + 3 files changed, 47 insertions(+) create mode 100644 src/util/trackedString.zig create mode 100644 src/util/utils.zig diff --git a/src/root.zig b/src/root.zig index d76a008..4dfe264 100644 --- a/src/root.zig +++ b/src/root.zig @@ -2,6 +2,7 @@ const std = @import("std"); pub const args = @import("./args/args.zig"); pub const log = @import("./log/logging.zig"); +pub const util = @import("./util/utils.zig"); comptime { // A hack to prevent the compiler from optimizing tests and "exports" away. @@ -16,5 +17,7 @@ comptime { std.mem.doNotOptimizeAway(log.init); std.mem.doNotOptimizeAway(log.deinit); std.mem.doNotOptimizeAway(log.logFn); + + std.mem.doNotOptimizeAway(util); } } diff --git a/src/util/trackedString.zig b/src/util/trackedString.zig new file mode 100644 index 0000000..2474395 --- /dev/null +++ b/src/util/trackedString.zig @@ -0,0 +1,43 @@ +const std = @import("std"); + +pub const TrackedString = struct { + data: []const u8, + kind: AllocKind, + + pub fn initAlloc(value: []const u8, allocator: std.mem.Allocator) !TrackedString { + return .{ + .data = try allocator.dupe(value), + .kind = .{ .Allocated = allocator }, + }; + } + + pub fn initConst(comptime value: []const u8) TrackedString { + return .{ + .data = value, + .kind = .{ .Constant = {} }, + }; + } + + pub fn deinit(self: TrackedString) void { + switch (self.kind) { + .Constant => { + self.value = undefined; + self.kind = .{ .Dead = {} }; + }, + + .Allocated => |allocator| { + allocator.free(self.value); + self.value = undefined; + self.kind = .{ .Dead = {} }; + }, + + .Dead => {}, + } + } +}; + +pub const AllocKind = union(enum) { + Constant: void, + Allocated: std.mem.Allocator, + Dead: void, +}; diff --git a/src/util/utils.zig b/src/util/utils.zig new file mode 100644 index 0000000..06e1560 --- /dev/null +++ b/src/util/utils.zig @@ -0,0 +1 @@ +pub const str = @import("trackedString.zig");