Function to [src]
Alias for std.math.big.int.Const.toInt
Convert self to integer type T.
Returns an error if self cannot be narrowed into the requested type without truncation.
Prototype
pub fn toInt(self: Const, comptime T: type) ConvertError!T
Parameters
self: Const
T: type
Possible Errors
Source
pub fn toInt(self: Const, comptime T: type) ConvertError!T {
switch (@typeInfo(T)) {
.int => |info| {
// Make sure -0 is handled correctly.
if (self.eqlZero()) return 0;
const UT = std.meta.Int(.unsigned, info.bits);
if (!self.fitsInTwosComp(info.signedness, info.bits)) {
return error.TargetTooSmall;
}
var r: UT = 0;
if (@sizeOf(UT) <= @sizeOf(Limb)) {
r = @as(UT, @intCast(self.limbs[0]));
} else {
for (self.limbs[0..self.limbs.len], 0..) |_, ri| {
const limb = self.limbs[self.limbs.len - ri - 1];
r <<= limb_bits;
r |= limb;
}
}
if (info.signedness == .unsigned) {
return if (self.positive) @as(T, @intCast(r)) else error.NegativeIntoUnsigned;
} else {
if (self.positive) {
return @intCast(r);
} else {
if (math.cast(T, r)) |ok| {
return -ok;
} else {
return minInt(T);
}
}
}
},
else => @compileError("expected int type, found '" ++ @typeName(T) ++ "'"),
}
}