From aa61d3a19167c7ef21fd2c7dcceb759005e81ea3 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 5 Aug 2023 15:38:12 +0900 Subject: refactor: introduce reference counting pointer --- src/rc.zig | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/rc.zig (limited to 'src/rc.zig') diff --git a/src/rc.zig b/src/rc.zig new file mode 100644 index 0000000..0c16023 --- /dev/null +++ b/src/rc.zig @@ -0,0 +1,47 @@ +const std = @import("std"); + +pub fn Rc(comptime T: type) type { + const Cell = struct { + value: T, + ref_count: usize, + }; + + return struct { + const Self = @This(); + + allocator: std.mem.Allocator, + ptr: *Cell, + + pub fn init(allocator: std.mem.Allocator) !Self { + const ptr = try allocator.create(Cell); + ptr.ref_count = 1; + return .{ + .allocator = allocator, + .ptr = ptr, + }; + } + + pub fn deinit(self: *const Self) void { + self.ptr.ref_count -= 1; + if (self.ptr.ref_count == 0) { + self.allocator.destroy(self.ptr); + } + } + + pub fn clone(self: *const Self) Self { + self.ptr.ref_count += 1; + return .{ + .allocator = self.allocator, + .ptr = self.ptr, + }; + } + + pub fn get(self: *const Self) *const T { + return &self.ptr.value; + } + + pub fn get_mut(self: *Self) *T { + return &self.ptr.value; + } + }; +} -- cgit v1.2.3-70-g09d2