| ... | ... | @@ -1,7 +1,5 @@ |
| 1 | | const std = @import("std.zig"); |
| 2 | 1 | const builtin = @import("builtin"); |
| 3 | | const root = @import("root"); |
| 4 | | const c = std.c; |
| 2 | const std = @import("std.zig"); |
| 5 | 3 | const is_windows = builtin.os.tag == .windows; |
| 6 | 4 | const windows = std.os.windows; |
| 7 | 5 | const posix = std.posix; |
| ... | ... | @@ -9,8 +7,6 @@ const math = std.math; |
| 9 | 7 | const assert = std.debug.assert; |
| 10 | 8 | const fs = std.fs; |
| 11 | 9 | const mem = std.mem; |
| 12 | | const meta = std.meta; |
| 13 | | const File = std.fs.File; |
| 14 | 10 | const Allocator = std.mem.Allocator; |
| 15 | 11 | const Alignment = std.mem.Alignment; |
| 16 | 12 | |
| ... | ... | @@ -972,6 +968,12 @@ pub const VTable = struct { |
| 972 | 968 | /// Thread-safe. |
| 973 | 969 | cancelRequested: *const fn (?*anyopaque) bool, |
| 974 | 970 | |
| 971 | mutexLock: *const fn (?*anyopaque, mutex: *Mutex) void, |
| 972 | mutexUnlock: *const fn (?*anyopaque, mutex: *Mutex) void, |
| 973 | |
| 974 | conditionWait: *const fn (?*anyopaque, cond: *Condition, mutex: *Mutex, timeout_ns: ?u64) Condition.WaitError!void, |
| 975 | conditionWake: *const fn (?*anyopaque, cond: *Condition, notify: Condition.Notify) void, |
| 976 | |
| 975 | 977 | createFile: *const fn (?*anyopaque, dir: fs.Dir, sub_path: []const u8, flags: fs.File.CreateFlags) FileOpenError!fs.File, |
| 976 | 978 | openFile: *const fn (?*anyopaque, dir: fs.Dir, sub_path: []const u8, flags: fs.File.OpenFlags) FileOpenError!fs.File, |
| 977 | 979 | closeFile: *const fn (?*anyopaque, fs.File) void, |
| ... | ... | @@ -985,11 +987,11 @@ pub const VTable = struct { |
| 985 | 987 | pub const OpenFlags = fs.File.OpenFlags; |
| 986 | 988 | pub const CreateFlags = fs.File.CreateFlags; |
| 987 | 989 | |
| 988 | | pub const FileOpenError = fs.File.OpenError || error{AsyncCancel}; |
| 989 | | pub const FileReadError = fs.File.ReadError || error{AsyncCancel}; |
| 990 | | pub const FilePReadError = fs.File.PReadError || error{AsyncCancel}; |
| 991 | | pub const FileWriteError = fs.File.WriteError || error{AsyncCancel}; |
| 992 | | pub const FilePWriteError = fs.File.PWriteError || error{AsyncCancel}; |
| 990 | pub const FileOpenError = fs.File.OpenError || error{Canceled}; |
| 991 | pub const FileReadError = fs.File.ReadError || error{Canceled}; |
| 992 | pub const FilePReadError = fs.File.PReadError || error{Canceled}; |
| 993 | pub const FileWriteError = fs.File.WriteError || error{Canceled}; |
| 994 | pub const FilePWriteError = fs.File.PWriteError || error{Canceled}; |
| 993 | 995 | |
| 994 | 996 | pub const Timestamp = enum(i96) { |
| 995 | 997 | _, |
| ... | ... | @@ -1006,8 +1008,8 @@ pub const Deadline = union(enum) { |
| 1006 | 1008 | nanoseconds: i96, |
| 1007 | 1009 | timestamp: Timestamp, |
| 1008 | 1010 | }; |
| 1009 | | pub const ClockGetTimeError = std.posix.ClockGetTimeError || error{AsyncCancel}; |
| 1010 | | pub const SleepError = error{ UnsupportedClock, Unexpected, AsyncCancel }; |
| 1011 | pub const ClockGetTimeError = std.posix.ClockGetTimeError || error{Canceled}; |
| 1012 | pub const SleepError = error{ UnsupportedClock, Unexpected, Canceled }; |
| 1011 | 1013 | |
| 1012 | 1014 | pub const AnyFuture = opaque {}; |
| 1013 | 1015 | |
| ... | ... | @@ -1036,6 +1038,302 @@ pub fn Future(Result: type) type { |
| 1036 | 1038 | }; |
| 1037 | 1039 | } |
| 1038 | 1040 | |
| 1041 | pub const Mutex = struct { |
| 1042 | state: std.atomic.Value(u32) = std.atomic.Value(u32).init(unlocked), |
| 1043 | |
| 1044 | pub const unlocked: u32 = 0b00; |
| 1045 | pub const locked: u32 = 0b01; |
| 1046 | pub const contended: u32 = 0b11; // must contain the `locked` bit for x86 optimization below |
| 1047 | |
| 1048 | pub fn tryLock(m: *Mutex) bool { |
| 1049 | // On x86, use `lock bts` instead of `lock cmpxchg` as: |
| 1050 | // - they both seem to mark the cache-line as modified regardless: https://stackoverflow.com/a/63350048 |
| 1051 | // - `lock bts` is smaller instruction-wise which makes it better for inlining |
| 1052 | if (builtin.target.cpu.arch.isX86()) { |
| 1053 | const locked_bit = @ctz(locked); |
| 1054 | return m.state.bitSet(locked_bit, .acquire) == 0; |
| 1055 | } |
| 1056 | |
| 1057 | // Acquire barrier ensures grabbing the lock happens before the critical section |
| 1058 | // and that the previous lock holder's critical section happens before we grab the lock. |
| 1059 | return m.state.cmpxchgWeak(unlocked, locked, .acquire, .monotonic) == null; |
| 1060 | } |
| 1061 | |
| 1062 | /// Avoids the vtable for uncontended locks. |
| 1063 | pub fn lock(m: *Mutex, io: Io) void { |
| 1064 | if (!m.tryLock()) { |
| 1065 | @branchHint(.unlikely); |
| 1066 | io.vtable.mutexLock(io.userdata, m); |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | pub fn unlock(m: *Mutex, io: Io) void { |
| 1071 | io.vtable.mutexUnlock(io.userdata, m); |
| 1072 | } |
| 1073 | }; |
| 1074 | |
| 1075 | pub const Condition = struct { |
| 1076 | state: u64 = 0, |
| 1077 | |
| 1078 | pub const WaitError = error{ |
| 1079 | Timeout, |
| 1080 | Canceled, |
| 1081 | }; |
| 1082 | |
| 1083 | /// How many waiters to wake up. |
| 1084 | pub const Notify = enum { |
| 1085 | one, |
| 1086 | all, |
| 1087 | }; |
| 1088 | |
| 1089 | pub fn wait(cond: *Condition, io: Io, mutex: *Mutex) void { |
| 1090 | io.vtable.conditionWait(io.userdata, cond, mutex, null) catch |err| switch (err) { |
| 1091 | error.Timeout => unreachable, // no timeout provided so we shouldn't have timed-out |
| 1092 | error.Canceled => return, // handled as spurious wakeup |
| 1093 | }; |
| 1094 | } |
| 1095 | |
| 1096 | pub fn timedWait(cond: *Condition, io: Io, mutex: *Mutex, timeout_ns: u64) WaitError!void { |
| 1097 | return io.vtable.conditionWait(io.userdata, cond, mutex, timeout_ns); |
| 1098 | } |
| 1099 | |
| 1100 | pub fn signal(cond: *Condition, io: Io) void { |
| 1101 | io.vtable.conditionWake(io.userdata, cond, .one); |
| 1102 | } |
| 1103 | |
| 1104 | pub fn broadcast(cond: *Condition, io: Io) void { |
| 1105 | io.vtable.conditionWake(io.userdata, cond, .all); |
| 1106 | } |
| 1107 | }; |
| 1108 | |
| 1109 | pub const TypeErasedQueue = struct { |
| 1110 | mutex: Mutex, |
| 1111 | |
| 1112 | /// Ring buffer. This data is logically *after* queued getters. |
| 1113 | buffer: []u8, |
| 1114 | put_index: usize, |
| 1115 | get_index: usize, |
| 1116 | |
| 1117 | putters: std.DoublyLinkedList(PutNode), |
| 1118 | getters: std.DoublyLinkedList(GetNode), |
| 1119 | |
| 1120 | const PutNode = struct { |
| 1121 | remaining: []const u8, |
| 1122 | condition: Condition, |
| 1123 | }; |
| 1124 | |
| 1125 | const GetNode = struct { |
| 1126 | remaining: []u8, |
| 1127 | condition: Condition, |
| 1128 | }; |
| 1129 | |
| 1130 | pub fn init(buffer: []u8) TypeErasedQueue { |
| 1131 | return .{ |
| 1132 | .mutex = .{}, |
| 1133 | .buffer = buffer, |
| 1134 | .put_index = 0, |
| 1135 | .get_index = 0, |
| 1136 | .putters = .{}, |
| 1137 | .getters = .{}, |
| 1138 | }; |
| 1139 | } |
| 1140 | |
| 1141 | pub fn put(q: *TypeErasedQueue, io: Io, elements: []const u8, min: usize) usize { |
| 1142 | assert(elements.len >= min); |
| 1143 | |
| 1144 | q.mutex.lock(io); |
| 1145 | defer q.mutex.unlock(io); |
| 1146 | |
| 1147 | // Getters have first priority on the data, and only when the getters |
| 1148 | // queue is empty do we start populating the buffer. |
| 1149 | |
| 1150 | var remaining = elements; |
| 1151 | while (true) { |
| 1152 | const getter = q.getters.popFirst() orelse break; |
| 1153 | const copy_len = @min(getter.data.remaining.len, remaining.len); |
| 1154 | @memcpy(getter.data.remaining[0..copy_len], remaining[0..copy_len]); |
| 1155 | remaining = remaining[copy_len..]; |
| 1156 | getter.data.remaining = getter.data.remaining[copy_len..]; |
| 1157 | if (getter.data.remaining.len == 0) { |
| 1158 | getter.data.condition.signal(io); |
| 1159 | continue; |
| 1160 | } |
| 1161 | q.getters.prepend(getter); |
| 1162 | assert(remaining.len == 0); |
| 1163 | return elements.len; |
| 1164 | } |
| 1165 | |
| 1166 | while (true) { |
| 1167 | { |
| 1168 | const available = q.buffer[q.put_index..]; |
| 1169 | const copy_len = @min(available.len, remaining.len); |
| 1170 | @memcpy(available[0..copy_len], remaining[0..copy_len]); |
| 1171 | remaining = remaining[copy_len..]; |
| 1172 | q.put_index += copy_len; |
| 1173 | if (remaining.len == 0) return elements.len; |
| 1174 | } |
| 1175 | { |
| 1176 | const available = q.buffer[0..q.get_index]; |
| 1177 | const copy_len = @min(available.len, remaining.len); |
| 1178 | @memcpy(available[0..copy_len], remaining[0..copy_len]); |
| 1179 | remaining = remaining[copy_len..]; |
| 1180 | q.put_index = copy_len; |
| 1181 | if (remaining.len == 0) return elements.len; |
| 1182 | } |
| 1183 | |
| 1184 | const total_filled = elements.len - remaining.len; |
| 1185 | if (total_filled >= min) return total_filled; |
| 1186 | |
| 1187 | var node: std.DoublyLinkedList(PutNode).Node = .{ |
| 1188 | .data = .{ .remaining = remaining, .condition = .{} }, |
| 1189 | }; |
| 1190 | q.putters.append(&node); |
| 1191 | node.data.condition.wait(io, &q.mutex); |
| 1192 | remaining = node.data.remaining; |
| 1193 | } |
| 1194 | } |
| 1195 | |
| 1196 | pub fn get(q: *@This(), io: Io, buffer: []u8, min: usize) usize { |
| 1197 | assert(buffer.len >= min); |
| 1198 | |
| 1199 | q.mutex.lock(io); |
| 1200 | defer q.mutex.unlock(io); |
| 1201 | |
| 1202 | // The ring buffer gets first priority, then data should come from any |
| 1203 | // queued putters, then finally the ring buffer should be filled with |
| 1204 | // data from putters so they can be resumed. |
| 1205 | |
| 1206 | var remaining = buffer; |
| 1207 | while (true) { |
| 1208 | if (q.get_index <= q.put_index) { |
| 1209 | const available = q.buffer[q.get_index..q.put_index]; |
| 1210 | const copy_len = @min(available.len, remaining.len); |
| 1211 | @memcpy(remaining[0..copy_len], available[0..copy_len]); |
| 1212 | q.get_index += copy_len; |
| 1213 | remaining = remaining[copy_len..]; |
| 1214 | if (remaining.len == 0) return fillRingBufferFromPutters(q, io, buffer.len); |
| 1215 | } else { |
| 1216 | { |
| 1217 | const available = q.buffer[q.get_index..]; |
| 1218 | const copy_len = @min(available.len, remaining.len); |
| 1219 | @memcpy(remaining[0..copy_len], available[0..copy_len]); |
| 1220 | q.get_index += copy_len; |
| 1221 | remaining = remaining[copy_len..]; |
| 1222 | if (remaining.len == 0) return fillRingBufferFromPutters(q, io, buffer.len); |
| 1223 | } |
| 1224 | { |
| 1225 | const available = q.buffer[0..q.put_index]; |
| 1226 | const copy_len = @min(available.len, remaining.len); |
| 1227 | @memcpy(remaining[0..copy_len], available[0..copy_len]); |
| 1228 | q.get_index = copy_len; |
| 1229 | remaining = remaining[copy_len..]; |
| 1230 | if (remaining.len == 0) return fillRingBufferFromPutters(q, io, buffer.len); |
| 1231 | } |
| 1232 | } |
| 1233 | // Copy directly from putters into buffer. |
| 1234 | while (remaining.len > 0) { |
| 1235 | const putter = q.putters.popFirst() orelse break; |
| 1236 | const copy_len = @min(putter.data.remaining.len, remaining.len); |
| 1237 | @memcpy(remaining[0..copy_len], putter.data.remaining[0..copy_len]); |
| 1238 | putter.data.remaining = putter.data.remaining[copy_len..]; |
| 1239 | remaining = remaining[copy_len..]; |
| 1240 | if (putter.data.remaining.len == 0) { |
| 1241 | putter.data.condition.signal(io); |
| 1242 | } else { |
| 1243 | assert(remaining.len == 0); |
| 1244 | q.putters.prepend(putter); |
| 1245 | return fillRingBufferFromPutters(q, io, buffer.len); |
| 1246 | } |
| 1247 | } |
| 1248 | // Both ring buffer and putters queue is empty. |
| 1249 | const total_filled = buffer.len - remaining.len; |
| 1250 | if (total_filled >= min) return total_filled; |
| 1251 | |
| 1252 | var node: std.DoublyLinkedList(GetNode).Node = .{ |
| 1253 | .data = .{ .remaining = remaining, .condition = .{} }, |
| 1254 | }; |
| 1255 | q.getters.append(&node); |
| 1256 | node.data.condition.wait(io, &q.mutex); |
| 1257 | remaining = node.data.remaining; |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | /// Called when there is nonzero space available in the ring buffer and |
| 1262 | /// potentially putters waiting. The mutex is already held and the task is |
| 1263 | /// to copy putter data to the ring buffer and signal any putters whose |
| 1264 | /// buffers been fully copied. |
| 1265 | fn fillRingBufferFromPutters(q: *TypeErasedQueue, io: Io, len: usize) usize { |
| 1266 | while (true) { |
| 1267 | const putter = q.putters.popFirst() orelse return len; |
| 1268 | const available = q.buffer[q.put_index..]; |
| 1269 | const copy_len = @min(available.len, putter.data.remaining.len); |
| 1270 | @memcpy(available[0..copy_len], putter.data.remaining[0..copy_len]); |
| 1271 | putter.data.remaining = putter.data.remaining[copy_len..]; |
| 1272 | q.put_index += copy_len; |
| 1273 | if (putter.data.remaining.len == 0) { |
| 1274 | putter.data.condition.signal(io); |
| 1275 | continue; |
| 1276 | } |
| 1277 | const second_available = q.buffer[0..q.get_index]; |
| 1278 | const second_copy_len = @min(second_available.len, putter.data.remaining.len); |
| 1279 | @memcpy(second_available[0..second_copy_len], putter.data.remaining[0..second_copy_len]); |
| 1280 | putter.data.remaining = putter.data.remaining[copy_len..]; |
| 1281 | q.put_index = copy_len; |
| 1282 | if (putter.data.remaining.len == 0) { |
| 1283 | putter.data.condition.signal(io); |
| 1284 | continue; |
| 1285 | } |
| 1286 | q.putters.prepend(putter); |
| 1287 | return len; |
| 1288 | } |
| 1289 | } |
| 1290 | }; |
| 1291 | |
| 1292 | /// Many producer, many consumer, thread-safe, runtime configurable buffer size. |
| 1293 | /// When buffer is empty, consumers suspend and are resumed by producers. |
| 1294 | /// When buffer is full, producers suspend and are resumed by consumers. |
| 1295 | pub fn Queue(Elem: type) type { |
| 1296 | return struct { |
| 1297 | type_erased: TypeErasedQueue, |
| 1298 | |
| 1299 | pub fn init(buffer: []Elem) @This() { |
| 1300 | return .{ .type_erased = .init(@ptrCast(buffer)) }; |
| 1301 | } |
| 1302 | |
| 1303 | /// Appends elements to the end of the queue. The function returns when |
| 1304 | /// at least `min` elements have been added to the buffer or sent |
| 1305 | /// directly to a consumer. |
| 1306 | /// |
| 1307 | /// Returns how many elements have been added to the queue. |
| 1308 | /// |
| 1309 | /// Asserts that `elements.len >= min`. |
| 1310 | pub fn put(q: *@This(), io: Io, elements: []const Elem, min: usize) usize { |
| 1311 | return @divExact(q.type_erased.put(io, @ptrCast(elements), min * @sizeOf(Elem)), @sizeOf(Elem)); |
| 1312 | } |
| 1313 | |
| 1314 | /// Receives elements from the beginning of the queue. The function |
| 1315 | /// returns when at least `min` elements have been populated inside |
| 1316 | /// `buffer`. |
| 1317 | /// |
| 1318 | /// Returns how many elements of `buffer` have been populated. |
| 1319 | /// |
| 1320 | /// Asserts that `buffer.len >= min`. |
| 1321 | pub fn get(q: *@This(), io: Io, buffer: []Elem, min: usize) usize { |
| 1322 | return @divExact(q.type_erased.get(io, @ptrCast(buffer), min * @sizeOf(Elem)), @sizeOf(Elem)); |
| 1323 | } |
| 1324 | |
| 1325 | pub fn putOne(q: *@This(), io: Io, item: Elem) void { |
| 1326 | assert(q.put(io, &.{item}, 1) == 1); |
| 1327 | } |
| 1328 | |
| 1329 | pub fn getOne(q: *@This(), io: Io) Elem { |
| 1330 | var buf: [1]Elem = undefined; |
| 1331 | assert(q.get(io, &buf, 1) == 1); |
| 1332 | return buf[0]; |
| 1333 | } |
| 1334 | }; |
| 1335 | } |
| 1336 | |
| 1039 | 1337 | /// Calls `function` with `args`, such that the return value of the function is |
| 1040 | 1338 | /// not guaranteed to be available until `await` is called. |
| 1041 | 1339 | pub fn async(io: Io, function: anytype, args: anytype) Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?) { |