| ... | @@ -1,88 +0,0 @@ |
| 1 | const std = @import("std.zig"); |
| 2 | const assert = std.debug.assert; |
| 3 | const testing = std.testing; |
| 4 | |
| 5 | /// Thread-safe initialization of global data. |
| 6 | /// TODO use a mutex instead of a spinlock |
| 7 | pub fn lazyInit(comptime T: type) LazyInit(T) { |
| 8 | return LazyInit(T){ |
| 9 | .data = undefined, |
| 10 | }; |
| 11 | } |
| 12 | |
| 13 | fn LazyInit(comptime T: type) type { |
| 14 | return struct { |
| 15 | state: State = .NotResolved, |
| 16 | data: Data, |
| 17 | |
| 18 | const State = enum(u8) { |
| 19 | NotResolved, |
| 20 | Resolving, |
| 21 | Resolved, |
| 22 | }; |
| 23 | |
| 24 | const Self = @This(); |
| 25 | |
| 26 | // TODO this isn't working for void, investigate and then remove this special case |
| 27 | const Data = if (@sizeOf(T) == 0) u8 else T; |
| 28 | const Ptr = if (T == void) void else *T; |
| 29 | |
| 30 | /// Returns a usable pointer to the initialized data, |
| 31 | /// or returns null, indicating that the caller should |
| 32 | /// perform the initialization and then call resolve(). |
| 33 | pub fn get(self: *Self) ?Ptr { |
| 34 | while (true) { |
| 35 | var state = @cmpxchgWeak(State, &self.state, .NotResolved, .Resolving, .SeqCst, .SeqCst) orelse return null; |
| 36 | switch (state) { |
| 37 | .NotResolved => continue, |
| 38 | .Resolving => { |
| 39 | // TODO mutex instead of a spinlock |
| 40 | continue; |
| 41 | }, |
| 42 | .Resolved => { |
| 43 | if (@sizeOf(T) == 0) { |
| 44 | return @as(T, undefined); |
| 45 | } else { |
| 46 | return &self.data; |
| 47 | } |
| 48 | }, |
| 49 | else => unreachable, |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | pub fn resolve(self: *Self) void { |
| 55 | const prev = @atomicRmw(State, &self.state, .Xchg, .Resolved, .SeqCst); |
| 56 | assert(prev != .Resolved); // resolve() called twice |
| 57 | } |
| 58 | }; |
| 59 | } |
| 60 | |
| 61 | var global_number = lazyInit(i32); |
| 62 | |
| 63 | test "std.lazyInit" { |
| 64 | if (global_number.get()) |_| @panic("bad") else { |
| 65 | global_number.data = 1234; |
| 66 | global_number.resolve(); |
| 67 | } |
| 68 | if (global_number.get()) |x| { |
| 69 | testing.expect(x.* == 1234); |
| 70 | } else { |
| 71 | @panic("bad"); |
| 72 | } |
| 73 | if (global_number.get()) |x| { |
| 74 | testing.expect(x.* == 1234); |
| 75 | } else { |
| 76 | @panic("bad"); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | var global_void = lazyInit(void); |
| 81 | |
| 82 | test "std.lazyInit(void)" { |
| 83 | if (global_void.get()) |_| @panic("bad") else { |
| 84 | global_void.resolve(); |
| 85 | } |
| 86 | testing.expect(global_void.get() != null); |
| 87 | testing.expect(global_void.get() != null); |
| 88 | } |