@@ -125,7 +125,7 @@ pub const SingleThreaded = struct {
125
125
}
126
126
}
127
127
128
- pub fn timeout (self : * Self , nanoseconds : u63 , js_cbk : ? JSCallback ) void {
128
+ pub fn timeout (self : * Self , nanoseconds : u63 , js_cbk : ? JSCallback ) usize {
129
129
const completion = self .alloc .create (IO .Completion ) catch unreachable ;
130
130
completion .* = undefined ;
131
131
const ctx = self .alloc .create (ContextTimeout ) catch unreachable ;
@@ -138,6 +138,51 @@ pub const SingleThreaded = struct {
138
138
if (builtin .is_test ) {
139
139
report ("start timeout {d} for {d} nanoseconds" , .{ old_events_nb + 1 , nanoseconds });
140
140
}
141
+
142
+ return @intFromPtr (completion );
143
+ }
144
+
145
+ const ContextCancel = struct {
146
+ loop : * Self ,
147
+ js_cbk : ? JSCallback ,
148
+ };
149
+
150
+ fn cancelCallback (
151
+ ctx : * ContextCancel ,
152
+ completion : * IO.Completion ,
153
+ result : IO .CancelError ! void ,
154
+ ) void {
155
+ defer ctx .loop .freeCbk (completion , ctx );
156
+
157
+ // TODO: return the error to the callback
158
+ result catch | err | @panic (@errorName (err ));
159
+
160
+ const old_events_nb = ctx .loop .removeEvent ();
161
+ if (builtin .is_test ) {
162
+ report ("timeout done, remaining events: {d}" , .{old_events_nb - 1 });
163
+ }
164
+
165
+ // js callback
166
+ if (ctx .js_cbk ) | js_cbk | {
167
+ defer js_cbk .deinit (ctx .loop .alloc );
168
+ js_cbk .call (null ) catch {
169
+ ctx .loop .cbk_error = true ;
170
+ };
171
+ }
172
+ }
173
+
174
+ pub fn cancel (self : * Self , id : usize , js_cbk : ? JSCallback ) void {
175
+ const comp_cancel : * IO.Completion = @ptrFromInt (id );
176
+
177
+ const completion = self .alloc .create (IO .Completion ) catch unreachable ;
178
+ completion .* = undefined ;
179
+ const ctx = self .alloc .create (ContextTimeout ) catch unreachable ;
180
+ ctx .* = ContextCancel {
181
+ .loop = self ,
182
+ .js_cbk = js_cbk ,
183
+ };
184
+
185
+ self .io .cancel (* ContextCancel , ctx , cancelCallback , completion , comp_cancel );
141
186
}
142
187
143
188
// Yield
0 commit comments