zig/test/behavior/bool.zig

81 lines
1.5 KiB
Zig
Raw Normal View History

2021-10-29 08:33:05 +08:00
const std = @import("std");
const expect = std.testing.expect;
2017-01-05 16:57:48 +08:00
2017-05-24 09:38:31 +08:00
test "bool literals" {
try expect(true);
try expect(!false);
2016-12-22 14:20:08 +08:00
}
2017-05-24 09:38:31 +08:00
test "cast bool to int" {
2016-12-22 14:20:08 +08:00
const t = true;
const f = false;
try expect(@boolToInt(t) == @as(u32, 1));
try expect(@boolToInt(f) == @as(u32, 0));
try nonConstCastBoolToInt(t, f);
2016-12-22 14:20:08 +08:00
}
fn nonConstCastBoolToInt(t: bool, f: bool) !void {
try expect(@boolToInt(t) == @as(u32, 1));
try expect(@boolToInt(f) == @as(u32, 0));
2016-12-22 14:20:08 +08:00
}
2017-05-24 09:38:31 +08:00
test "bool cmp" {
try expect(testBoolCmp(true, false) == false);
2016-12-22 14:42:30 +08:00
}
fn testBoolCmp(a: bool, b: bool) bool {
return a == b;
2016-12-22 14:42:30 +08:00
}
const global_f = false;
const global_t = true;
const not_global_f = !global_f;
const not_global_t = !global_t;
2017-05-24 09:38:31 +08:00
test "compile time bool not" {
try expect(not_global_f);
try expect(!not_global_t);
}
test "short circuit" {
try testShortCircuit(false, true);
comptime try testShortCircuit(false, true);
}
fn testShortCircuit(f: bool, t: bool) !void {
var hit_1 = f;
var hit_2 = f;
var hit_3 = f;
var hit_4 = f;
if (t or x: {
try expect(f);
break :x f;
}) {
hit_1 = t;
}
if (f or x: {
hit_2 = t;
break :x f;
}) {
try expect(f);
}
if (t and x: {
hit_3 = t;
break :x f;
}) {
try expect(f);
}
if (f and x: {
try expect(f);
break :x f;
}) {
try expect(f);
} else {
hit_4 = t;
}
try expect(hit_1);
try expect(hit_2);
try expect(hit_3);
try expect(hit_4);
}