Skip to content

Commit d53fae3

Browse files
tiehuisandrewrk
authored andcommittedJul 22, 2018
Add big int fits function (#1279)
Returns whether the current value in an Int fits in the requested type.
1 parent 07b6a3d commit d53fae3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
 

‎std/math/big/int.zig‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,18 @@ pub const Int = struct {
150150
return bits;
151151
}
152152

153+
pub fn fits(self: Int, comptime T: type) bool {
154+
if (self.eqZero()) {
155+
return true;
156+
}
157+
if (!T.is_signed and !self.positive) {
158+
return false;
159+
}
160+
161+
const req_bits = self.bitCountTwosComp() + @boolToInt(self.positive and T.is_signed);
162+
return T.bit_count >= req_bits;
163+
}
164+
153165
// Returns the approximate size of the integer in the given base. Negative values accomodate for
154166
// the minus sign. This is used for determining the number of characters needed to print the
155167
// value. It is inexact and will exceed the given value by 1-2 digits.
@@ -1217,6 +1229,33 @@ test "big.int bitcount/to" {
12171229
debug.assert((try a.to(i9)) == -129);
12181230
}
12191231

1232+
test "big.int fits" {
1233+
var a = try Int.init(al);
1234+
1235+
try a.set(0);
1236+
debug.assert(a.fits(u0));
1237+
debug.assert(a.fits(i0));
1238+
1239+
try a.set(255);
1240+
debug.assert(!a.fits(u0));
1241+
debug.assert(!a.fits(u1));
1242+
debug.assert(!a.fits(i8));
1243+
debug.assert(a.fits(u8));
1244+
debug.assert(a.fits(u9));
1245+
debug.assert(a.fits(i9));
1246+
1247+
try a.set(-128);
1248+
debug.assert(!a.fits(i7));
1249+
debug.assert(a.fits(i8));
1250+
debug.assert(a.fits(i9));
1251+
debug.assert(!a.fits(u9));
1252+
1253+
try a.set(0x1ffffffffeeeeeeee);
1254+
debug.assert(!a.fits(u32));
1255+
debug.assert(!a.fits(u64));
1256+
debug.assert(a.fits(u65));
1257+
}
1258+
12201259
test "big.int string set" {
12211260
var a = try Int.init(al);
12221261
try a.setString(10, "120317241209124781241290847124");

0 commit comments

Comments
 (0)