feature. See also
. The project being documented here (as the example) is the Zig library itself.
Kqueue.Fiber
const Fiber = struct
File
Code
const Fiber = struct {
required_align: void align(4),
context: Io.fiber.Context,
awaiter: ?*Fiber,
queue_next: ?*Fiber,
cancel_thread: ?*Thread,
awaiting_completions: std.bit_set.Static(3),
const finished: ?*Fiber = @ptrFromInt(@alignOf(Thread));
const max_result_align: Alignment = .@"16";
const max_result_size = max_result_align.forward(64);
const min_stack_size = 4 * 1024 * 1024;
const max_context_align: Alignment = .@"16";
const max_context_size = max_context_align.forward(1024);
const max_closure_size: usize = @sizeOf(AsyncClosure);
const max_closure_align: Alignment = .of(AsyncClosure);
const allocation_size = std.mem.alignForward(
usize,
max_closure_align.max(max_context_align).forward(
max_result_align.forward(@sizeOf(Fiber)) + max_result_size + min_stack_size,
) + max_closure_size + max_context_size,
std.heap.page_size_max,
);
fn allocate(k: *Kqueue) error{OutOfMemory}!*Fiber {
return @ptrCast(try k.gpa.alignedAlloc(u8, .of(Fiber), allocation_size));
}
fn allocatedSlice(f: *Fiber) []align(@alignOf(Fiber)) u8 {
return @as([*]align(@alignOf(Fiber)) u8, @ptrCast(f))[0..allocation_size];
}
fn allocatedEnd(f: *Fiber) [*]u8 {
const allocated_slice = f.allocatedSlice();
return allocated_slice[allocated_slice.len..].ptr;
}
fn resultPointer(f: *Fiber, comptime Result: type) *Result {
return @ptrCast(@alignCast(f.resultBytes(.of(Result))));
}
fn resultBytes(f: *Fiber, alignment: Alignment) [*]u8 {
return @ptrFromInt(alignment.forward(@intFromPtr(f) + @sizeOf(Fiber)));
}
fn enterCancelRegion(fiber: *Fiber, thread: *Thread) error{Canceled}!void {
if (@cmpxchgStrong(
?*Thread,
&fiber.cancel_thread,
null,
thread,
.acq_rel,
.acquire,
)) |cancel_thread| {
assert(cancel_thread == Thread.canceling);
return error.Canceled;
}
}
fn exitCancelRegion(fiber: *Fiber, thread: *Thread) void {
if (@cmpxchgStrong(
?*Thread,
&fiber.cancel_thread,
thread,
null,
.acq_rel,
.acquire,
)) |cancel_thread| assert(cancel_thread == Thread.canceling);
}
const Queue = struct { head: *Fiber, tail: *Fiber };
}