authorgravatar for topolarity@tapscott.meCody Tapscott <topolarity@tapscott.me> 2022-02-11 09:24:08-07:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2022-02-13 14:47:58+02:00
logf516e2c5b1d0e073d9ab4cd417aeb21f6cdf4a99
tree20acf406ee278710a081a2ec4cd87d6277d25562
parent3bbe6a28e069b03c8a9185dd14129517453e26d2

Simplify implementation of floorPowerOfTwo in std.math


1 files changed, 9 insertions(+), 8 deletions(-)

lib/std/math.zig+9-8
......@@ -1045,14 +1045,9 @@ pub fn isPowerOfTwo(v: anytype) bool {
10451045/// Returns the nearest power of two less than or equal to value, or
10461046/// zero if value is less than or equal to zero.
10471047pub fn floorPowerOfTwo(comptime T: type, value: T) T {
1048 var x = value;
1049
1050 comptime var i = 1;
1051 inline while (@typeInfo(T).Int.bits > i) : (i *= 2) {
1052 x |= (x >> i);
1053 }
1054
1055 return x - (x >> 1);
1048 const uT = std.meta.Int(.unsigned, @typeInfo(T).Int.bits);
1049 if (value <= 0) return 0;
1050 return @as(T, 1) << log2_int(uT, @intCast(uT, value));
10561051}
10571052
10581053test "math.floorPowerOfTwo" {
......@@ -1064,9 +1059,15 @@ fn testFloorPowerOfTwo() !void {
10641059 try testing.expect(floorPowerOfTwo(u32, 63) == 32);
10651060 try testing.expect(floorPowerOfTwo(u32, 64) == 64);
10661061 try testing.expect(floorPowerOfTwo(u32, 65) == 64);
1062 try testing.expect(floorPowerOfTwo(u32, 0) == 0);
10671063 try testing.expect(floorPowerOfTwo(u4, 7) == 4);
10681064 try testing.expect(floorPowerOfTwo(u4, 8) == 8);
10691065 try testing.expect(floorPowerOfTwo(u4, 9) == 8);
1066 try testing.expect(floorPowerOfTwo(u4, 0) == 0);
1067 try testing.expect(floorPowerOfTwo(i4, 7) == 4);
1068 try testing.expect(floorPowerOfTwo(i4, -8) == 0);
1069 try testing.expect(floorPowerOfTwo(i4, -1) == 0);
1070 try testing.expect(floorPowerOfTwo(i4, 0) == 0);
10701071}
10711072
10721073/// Returns the next power of two (if the value is not already a power of two).