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