diff options
| author | nsfisis <nsfisis@gmail.com> | 2023-08-05 15:38:12 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2023-08-05 16:19:41 +0900 |
| commit | aa61d3a19167c7ef21fd2c7dcceb759005e81ea3 (patch) | |
| tree | f2fa90c1ae3d63655391e752baa50be5431efde5 /src/rc.zig | |
| parent | 2fe3e2233800267647ea76612954ceb343a535b1 (diff) | |
| download | RayTracingInOneWeekend.zig-aa61d3a19167c7ef21fd2c7dcceb759005e81ea3.tar.gz RayTracingInOneWeekend.zig-aa61d3a19167c7ef21fd2c7dcceb759005e81ea3.tar.zst RayTracingInOneWeekend.zig-aa61d3a19167c7ef21fd2c7dcceb759005e81ea3.zip | |
refactor: introduce reference counting pointer
Diffstat (limited to 'src/rc.zig')
| -rw-r--r-- | src/rc.zig | 47 |
1 files changed, 47 insertions, 0 deletions
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; + } + }; +} |
