master
1const std = @import("std");
2const builtin = @import("builtin");
3const expect = std.testing.expect;
4const expectEqual = std.testing.expectEqual;
5
6test "bool literals" {
7 try expect(true);
8 try expect(!false);
9}
10
11test "cast bool to int" {
12 if (builtin.zig_backend == .stage2_riscv64) return error.SkipZigTest;
13 if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest;
14
15 const t = true;
16 const f = false;
17 try expectEqual(@as(u32, 1), @intFromBool(t));
18 try expectEqual(@as(u32, 0), @intFromBool(f));
19 try expectEqual(-1, @as(i1, @bitCast(@intFromBool(t))));
20 try expectEqual(0, @as(i1, @bitCast(@intFromBool(f))));
21 try expectEqual(u1, @TypeOf(@intFromBool(t)));
22 try expectEqual(u1, @TypeOf(@intFromBool(f)));
23 try nonConstCastIntFromBool(t, f);
24}
25
26fn nonConstCastIntFromBool(t: bool, f: bool) !void {
27 try expectEqual(@as(u32, 1), @intFromBool(t));
28 try expectEqual(@as(u32, 0), @intFromBool(f));
29 try expectEqual(@as(i1, -1), @as(i1, @bitCast(@intFromBool(t))));
30 try expectEqual(@as(i1, 0), @as(i1, @bitCast(@intFromBool(f))));
31 try expectEqual(u1, @TypeOf(@intFromBool(t)));
32 try expectEqual(u1, @TypeOf(@intFromBool(f)));
33}
34
35test "bool cmp" {
36 try expect(testBoolCmp(true, false) == false);
37}
38fn testBoolCmp(a: bool, b: bool) bool {
39 return a == b;
40}
41
42const global_f = false;
43const global_t = true;
44const not_global_f = !global_f;
45const not_global_t = !global_t;
46test "compile time bool not" {
47 try expect(not_global_f);
48 try expect(!not_global_t);
49}
50
51test "short circuit" {
52 try testShortCircuit(false, true);
53 try comptime testShortCircuit(false, true);
54}
55
56fn testShortCircuit(f: bool, t: bool) !void {
57 var hit_1 = f;
58 var hit_2 = f;
59 var hit_3 = f;
60 var hit_4 = f;
61
62 if (t or x: {
63 try expect(f);
64 break :x f;
65 }) {
66 hit_1 = t;
67 }
68 if (f or x: {
69 hit_2 = t;
70 break :x f;
71 }) {
72 try expect(f);
73 }
74
75 if (t and x: {
76 hit_3 = t;
77 break :x f;
78 }) {
79 try expect(f);
80 }
81 if (f and x: {
82 try expect(f);
83 break :x f;
84 }) {
85 try expect(f);
86 } else {
87 hit_4 = t;
88 }
89 try expect(hit_1);
90 try expect(hit_2);
91 try expect(hit_3);
92 try expect(hit_4);
93}
94
95test "or with noreturn operand" {
96 const S = struct {
97 fn foo(a: u32, b: u32) bool {
98 return a == 5 or b == 2 or @panic("oh no");
99 }
100 };
101 _ = S.foo(2, 2);
102}