From 8e0670198b249f44e789f4380fd17d6de918832c Mon Sep 17 00:00:00 2001 From: Sahnvour Date: Sun, 9 Jun 2019 14:44:41 +0200 Subject: allow comptime_int in math.shl and math.shr --- std/math.zig | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'std/math.zig') diff --git a/std/math.zig b/std/math.zig index 765df6280c..92b6065e3c 100644 --- a/std/math.zig +++ b/std/math.zig @@ -288,10 +288,8 @@ pub fn shl(comptime T: type, a: T, shift_amt: var) T { const abs_shift_amt = absCast(shift_amt); const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else @intCast(Log2Int(T), abs_shift_amt); - if (@typeOf(shift_amt).is_signed) { - if (shift_amt >= 0) { - return a << casted_shift_amt; - } else { + if (@typeOf(shift_amt) == comptime_int or @typeOf(shift_amt).is_signed) { + if (shift_amt < 0) { return a >> casted_shift_amt; } } @@ -304,6 +302,10 @@ test "math.shl" { testing.expect(shl(u8, 0b11111111, usize(8)) == 0); testing.expect(shl(u8, 0b11111111, usize(9)) == 0); testing.expect(shl(u8, 0b11111111, isize(-2)) == 0b00111111); + testing.expect(shl(u8, 0b11111111, 3) == 0b11111000); + testing.expect(shl(u8, 0b11111111, 8) == 0); + testing.expect(shl(u8, 0b11111111, 9) == 0); + testing.expect(shl(u8, 0b11111111, -2) == 0b00111111); } /// Shifts right. Overflowed bits are truncated. @@ -312,7 +314,7 @@ pub fn shr(comptime T: type, a: T, shift_amt: var) T { const abs_shift_amt = absCast(shift_amt); const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else @intCast(Log2Int(T), abs_shift_amt); - if (@typeOf(shift_amt).is_signed) { + if (@typeOf(shift_amt) == comptime_int or @typeOf(shift_amt).is_signed) { if (shift_amt >= 0) { return a >> casted_shift_amt; } else { @@ -328,6 +330,10 @@ test "math.shr" { testing.expect(shr(u8, 0b11111111, usize(8)) == 0); testing.expect(shr(u8, 0b11111111, usize(9)) == 0); testing.expect(shr(u8, 0b11111111, isize(-2)) == 0b11111100); + testing.expect(shr(u8, 0b11111111, 3) == 0b00011111); + testing.expect(shr(u8, 0b11111111, 8) == 0); + testing.expect(shr(u8, 0b11111111, 9) == 0); + testing.expect(shr(u8, 0b11111111, -2) == 0b11111100); } /// Rotates right. Only unsigned values can be rotated. -- cgit v1.2.3 From ebedc99ac1148c8d3465ad2338d3db142e57579f Mon Sep 17 00:00:00 2001 From: daurnimator Date: Mon, 20 May 2019 23:22:58 +1000 Subject: std: add math.isPowerOfTwo --- std/math.zig | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'std/math.zig') diff --git a/std/math.zig b/std/math.zig index 765df6280c..7464a9fc97 100644 --- a/std/math.zig +++ b/std/math.zig @@ -680,6 +680,11 @@ pub fn alignCast(comptime alignment: u29, ptr: var) AlignCastError!@typeOf(@alig return @alignCast(alignment, ptr); } +pub fn isPowerOfTwo(v: var) bool { + assert(v != 0); + return (v & (v - 1)) == 0; +} + pub fn floorPowerOfTwo(comptime T: type, value: T) T { var x = value; -- cgit v1.2.3