authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2019-06-04 15:49:27-07:00
committergravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2019-06-04 15:49:27-07:00
loga0d66fa1e6e8b9620e4990a33c32b0db11469aec
tree3d719bee622c220dc902fbf76ac17db54f3cf09e
parent9bed6e1bf94b79ff027cb5aab3fa7231973337a9

std.math: Clarify ceilPowerOfTwo inputs and disallow zero as an input


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

std/math.zig+7-9
......@@ -706,23 +706,23 @@ fn testFloorPowerOfTwo() void {
706706}
707707
708708/// Returns the next power of two (if the value is not already a power of two).
709/// Only unsigned integers can be used. Zero is not an allowed input.
709710/// Result is a type with 1 more bit than the input type.
710711pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) @IntType(T.is_signed, T.bit_count + 1) {
711 if (T.is_signed) {
712 @compileError("signed integers not supported");
713 }
712 comptime assert(@typeId(T) == builtin.TypeId.Int);
713 comptime assert(!T.is_signed);
714 assert(value != 0);
714715 comptime const promotedType = @IntType(T.is_signed, T.bit_count + 1);
715716 comptime const shiftType = std.math.Log2Int(promotedType);
716 if (value == 0) return promotedType(0);
717717 return promotedType(1) << @intCast(shiftType, T.bit_count - @clz(T, value - 1));
718718}
719719
720720/// Returns the next power of two (if the value is not already a power of two).
721/// Only unsigned integers can be used. Zero is not an allowed input.
721722/// If the value doesn't fit, returns an error.
722723pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) {
723 if (T.is_signed) {
724 @compileError("signed integers not supported");
725 }
724 comptime assert(@typeId(T) == builtin.TypeId.Int);
725 comptime assert(!T.is_signed);
726726 comptime const promotedType = @IntType(T.is_signed, T.bit_count + 1);
727727 comptime const overflowBit = promotedType(1) << T.bit_count;
728728 var x = ceilPowerOfTwoPromote(T, value);
......@@ -738,7 +738,6 @@ test "math.ceilPowerOfTwoPromote" {
738738}
739739
740740fn testCeilPowerOfTwoPromote() void {
741 testing.expectEqual(u33(0), ceilPowerOfTwoPromote(u32, 0));
742741 testing.expectEqual(u33(1), ceilPowerOfTwoPromote(u32, 1));
743742 testing.expectEqual(u33(2), ceilPowerOfTwoPromote(u32, 2));
744743 testing.expectEqual(u33(64), ceilPowerOfTwoPromote(u32, 63));
......@@ -756,7 +755,6 @@ test "math.ceilPowerOfTwo" {
756755}
757756
758757fn testCeilPowerOfTwo() !void {
759 testing.expectEqual(u32(0), try ceilPowerOfTwo(u32, 0));
760758 testing.expectEqual(u32(1), try ceilPowerOfTwo(u32, 1));
761759 testing.expectEqual(u32(2), try ceilPowerOfTwo(u32, 2));
762760 testing.expectEqual(u32(64), try ceilPowerOfTwo(u32, 63));