aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/jv/rc.zig
blob: 62a4feb68c57c828a65a01234589f86a239b114b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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;
        }
    };
}