Function boolMask [src]
Returns a mask of all ones if value is true,
and a mask of all zeroes if value is false.
Compiles to one instruction for register sized integers.
Prototype
pub inline fn boolMask(comptime MaskInt: type, value: bool) MaskInt
Parameters
MaskInt: type
value: bool
Example
test boolMask {
const runTest = struct {
fn runTest() !void {
try testing.expectEqual(@as(u1, 0), boolMask(u1, false));
try testing.expectEqual(@as(u1, 1), boolMask(u1, true));
try testing.expectEqual(@as(i1, 0), boolMask(i1, false));
try testing.expectEqual(@as(i1, -1), boolMask(i1, true));
try testing.expectEqual(@as(u13, 0), boolMask(u13, false));
try testing.expectEqual(@as(u13, 0x1FFF), boolMask(u13, true));
try testing.expectEqual(@as(i13, 0), boolMask(i13, false));
try testing.expectEqual(@as(i13, -1), boolMask(i13, true));
try testing.expectEqual(@as(u32, 0), boolMask(u32, false));
try testing.expectEqual(@as(u32, 0xFFFF_FFFF), boolMask(u32, true));
try testing.expectEqual(@as(i32, 0), boolMask(i32, false));
try testing.expectEqual(@as(i32, -1), boolMask(i32, true));
}
}.runTest;
try runTest();
try comptime runTest();
}
Source
pub inline fn boolMask(comptime MaskInt: type, value: bool) MaskInt {
if (@typeInfo(MaskInt) != .int)
@compileError("boolMask requires an integer mask type.");
if (MaskInt == u0 or MaskInt == i0)
@compileError("boolMask cannot convert to u0 or i0, they are too small.");
// The u1 and i1 cases tend to overflow,
// so we special case them here.
if (MaskInt == u1) return @intFromBool(value);
if (MaskInt == i1) {
// The @as here is a workaround for #7950
return @as(i1, @bitCast(@as(u1, @intFromBool(value))));
}
return -%@as(MaskInt, @intCast(@intFromBool(value)));
}