const Fiber = struct This includes any stack realignments that need to happen, and also the initial frame return address slot and argument frame, depending on target.
fn allocate(k: *Kqueue) errorfn allocatedSlice(f: *Fiber) []align(@alignOf(Fiber)) u8fn allocatedEnd(f: *Fiber) [*]u8fn resultPointer(f: *Fiber, comptime Result: type) *Resultfn resultBytes(f: *Fiber, alignment: Alignment) [*]u8fn enterCancelRegion(fiber: *Fiber, thread: *Thread) errorfn exitCancelRegion(fiber: *Fiber, thread: *Thread) void76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150const 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);
/// This includes any stack realignments that need to happen, and also the
/// initial frame return address slot and argument frame, depending on target.
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 };
}