2018-02-28 15:22:43 -08:00
|
|
|
const std = @import("std");
|
|
|
|
const assert = std.debug.assert;
|
|
|
|
|
|
|
|
var x: i32 = 1;
|
|
|
|
|
|
|
|
test "create a coroutine and cancel it" {
|
2018-02-28 15:56:26 -08:00
|
|
|
const p = try (async(std.debug.global_allocator) simpleAsyncFn());
|
2018-02-28 15:22:43 -08:00
|
|
|
cancel p;
|
|
|
|
assert(x == 2);
|
|
|
|
}
|
|
|
|
|
2018-02-28 15:56:26 -08:00
|
|
|
async fn simpleAsyncFn() void {
|
2018-02-28 15:22:43 -08:00
|
|
|
x += 1;
|
|
|
|
suspend;
|
|
|
|
x += 1;
|
|
|
|
}
|
2018-02-28 19:18:48 -08:00
|
|
|
|
|
|
|
test "coroutine suspend, resume, cancel" {
|
|
|
|
seq('a');
|
|
|
|
const p = (async(std.debug.global_allocator) testAsyncSeq()) catch unreachable;
|
|
|
|
seq('c');
|
|
|
|
resume p;
|
|
|
|
seq('f');
|
|
|
|
cancel p;
|
|
|
|
seq('g');
|
|
|
|
|
|
|
|
assert(std.mem.eql(u8, points, "abcdefg"));
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn testAsyncSeq() void {
|
|
|
|
defer seq('e');
|
|
|
|
|
|
|
|
seq('b');
|
|
|
|
suspend;
|
|
|
|
seq('d');
|
|
|
|
}
|
|
|
|
var points = []u8{0} ** "abcdefg".len;
|
|
|
|
var index: usize = 0;
|
|
|
|
|
|
|
|
fn seq(c: u8) void {
|
|
|
|
points[index] = c;
|
|
|
|
index += 1;
|
|
|
|
}
|
2018-02-28 19:26:26 -08:00
|
|
|
|
|
|
|
test "coroutine suspend with block" {
|
|
|
|
const p = (async(std.debug.global_allocator) testSuspendBlock()) catch unreachable;
|
|
|
|
std.debug.assert(!result);
|
|
|
|
resume a_promise;
|
|
|
|
std.debug.assert(result);
|
|
|
|
cancel p;
|
|
|
|
}
|
|
|
|
|
|
|
|
var a_promise: promise = undefined;
|
|
|
|
var result = false;
|
|
|
|
|
|
|
|
async fn testSuspendBlock() void {
|
|
|
|
suspend |p| {
|
|
|
|
a_promise = p;
|
|
|
|
}
|
|
|
|
result = true;
|
|
|
|
}
|