Function ceilPowerOfTwo [src]
Returns the next power of two (if the value is not already a power of two).
Only unsigned integers can be used. Zero is not an allowed input.
If the value doesn't fit, returns an error.
Prototype
pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T)
Parameters
T: type
value: T
Example
test ceilPowerOfTwo {
try testCeilPowerOfTwo();
try comptime testCeilPowerOfTwo();
}
Source
pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) {
comptime assert(@typeInfo(T) == .int);
const info = @typeInfo(T).int;
comptime assert(info.signedness == .unsigned);
const PromotedType = std.meta.Int(info.signedness, info.bits + 1);
const overflowBit = @as(PromotedType, 1) << info.bits;
const x = ceilPowerOfTwoPromote(T, value);
if (overflowBit & x != 0) {
return error.Overflow;
}
return @as(T, @intCast(x));
}