From 617ddc62aa4d3153850362526069b85bfaf5e59e Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 31 Jan 2026 15:31:15 +0900 Subject: use reference counting to manage JSON value lifetime --- src/jv/rc.zig | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/jv/rc.zig (limited to 'src/jv/rc.zig') diff --git a/src/jv/rc.zig b/src/jv/rc.zig new file mode 100644 index 0000000..62a4feb --- /dev/null +++ b/src/jv/rc.zig @@ -0,0 +1,40 @@ +const std = @import("std"); + +pub fn Rc(comptime T: type) type { + const Cell = struct { + value: T, + ref_count: usize, + }; + + return struct { + const Self = @This(); + + cell: *Cell, + + pub fn init(allocator: std.mem.Allocator, value: T) std.mem.Allocator.Error!Self { + const cell = try allocator.create(Cell); + cell.* = .{ .value = value, .ref_count = 1 }; + return .{ .cell = cell }; + } + + pub fn release(self: Self, allocator: std.mem.Allocator) void { + self.cell.ref_count -= 1; + if (self.cell.ref_count == 0) { + allocator.destroy(self.cell); + } + } + + pub fn retain(self: Self) Self { + self.cell.ref_count += 1; + return .{ .cell = self.cell }; + } + + pub fn isUnique(self: Self) bool { + return self.cell.ref_count == 1; + } + + pub fn get(self: Self) *T { + return &self.cell.value; + } + }; +} -- cgit v1.3-1-g0d28