| ... | @@ -150,6 +150,18 @@ pub const Int = struct { | ... | @@ -150,6 +150,18 @@ pub const Int = struct { |
| 150 | return bits; | 150 | return bits; |
| 151 | } | 151 | } |
| 152 | | 152 | |
| | 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 for | 165 | // 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 the | 166 | // 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 | } |
| 1219 | | 1231 | |
| | 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 | |
| 1220 | test "big.int string set" { | 1259 | test "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"); |