zig/test/cases/defer.zig

46 lines
1.1 KiB
Zig
Raw Normal View History

2017-01-05 00:57:48 -08:00
const assert = @import("std").debug.assert;
2016-12-19 13:45:15 -08:00
var result: [3]u8 = undefined;
var index: usize = undefined;
error FalseNotAllowed;
2016-12-19 14:25:09 -08:00
fn runSomeErrorDefers(x: bool) -> %bool {
2016-12-19 13:45:15 -08:00
index = 0;
defer {result[index] = 'a'; index += 1;}
%defer {result[index] = 'b'; index += 1;}
defer {result[index] = 'c'; index += 1;}
2016-12-19 13:45:15 -08:00
return if (x) x else error.FalseNotAllowed;
}
test "mixing normal and error defers" {
2016-12-19 14:25:09 -08:00
assert(%%runSomeErrorDefers(true));
2016-12-19 13:45:15 -08:00
assert(result[0] == 'c');
assert(result[1] == 'a');
const ok = runSomeErrorDefers(false) catch |err| x: {
2016-12-19 13:45:15 -08:00
assert(err == error.FalseNotAllowed);
break :x true;
2016-12-19 13:45:15 -08:00
};
assert(ok);
assert(result[0] == 'c');
assert(result[1] == 'b');
assert(result[2] == 'a');
}
test "break and continue inside loop inside defer expression" {
testBreakContInDefer(10);
comptime testBreakContInDefer(10);
}
fn testBreakContInDefer(x: usize) {
defer {
var i: usize = 0;
while (i < x) : (i += 1) {
if (i < 5) continue;
if (i == 5) break;
}
assert(i == 5);
}
}