Debian Codegraph @

rpython/rlib/test/test_rbigint.py

raw symbols SCIP
1 from __future__ import division
2
3 import operator
4 import sys, os
5 import math
6 from random import random, randint, sample
7
8 try:
9 import pytest
10 except ImportError:
11 print 'cwd', os.getcwd()
12 print 'sys.path', sys.path
13 raise
14
15 from rpython.rlib import rbigint as lobj
16 from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong, intmask, LONG_BIT
17 from rpython.rlib.rbigint import (frombytes_int, rbigint, SHIFT, MASK, KARATSUBA_CUTOFF,
18 _store_digit, _mask_digit, InvalidEndiannessError, InvalidSignednessError,
19 gcd_lehmer, lehmer_xgcd, gcd_binary, divmod_big, ONERBIGINT, MaxIntError,
20 _str_to_int_big_w5pow, _str_to_int_big_base10, _str_to_int_big_inner10,
21 _format_lowest_level_divmod_int_results, _format_int10_18digits,
22 bit_length_int, _bitcount64, tobytes_int)
23 from rpython.rlib.rbigint import HOLDER
24 from rpython.rlib.rfloat import NAN
25 from rpython.rtyper.test.test_llinterp import interpret
26 from rpython.translator.c.test.test_standalone import StandaloneTests
27 from rpython.rtyper.tool.rfficache import platform
28 from rpython.rlib.rstring import StringBuilder
29
30 from hypothesis import given, strategies, example, settings, assume, HealthCheck
31
32 longs = strategies.builds(
33 long, strategies.integers())
34 ints = strategies.integers(-sys.maxint-1, sys.maxint)
35 _BIG_INT_MAX = 10000 if sys.maxint > 2 ** 32 else 2000
36
37
38 def makelong(data):
39 numbits = data.draw(strategies.integers(1, 2000))
40 r = data.draw(strategies.integers(0, 1 << numbits))
41 if data.draw(strategies.booleans()):
42 return -r
43 return r
44
45 def makelong_long_sequences(data, ndigits):
46 """ From CPython:
47 Get quasi-random long consisting of ndigits digits (in base BASE).
48 quasi == the most-significant digit will not be 0, and the number
49 is constructed to contain long strings of 0 and 1 bits. These are
50 more likely than random bits to provoke digit-boundary errors.
51 The sign of the number is also random.
52 """
53 nbits_hi = ndigits * SHIFT
54 nbits_lo = nbits_hi - SHIFT + 1
55 answer = 0L
56 nbits = 0
57 r = data.draw(strategies.integers(0, SHIFT * 2 - 1)) | 1 # force 1 bits to start
58 while nbits < nbits_lo:
59 bits = (r >> 1) + 1
60 bits = min(bits, nbits_hi - nbits)
61 assert 1 <= bits <= SHIFT
62 nbits = nbits + bits
63 answer = answer << bits
64 if r & 1:
65 answer = answer | ((1 << bits) - 1)
66 r = data.draw(strategies.integers(0, SHIFT * 2 - 1))
67 assert nbits_lo <= nbits <= nbits_hi
68 if data.draw(strategies.booleans()):
69 answer = -answer
70 return answer
71
72
73 MAXDIGITS = 15
74 digitsizes = strategies.sampled_from(
75 range(1, MAXDIGITS+1) +
76 range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 14) +
77 [KARATSUBA_CUTOFF * 3, KARATSUBA_CUTOFF * 1000]
78 )
79
80 def make_biglongs_for_division(data):
81 size1 = data.draw(digitsizes)
82 val1 = makelong_long_sequences(data, size1)
83 size2 = data.draw(digitsizes)
84 val2 = makelong_long_sequences(data, size2)
85 return val1, val2
86
87 tuples_biglongs_for_division = strategies.builds(
88 make_biglongs_for_division,
89 strategies.data())
90
91 biglongs = strategies.builds(makelong, strategies.data())
92
93
94 def makerarithint(data):
95 classlist = platform.numbertype_to_rclass.values()
96 cls = data.draw(strategies.sampled_from(classlist))
97 if cls is int:
98 minimum = -sys.maxint-1
99 maximum = sys.maxint
100 else:
101 BITS = cls.BITS
102 if cls.SIGNED:
103 minimum = -2 ** (BITS - 1)
104 maximum = 2 ** (BITS - 1) - 1
105 else:
106 minimum = 0
107 maximum = 2 ** BITS - 1
108 value = data.draw(strategies.integers(minimum, maximum))
109 return cls(value)
110 rarith_ints = strategies.builds(makerarithint, strategies.data())
111
112
113 def gen_signs(l):
114 for s in l:
115 if s == 0:
116 yield s
117 else:
118 yield s
119 yield -s
120
121 long_vals_not_too_big = range(17) + [
122 37, 39, 50,
123 127, 128, 129, 511, 512, 513, sys.maxint, sys.maxint + 1,
124 12345678901234567890L,
125 123456789123456789000000L,
126 ]
127
128 long_vals = long_vals_not_too_big + [
129 1 << 100, 3 ** 10000]
130
131 int_vals = range(33) + [
132 1000,
133 0x11111111, 0x11111112, 8888,
134 9999, sys.maxint, 2 ** 19, 2 ** 18 - 1
135 ]
136 signed_int_vals = list(gen_signs(int_vals)) + [-sys.maxint-1]
137
138 class TestRLong(object):
139 def test_simple(self):
140 for op1 in [-2, -1, 0, 1, 2, 10, 50]:
141 for op2 in [-2, -1, 0, 1, 2, 10, 50]:
142 rl_op1 = rbigint.fromint(op1)
143 rl_op2 = rbigint.fromint(op2)
144 for op in "add sub mul".split():
145 r1 = getattr(rl_op1, op)(rl_op2)
146 r2 = getattr(operator, op)(op1, op2)
147 assert r1.tolong() == r2
148
149 def test_frombool(self):
150 assert rbigint.frombool(False).tolong() == 0
151 assert rbigint.frombool(True).tolong() == 1
152
153 def test_str(self):
154 n = 1
155 r1 = rbigint.fromint(1)
156 three = rbigint.fromint(3)
157 for i in range(300):
158 n *= 3
159 r1 = r1.mul(three)
160 assert r1.str() == str(n)
161 r2 = r1.neg()
162 assert r2.str() == str(-n)
163
164 def test_floordiv(self):
165 for op1 in gen_signs(long_vals):
166 rl_op1 = rbigint.fromlong(op1)
167 for op2 in gen_signs(long_vals):
168 if not op2:
169 continue
170 rl_op2 = rbigint.fromlong(op2)
171 r1 = rl_op1.floordiv(rl_op2)
172 r2 = op1 // op2
173 assert r1.tolong() == r2
174
175 def test_int_floordiv(self):
176 x = 1000L
177 r = rbigint.fromlong(x)
178 r2 = r.int_floordiv(10)
179 assert r2.tolong() == 100L
180
181 for op1 in gen_signs(long_vals):
182 for op2 in signed_int_vals:
183 if not op2:
184 continue
185 rl_op1 = rbigint.fromlong(op1)
186 r1 = rl_op1.int_floordiv(op2)
187 r2 = op1 // op2
188 assert r1.tolong() == r2
189
190 with pytest.raises(ZeroDivisionError):
191 r.int_floordiv(0)
192
193 # Error pointed out by Armin Rigo
194 n = sys.maxint+1
195 r = rbigint.fromlong(n)
196 assert r.int_floordiv(int(-n)).tolong() == -1L
197
198 for x in int_vals:
199 if not x:
200 continue
201 r = rbigint.fromlong(x)
202 rn = rbigint.fromlong(-x)
203 res = r.int_floordiv(x)
204 res2 = r.int_floordiv(-x)
205 res3 = rn.int_floordiv(x)
206 assert res.tolong() == 1L
207 assert res2.tolong() == -1L
208 assert res3.tolong() == -1L
209
210 def test_floordiv2(self):
211 n1 = rbigint.fromlong(sys.maxint + 1)
212 n2 = rbigint.fromlong(-(sys.maxint + 1))
213 assert n1.floordiv(n2).tolong() == -1L
214 assert n2.floordiv(n1).tolong() == -1L
215
216 def test_truediv(self):
217 for op1 in gen_signs(long_vals_not_too_big):
218 rl_op1 = rbigint.fromlong(op1)
219 for op2 in gen_signs(long_vals):
220 rl_op2 = rbigint.fromlong(op2)
221 if not op2:
222 with pytest.raises(ZeroDivisionError):
223 rl_op1.truediv(rl_op2)
224 continue
225 r1 = rl_op1.truediv(rl_op2)
226 r2 = op1 / op2
227 assert r1 == r2
228
229 def test_truediv_precision(self):
230 op1 = rbigint.fromlong(12345*2**30)
231 op2 = rbigint.fromlong(98765*7**81)
232 f = op1.truediv(op2)
233 assert f == 4.7298422347492634e-61 # exactly
234
235 def test_truediv_overflow(self):
236 overflowing = 2**1024 - 2**(1024-53-1)
237 op1 = rbigint.fromlong(overflowing-1)
238 op2 = rbigint.fromlong(1)
239 f = op1.truediv(op2)
240 assert f == 1.7976931348623157e+308 # exactly
241
242 op1 = rbigint.fromlong(overflowing-1)
243 op2 = rbigint.fromlong(-1)
244 f = op1.truediv(op2)
245 assert f == -1.7976931348623157e+308 # exactly
246
247 op1 = rbigint.fromlong(-overflowing+1)
248 op2 = rbigint.fromlong(-1)
249 f = op1.truediv(op2)
250 assert f == +1.7976931348623157e+308 # exactly
251
252 op1 = rbigint.fromlong(overflowing)
253 op2 = rbigint.fromlong(1)
254 with pytest.raises(OverflowError):
255 op1.truediv(op2)
256
257 def test_truediv_overflow2(self):
258 overflowing = 2**1024 - 2**(1024-53-1)
259 op1 = rbigint.fromlong(2*overflowing - 10)
260 op2 = rbigint.fromlong(2)
261 f = op1.truediv(op2)
262 assert f == 1.7976931348623157e+308 # exactly
263 op2 = rbigint.fromlong(-2)
264 f = op1.truediv(op2)
265 assert f == -1.7976931348623157e+308 # exactly
266
267 def test_mod(self):
268 for op1 in gen_signs(long_vals):
269 rl_op1 = rbigint.fromlong(op1)
270 for op2 in gen_signs(long_vals):
271 rl_op2 = rbigint.fromlong(op2)
272 if not op2:
273 with pytest.raises(ZeroDivisionError):
274 rl_op1.mod(rl_op2)
275 continue
276 r1 = rl_op1.mod(rl_op2)
277 r2 = op1 % op2
278
279 assert r1.tolong() == r2
280
281 def test_int_mod(self):
282 for x in gen_signs(long_vals):
283 op1 = rbigint.fromlong(x)
284 for y in signed_int_vals:
285 if not y:
286 with pytest.raises(ZeroDivisionError):
287 op1.int_mod(0)
288 continue
289 r1 = op1.int_mod(y)
290 r2 = x % y
291 assert r1.tolong() == r2
292
293 def test_int_mod_int_result(self):
294 for x in gen_signs(long_vals):
295 op1 = rbigint.fromlong(x)
296 for y in signed_int_vals:
297 if not y:
298 with pytest.raises(ZeroDivisionError):
299 op1.int_mod_int_result(0)
300 continue
301 r1 = op1.int_mod_int_result(y)
302 r2 = x % y
303 assert r1 == r2
304
305 def test_int_divmod_int_result(self):
306 for x in gen_signs(long_vals):
307 op1 = rbigint.fromlong(x)
308 for y in signed_int_vals:
309 if not y:
310 continue
311 r1 = op1.int_mod_int_result(y)
312 r2 = x % y
313 assert r1 == r2
314
315
316 def test_pow(self):
317 for op1 in gen_signs(long_vals_not_too_big):
318 rl_op1 = rbigint.fromlong(op1)
319 for op2 in [0, 1, 2, 8, 9, 10, 11]:
320 rl_op2 = rbigint.fromint(op2)
321 r1 = rl_op1.pow(rl_op2)
322 r2 = op1 ** op2
323 assert r1.tolong() == r2
324
325 for op3 in gen_signs([1, 2, 5, 1000, 12312312312312235659969696l]):
326 if not op3:
327 continue
328 r3 = rl_op1.pow(rl_op2, rbigint.fromlong(op3))
329 r4 = pow(op1, op2, op3)
330 assert r3.tolong() == r4
331
332 def test_int_pow(self):
333 for op1 in gen_signs(long_vals_not_too_big):
334 rl_op1 = rbigint.fromlong(op1)
335 for op2 in [0, 1, 2, 8, 9, 10, 11, 127, 128, 129]:
336 r1 = rl_op1.int_pow(op2)
337 r2 = op1 ** op2
338 assert r1.tolong() == r2
339
340 for op3 in gen_signs(long_vals_not_too_big):
341 if not op3:
342 continue
343 r3 = rl_op1.int_pow(op2, rbigint.fromlong(op3))
344 r4 = pow(op1, op2, op3)
345 assert r3.tolong() == r4
346
347 def test_int_pow_big(self):
348 if sys.maxint < 2**32:
349 pytest.skip("64-bit only")
350 for op1 in gen_signs(int_vals):
351 rl_op1 = rbigint.fromint(op1)
352 for op2 in [2**31, 2**32-1, 2**32]:
353 r1 = rl_op1.int_pow(op2, rbigint.fromint(sys.maxint))
354 r2 = pow(op1, op2, sys.maxint)
355 assert r1.tolong() == r2
356
357 def test_pow_raises(self):
358 r1 = rbigint.fromint(2)
359 r0 = rbigint.fromint(0)
360 with pytest.raises(ValueError):
361 r1.int_pow(2, r0)
362 with pytest.raises(ValueError):
363 r1.pow(r1, r0)
364
365 def test_touint(self):
366 result = r_uint(sys.maxint + 42)
367 rl = rbigint.fromint(sys.maxint).add(rbigint.fromint(42))
368 assert rl.touint() == result
369
370 def test_eq_ne_operators(self):
371 a1 = rbigint.fromint(12)
372 a2 = rbigint.fromint(12)
373 a3 = rbigint.fromint(123)
374
375 assert a1 == a2
376 assert a1 != a3
377 assert not (a1 != a2)
378 assert not (a1 == a3)
379
380 def test_divmod_big2(self):
381 def check(a, b):
382 fa = rbigint.fromlong(a)
383 fb = rbigint.fromlong(b)
384 div, mod = divmod_big(fa, fb)
385 assert div.mul(fb).add(mod).eq(fa)
386 check(2, 3)
387 check(3, 2)
388 check((2 << 1000) - 1, (2 << (65 * 3 + 2)) - 1)
389 check((2 + 5 * 2 ** SHIFT) << (100 * SHIFT), 5 << (100 * SHIFT))
390
391 def test_divmod_big_is_used(self, monkeypatch):
392 # make sure that the big divmod path is actually hit
393 monkeypatch.setattr(rbigint, "_divmod_small", None)
394 fa = rbigint.fromlong(3 ** (SHIFT * HOLDER.DIV_LIMIT * 2))
395 fb = rbigint.fromlong(5 ** (SHIFT * HOLDER.DIV_LIMIT))
396 div, mod = fa.divmod(fb)
397 assert div.mul(fb).add(mod).eq(fa)
398
399 def test_karatsuba_not_used_bug(self):
400 a = rbigint.fromlong(2 ** 2000 + 1)
401 b = rbigint.fromlong(2 ** 5000 + 7)
402 assert a.mul(b).tolong() == a.tolong() * b.tolong()
403
404 def test_lopsided_bug(self):
405 la = 0x1b8e499a888235ea66f6497e3640bc118592a4ecb800e53e0121af9b2dede38c9323dc160ad564c10ff34095fcc89ecefde3116e7ad99bd5a5b785d811a1e930ae0b0a919623569c99d6c1e779aa5345609a14fc64a83970991d7df672d3bf2fe800766932291b2593382495d1b2a9de1a212d0e517d35764a8a30d060d4218f034807c59728a009683887c3f239f6b958216fd6e36db778bf350941be6ee987f87ea6460ba77f1db154fff175d20117107b5ebd48305b4190d082433419f3daace778d9ce9975ca33293c8b7ad7dd253321e208c22e1bf3833535dd4c76395117e6f32444254fdb9e77cd0b5f8d98c31dafaab720067ef925
406 a = rbigint.fromlong(la)
407 lb = 0x30fcf4a0f2ae98bd28d249c3eeabf902b492ec4f8001978aacada9f76e18b0f9e9234e6013427a3ac705c82716b9fde1c35ac9a7f6d8317bd14643473bca821da73012c9ee77b66bbc287529bbd97797c82e5e327a0e9f0110346e27e894e21c471d44493cbadaed7780410a585a118ad91e88fd02a5b4608483e500ac23c9e1ccf1d4ed7e811c8280647f953cd8d3109cad389a77df7f0f8cd01074e0c52d6380e12798f84637513b41c7029891c90c8f1436a5d5ab4ce656c80405b1f53fbda529ba66c49f0a4b059ea4862fb8a5977758ae4875a74e22b05e98a5dd43f41e6361b0407925e34d8b7fa5698d6d815adf712f7e71d2a8d75ee7749e22e558157d73c1ed1089063dd7a29c915990836b5a951aa77917847bd9807d6c89b4262871127d17ca5a84e2b23bc5eb66137cce412dcbd88622b55b05b710258affcc845a8e1b99d33c187a237eacd21e9628063948f711b2e5617b647f3fe7c28bac1989612a66d6be34d59ffee63e15e0cdf10d43c6f6301c47e7c7f3ca71dc4e312873633957a6054f25d4db49dcc401aba272ff7c23e077c143510a040f5eb80fe096384c3a4ab0604d951710956f84cdefb631a2ed806ad8f5fef5ef1223dbea4b8a7b49309e9672e77c763dbb698432c77cfff875ab5c97d24f4441b5a3704deda8835135e3e6314be281a97963b49eccf06571b634efa16605a0ec2eda8148a6537e24da5fb128cfbde3ea6c28d850eac3815dd2a0a72844a14590124a6e9062befbdf7fb14c7783ee5096481a5ef0ef9dabf4bc831213afc469a5256818e1dba97cae6f63d6cf2b9584361f36b1b8fa60286fe6bc010129b7f99ee250907ed0a134900513bd3c38555de3b085e7e86
408 b = rbigint.fromlong(lb)
409 x = a.mul(b)
410 assert x.tolong() == la * lb
411
412 def test_mul_bug(self):
413 x = -0x1fffffffffffe00000000000007fffffffffffffffffe0000000000000fffffffffffffc0000000000000003fffffffffff1fffffffffffffffffffff8000000000000000ff80000000000000fffffff000000000000000000000fff800000000000003fffffffffffffffffffffffffffffffe000000000000000000fffffffffffffffffffffffffffffffffffffffffffffc3ffffffffffffff80000000003fffffffffffffe000000000000003fffffffffffffffffffffffffffffffffffffc000000000000000007ffc00000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe00000000000000000000000fffffffffe0000000000000000000000000000000007ffffffffff8000000000000000000000000007ffffffffe00000000000001ffffffff00000000007fffffffffc0000000000000000000007fffffffffffffe0000000000ffffffffffffffffffffffffffffff0000000000000000000000000000004000000000000000000007fffffffffffffffc00fffffffff80000001fffffffffffe0000000007ffffffffffffffffc000000000000000000000003f00fffffff000000001fffffffffffffffffffffffffffffffffe000000000000003ffffffffffffffc000000000000000000000000000000000000000000000000fffffffffffff8000001ffffffffffffffffffffffffe00000000000003ffffffffffffffffffffffff00000000fffffffffff000000000L
414 y = -0x3fffffffffffc0000000000000000007ffffffffffff800000000000000000001ffffffffffffffc0000000000000000000000ffffffffffffffffffffffffffffc000000000000000000001ffffffffffffffffffffffffffffffffffffffffffffffffffffe00000000000000000000000000007fffffffffff000000000000000000000000fffffffffffffffffffffffffffffffffffffffff0000000003e007fffffffffffffffffff80000000000000000003fffffffffc000000000000007fffc0000000007ffffffffffffff0000000000010000000000000001fffffffffffffffffffffffffffffffffe000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0000000000001ffff007fff0000000000000000000000001f000000000001fffffffffffffffffc00000000001fffffffffffffffffffffffffffffffffffffff0000000000000000001ffffffffffff00000000000000000000000000000000000003fffffffff00003fffffffe00000000000000000000ffffffffffffffffffffff800001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000000000000001ffe000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000000fffffffffff800000000000000000fffffffffffffffffffe00000000003ffffffffffffffffffffffffffffffffffffffffc000000000000000006000001fffffffe0000000000ffffffffffffffffffffffffff8003fffffffffffffffffffffffffffe0000007fffc0000000000000000000000001ffffffffffffffffffffffffffffffffffff0000000000001fffe00000000000000000000000000000000000000000000000000000003fffffff0000000000007ffffff8000000000000001fffffffffffffffff80001fffffffffffffffffffffffffff800000000000000000001ffffe00000000000000000003fffffffffffffffffffffffff000000000000000fffffffffffffffffffffffffffffc0000000000000003fffffe0000000000000000000000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0000000003fff00001ffffffffffffffffffff0000000000001fffffffffffffc0000000000007ffffffffffffffffffffc000000000007fffffffffffffffffff80000000000003ffffffffffffc0000000000000000000000000000000000000000000000ffffe000000000000000000000000000001ffffffffffffffffffffffffffffffffffffe007ffffffffffff000000000000003fffffffffffffffffff800000000000000ff0000000000000000000000000000001ffffffffffffe00000000000007ffffffffffffff8000000000000001ffffffffffffc0000000000007ff000003fffffffffffffffffffffffffffffffffffffe00000007ffffffffffffffffffffe00000007ffffff0000000000000000ffffc00000000000000000ffffffffff8000000000000000fffffe0000000000000000000007fffffffffc000000fe0000000000000000000001ffffff800000000000000001ffffffffff00000000000000000000000000000000000000000000000ffffffffffffffffff000000000000000000000007fffffffffffffc0000fffffffffffffffffffffffffe000003ffffffffffff800000000000001fffffffffffffc000000000000000000000000001fff8000000000000000000000000000fffffffffffffffffffffffff0000000000000000003fe00000003fffffffffffffffff00000000000000ffffffffffe07fffffffffffffffc000000000000000000000003fffffff800000000000000000000003fffffffffffc0000000000000000000000003fffffffffffffffffc0000000000ffffffffffffffffffffffffffffffffffffffffffffffffffe000ffffffffffffffffc000000000000000000000000000000000000000000ffffffffffffffff8000000000000000000000000000000000000000000000000000000000fffffffffffffffc00000000000000003fffffffffffffffffffffffffffffffffffffe00003fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0000000000003fffffff00000000007ffffffffffc0007ffffffffe00000ffffc000700000000000000fffffffffff80000000000000000000000L
415 xl = rbigint.fromlong(x)
416 yl = rbigint.fromlong(y)
417 assert xl.mul(yl).tolong() == x * y
418 assert yl.mul(xl).tolong() == x * y
419
420
421 def bigint(lst, sign):
422 for digit in lst:
423 assert digit & MASK == digit # wrongly written test!
424 return rbigint(map(_store_digit, map(_mask_digit, lst)), sign)
425
426
427 class Test_rbigint(object):
428
429 def test_args_from_long(self):
430 BASE = 1 << SHIFT
431 assert rbigint.fromlong(0).eq(bigint([0], 0))
432 assert rbigint.fromlong(17).eq(bigint([17], 1))
433 assert rbigint.fromlong(BASE-1).eq(bigint([intmask(BASE-1)], 1))
434 assert rbigint.fromlong(BASE).eq(bigint([0, 1], 1))
435 assert rbigint.fromlong(BASE**2).eq(bigint([0, 0, 1], 1))
436 assert rbigint.fromlong(-17).eq(bigint([17], -1))
437 assert rbigint.fromlong(-(BASE-1)).eq(bigint([intmask(BASE-1)], -1))
438 assert rbigint.fromlong(-BASE).eq(bigint([0, 1], -1))
439 assert rbigint.fromlong(-(BASE**2)).eq(bigint([0, 0, 1], -1))
440 # assert rbigint.fromlong(-sys.maxint-1).eq(
441 # rbigint.digits_for_most_neg_long(-sys.maxint-1), -1)
442
443 def test_args_from_int(self):
444 BASE = 1 << 31 # Can't can't shift here. Shift might be from longlonglong
445 MAX = int(BASE-1)
446 assert rbigint.fromrarith_int(0).eq(bigint([0], 0))
447 assert rbigint.fromrarith_int(17).eq(bigint([17], 1))
448 assert rbigint.fromrarith_int(MAX).eq(bigint([MAX], 1))
449 # No longer true.
450 """assert rbigint.fromrarith_int(r_longlong(BASE)).eq(bigint([0, 1], 1))
451 assert rbigint.fromrarith_int(r_longlong(BASE**2)).eq(
452 bigint([0, 0, 1], 1))"""
453 assert rbigint.fromrarith_int(-17).eq(bigint([17], -1))
454 assert rbigint.fromrarith_int(-MAX).eq(bigint([MAX], -1))
455 """assert rbigint.fromrarith_int(-MAX-1).eq(bigint([0, 1], -1))
456 assert rbigint.fromrarith_int(r_longlong(-(BASE**2))).eq(
457 bigint([0, 0, 1], -1))"""
458 # assert rbigint.fromrarith_int(-sys.maxint-1).eq((
459 # rbigint.digits_for_most_neg_long(-sys.maxint-1), -1)
460
461 def test_args_from_uint(self):
462 BASE = 1 << SHIFT
463 assert rbigint.fromrarith_int(r_uint(0)).eq(bigint([0], 0))
464 assert rbigint.fromrarith_int(r_uint(17)).eq(bigint([17], 1))
465 assert rbigint.fromrarith_int(r_uint(BASE-1)).eq(bigint([intmask(BASE-1)], 1))
466 assert rbigint.fromrarith_int(r_uint(BASE)).eq(bigint([0, 1], 1))
467 #assert rbigint.fromrarith_int(r_uint(BASE**2)).eq(bigint([0], 0))
468 assert rbigint.fromrarith_int(r_uint(sys.maxint)).eq(
469 rbigint.fromint(sys.maxint))
470 assert rbigint.fromrarith_int(r_uint(sys.maxint+1)).eq(
471 rbigint.fromlong(sys.maxint+1))
472 assert rbigint.fromrarith_int(r_uint(2*sys.maxint+1)).eq(
473 rbigint.fromlong(2*sys.maxint+1))
474
475 def test_fromdecimalstr(self):
476 x = rbigint.fromdecimalstr("12345678901234567890523897987")
477 assert x.tolong() == 12345678901234567890523897987L
478 assert x.tobool() is True
479 x = rbigint.fromdecimalstr("+12345678901234567890523897987")
480 assert x.tolong() == 12345678901234567890523897987L
481 assert x.tobool() is True
482 x = rbigint.fromdecimalstr("-12345678901234567890523897987")
483 assert x.tolong() == -12345678901234567890523897987L
484 assert x.tobool() is True
485 x = rbigint.fromdecimalstr("+0")
486 assert x.tolong() == 0
487 assert x.tobool() is False
488 x = rbigint.fromdecimalstr("-0")
489 assert x.tolong() == 0
490 assert x.tobool() is False
491
492 def test_fromstr(self):
493 from rpython.rlib.rstring import ParseStringError
494 assert rbigint.fromstr('123L').tolong() == 123
495 assert rbigint.fromstr('123L ').tolong() == 123
496 with pytest.raises(ParseStringError):
497 rbigint.fromstr('L')
498 with pytest.raises(ParseStringError):
499 rbigint.fromstr('L ')
500 assert rbigint.fromstr('123L', 4).tolong() == 27
501 assert rbigint.fromstr('123L', 30).tolong() == 27000 + 1800 + 90 + 21
502 assert rbigint.fromstr('123L', 22).tolong() == 10648 + 968 + 66 + 21
503 assert rbigint.fromstr('123L', 21).tolong() == 441 + 42 + 3
504 assert rbigint.fromstr('1891234174197319').tolong() == 1891234174197319
505 assert rbigint.fromstr('1891_234_17_4_19731_9', allow_underscores=True).tolong() == 1891234174197319
506 assert rbigint.fromstr('1_1' * 6000, allow_underscores=True).tolong() == int('11' * 6000)
507
508 def test__from_numberstring_parser_rewind_bug(self):
509 from rpython.rlib.rstring import NumberStringParser
510 s = "-99"
511 p = NumberStringParser(s, s, 10, 'int')
512 assert p.sign == -1
513 res = p.next_digit()
514 assert res == 9
515 res = p.next_digit()
516 assert res == 9
517 res = p.next_digit()
518 assert res == -1
519 p.rewind()
520 res = p.next_digit()
521 assert res == 9
522 res = p.next_digit()
523 assert res == 9
524 res = p.next_digit()
525 assert res == -1
526
527 def test_fromstr_huge(self):
528 assert _str_to_int_big_base10("1" * 1000, 0, 1000).tolong() == int("1" * 1000)
529 mem = {}
530
531 result = _str_to_int_big_inner10('123952' * 1000, 0, 6000, mem, 20)
532 assert len(mem) == 13
533 assert result
534
535 def test_from_numberstring_parser(self):
536 from rpython.rlib.rstring import NumberStringParser
537 parser = NumberStringParser("1231231241", "1231231241", 10, "long")
538 assert rbigint._from_numberstring_parser(parser).tolong() == 1231231241
539
540 def test_from_numberstring_parser_no_implicit_octal(self):
541 from rpython.rlib.rstring import NumberStringParser, ParseStringError
542 s = "077777777777777777777777777777"
543 parser = NumberStringParser(s, s, 0, "long",
544 no_implicit_octal=True)
545 with pytest.raises(ParseStringError):
546 rbigint._from_numberstring_parser(parser)
547 parser = NumberStringParser("000", "000", 0, "long",
548 no_implicit_octal=True)
549 assert rbigint._from_numberstring_parser(parser).tolong() == 0
550
551 def test_limit(self):
552 from rpython.rlib.rstring import NumberStringParser, MaxDigitsError
553 max_str_digits = 999
554 s = '0' * (max_str_digits)
555 s0 = '1' + s
556 s1 = '1' + s[1:]
557 s2 = ' - 1' + s[1:]
558 with pytest.raises(MaxDigitsError):
559 parser = NumberStringParser(s0, s0, 0, "long",
560 max_str_digits=max_str_digits)
561 # these succeed
562 parser = NumberStringParser(s2, s2, 0, "long",
563 max_str_digits=max_str_digits)
564 parser = NumberStringParser(s1, s1, 0, "long",
565 max_str_digits=max_str_digits)
566 x = rbigint._from_numberstring_parser(parser)
567
568 assert s1 == x.str(max_str_digits)
569 with pytest.raises(MaxIntError):
570 x.str(max_str_digits - 1)
571
572 def test_add(self):
573 for x in gen_signs(long_vals):
574 f1 = rbigint.fromlong(x)
575 for y in gen_signs(long_vals):
576 f2 = rbigint.fromlong(y)
577 result = f1.add(f2)
578 assert result.tolong() == x + y
579
580
581
582 def test_add(self):
583 for x in gen_signs(long_vals):
584 f1 = rbigint.fromlong(x)
585 for y in gen_signs(long_vals):
586 f2 = rbigint.fromlong(y)
587 result = f1.add(f2)
588 assert result.tolong() == x + y
589
590 def test_int_add(self):
591 for x in gen_signs(long_vals):
592 f1 = rbigint.fromlong(x)
593 for y in signed_int_vals:
594 result = f1.int_add(y)
595 assert result.tolong() == x + y
596
597 def test_sub(self):
598 for x in gen_signs(long_vals):
599 f1 = rbigint.fromlong(x)
600 for y in gen_signs(long_vals):
601 f2 = rbigint.fromlong(y)
602 result = f1.sub(f2)
603 assert result.tolong() == x - y
604
605 def test_int_sub(self):
606 for x in gen_signs(long_vals):
607 f1 = rbigint.fromlong(x)
608 for y in signed_int_vals:
609 result = f1.int_sub(y)
610 assert result.tolong() == x - y
611
612 def test_subzz(self):
613 w_l0 = rbigint.fromint(0)
614 assert w_l0.sub(w_l0).tolong() == 0
615
616 def test_mul(self):
617 for x in gen_signs(long_vals):
618 f1 = rbigint.fromlong(x)
619 for y in gen_signs(long_vals_not_too_big):
620 f2 = rbigint.fromlong(y)
621 result = f1.mul(f2)
622 assert result.tolong() == x * y
623 # there's a special case for a is b
624 result = f1.mul(f1)
625 assert result.tolong() == x * x
626
627 def test_int_mul(self):
628 for x in gen_signs(long_vals):
629 f1 = rbigint.fromlong(x)
630 for y in signed_int_vals:
631 result = f1.int_mul(y)
632 assert result.tolong() == x * y
633
634 def test_add_int_int_rbigint_result(self):
635 for x in signed_int_vals:
636 for y in signed_int_vals:
637 result = rbigint.add_int_int_bigint_result(x, y)
638 assert result.tolong() == x + y
639
640 def test_sub_int_int_rbigint_result(self):
641 for x in signed_int_vals:
642 for y in signed_int_vals:
643 result = rbigint.sub_int_int_bigint_result(x, y)
644 assert result.tolong() == x - y
645
646 def test_mul_int_int_rbigint_result(self):
647 for x in signed_int_vals:
648 for y in signed_int_vals:
649 result = rbigint.mul_int_int_bigint_result(x, y)
650 assert result.tolong() == x * y
651
652 def test_tofloat(self):
653 x = 12345678901234567890L ** 10
654 f1 = rbigint.fromlong(x)
655 d = f1.tofloat()
656 assert d == float(x)
657 x = x ** 100
658 f1 = rbigint.fromlong(x)
659 with pytest.raises(OverflowError):
660 f1.tofloat()
661 f2 = rbigint.fromlong(2097152 << SHIFT)
662 d = f2.tofloat()
663 assert d == float(2097152 << SHIFT)
664
665 def test_tofloat_precision(self):
666 assert rbigint.fromlong(0).tofloat() == 0.0
667 for sign in [1, -1]:
668 for p in xrange(100):
669 x = long(2**p * (2**53 + 1) + 1) * sign
670 y = long(2**p * (2**53+ 2)) * sign
671 rx = rbigint.fromlong(x)
672 rxf = rx.tofloat()
673 assert rxf == float(y)
674 assert rbigint.fromfloat(rxf).tolong() == y
675 #
676 x = long(2**p * (2**53 + 1)) * sign
677 y = long(2**p * 2**53) * sign
678 rx = rbigint.fromlong(x)
679 rxf = rx.tofloat()
680 assert rxf == float(y)
681 assert rbigint.fromfloat(rxf).tolong() == y
682
683 def test_fromfloat(self):
684 x = 1234567890.1234567890
685 f1 = rbigint.fromfloat(x)
686 y = f1.tofloat()
687 assert f1.tolong() == long(x)
688 # check overflow
689 #x = 12345.6789e10000000000000000000000000000
690 # XXX don't use such consts. marshal doesn't handle them right.
691 x = 12345.6789e200
692 x *= x
693 with pytest.raises(OverflowError):
694 rbigint.fromfloat(x)
695 with pytest.raises(ValueError):
696 rbigint.fromfloat(NAN)
697 #
698 f1 = rbigint.fromfloat(9007199254740991.0)
699 assert f1.tolong() == 9007199254740991
700
701 null = rbigint.fromfloat(-0.0)
702 assert null.int_eq(0)
703
704 def test_eq_ne(self):
705 x = 5858393919192332223L
706 y = 585839391919233111223311112332L
707 f1 = rbigint.fromlong(x)
708 f2 = rbigint.fromlong(-x)
709 f3 = rbigint.fromlong(y)
710 assert f1.eq(f1)
711 assert f2.eq(f2)
712 assert f3.eq(f3)
713 assert not f1.eq(f2)
714 assert not f1.eq(f3)
715
716 assert not f1.ne(f1)
717 assert not f2.ne(f2)
718 assert not f3.ne(f3)
719 assert f1.ne(f2)
720 assert f1.ne(f3)
721
722 def test_eq_fastpath(self):
723 x = 1234
724 y = 1234
725 f1 = rbigint.fromint(x)
726 f2 = rbigint.fromint(y)
727 assert f1.eq(f2)
728
729 def test_lt(self):
730 val = [0, 0x111111111111, 0x111111111112, 0x111111111112FFFF]
731 for x in gen_signs(val):
732 for y in gen_signs(val):
733 f1 = rbigint.fromlong(x)
734 f2 = rbigint.fromlong(y)
735 assert (x < y) == f1.lt(f2)
736
737 def test_int_comparison(self):
738 for x in gen_signs(long_vals):
739 for y in signed_int_vals:
740 f1 = rbigint.fromlong(x)
741 assert (x < y) == f1.int_lt(y)
742 assert (x <= y) == f1.int_le(y)
743 assert (x > y) == f1.int_gt(y)
744 assert (x >= y) == f1.int_ge(y)
745 assert (x == y) == f1.int_eq(y)
746 assert (x != y) == f1.int_ne(y)
747
748 def test_order(self):
749 f6 = rbigint.fromint(6)
750 f7 = rbigint.fromint(7)
751 assert (f6.lt(f6), f6.lt(f7), f7.lt(f6)) == (0,1,0)
752 assert (f6.le(f6), f6.le(f7), f7.le(f6)) == (1,1,0)
753 assert (f6.gt(f6), f6.gt(f7), f7.gt(f6)) == (0,0,1)
754 assert (f6.ge(f6), f6.ge(f7), f7.ge(f6)) == (1,0,1)
755
756 def test_int_order(self):
757 f6 = rbigint.fromint(6)
758 f7 = rbigint.fromint(7)
759 assert (f6.int_lt(6), f6.int_lt(7), f7.int_lt(6)) == (0,1,0)
760 assert (f6.int_le(6), f6.int_le(7), f7.int_le(6)) == (1,1,0)
761 assert (f6.int_gt(6), f6.int_gt(7), f7.int_gt(6)) == (0,0,1)
762 assert (f6.int_ge(6), f6.int_ge(7), f7.int_ge(6)) == (1,0,1)
763
764 def test_int_conversion(self):
765 f1 = rbigint.fromlong(12332)
766 f2 = rbigint.fromint(12332)
767 assert f2.tolong() == f1.tolong()
768 assert f2.toint()
769 assert rbigint.fromlong(42).tolong() == 42
770 assert rbigint.fromlong(-42).tolong() == -42
771
772 u = f2.touint()
773 assert u == 12332
774 assert type(u) is r_uint
775
776 def test_conversions(self):
777 for v in (0, 1, -1, sys.maxint, -sys.maxint-1):
778 assert rbigint.fromlong(long(v)).tolong() == long(v)
779 l = rbigint.fromint(v)
780 assert l.toint() == v
781 if v >= 0:
782 u = l.touint()
783 assert u == v
784 assert type(u) is r_uint
785 else:
786 with pytest.raises(ValueError):
787 l.touint()
788
789 toobig_lv1 = rbigint.fromlong(sys.maxint+1)
790 assert toobig_lv1.tolong() == sys.maxint+1
791 toobig_lv2 = rbigint.fromlong(sys.maxint+2)
792 assert toobig_lv2.tolong() == sys.maxint+2
793 toobig_lv3 = rbigint.fromlong(-sys.maxint-2)
794 assert toobig_lv3.tolong() == -sys.maxint-2
795
796 for lv in (toobig_lv1, toobig_lv2, toobig_lv3):
797 with pytest.raises(OverflowError):
798 lv.toint()
799
800 lmaxuint = rbigint.fromlong(2*sys.maxint+1)
801 toobig_lv4 = rbigint.fromlong(2*sys.maxint+2)
802
803 u = lmaxuint.touint()
804 assert u == 2*sys.maxint+1
805
806 with pytest.raises(ValueError):
807 toobig_lv3.touint()
808 with pytest.raises(OverflowError):
809 toobig_lv4.touint()
810
811
812 def test_pow_lll(self):
813 x = 10L
814 y = 2L
815 z = 13L
816 f1 = rbigint.fromlong(x)
817 f2 = rbigint.fromlong(y)
818 f3 = rbigint.fromlong(z)
819 v = f1.pow(f2, f3)
820 assert v.tolong() == pow(x, y, z)
821 f3n = f3.neg()
822 v = f1.pow(f2, f3n)
823 assert v.tolong() == pow(x, y, -z)
824 #
825 f1, f2, f3 = [rbigint.fromlong(i)
826 for i in (10L, -1L, 42L)]
827 with pytest.raises(TypeError):
828 f1.pow(f2, f3)
829 f1, f2, f3 = [rbigint.fromlong(i)
830 for i in (10L, 5L, 0L)]
831 with pytest.raises(ValueError):
832 f1.pow(f2, f3)
833
834 def test_pow_lll_bug(self):
835 two = rbigint.fromint(2)
836 t = rbigint.fromlong(2655689964083835493447941032762343136647965588635159615997220691002017799304)
837 for n, expected in [(37, 9), (1291, 931), (67889, 39464)]:
838 v = two.pow(t, rbigint.fromint(n))
839 assert v.toint() == expected
840 #
841 # more tests, comparing against CPython's answer
842 enabled = sample(range(5*32), 10)
843 for i in range(5*32):
844 t = t.mul(two) # add one random bit
845 if random() >= 0.5:
846 t = t.add(rbigint.fromint(1))
847 if i not in enabled:
848 continue # don't take forever
849 n = randint(1, sys.maxint)
850 v = two.pow(t, rbigint.fromint(n))
851 assert v.toint() == pow(2, t.tolong(), n)
852
853 def test_pow_lll_bug2(self):
854 x = rbigint.fromlong(2)
855 y = rbigint.fromlong(5100894665148900058249470019412564146962964987365857466751243988156579407594163282788332839328303748028644825680244165072186950517295679131100799612871613064597)
856 z = rbigint.fromlong(538564)
857 expected = rbigint.fromlong(163464)
858 got = x.pow(y, z)
859 assert got.eq(expected)
860
861 def test_pow_lln(self):
862 x = 10L
863 y = 2L
864 f1 = rbigint.fromlong(x)
865 f2 = rbigint.fromlong(y)
866 v = f1.pow(f2)
867 assert v.tolong() == x ** y
868
869 def test_normalize(self):
870 f1 = bigint([1, 0], 1)
871 f1._normalize()
872 assert f1.numdigits() == 1
873 f0 = bigint([0], 0)
874 f0._normalize()
875 assert f0.numdigits() == 1
876 assert f0._size == 0
877 assert f1.sub(f1).eq(f0)
878
879 def test_invert(self):
880 x = 3 ** 40
881 f1 = rbigint.fromlong(x)
882 f2 = rbigint.fromlong(-x)
883 r1 = f1.invert()
884 r2 = f2.invert()
885 assert r1.tolong() == -(x + 1)
886 assert r2.tolong() == -(-x + 1)
887
888 def test_shift(self):
889 negative = -23
890 masks_list = [int((1 << i) - 1) for i in range(1, r_uint.BITS-1)]
891 for x in gen_signs([3L ** 30L, 5L ** 20L, 7 ** 300, 0L, 1L]):
892 f1 = rbigint.fromlong(x)
893 with pytest.raises(ValueError):
894 f1.lshift(negative)
895 with pytest.raises(ValueError):
896 f1.rshift(negative)
897 for y in [0L, 1L, 32L, 2304L, 11233L, 3 ** 9]:
898 res1 = f1.lshift(int(y)).tolong()
899 res2 = f1.rshift(int(y)).tolong()
900 assert res1 == x << y
901 assert res2 == x >> y
902 for mask in masks_list:
903 res3 = f1.abs_rshift_and_mask(r_ulonglong(y), mask)
904 assert res3 == (abs(x) >> y) & mask
905
906 # test special optimization case in rshift:
907 assert rbigint.fromlong(-(1 << 100)).rshift(5).tolong() == -(1 << 100) >> 5
908
909 # Chek value accuracy.
910 assert rbigint.fromlong(18446744073709551615L).rshift(1).tolong() == 18446744073709551615L >> 1
911
912 def test_shift_optimization(self):
913 # does not crash with memory error
914 assert rbigint.fromint(0).lshift(sys.maxint).tolong() == 0
915
916 def test_qshift(self):
917 for x in range(10):
918 for y in range(1, 161, 16):
919 num = (x << y) + x
920 f1 = rbigint.fromlong(num)
921 nf1 = rbigint.fromlong(-num)
922
923 for z in range(1, 31):
924 res1 = f1.lqshift(z).tolong()
925 res2 = f1.rqshift(z).tolong()
926 res3 = nf1.lqshift(z).tolong()
927
928 assert res1 == num << z
929 assert res2 == num >> z
930 assert res3 == -num << z
931
932 # Large digit
933 for x in range((1 << SHIFT) - 10, (1 << SHIFT) + 10):
934 f1 = rbigint.fromlong(x)
935 assert f1.rqshift(SHIFT).tolong() == x >> SHIFT
936 assert f1.rqshift(SHIFT+1).tolong() == x >> (SHIFT+1)
937
938 def test_from_list_n_bits(self):
939 for x in ([3L ** 30L, 5L ** 20L, 7 ** 300] +
940 [1L << i for i in range(130)] +
941 [(1L << i) - 1L for i in range(130)]):
942 for nbits in range(1, SHIFT+1):
943 mask = (1 << nbits) - 1
944 lst = []
945 got = x
946 while got > 0:
947 lst.append(int(got & mask))
948 got >>= nbits
949 f1 = rbigint.from_list_n_bits(lst, nbits)
950 assert f1.tolong() == x
951
952 def test_bitwise(self):
953 for x in gen_signs(long_vals):
954 lx = rbigint.fromlong(x)
955 for y in gen_signs(long_vals):
956 ly = rbigint.fromlong(y)
957 for mod in "xor and_ or_".split():
958 res1 = getattr(lx, mod)(ly).tolong()
959 res2 = getattr(operator, mod)(x, y)
960 assert res1 == res2
961
962 def test_int_bitwise(self):
963 for x in gen_signs(long_vals):
964 lx = rbigint.fromlong(x)
965 for y in signed_int_vals:
966 for mod in "xor and_ or_".split():
967 res1 = getattr(lx, 'int_' + mod)(y).tolong()
968 res2 = getattr(operator, mod)(x, y)
969 assert res1 == res2
970
971 def test_mul_eq_shift(self):
972 p2 = rbigint.fromlong(1).lshift(63)
973 f1 = rbigint.fromlong(0).lshift(63)
974 f2 = rbigint.fromlong(0).mul(p2)
975 assert f1.eq(f2)
976
977 def test_tostring(self):
978 z = rbigint.fromlong(0)
979 assert z.str() == '0'
980 assert z.repr() == '0L'
981 assert z.hex() == '0x0L'
982 assert z.oct() == '0L'
983 x = rbigint.fromlong(-18471379832321)
984 assert x.str() == '-18471379832321'
985 assert x.repr() == '-18471379832321L'
986 assert x.hex() == '-0x10ccb4088e01L'
987 assert x.oct() == '-0414626402107001L'
988 assert x.format('.!') == (
989 '-!....!!..!!..!.!!.!......!...!...!!!........!')
990 assert x.format('abcdefghijkl', '<<', '>>') == '-<<cakdkgdijffjf>>'
991 x = rbigint.fromlong(-18471379832321000000000000000000000000000000000000000000)
992 assert x.str() == '-18471379832321000000000000000000000000000000000000000000'
993 assert x.repr() == '-18471379832321000000000000000000000000000000000000000000L'
994 assert x.hex() == '-0xc0d9a6f41fbcf1718b618443d45516a051e40000000000L'
995 assert x.oct() == '-014033151572037571705614266060420752125055201217100000000000000L'
996
997 def test_format_caching(self):
998 big = rbigint.fromlong(2 ** 1000)
999 res1 = big.str()
1000 oldpow = rbigint.__dict__['pow']
1001 rbigint.pow = None
1002 # make sure pow is not used the second time
1003 try:
1004 res2 = big.str()
1005 assert res2 == res1
1006 finally:
1007 rbigint.pow = oldpow
1008
1009 def test_overzealous_assertion(self):
1010 a = rbigint.fromlong(-1<<10000)
1011 b = rbigint.fromlong(-1<<3000)
1012 assert a.mul(b).tolong() == (-1<<10000)*(-1<<3000)
1013
1014 def test_bit_length(self):
1015 assert rbigint.fromlong(0).bit_length() == 0
1016 assert rbigint.fromlong(1).bit_length() == 1
1017 assert rbigint.fromlong(2).bit_length() == 2
1018 assert rbigint.fromlong(3).bit_length() == 2
1019 assert rbigint.fromlong(4).bit_length() == 3
1020 assert rbigint.fromlong(-3).bit_length() == 2
1021 assert rbigint.fromlong(-4).bit_length() == 3
1022 assert rbigint.fromlong(1<<40).bit_length() == 41
1023
1024 def test_bit_length_int(self):
1025 assert bit_length_int(0) == 0
1026 assert bit_length_int(1) == 1
1027 assert bit_length_int(sys.maxint) in (31, 63)
1028 assert bit_length_int(-sys.maxint-1) in (32, 64)
1029
1030 def test_hash(self):
1031 for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1032 sys.maxint-3, sys.maxint-2, sys.maxint-1, sys.maxint,
1033 ]:
1034 # hash of machine-sized integers
1035 assert rbigint.fromint(i).hash() == i
1036 # hash of negative machine-sized integers
1037 assert rbigint.fromint(-i-1).hash() == -i-1
1038 #
1039
1040 def test_log(self):
1041 from rpython.rlib.rfloat import ulps_check
1042 for op in long_vals:
1043 for base in [0, 2, 4, 8, 16, 10, math.e]:
1044 if not op:
1045 with pytest.raises(ValueError):
1046 rbigint.fromlong(op).log(base)
1047 continue
1048 l = rbigint.fromlong(op).log(base)
1049 if base:
1050 assert ulps_check(l, math.log(op, base)) is None
1051 else:
1052 assert ulps_check(l, math.log(op)) is None
1053
1054 def test_log2(self):
1055 assert rbigint.fromlong(1).log(2.0) == 0.0
1056 assert rbigint.fromlong(2).log(2.0) == 1.0
1057 assert rbigint.fromlong(2**1023).log(2.0) == 1023.0
1058
1059 def test_frombytes(self):
1060 bigint = rbigint.frombytes('', byteorder='big', signed=True)
1061 assert bigint.tolong() == 0
1062 s = "\xFF\x12\x34\x56"
1063 bigint = rbigint.frombytes(s, byteorder="big", signed=False)
1064 assert bigint.tolong() == 0xFF123456
1065 bigint = rbigint.frombytes(s, byteorder="little", signed=False)
1066 assert bigint.tolong() == 0x563412FF
1067 s = "\xFF\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\xFF"
1068 bigint = rbigint.frombytes(s, byteorder="big", signed=False)
1069 assert s == bigint.tobytes(16, byteorder="big", signed=False)
1070 with pytest.raises(InvalidEndiannessError):
1071 bigint.frombytes('\xFF', 'foo', signed=True)
1072 bigint = rbigint.frombytes('\x82', byteorder='big', signed=True)
1073 assert bigint.tolong() == -126
1074
1075 def test_tobytes(self):
1076 assert rbigint.fromint(0).tobytes(1, 'big', signed=True) == '\x00'
1077 assert rbigint.fromint(1).tobytes(2, 'big', signed=True) == '\x00\x01'
1078 with pytest.raises(OverflowError):
1079 rbigint.fromint(255).tobytes(1, 'big', signed=True)
1080 assert rbigint.fromint(-129).tobytes(2, 'big', signed=True) == '\xff\x7f'
1081 assert rbigint.fromint(-129).tobytes(2, 'little', signed=True) == '\x7f\xff'
1082 assert rbigint.fromint(65535).tobytes(3, 'big', signed=True) == '\x00\xff\xff'
1083 assert rbigint.fromint(-65536).tobytes(3, 'little', signed=True) == '\x00\x00\xff'
1084 assert rbigint.fromint(65535).tobytes(2, 'big', signed=False) == '\xff\xff'
1085 assert rbigint.fromint(-8388608).tobytes(3, 'little', signed=True) == '\x00\x00\x80'
1086 i = rbigint.fromint(-8388608)
1087 with pytest.raises(InvalidEndiannessError):
1088 i.tobytes(3, 'foo', signed=True)
1089 with pytest.raises(InvalidSignednessError):
1090 i.tobytes(3, 'little', signed=False)
1091 with pytest.raises(OverflowError):
1092 i.tobytes(2, 'little', signed=True)
1093
1094 def test_gcd(self):
1095 assert gcd_binary(2*3*7**2, 2**2*7) == 2*7
1096 pytest.raises(ValueError, gcd_binary, 2*3*7**2, -2**2*7)
1097 assert gcd_binary(1234, 5678) == 2
1098 assert gcd_binary(13, 13**6) == 13
1099 assert gcd_binary(12, 0) == 12
1100 assert gcd_binary(0, 0) == 0
1101 with pytest.raises(ValueError):
1102 gcd_binary(-10, 0)
1103 with pytest.raises(ValueError):
1104 gcd_binary(10, -10)
1105
1106 x = rbigint.fromlong(9969216677189303386214405760200)
1107 y = rbigint.fromlong(16130531424904581415797907386349)
1108 g = x.gcd(y)
1109 assert g == rbigint.fromlong(1)
1110
1111 for x in gen_signs([12843440367927679363613699686751681643652809878241019930204617606850071260822269719878805]):
1112 x = rbigint.fromlong(x)
1113 for y in gen_signs([12372280584571061381380725743231391746505148712246738812788540537514927882776203827701778968535]):
1114 y = rbigint.fromlong(y)
1115 g = x.gcd(y)
1116 assert g.tolong() == 18218089570126697993340888567155155527541105
1117
1118
1119 def test_tobytes_int():
1120 assert tobytes_int(0, 1, 'big', signed=True) == '\x00'
1121 assert tobytes_int(1, 2, 'big', signed=True) == '\x00\x01'
1122 with pytest.raises(OverflowError):
1123 tobytes_int(255, 1, 'big', signed=True)
1124 assert tobytes_int(-129, 2, 'big', signed=True) == '\xff\x7f'
1125 assert tobytes_int(-129, 2, 'little', signed=True) == '\x7f\xff'
1126 assert tobytes_int(65535, 3, 'big', signed=True) == '\x00\xff\xff'
1127 assert tobytes_int(-65536, 3, 'little', signed=True) == '\x00\x00\xff'
1128 assert tobytes_int(65535, 2, 'big', signed=False) == '\xff\xff'
1129 assert tobytes_int(-8388608, 3, 'little', signed=True) == '\x00\x00\x80'
1130 i = -8388608
1131 with pytest.raises(InvalidEndiannessError):
1132 tobytes_int(i, 3, 'foo', signed=True)
1133 with pytest.raises(InvalidSignednessError):
1134 tobytes_int(i, 3, 'little', signed=False)
1135 with pytest.raises(OverflowError):
1136 tobytes_int(i, 2, 'little', signed=True)
1137
1138
1139 def test_frombytes_int():
1140 val = frombytes_int('', byteorder='big', signed=True)
1141 assert val == 0
1142 s = "\x12\x34\x56"
1143 val = frombytes_int(s, byteorder="big", signed=False)
1144 assert val == 0x123456
1145 val = frombytes_int(s, byteorder="little", signed=False)
1146 assert val == 0x563412
1147 if LONG_BIT == 64:
1148 s = "\xFF\x12\x34\x56"
1149 val = frombytes_int(s, byteorder="big", signed=False)
1150 assert val == 0xFF123456
1151 val = frombytes_int(s, byteorder="little", signed=False)
1152 assert val == 0x563412FF
1153 with pytest.raises(InvalidEndiannessError):
1154 frombytes_int('\xFF', 'foo', signed=True)
1155 val = frombytes_int('\x82', byteorder='big', signed=True)
1156 assert val == -126
1157 # Test overflow - too many bytes to fit in a machine int
1158 s = "\xFF" * 100
1159 with pytest.raises(OverflowError):
1160 frombytes_int(s, byteorder='big', signed=False)
1161 # Test minint (two's complement asymmetry)
1162 import sys
1163 minint = -sys.maxint - 1
1164 # minint in 8 bytes (for 64-bit) or 4 bytes (for 32-bit)
1165 nbytes = LONG_BIT // 8
1166 s = tobytes_int(minint, nbytes, 'big', signed=True)
1167 val = frombytes_int(s, 'big', signed=True)
1168 assert val == minint
1169 # Also test with little endian
1170 s = tobytes_int(minint, nbytes, 'little', signed=True)
1171 val = frombytes_int(s, 'little', signed=True)
1172 assert val == minint
1173 # Test with extra padding byte (sign extension)
1174 s = tobytes_int(minint, nbytes + 1, 'big', signed=True)
1175 val = frombytes_int(s, 'big', signed=True)
1176 assert val == minint
1177
1178 # check that all the higher bytes are the same
1179 s = "\x00\x00\x00\x00\x00\x00\x00\x00\xff"
1180 with pytest.raises(OverflowError):
1181 frombytes_int(s, byteorder='little', signed=True)
1182
1183 # unsigned value with high bit set (e.g. 2**63 on 64-bit) must overflow,
1184 # not silently wrap to a negative int via intmask
1185 s_big = b'\x80' + b'\x00' * (nbytes - 1)
1186 s_little = b'\x00' * (nbytes - 1) + b'\x80'
1187 with pytest.raises(OverflowError):
1188 frombytes_int(s_big, byteorder='big', signed=False)
1189 with pytest.raises(OverflowError):
1190 frombytes_int(s_little, byteorder='little', signed=False)
1191
1192
1193 @given(ints, strategies.booleans(), strategies.booleans(), strategies.integers(0, 1000))
1194 def test_tobytes_frombytes_int_hypothesis(value, big, signed, extra_size):
1195 # check the roundtrip from binary strings to bigints and back
1196 byteorder = 'big' if big else 'little'
1197 size = (value.bit_length() >> 3) + 1
1198 if not signed and value < 0:
1199 value = int(abs(value))
1200 assume(type(value) is int) # exclude the minint case
1201 s = tobytes_int(value, size + extra_size, byteorder, signed)
1202 bigint = rbigint.frombytes(s, byteorder=byteorder, signed=signed)
1203 assert bigint.toint() == value
1204 value2 = frombytes_int(s, byteorder, signed)
1205 assert value2 == value
1206
1207
1208 @given(strategies.binary(), strategies.booleans(), strategies.booleans())
1209 def test_frombytes_tobytes_int_hypothesis(s, big, signed):
1210 # check the roundtrip from binary strings to bigints and back
1211 signed = True
1212 byteorder = 'big' if big else 'little'
1213 bigint = rbigint.frombytes(s, byteorder=byteorder, signed=signed)
1214 try:
1215 value2 = frombytes_int(s, byteorder, signed)
1216 except OverflowError:
1217 assert not (-sys.maxint-1 <= bigint.tolong() <= sys.maxint)
1218 else:
1219 assert bigint.bit_length() <= LONG_BIT
1220 assert value2 == bigint.toint()
1221
1222 class TestInternalFunctions(object):
1223 def test__inplace_divrem1(self):
1224 # signs are not handled in the helpers!
1225 for x, y in [(1238585838347L, 3), (1234123412311231L, 1231231), (99, 100)]:
1226 if y > MASK:
1227 continue
1228 f1 = rbigint.fromlong(x)
1229 f2 = y
1230 remainder = lobj._inplace_divrem1(f1, f1, f2)
1231 f1._normalize()
1232 assert (f1.tolong(), remainder) == divmod(x, y)
1233 out = bigint([99, 99], 1)
1234 remainder = lobj._inplace_divrem1(out, out, 100)
1235
1236 def test__divrem1(self):
1237 # signs are not handled in the helpers!
1238 x = 1238585838347L
1239 y = 3
1240 f1 = rbigint.fromlong(x)
1241 f2 = y
1242 div, rem = lobj._divrem1(f1, f2)
1243 assert (div.tolong(), rem) == divmod(x, y)
1244
1245 def test__muladd1(self):
1246 x = 1238585838347L
1247 y = 3
1248 z = 42
1249 f1 = rbigint.fromlong(x)
1250 f2 = y
1251 f3 = z
1252 prod = lobj._muladd1(f1, f2, f3)
1253 assert prod.tolong() == x * y + z
1254
1255 def test__x_divrem(self):
1256 x = 12345678901234567890L
1257 for i in range(100):
1258 y = long(randint(1, 1 << 60))
1259 y <<= 60
1260 y += randint(1, 1 << 60)
1261 if y > x:
1262 x <<= 100
1263
1264 f1 = rbigint.fromlong(x)
1265 f2 = rbigint.fromlong(y)
1266 div, rem = lobj._x_divrem(f1, f2)
1267 _div, _rem = divmod(x, y)
1268 assert div.tolong() == _div
1269 assert rem.tolong() == _rem
1270
1271 def test__x_divrem2(self):
1272 Rx = 1 << 130
1273 Rx2 = 1 << 150
1274 Ry = 1 << 127
1275 Ry2 = 1 << 150
1276 for i in range(10):
1277 x = long(randint(Rx, Rx2))
1278 y = long(randint(Ry, Ry2))
1279 f1 = rbigint.fromlong(x)
1280 f2 = rbigint.fromlong(y)
1281 div, rem = lobj._x_divrem(f1, f2)
1282 _div, _rem = divmod(x, y)
1283 assert div.tolong() == _div
1284 assert rem.tolong() == _rem
1285
1286 def test_divmod(self):
1287 x = 12345678901234567890L
1288 for i in range(100):
1289 y = long(randint(0, 1 << 60))
1290 y <<= 60
1291 y += randint(0, 1 << 60)
1292 for sx, sy in (1, 1), (1, -1), (-1, -1), (-1, 1):
1293 sx *= x
1294 sy *= y
1295 f1 = rbigint.fromlong(sx)
1296 f2 = rbigint.fromlong(sy)
1297 div, rem = f1.divmod(f2)
1298 _div, _rem = divmod(sx, sy)
1299 assert div.tolong() == _div
1300 assert rem.tolong() == _rem
1301 with pytest.raises(ZeroDivisionError):
1302 rbigint.fromlong(x).divmod(rbigint.fromlong(0))
1303
1304 # an explicit example for a very rare case in _x_divrem:
1305 # "add w back if q was too large (this branch taken rarely)"
1306 x = 2401064762424988628303678384283622960038813848808995811101817752058392725584695633
1307 y = 510439143470502793407446782273075179624699774495710665331026
1308 f1 = rbigint.fromlong(x)
1309 f2 = rbigint.fromlong(y)
1310 div, rem = f1.divmod(f2)
1311 _div, _rem = divmod(x, y)
1312 assert div.tolong() == _div
1313 assert rem.tolong() == _rem
1314
1315 def test_divmod_big_bug(self):
1316 a = -0x13131313131313131313cfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfcfd0
1317 b = -0x131313131313131313d0
1318 ra = rbigint.fromlong(a)
1319 rb = rbigint.fromlong(b)
1320 oldval = HOLDER.DIV_LIMIT
1321 try:
1322 HOLDER.DIV_LIMIT = 2 # set limit low to test divmod_big more
1323 rdiv, rmod = divmod_big(ra, rb)
1324 div, mod = divmod(a, b)
1325 assert rdiv.tolong() == div
1326 assert rmod.tolong() == mod
1327 finally:
1328 HOLDER.DIV_LIMIT = oldval
1329
1330 def test_int_divmod(self):
1331 for x in long_vals:
1332 for y in int_vals + [-sys.maxint-1]:
1333 if not y:
1334 continue
1335 for sx, sy in (1, 1), (1, -1), (-1, -1), (-1, 1):
1336 sx *= x
1337 sy *= y
1338 if sy == sys.maxint + 1:
1339 continue
1340 f1 = rbigint.fromlong(sx)
1341 div, rem = f1.int_divmod(sy)
1342 div1, rem1 = f1.divmod(rbigint.fromlong(sy))
1343 _div, _rem = divmod(sx, sy)
1344 assert div1.tolong() == _div
1345 assert rem1.tolong() == _rem
1346 assert div.tolong() == _div
1347 assert rem.tolong() == _rem
1348 with pytest.raises(ZeroDivisionError):
1349 rbigint.fromlong(x).int_divmod(0)
1350
1351 # testing Karatsuba stuff
1352 def test__v_iadd(self):
1353 f1 = bigint([lobj.MASK] * 10, 1)
1354 f2 = bigint([1], 1)
1355 carry = lobj._v_iadd(f1, 1, len(f1._digits)-1, f2, 1)
1356 assert carry == 1
1357 assert f1.tolong() == lobj.MASK
1358
1359 def test__v_isub(self):
1360 f1 = bigint([lobj.MASK] + [0] * 9 + [1], 1)
1361 f2 = bigint([1], 1)
1362 borrow = lobj._v_isub(f1, 1, len(f1._digits)-1, f2, 1)
1363 assert borrow == 0
1364 assert f1.tolong() == (1 << lobj.SHIFT) ** 10 - 1
1365
1366 def test__kmul_split(self):
1367 split = 5
1368 diglo = [0] * split
1369 dighi = [lobj.MASK] * split
1370 f1 = bigint(diglo + dighi, 1)
1371 hi, lo = lobj._kmul_split(f1, split)
1372 assert lo._digits == [_store_digit(0)]
1373 assert hi._digits == map(_store_digit, dighi)
1374
1375 def test__k_mul(self):
1376 digs = KARATSUBA_CUTOFF * 5
1377 f1 = bigint([lobj.MASK] * digs, 1)
1378 f2 = lobj._x_add(f1, bigint([1], 1))
1379 ret = lobj._k_mul(f1, f2)
1380 assert ret.tolong() == f1.tolong() * f2.tolong()
1381
1382 def test_longlong(self):
1383 max = 1L << (r_longlong.BITS-1)
1384 f1 = rbigint.fromlong(max-1) # fits in r_longlong
1385 f2 = rbigint.fromlong(-max) # fits in r_longlong
1386 f3 = rbigint.fromlong(max) # overflows
1387 f4 = rbigint.fromlong(-max-1) # overflows
1388 assert f1.tolonglong() == max-1
1389 assert f2.tolonglong() == -max
1390 with pytest.raises(OverflowError):
1391 f3.tolonglong()
1392 with pytest.raises(OverflowError):
1393 f4.tolonglong()
1394
1395 def test_uintmask(self):
1396 assert rbigint.fromint(-1).uintmask() == r_uint(-1)
1397 assert rbigint.fromint(0).uintmask() == r_uint(0)
1398 assert (rbigint.fromint(sys.maxint).uintmask() ==
1399 r_uint(sys.maxint))
1400 assert (rbigint.fromlong(sys.maxint+1).uintmask() ==
1401 r_uint(-sys.maxint-1))
1402
1403 def test_ulonglongmask(self):
1404 assert rbigint.fromlong(-1).ulonglongmask() == r_ulonglong(-1)
1405 assert rbigint.fromlong(0).ulonglongmask() == r_ulonglong(0)
1406 assert (rbigint.fromlong(sys.maxint).ulonglongmask() ==
1407 r_ulonglong(sys.maxint))
1408 assert (rbigint.fromlong(9**50).ulonglongmask() ==
1409 r_ulonglong(9**50))
1410 assert (rbigint.fromlong(-9**50).ulonglongmask() ==
1411 r_ulonglong(-9**50))
1412
1413 def test_toulonglong(self):
1414 with pytest.raises(ValueError):
1415 rbigint.fromlong(-1).toulonglong()
1416
1417 def test_fits_int(self):
1418 assert rbigint.fromlong(0).fits_int()
1419 assert rbigint.fromlong(42).fits_int()
1420 assert rbigint.fromlong(-42).fits_int()
1421 assert rbigint.fromlong(sys.maxint).fits_int()
1422 assert not rbigint.fromlong(sys.maxint + 1).fits_int()
1423 assert rbigint.fromlong(-sys.maxint - 1).fits_int()
1424 assert not rbigint.fromlong(-sys.maxint - 2).fits_int()
1425 assert not rbigint.fromlong(-73786976294838206459).fits_int()
1426 assert not rbigint.fromlong(1 << 1000).fits_int()
1427
1428 def test_parse_digit_string(self):
1429 from rpython.rlib.rbigint import parse_digit_string
1430 class Parser:
1431 def __init__(self, base, sign, digits):
1432 self.base = base
1433 self.sign = sign
1434 self.i = 0
1435 self._digits = digits
1436 self.start = 0
1437 self.end = len(digits)
1438 def next_digit(self):
1439 i = self.i
1440 if i == len(self._digits):
1441 return -1
1442 self.i = i + 1
1443 return self._digits[i]
1444 def prev_digit(self):
1445 i = self.i - 1
1446 assert i >= 0
1447 self.i = i
1448 return self._digits[i]
1449 x = parse_digit_string(Parser(10, 1, [6]))
1450 assert x.eq(rbigint.fromint(6))
1451 x = parse_digit_string(Parser(10, 1, [6, 2, 3]))
1452 assert x.eq(rbigint.fromint(623))
1453 x = parse_digit_string(Parser(10, -1, [6, 2, 3]))
1454 assert x.eq(rbigint.fromint(-623))
1455 x = parse_digit_string(Parser(16, 1, [0xA, 0x4, 0xF]))
1456 assert x.eq(rbigint.fromint(0xA4F))
1457 num = 0
1458 for i in range(36):
1459 x = parse_digit_string(Parser(36, 1, range(i)))
1460 assert x.eq(rbigint.fromlong(num))
1461 num = num * 36 + i
1462 x = parse_digit_string(Parser(16, -1, range(15,-1,-1)*99))
1463 assert x.eq(rbigint.fromlong(long('-0x' + 'FEDCBA9876543210'*99, 16)))
1464 assert x.tobool() is True
1465 x = parse_digit_string(Parser(7, 1, [0, 0, 0]))
1466 assert x.tobool() is False
1467 x = parse_digit_string(Parser(7, -1, [0, 0, 0]))
1468 assert x.tobool() is False
1469
1470 for base in [2, 4, 8, 16, 32]:
1471 for inp in [[0], [1], [1, 0], [0, 1], [1, 0, 1], [1, 0, 0, 1],
1472 [1, 0, 0, base-1, 0, 1], [base-1, 1, 0, 0, 0, 1, 0],
1473 [base-1]]:
1474 inp = inp * 97
1475 x = parse_digit_string(Parser(base, -1, inp))
1476 num = sum(inp[i] * (base ** (len(inp)-1-i))
1477 for i in range(len(inp)))
1478 assert x.eq(rbigint.fromlong(-num))
1479
1480
1481 BASE = 2 ** SHIFT
1482
1483 class TestTranslatable(object):
1484 def test_square(self):
1485 def test():
1486 xlo = rbigint.fromint(1410065408)
1487 xhi = rbigint.fromint(4)
1488 x = xlo.or_(xhi.lshift(31))
1489 y = x.mul(x)
1490 return y.str()
1491 res = interpret(test, [])
1492 assert "".join(res.chars) == test()
1493
1494 def test_add(self):
1495 x = rbigint.fromint(-2147483647)
1496 y = rbigint.fromint(-1)
1497 z = rbigint.fromint(-2147483648)
1498 def test():
1499 return x.add(y).eq(z)
1500 assert test()
1501 res = interpret(test, [])
1502 assert res
1503
1504 def test_args_from_rarith_int(self):
1505 from rpython.rlib.rarithmetic import r_int
1506 from rpython.rlib.unroll import unrolling_iterable
1507 from rpython.rtyper.lltypesystem.rffi import r_int_real, r_uint_real
1508 classlist = platform.numbertype_to_rclass.values()
1509 cases = [] # tuples of (values, strvalues, typename)
1510 for r in classlist:
1511 if r in (r_int, r_int_real, r_uint_real): # and also r_longlong on 64-bit
1512 continue
1513 if r is int:
1514 mask = sys.maxint*2+1
1515 signed = True
1516 else:
1517 mask = r.MASK
1518 signed = r.SIGNED
1519 values = [0, -1, mask>>1, -(mask>>1)-1]
1520 if not signed:
1521 values = [x & mask for x in values]
1522 values = [r(x) for x in values]
1523 results = [str(long(x)) for x in values]
1524 cases.append((values, results, str(r)))
1525 cases = unrolling_iterable(cases)
1526 def fn():
1527 for values, results, typname in cases:
1528 for i in range(len(values)):
1529 n = rbigint.fromrarith_int(values[i])
1530 n = rbigint.fromrarith_int(values[i])
1531 if n.str() != results[i]:
1532 return typname + str(i)
1533 return None
1534 res = interpret(fn, [])
1535 assert not res
1536
1537 def test_truediv_overflow(self):
1538 overflowing = 2**1024 - 2**(1024-53-1)
1539 op1 = rbigint.fromlong(overflowing)
1540
1541 def fn():
1542 try:
1543 return op1.truediv(rbigint.fromint(1))
1544 except OverflowError:
1545 return -42.0
1546
1547 res = interpret(fn, [])
1548 assert res == -42.0
1549
1550 def test_isqrt(self):
1551 def fn(x):
1552 num = rbigint.fromint(3).int_pow(x)
1553 return num.mul(num).isqrt().eq(num)
1554
1555
1556 res = interpret(fn, [100])
1557 assert res == True
1558
1559 def test_mul_int_int_rbigint_result(self):
1560 def fn(x, y):
1561 res = rbigint.mul_int_int_bigint_result(x, y)
1562 return len(res.str())
1563 res = interpret(fn, [sys.maxint, sys.maxint])
1564
1565
1566 class TestTranslated(StandaloneTests):
1567
1568 def test_gcc_4_9(self):
1569 MIN = -sys.maxint-1
1570
1571 def entry_point(argv):
1572 print rbigint.fromint(MIN+1)._digits
1573 print rbigint.fromint(MIN)._digits
1574 return 0
1575
1576 t, cbuilder = self.compile(entry_point)
1577 data = cbuilder.cmdexec('hi there')
1578 if SHIFT == LONG_BIT-1:
1579 assert data == '[%d]\n[0, 1]\n' % sys.maxint
1580 else:
1581 # assume 64-bit without native 128-bit type
1582 assert data == '[%d, %d, 1]\n[0, 0, 2]\n' % (2**31-1, 2**31-1)
1583
1584 class TestHypothesis(object):
1585 @given(longs, longs, longs)
1586 def test_pow(self, x, y, z):
1587 f1 = rbigint.fromlong(x)
1588 f2 = rbigint.fromlong(y)
1589 f3 = rbigint.fromlong(z)
1590 try:
1591 res = pow(x, y, z)
1592 except Exception as e:
1593 with pytest.raises(type(e)):
1594 f1.pow(f2, f3)
1595 else:
1596 v1 = f1.pow(f2, f3)
1597 try:
1598 v2 = f1.int_pow(f2.toint(), f3)
1599 except OverflowError:
1600 pass
1601 else:
1602 assert v2.tolong() == res
1603 assert v1.tolong() == res
1604
1605 @given(biglongs, biglongs)
1606 @example(510439143470502793407446782273075179618477362188870662225920,
1607 108089693021945158982483698831267549521)
1608 def test_divmod(self, x, y):
1609 if x < y:
1610 x, y = y, x
1611
1612 f1 = rbigint.fromlong(x)
1613 f2 = rbigint.fromlong(y)
1614 try:
1615 res = divmod(x, y)
1616 except Exception as e:
1617 with pytest.raises(type(e)):
1618 f1.divmod(f2)
1619 else:
1620 a, b = f1.divmod(f2)
1621 assert (a.tolong(), b.tolong()) == res
1622
1623 @given(biglongs, biglongs)
1624 @example(510439143470502793407446782273075179618477362188870662225920,
1625 108089693021945158982483698831267549521)
1626 def test_divmod_small(self, x, y):
1627 if x < y:
1628 x, y = y, x
1629
1630 f1 = rbigint.fromlong(x)
1631 f2 = rbigint.fromlong(y)
1632 try:
1633 res = divmod(x, y)
1634 except Exception as e:
1635 with pytest.raises(type(e)):
1636 f1._divmod_small(f2)
1637 else:
1638 a, b = f1._divmod_small(f2)
1639 assert (a.tolong(), b.tolong()) == res
1640
1641
1642 @given(biglongs, biglongs)
1643 @example(510439143470502793407446782273075179618477362188870662225920,
1644 108089693021945158982483698831267549521)
1645 @example(51043991434705027934074467822730751796184773621888706622259209143470502793407446782273075179618477362188870662225920143470502793407446782273075179618477362188870662225920,
1646 10808)
1647 @example(17, 257)
1648 @example(510439143470502793407446782273075179618477362188870662225920L, 108089693021945158982483698831267549521L)
1649 def test_divmod_big(self, x, y):
1650 oldval = HOLDER.DIV_LIMIT
1651 try:
1652 HOLDER.DIV_LIMIT = 2 # set limit low to test divmod_big more
1653 if x < y:
1654 x, y = y, x
1655
1656 # boost size
1657 x *= 3 ** (HOLDER.DIV_LIMIT * SHIFT * 5) - 1
1658 y *= 2 ** (HOLDER.DIV_LIMIT * SHIFT * 5) - 1
1659
1660 f1 = rbigint.fromlong(x)
1661 f2 = rbigint.fromlong(y)
1662 try:
1663 res = divmod(x, y)
1664 except Exception as e:
1665 with pytest.raises(type(e)):
1666 divmod_big(f1, f2)
1667 else:
1668 a, b = divmod_big(f1, f2)
1669 assert (a.tolong(), b.tolong()) == res
1670 finally:
1671 HOLDER.DIV_LIMIT = oldval
1672
1673 @given(tuples_biglongs_for_division)
1674 @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow])
1675 def test_divmod_consistency(self, tup):
1676 lx, ly = tup
1677 ly = ly or 1
1678 x = rbigint.fromlong(lx)
1679 y = rbigint.fromlong(ly)
1680 q, r = x.divmod(y)
1681 q2, r2 = x.floordiv(y), x.mod(y)
1682 pab, pba = x.mul(y), y.mul(x)
1683 assert pab.eq(pba)
1684 assert q.eq(q2)
1685 assert r.eq(r2)
1686 assert x.eq(q.mul(y).add(r))
1687 if y.int_gt(0):
1688 assert r.lt(y)
1689 assert r.int_ge(0)
1690 else:
1691 assert y.lt(r)
1692 assert y.int_le(0)
1693
1694 @given(biglongs, ints)
1695 def test_int_divmod(self, x, iy):
1696 f1 = rbigint.fromlong(x)
1697 try:
1698 res = divmod(x, iy)
1699 except Exception as e:
1700 with pytest.raises(type(e)):
1701 f1.int_divmod(iy)
1702 else:
1703 a, b = f1.int_divmod(iy)
1704 assert (a.tolong(), b.tolong()) == res
1705
1706 @given(longs)
1707 def test_hash(self, x):
1708 # hash of large integers: should be equal to the hash of the
1709 # integer reduced modulo 2**64-1, to make decimal.py happy
1710 x = abs(x)
1711 y = x % (2**64-1)
1712 assert rbigint.fromlong(x).hash() == rbigint.fromlong(y).hash()
1713 assert rbigint.fromlong(-x).hash() == rbigint.fromlong(-y).hash()
1714
1715 @given(ints)
1716 def test_hash_int(self, x):
1717 # hash of machine-sized integers
1718 assert rbigint.fromint(x).hash() == x
1719 # hash of negative machine-sized integers
1720 assert rbigint.fromint(-x-1).hash() == -x-1
1721
1722 @given(longs)
1723 def test_abs(self, x):
1724 assert rbigint.fromlong(x).abs().tolong() == abs(x)
1725
1726 @given(longs, longs)
1727 def test_truediv(self, a, b):
1728 ra = rbigint.fromlong(a)
1729 rb = rbigint.fromlong(b)
1730 if not b:
1731 with pytest.raises(ZeroDivisionError):
1732 ra.truediv(rb)
1733 else:
1734 assert repr(ra.truediv(rb)) == repr(a / b)
1735
1736 @given(longs, longs)
1737 def test_bitwise_and_mul(self, x, y):
1738 lx = rbigint.fromlong(x)
1739 ly = rbigint.fromlong(y)
1740 for mod in "xor and_ or_ mul".split():
1741 res1a = getattr(lx, mod)(ly).tolong()
1742 res1b = getattr(ly, mod)(lx).tolong()
1743 res2 = getattr(operator, mod)(x, y)
1744 assert res1a == res2
1745
1746 @given(longs, ints)
1747 def test_int_bitwise_and_mul(self, x, y):
1748 lx = rbigint.fromlong(x)
1749 for mod in "xor and_ or_ mul".split():
1750 res1 = getattr(lx, 'int_' + mod)(y).tolong()
1751 res2 = getattr(operator, mod)(x, y)
1752 assert res1 == res2
1753
1754 @given(longs, ints)
1755 def test_int_comparison(self, x, y):
1756 lx = rbigint.fromlong(x)
1757 assert lx.int_lt(y) == (x < y)
1758 assert lx.int_eq(y) == (x == y)
1759 assert lx.int_le(y) == (x <= y)
1760
1761 @given(longs, longs)
1762 def test_int_comparison2(self, x, y):
1763 lx = rbigint.fromlong(x)
1764 ly = rbigint.fromlong(y)
1765 assert lx.lt(ly) == (x < y)
1766 assert lx.eq(ly) == (x == y)
1767 assert lx.le(ly) == (x <= y)
1768
1769 @given(ints, ints, ints)
1770 def test_gcd_binary(self, x, y, z):
1771 x, y, z = abs(x), abs(y), abs(z)
1772
1773 def test(a, b, res):
1774 g = gcd_binary(a, b)
1775
1776 assert g == res
1777
1778 a, b = x, y
1779 while b:
1780 a, b = b, a % b
1781
1782 gcd_x_y = a
1783
1784 test(x, y, gcd_x_y)
1785 test(x, 0, x)
1786 test(0, x, x)
1787 test(x * z, y * z, gcd_x_y * z)
1788 test(x * z, z, z)
1789 test(z, y * z, z)
1790
1791 @given(biglongs, biglongs, biglongs)
1792 @example(112233445566778899112233445566778899112233445566778899,
1793 13579246801357924680135792468013579246801,
1794 99887766554433221113)
1795 @settings(max_examples=10)
1796 def test_gcd(self, x, y, z):
1797 x, y, z = abs(x), abs(y), abs(z)
1798
1799 def test(a, b, res):
1800 g = rbigint.fromlong(a).gcd(rbigint.fromlong(b)).tolong()
1801
1802 assert g == res
1803
1804 a, b = x, y
1805 while b:
1806 a, b = b, a % b
1807
1808 gcd_x_y = a
1809
1810 test(x, y, gcd_x_y)
1811 test(x * z, y * z, gcd_x_y * z)
1812 test(x * z, z, z)
1813 test(z, y * z, z)
1814 test(x, 0, x)
1815 test(0, x, x)
1816
1817 @given(ints)
1818 def test_longlong_roundtrip(self, x):
1819 try:
1820 rx = r_longlong(x)
1821 except OverflowError:
1822 pass
1823 else:
1824 assert rbigint.fromrarith_int(rx).tolonglong() == rx
1825
1826 @given(longs)
1827 def test_unsigned_roundtrip(self, x):
1828 x = abs(x)
1829 rx = r_uint(x) # will wrap on overflow
1830 assert rbigint.fromrarith_int(rx).touint() == rx
1831 rx = r_ulonglong(x) # will wrap on overflow
1832 assert rbigint.fromrarith_int(rx).toulonglong() == rx
1833
1834 @given(biglongs, biglongs)
1835 def test_mod(self, x, y):
1836 rx = rbigint.fromlong(x)
1837 ry = rbigint.fromlong(y)
1838 if not y:
1839 with pytest.raises(ZeroDivisionError):
1840 rx.mod(ry)
1841 return
1842 r1 = rx.mod(ry)
1843 r2 = x % y
1844
1845 assert r1.tolong() == r2
1846
1847 @given(biglongs, ints)
1848 def test_int_mod(self, x, y):
1849 rx = rbigint.fromlong(x)
1850 if not y:
1851 with pytest.raises(ZeroDivisionError):
1852 rx.int_mod(0)
1853 return
1854 r1 = rx.int_mod(y)
1855 r2 = x % y
1856 assert r1.tolong() == r2
1857
1858 @given(biglongs, ints)
1859 def test_int_mod_int_result(self, x, y):
1860 rx = rbigint.fromlong(x)
1861 if not y:
1862 with pytest.raises(ZeroDivisionError):
1863 rx.int_mod_int_result(0)
1864 return
1865 r1 = rx.int_mod_int_result(y)
1866 r2 = x % y
1867 assert r1 == r2
1868
1869 @given(longs, strategies.integers(0, 2000))
1870 def test_shift(self, x, shift):
1871 rx = rbigint.fromlong(x)
1872 r1 = rx.lshift(shift)
1873 assert r1.tolong() == x << shift
1874
1875 r1 = rx.rshift(shift)
1876 assert r1.tolong() == x >> shift
1877
1878 @given(longs, strategies.integers(0, 2000), strategies.data())
1879 def test_abs_rshift_and_mask(self, x, shift, data):
1880 mask = data.draw(
1881 strategies.sampled_from(
1882 [int((1 << i) - 1) for i in range(1, min(SHIFT, r_uint.BITS - 1))]))
1883 rx = rbigint.fromlong(x)
1884 r1 = rx.abs_rshift_and_mask(r_ulonglong(shift), mask)
1885 assert r1 == (abs(x) >> shift) & mask
1886
1887 @given(biglongs, strategies.integers(min_value=1, max_value=_BIG_INT_MAX))
1888 def test_str_to_int_big_base10(self, l, limit):
1889 l = abs(l)
1890 s = str(l)
1891 assert _str_to_int_big_base10(str(l), 0, len(s), limit).tolong() == l
1892
1893 @given(biglongs)
1894 def test_fromstr(self, l):
1895 assert rbigint.fromstr(str(l)).tolong() == l
1896
1897 @given(biglongs)
1898 def test_fromstr_str_consistency(self, l):
1899 assert rbigint.fromstr(rbigint.fromlong(l).str()).tolong() == l
1900
1901 @given(biglongs)
1902 def test_fromstr_small_limit(self, l):
1903 # set limits to 2 to stress the recursive algorithm some more
1904 oldval = HOLDER.STR2INT_LIMIT
1905 oldval2 = HOLDER.MINSIZE_STR2INT
1906 try:
1907 HOLDER.STR2INT_LIMIT = 2
1908 HOLDER.MINSIZE_STR2INT = 1
1909 assert rbigint.fromstr(str(l)).tolong() == l
1910 assert rbigint.fromstr(str(l) + "_1", allow_underscores=True).tolong() == int(str(l) + '1')
1911 finally:
1912 HOLDER.STR2INT_LIMIT = oldval
1913 HOLDER.MINSIZE_STR2INT = 1
1914
1915 @given(strategies.integers(min_value=1, max_value=_BIG_INT_MAX), strategies.integers(min_value=1, max_value=_BIG_INT_MAX))
1916 @settings(max_examples=10)
1917 def test_str_to_int_big_w5pow(self, exp, limit):
1918 mem = {}
1919 assert (_str_to_int_big_w5pow(exp, mem, limit).tolong() == 5 ** exp ==
1920 rbigint.fromint(5).int_pow(exp).tolong())
1921
1922 @given(biglongs)
1923 def test_bit_count(self, val):
1924 assert rbigint.fromlong(val).bit_count() == bin(abs(val)).count("1")
1925
1926 @given(strategies.integers(0, 2**64-1))
1927 @example(1)
1928 @example(0b110001010111)
1929 def test_bitcount64(self, val):
1930 assert _bitcount64(r_ulonglong(val)) == bin(val).count("1")
1931
1932 @given(strategies.binary(), strategies.booleans(), strategies.booleans())
1933 def test_frombytes_tobytes_hypothesis(self, s, big, signed):
1934 # check the roundtrip from binary strings to bigints and back
1935 byteorder = 'big' if big else 'little'
1936 bigint = rbigint.frombytes(s, byteorder=byteorder, signed=signed)
1937 t = bigint.tobytes(len(s), byteorder=byteorder, signed=signed)
1938 assert s == t
1939
1940 @given(biglongs, biglongs, biglongs)
1941 def test_distributive(self, a, b, c):
1942 la = rbigint.fromlong(a)
1943 lb = rbigint.fromlong(b)
1944 lc = rbigint.fromlong(c)
1945 # a * (b + c) == a * b + a * c
1946 assert la.mul(lb.add(lc)).eq(la.mul(lb).add(la.mul(lc)))
1947
1948 @given(biglongs, biglongs, biglongs)
1949 def test_associative(self, a, b, c):
1950 la = rbigint.fromlong(a)
1951 lb = rbigint.fromlong(b)
1952 lc = rbigint.fromlong(c)
1953 # a * (b * c) == (a * b) * c
1954 assert la.mul(lb.mul(lc)).eq(la.mul(lb).mul(lc))
1955 # a + (b + c) == (a + b) + c
1956 assert la.add(lb.add(lc)).eq(la.add(lb).add(lc))
1957
1958 @given(biglongs, biglongs)
1959 def test_commutative(self, a, b):
1960 la = rbigint.fromlong(a)
1961 lb = rbigint.fromlong(b)
1962 # a * b == b * a
1963 assert la.mul(lb).eq(lb.mul(la))
1964 # a + b == b + a
1965 assert la.add(lb).eq(lb.add(la))
1966
1967 @given(longs, strategies.integers(0, 100), strategies.integers(0, 100))
1968 @settings(max_examples=10)
1969 def test_pow_mul(self, a, b, c):
1970 la = rbigint.fromlong(a)
1971 lb = rbigint.fromlong(b)
1972 lc = rbigint.fromlong(c)
1973 # a ** (b + c) == a ** b * a ** c
1974 assert la.pow(lb.add(lc)).eq(la.pow(lb).mul(la.pow(lc)))
1975
1976 @given(rarith_ints)
1977 def test_args_from_rarith_int(self, i):
1978 li = rbigint.fromrarith_int(i)
1979 assert li.tolong() == int(i)
1980
1981 @given(biglongs)
1982 @example(3**100)
1983 def test_isqrt(self, a):
1984 a = abs(a)
1985 la = rbigint.fromlong(a)
1986 lsq = la.isqrt()
1987 sq = lsq.tolong()
1988 assert sq * sq <= a
1989 assert (sq + 1) ** 2 > a
1990
1991 x = a * a
1992 lx = rbigint.fromlong(x)
1993 assert lx.isqrt().tolong() == a
1994
1995 @given(ints, ints)
1996 def test_add_int_int_rbigint_result(self, a, b):
1997 res = rbigint.add_int_int_bigint_result(a, b)
1998 assert res.tolong() == a + b
1999
2000 @given(ints, ints)
2001 def test_sub_int_int_rbigint_result(self, a, b):
2002 res = rbigint.sub_int_int_bigint_result(a, b)
2003 assert res.tolong() == a - b
2004
2005 @given(ints, ints)
2006 def test_mul_int_int_rbigint_result(self, a, b):
2007 res = rbigint.mul_int_int_bigint_result(a, b)
2008 assert res.tolong() == a * b
2009
2010 @example(-sys.maxint-1, 5)
2011 @example(-1, 10)
2012 @example(1, 1071)
2013 @given(ints, strategies.integers(0, 2000))
2014 def test_lshift_int_int_rbigint_result(self, a, b):
2015 res = rbigint.lshift_int_int_bigint_result(a, b)
2016 assert res.tolong() == a << b
2017
2018 @given(strategies.data())
2019 def test_format_lowest_level_divmod_int_results(self, data):
2020 b = data.draw(strategies.integers(1, MASK))
2021 a = data.draw(strategies.integers(0, b-1))
2022 c = data.draw(strategies.integers(0, b-1))
2023 assume(bool(b))
2024 atimesbplusb = rbigint.mul_int_int_bigint_result(a, b).int_add(c)
2025 div, mod = _format_lowest_level_divmod_int_results(atimesbplusb, b)
2026 print a, b, c, atimesbplusb, div, mod
2027 assert (div, mod) == divmod(atimesbplusb.tolong(), b)
2028
2029 @given(strategies.integers(0, 10**18-1))
2030 def test_format_int10_18digits(self, val):
2031 builder = StringBuilder()
2032 _format_int10_18digits(val, builder)
2033 s = builder.build()
2034 assert len(s) == 18
2035 assert s.lstrip('0') == str(val).lstrip('0')
2036
2037 @given(longs)
2038 def test_bit_length(self, val):
2039 rval = rbigint.fromlong(val)
2040 assert val.bit_length() == rval.bit_length()
2041
2042 @given(ints)
2043 def test_bit_length_int(self, val):
2044 res = bit_length_int(val)
2045 assert res == val.bit_length()
2046 if val > 0:
2047 assert 2 ** (res - 1) <= val < 2 ** res
2048 if not val:
2049 assert res == 0
2050 if val < 0:
2051 assert res == (-val).bit_length()
2052
2053
2054 @pytest.mark.parametrize(['methname'], [(methodname, ) for methodname in dir(TestHypothesis) if methodname.startswith("test_")])
2055 def test_hypothesis_small_shift(methname):
2056 # run the TestHypothesis in a subprocess with a smaller SHIFT value
2057 # the idea is that this finds hopefully finds edge cases more easily
2058 import subprocess, os
2059 # The cwd on the buildbot is actually in rpython
2060 # Add the pypy basedir so we get the local pytest
2061 env = os.environ.copy()
2062 parent = os.path.dirname
2063 env['PYTHONPATH'] = parent(parent(parent(parent(__file__))))
2064 p = subprocess.Popen(" ".join([sys.executable, os.path.abspath(__file__), methname]),
2065 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2066 shell=True, env=env)
2067 stdout, stderr = p.communicate()
2068 if p.returncode:
2069 print stdout
2070 print stderr
2071 assert not p.returncode
2072
2073 def _get_hacked_rbigint(shift):
2074 testpath = os.path.dirname(os.path.abspath(__file__))
2075 with open(os.path.join(os.path.dirname(testpath), "rbigint.py")) as f:
2076 s = f.read()
2077 s = s.replace("SHIFT = 63", "SHIFT = %s" % (shift, ))
2078 s = s.replace("SHIFT = 31", "SHIFT = %s" % (shift, ))
2079 with open(os.path.join(testpath, "_hacked_rbigint.py"), "w") as f:
2080 f.write(s)
2081
2082 from rpython.rlib.test import _hacked_rbigint
2083 assert _hacked_rbigint.SHIFT == shift
2084 return _hacked_rbigint
2085
2086 def run():
2087 shift = 9
2088 print "USING SHIFT", shift, sys.argv[1]
2089 _hacked_rbigint = _get_hacked_rbigint(shift)
2090 globals().update(_hacked_rbigint.__dict__) # emulate import *
2091 assert SHIFT == shift
2092 t = TestHypothesis()
2093 try:
2094 getattr(t, sys.argv[1])()
2095 except:
2096 if "--pdb" in sys.argv:
2097 import traceback, pdb
2098 info = sys.exc_info()
2099 print(traceback.format_exc())
2100 pdb.post_mortem(info[2], pdb.Pdb)
2101 raise
2102
2103
2104 if __name__ == '__main__':
2105 run()