authorgravatar for r00ster91@proton.meWooster <r00ster91@proton.me> 2023-05-29 01:48:24+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-06-18 10:42:03-07:00
log2839e35d1c06ca5b6bda1f20ae870f2b2fbbbfb1
treee563096f2b145f0edbc6e556b43284d5fd006582
parentc13ac52972b864ff3aa9fc373f96d7ede41d5a31

std.math.isPowerOfTwo: add tests and doc comment and improve assert

The assert is changed from `int != 0` to `int > 0` because negative integers always return `false`. Python's `math.log2` does the same and errors for 0 or negative integers.

1 files changed, 16 insertions(+), 3 deletions(-)

lib/std/math.zig+16-3
......@@ -1111,9 +1111,22 @@ pub fn alignCast(comptime alignment: u29, ptr: anytype) AlignCastError!@TypeOf(@
11111111 return @alignCast(alignment, ptr);
11121112}
11131113
1114pub fn isPowerOfTwo(v: anytype) bool {
1115 assert(v != 0);
1116 return (v & (v - 1)) == 0;
1114/// Asserts `int > 0`.
1115pub fn isPowerOfTwo(int: anytype) bool {
1116 assert(int > 0);
1117 return (int & (int - 1)) == 0;
1118}
1119
1120test isPowerOfTwo {
1121 try testing.expect(isPowerOfTwo(@as(u8, 1)));
1122 try testing.expect(isPowerOfTwo(2));
1123 try testing.expect(!isPowerOfTwo(@as(i16, 3)));
1124 try testing.expect(isPowerOfTwo(4));
1125 try testing.expect(!isPowerOfTwo(@as(u32, 31)));
1126 try testing.expect(isPowerOfTwo(32));
1127 try testing.expect(!isPowerOfTwo(@as(i64, 63)));
1128 try testing.expect(isPowerOfTwo(128));
1129 try testing.expect(isPowerOfTwo(@as(u128, 256)));
11171130}
11181131
11191132/// Aligns the given integer type bit width to a width divisible by 8.