aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/rc.zig
blob: 0c16023f94c99ad375974a3eeba0d300e5abdffc (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
41
42
43
44
45
46
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;
        }
    };
}