2022-02-22 13:15:09 +00:00
|
|
|
const std = @import("std");
|
|
|
|
const builtin = @import("builtin");
|
|
|
|
const expect = std.testing.expect;
|
2017-02-02 22:09:27 +00:00
|
|
|
|
2017-05-24 02:38:31 +01:00
|
|
|
test "try on error union" {
|
2022-02-22 13:15:09 +00:00
|
|
|
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
|
|
|
|
|
2021-05-04 19:23:22 +01:00
|
|
|
try tryOnErrorUnionImpl();
|
|
|
|
comptime try tryOnErrorUnionImpl();
|
2017-02-28 08:07:11 +00:00
|
|
|
}
|
|
|
|
|
2021-05-04 19:23:22 +01:00
|
|
|
fn tryOnErrorUnionImpl() !void {
|
2018-05-01 01:35:54 +01:00
|
|
|
const x = if (returnsTen()) |val| val + 1 else |err| switch (err) {
|
2018-05-29 01:23:55 +01:00
|
|
|
error.ItBroke, error.NoMem => 1,
|
2019-11-07 04:25:57 +00:00
|
|
|
error.CrappedOut => @as(i32, 2),
|
2017-05-07 17:07:35 +01:00
|
|
|
else => unreachable,
|
2017-02-02 22:09:27 +00:00
|
|
|
};
|
2021-05-04 19:23:22 +01:00
|
|
|
try expect(x == 11);
|
2017-02-02 22:09:27 +00:00
|
|
|
}
|
|
|
|
|
2018-11-13 13:08:37 +00:00
|
|
|
fn returnsTen() anyerror!i32 {
|
2017-12-22 05:50:30 +00:00
|
|
|
return 10;
|
2017-02-02 22:09:27 +00:00
|
|
|
}
|
2017-02-05 23:58:58 +00:00
|
|
|
|
2017-05-24 02:38:31 +01:00
|
|
|
test "try without vars" {
|
2019-11-07 04:25:57 +00:00
|
|
|
const result1 = if (failIfTrue(true)) 1 else |_| @as(i32, 2);
|
2021-05-04 19:23:22 +01:00
|
|
|
try expect(result1 == 2);
|
2017-02-05 23:58:58 +00:00
|
|
|
|
2019-11-07 04:25:57 +00:00
|
|
|
const result2 = if (failIfTrue(false)) 1 else |_| @as(i32, 2);
|
2021-05-04 19:23:22 +01:00
|
|
|
try expect(result2 == 1);
|
2017-02-05 23:58:58 +00:00
|
|
|
}
|
|
|
|
|
2018-11-13 13:08:37 +00:00
|
|
|
fn failIfTrue(ok: bool) anyerror!void {
|
2017-02-05 23:58:58 +00:00
|
|
|
if (ok) {
|
|
|
|
return error.ItBroke;
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2017-02-28 08:07:11 +00:00
|
|
|
|
2017-05-02 03:37:34 +01:00
|
|
|
test "try then not executed with assignment" {
|
2017-05-03 22:23:11 +01:00
|
|
|
if (failIfTrue(true)) {
|
2017-05-02 03:37:34 +01:00
|
|
|
unreachable;
|
|
|
|
} else |err| {
|
2021-05-04 19:23:22 +01:00
|
|
|
try expect(err == error.ItBroke);
|
2017-05-02 03:37:34 +01:00
|
|
|
}
|
|
|
|
}
|