Skip to content

Commit

Permalink
std.math.isPowerOfTwo: add tests and doc comment and improve assert
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
wooster0 authored and andrewrk committed Jun 18, 2023
1 parent c13ac52 commit 2839e35
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions lib/std/math.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1111,9 +1111,22 @@ pub fn alignCast(comptime alignment: u29, ptr: anytype) AlignCastError!@TypeOf(@
return @alignCast(alignment, ptr);
}

pub fn isPowerOfTwo(v: anytype) bool {
assert(v != 0);
return (v & (v - 1)) == 0;
/// Asserts `int > 0`.
pub fn isPowerOfTwo(int: anytype) bool {
assert(int > 0);
return (int & (int - 1)) == 0;
}

test isPowerOfTwo {
try testing.expect(isPowerOfTwo(@as(u8, 1)));
try testing.expect(isPowerOfTwo(2));
try testing.expect(!isPowerOfTwo(@as(i16, 3)));
try testing.expect(isPowerOfTwo(4));
try testing.expect(!isPowerOfTwo(@as(u32, 31)));
try testing.expect(isPowerOfTwo(32));
try testing.expect(!isPowerOfTwo(@as(i64, 63)));
try testing.expect(isPowerOfTwo(128));
try testing.expect(isPowerOfTwo(@as(u128, 256)));
}

/// Aligns the given integer type bit width to a width divisible by 8.
Expand Down

0 comments on commit 2839e35

Please sign in to comment.