diff options
| author | Andrew Kelley <superjoe30@gmail.com> | 2018-05-10 11:37:25 -0400 |
|---|---|---|
| committer | Andrew Kelley <superjoe30@gmail.com> | 2018-05-10 11:37:25 -0400 |
| commit | 284ab109c4b83f7bb9a832f284f706e641b002fd (patch) | |
| tree | d7dc258a7e0676a9867e7941d8605074b57ea74a /std/math | |
| parent | 7e37d268c86ccc823c4a381a42029722d36c3975 (diff) | |
| parent | efa39c5343e13a13e65210f55da5df23ee3feb3e (diff) | |
| download | zig-284ab109c4b83f7bb9a832f284f706e641b002fd.tar.gz zig-284ab109c4b83f7bb9a832f284f706e641b002fd.zip | |
Merge remote-tracking branch 'origin/master' into llvm7
Diffstat (limited to 'std/math')
| -rw-r--r-- | std/math/index.zig | 26 | ||||
| -rw-r--r-- | std/math/log2.zig | 7 |
2 files changed, 27 insertions, 6 deletions
diff --git a/std/math/index.zig b/std/math/index.zig index 83ba055329..a549a6bb61 100644 --- a/std/math/index.zig +++ b/std/math/index.zig @@ -558,6 +558,32 @@ test "math.floorPowerOfTwo" { comptime testFloorPowerOfTwo(); } +pub fn log2_int(comptime T: type, x: T) Log2Int(T) { + assert(x != 0); + return Log2Int(T)(T.bit_count - 1 - @clz(x)); +} + +pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) { + assert(x != 0); + const log2_val = log2_int(T, x); + if (T(1) << log2_val == x) + return log2_val; + return log2_val + 1; +} + +test "std.math.log2_int_ceil" { + assert(log2_int_ceil(u32, 1) == 0); + assert(log2_int_ceil(u32, 2) == 1); + assert(log2_int_ceil(u32, 3) == 2); + assert(log2_int_ceil(u32, 4) == 2); + assert(log2_int_ceil(u32, 5) == 3); + assert(log2_int_ceil(u32, 6) == 3); + assert(log2_int_ceil(u32, 7) == 3); + assert(log2_int_ceil(u32, 8) == 3); + assert(log2_int_ceil(u32, 9) == 4); + assert(log2_int_ceil(u32, 10) == 4); +} + fn testFloorPowerOfTwo() void { assert(floorPowerOfTwo(u32, 63) == 32); assert(floorPowerOfTwo(u32, 64) == 64); diff --git a/std/math/log2.zig b/std/math/log2.zig index 998d6d6c5e..d5bbe385c2 100644 --- a/std/math/log2.zig +++ b/std/math/log2.zig @@ -31,17 +31,12 @@ pub fn log2(x: var) @typeOf(x) { return result; }, TypeId.Int => { - return log2_int(T, x); + return math.log2_int(T, x); }, else => @compileError("log2 not implemented for " ++ @typeName(T)), } } -pub fn log2_int(comptime T: type, x: T) T { - assert(x != 0); - return T.bit_count - 1 - T(@clz(x)); -} - pub fn log2_32(x_: f32) f32 { const ivln2hi: f32 = 1.4428710938e+00; const ivln2lo: f32 = -1.7605285393e-04; |
