authorgravatar for marc@tiehu.isMarc Tiehuis <marc@tiehu.is> 2018-07-23 02:11:27+12:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-07-22 10:11:27-04:00
logd53fae3551f6215b99f065e837f1f4439ba850fd
tree1ccf863eb9c128fed560adb48d42d7f6d7ea44ed
parent07b6a3d335450778f69a6ee5afa5716e4fe83fe3

Add big int fits function (#1279)

Returns whether the current value in an Int fits in the requested type.

1 files changed, 39 insertions(+), 0 deletions(-)

std/math/big/int.zig+39
...@@ -150,6 +150,18 @@ pub const Int = struct {...@@ -150,6 +150,18 @@ pub const Int = struct {
150 return bits;150 return bits;
151 }151 }
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
153 // Returns the approximate size of the integer in the given base. Negative values accomodate for165 // Returns the approximate size of the integer in the given base. Negative values accomodate for
154 // the minus sign. This is used for determining the number of characters needed to print the166 // the minus sign. This is used for determining the number of characters needed to print the
155 // value. It is inexact and will exceed the given value by 1-2 digits.167 // value. It is inexact and will exceed the given value by 1-2 digits.
...@@ -1217,6 +1229,33 @@ test "big.int bitcount/to" {...@@ -1217,6 +1229,33 @@ test "big.int bitcount/to" {
1217 debug.assert((try a.to(i9)) == -129);1229 debug.assert((try a.to(i9)) == -129);
1218}1230}
12191231
1232test "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
1220test "big.int string set" {1259test "big.int string set" {
1221 var a = try Int.init(al);1260 var a = try Int.init(al);
1222 try a.setString(10, "120317241209124781241290847124");1261 try a.setString(10, "120317241209124781241290847124");