PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/rpython/rlib/test/test_rbigint.py

https://bitbucket.org/pypy/pypy/
Python | 993 lines | 865 code | 97 blank | 31 comment | 87 complexity | e25f1e0150aaa153794cb3de3ff36b2d MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from __future__ import division
  2. import operator
  3. import sys
  4. import math
  5. from random import random, randint, sample, seed
  6. import py
  7. from rpython.rlib import rbigint as lobj
  8. from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong, intmask
  9. from rpython.rlib.rbigint import (rbigint, SHIFT, MASK, KARATSUBA_CUTOFF,
  10. _store_digit, _mask_digit, InvalidEndiannessError, InvalidSignednessError)
  11. from rpython.rlib.rfloat import NAN
  12. from rpython.rtyper.test.test_llinterp import interpret
  13. from rpython.translator.c.test.test_standalone import StandaloneTests
  14. from hypothesis import given, strategies
  15. long_vals_not_too_big = range(17) + [
  16. 37, 50,
  17. 127, 128, 129, 511, 512, 513, sys.maxint, sys.maxint + 1,
  18. 123456789123456789000000L,
  19. ]
  20. long_vals = long_vals_not_too_big + [
  21. 1 << 100, 3 ** 10000]
  22. class TestRLong(object):
  23. def test_simple(self):
  24. for op1 in [-2, -1, 0, 1, 2, 50]:
  25. for op2 in [-2, -1, 0, 1, 2, 50]:
  26. rl_op1 = rbigint.fromint(op1)
  27. rl_op2 = rbigint.fromint(op2)
  28. for op in "add sub mul".split():
  29. r1 = getattr(rl_op1, op)(rl_op2)
  30. r2 = getattr(operator, op)(op1, op2)
  31. print op, op1, op2
  32. assert r1.tolong() == r2
  33. def test_frombool(self):
  34. assert rbigint.frombool(False).tolong() == 0
  35. assert rbigint.frombool(True).tolong() == 1
  36. def test_str(self):
  37. n = 1
  38. r1 = rbigint.fromint(1)
  39. three = rbigint.fromint(3)
  40. for i in range(300):
  41. n *= 3
  42. r1 = r1.mul(three)
  43. assert r1.str() == str(n)
  44. r2 = r1.neg()
  45. assert r2.str() == str(-n)
  46. def test_floordiv(self):
  47. for op1 in gen_signs(long_vals):
  48. for op2 in gen_signs(long_vals):
  49. if not op2:
  50. continue
  51. rl_op1 = rbigint.fromlong(op1)
  52. rl_op2 = rbigint.fromlong(op2)
  53. r1 = rl_op1.floordiv(rl_op2)
  54. r2 = op1 // op2
  55. assert r1.tolong() == r2
  56. def test_truediv(self):
  57. for op1 in gen_signs(long_vals_not_too_big):
  58. for op2 in gen_signs(long_vals):
  59. if not op2:
  60. continue
  61. rl_op1 = rbigint.fromlong(op1)
  62. rl_op2 = rbigint.fromlong(op2)
  63. r1 = rl_op1.truediv(rl_op2)
  64. r2 = op1 / op2
  65. assert r1 == r2
  66. def test_truediv_precision(self):
  67. op1 = rbigint.fromlong(12345*2**30)
  68. op2 = rbigint.fromlong(98765*7**81)
  69. f = op1.truediv(op2)
  70. assert f == 4.7298422347492634e-61 # exactly
  71. def test_truediv_overflow(self):
  72. overflowing = 2**1024 - 2**(1024-53-1)
  73. op1 = rbigint.fromlong(overflowing-1)
  74. op2 = rbigint.fromlong(1)
  75. f = op1.truediv(op2)
  76. assert f == 1.7976931348623157e+308 # exactly
  77. op1 = rbigint.fromlong(overflowing-1)
  78. op2 = rbigint.fromlong(-1)
  79. f = op1.truediv(op2)
  80. assert f == -1.7976931348623157e+308 # exactly
  81. op1 = rbigint.fromlong(-overflowing+1)
  82. op2 = rbigint.fromlong(-1)
  83. f = op1.truediv(op2)
  84. assert f == +1.7976931348623157e+308 # exactly
  85. op1 = rbigint.fromlong(overflowing)
  86. op2 = rbigint.fromlong(1)
  87. py.test.raises(OverflowError, op1.truediv, op2)
  88. def test_truediv_overflow2(self):
  89. overflowing = 2**1024 - 2**(1024-53-1)
  90. op1 = rbigint.fromlong(2*overflowing - 10)
  91. op2 = rbigint.fromlong(2)
  92. f = op1.truediv(op2)
  93. assert f == 1.7976931348623157e+308 # exactly
  94. op2 = rbigint.fromlong(-2)
  95. f = op1.truediv(op2)
  96. assert f == -1.7976931348623157e+308 # exactly
  97. def test_mod(self):
  98. for op1 in gen_signs(long_vals):
  99. for op2 in gen_signs(long_vals):
  100. if not op2:
  101. continue
  102. rl_op1 = rbigint.fromlong(op1)
  103. rl_op2 = rbigint.fromlong(op2)
  104. r1 = rl_op1.mod(rl_op2)
  105. r2 = op1 % op2
  106. print op1, op2
  107. assert r1.tolong() == r2
  108. def test_int_mod(self):
  109. for x in gen_signs(long_vals):
  110. for y in gen_signs([1, 2, 4, 8, 8888, sys.maxint, 2 ** 19, 2 ** 18 - 1]):
  111. op1 = rbigint.fromlong(x)
  112. r1 = op1.int_mod(y)
  113. r2 = x % y
  114. assert r1.tolong() == r2
  115. def test_pow(self):
  116. for op1 in gen_signs(long_vals_not_too_big):
  117. for op2 in [0, 1, 2, 8, 9, 10, 11]:
  118. rl_op1 = rbigint.fromlong(op1)
  119. rl_op2 = rbigint.fromint(op2)
  120. r1 = rl_op1.pow(rl_op2)
  121. r2 = op1 ** op2
  122. assert r1.tolong() == r2
  123. def test_touint(self):
  124. result = r_uint(sys.maxint + 42)
  125. rl = rbigint.fromint(sys.maxint).add(rbigint.fromint(42))
  126. assert rl.touint() == result
  127. def test_eq_ne_operators(self):
  128. a1 = rbigint.fromint(12)
  129. a2 = rbigint.fromint(12)
  130. a3 = rbigint.fromint(123)
  131. assert a1 == a2
  132. assert a1 != a3
  133. assert not (a1 != a2)
  134. assert not (a1 == a3)
  135. def gen_signs(l):
  136. for s in l:
  137. if s == 0:
  138. yield s
  139. else:
  140. yield s
  141. yield -s
  142. def bigint(lst, sign):
  143. for digit in lst:
  144. assert digit & MASK == digit # wrongly written test!
  145. return rbigint(map(_store_digit, map(_mask_digit, lst)), sign)
  146. class Test_rbigint(object):
  147. def test_args_from_long(self):
  148. BASE = 1 << SHIFT
  149. assert rbigint.fromlong(0).eq(bigint([0], 0))
  150. assert rbigint.fromlong(17).eq(bigint([17], 1))
  151. assert rbigint.fromlong(BASE-1).eq(bigint([intmask(BASE-1)], 1))
  152. assert rbigint.fromlong(BASE).eq(bigint([0, 1], 1))
  153. assert rbigint.fromlong(BASE**2).eq(bigint([0, 0, 1], 1))
  154. assert rbigint.fromlong(-17).eq(bigint([17], -1))
  155. assert rbigint.fromlong(-(BASE-1)).eq(bigint([intmask(BASE-1)], -1))
  156. assert rbigint.fromlong(-BASE).eq(bigint([0, 1], -1))
  157. assert rbigint.fromlong(-(BASE**2)).eq(bigint([0, 0, 1], -1))
  158. # assert rbigint.fromlong(-sys.maxint-1).eq(
  159. # rbigint.digits_for_most_neg_long(-sys.maxint-1), -1)
  160. def test_args_from_int(self):
  161. BASE = 1 << 31 # Can't can't shift here. Shift might be from longlonglong
  162. MAX = int(BASE-1)
  163. assert rbigint.fromrarith_int(0).eq(bigint([0], 0))
  164. assert rbigint.fromrarith_int(17).eq(bigint([17], 1))
  165. assert rbigint.fromrarith_int(MAX).eq(bigint([MAX], 1))
  166. # No longer true.
  167. """assert rbigint.fromrarith_int(r_longlong(BASE)).eq(bigint([0, 1], 1))
  168. assert rbigint.fromrarith_int(r_longlong(BASE**2)).eq(
  169. bigint([0, 0, 1], 1))"""
  170. assert rbigint.fromrarith_int(-17).eq(bigint([17], -1))
  171. assert rbigint.fromrarith_int(-MAX).eq(bigint([MAX], -1))
  172. """assert rbigint.fromrarith_int(-MAX-1).eq(bigint([0, 1], -1))
  173. assert rbigint.fromrarith_int(r_longlong(-(BASE**2))).eq(
  174. bigint([0, 0, 1], -1))"""
  175. # assert rbigint.fromrarith_int(-sys.maxint-1).eq((
  176. # rbigint.digits_for_most_neg_long(-sys.maxint-1), -1)
  177. def test_args_from_uint(self):
  178. BASE = 1 << SHIFT
  179. assert rbigint.fromrarith_int(r_uint(0)).eq(bigint([0], 0))
  180. assert rbigint.fromrarith_int(r_uint(17)).eq(bigint([17], 1))
  181. assert rbigint.fromrarith_int(r_uint(BASE-1)).eq(bigint([intmask(BASE-1)], 1))
  182. assert rbigint.fromrarith_int(r_uint(BASE)).eq(bigint([0, 1], 1))
  183. #assert rbigint.fromrarith_int(r_uint(BASE**2)).eq(bigint([0], 0))
  184. assert rbigint.fromrarith_int(r_uint(sys.maxint)).eq(
  185. rbigint.fromint(sys.maxint))
  186. assert rbigint.fromrarith_int(r_uint(sys.maxint+1)).eq(
  187. rbigint.fromlong(sys.maxint+1))
  188. assert rbigint.fromrarith_int(r_uint(2*sys.maxint+1)).eq(
  189. rbigint.fromlong(2*sys.maxint+1))
  190. def test_fromdecimalstr(self):
  191. x = rbigint.fromdecimalstr("12345678901234567890523897987")
  192. assert x.tolong() == 12345678901234567890523897987L
  193. assert x.tobool() is True
  194. x = rbigint.fromdecimalstr("+12345678901234567890523897987")
  195. assert x.tolong() == 12345678901234567890523897987L
  196. assert x.tobool() is True
  197. x = rbigint.fromdecimalstr("-12345678901234567890523897987")
  198. assert x.tolong() == -12345678901234567890523897987L
  199. assert x.tobool() is True
  200. x = rbigint.fromdecimalstr("+0")
  201. assert x.tolong() == 0
  202. assert x.tobool() is False
  203. x = rbigint.fromdecimalstr("-0")
  204. assert x.tolong() == 0
  205. assert x.tobool() is False
  206. def test_fromstr(self):
  207. from rpython.rlib.rstring import ParseStringError
  208. assert rbigint.fromstr('123L').tolong() == 123
  209. assert rbigint.fromstr('123L ').tolong() == 123
  210. py.test.raises(ParseStringError, rbigint.fromstr, 'L')
  211. py.test.raises(ParseStringError, rbigint.fromstr, 'L ')
  212. assert rbigint.fromstr('123L', 4).tolong() == 27
  213. assert rbigint.fromstr('123L', 30).tolong() == 27000 + 1800 + 90 + 21
  214. assert rbigint.fromstr('123L', 22).tolong() == 10648 + 968 + 66 + 21
  215. assert rbigint.fromstr('123L', 21).tolong() == 441 + 42 + 3
  216. assert rbigint.fromstr('1891234174197319').tolong() == 1891234174197319
  217. def test_from_numberstring_parser(self):
  218. from rpython.rlib.rstring import NumberStringParser
  219. parser = NumberStringParser("1231231241", "1231231241", 10, "long")
  220. assert rbigint._from_numberstring_parser(parser).tolong() == 1231231241
  221. def test_add(self):
  222. x = 123456789123456789000000L
  223. y = 123858582373821923936744221L
  224. for i in [-1, 1]:
  225. for j in [-1, 1]:
  226. f1 = rbigint.fromlong(x * i)
  227. f2 = rbigint.fromlong(y * j)
  228. result = f1.add(f2)
  229. assert result.tolong() == x * i + y * j
  230. def test_int_add(self):
  231. for x in gen_signs(long_vals):
  232. for y in gen_signs([0, 1, 9999, sys.maxint, 2 ** 19, 2 ** 18 - 1]):
  233. f1 = rbigint.fromlong(x)
  234. result = f1.int_add(y)
  235. assert result.tolong() == x + y
  236. def test_sub(self):
  237. x = 12378959520302182384345L
  238. y = 88961284756491823819191823L
  239. for i in [-1, 1]:
  240. for j in [-1, 1]:
  241. f1 = rbigint.fromlong(x * i)
  242. f2 = rbigint.fromlong(y * j)
  243. result = f1.sub(f2)
  244. assert result.tolong() == x * i - y * j
  245. def test_int_sub(self):
  246. for x in gen_signs([0, 123456789123456789000000L, 1 << 100, 3 ** 10000]):
  247. for y in gen_signs([0, 1, 8888, sys.maxint, 2 ** 19, 2 ** 18 - 1]):
  248. f1 = rbigint.fromlong(x)
  249. result = f1.int_sub(y)
  250. assert result.tolong() == x - y
  251. def test_subzz(self):
  252. w_l0 = rbigint.fromint(0)
  253. assert w_l0.sub(w_l0).tolong() == 0
  254. def test_mul(self):
  255. for x in gen_signs(long_vals):
  256. f1 = rbigint.fromlong(x)
  257. for y in gen_signs(long_vals_not_too_big):
  258. f2 = rbigint.fromlong(y)
  259. result = f1.mul(f2)
  260. assert result.tolong() == x * y
  261. # there's a special case for a is b
  262. result = f1.mul(f1)
  263. assert result.tolong() == x * x
  264. def test_int_mul(self):
  265. for x in gen_signs([39, 128, 111111111, 123456789123456789000000L, 1 << 100, 3 ** 10000]):
  266. for y in gen_signs([0, 1, 8888, sys.maxint, 2 ** 19, 2 ** 18 - 1]):
  267. f1 = rbigint.fromlong(x)
  268. result = f1.int_mul(y)
  269. assert result.tolong() == x * y
  270. def test_tofloat(self):
  271. x = 12345678901234567890L ** 10
  272. f1 = rbigint.fromlong(x)
  273. d = f1.tofloat()
  274. assert d == float(x)
  275. x = x ** 100
  276. f1 = rbigint.fromlong(x)
  277. assert py.test.raises(OverflowError, f1.tofloat)
  278. f2 = rbigint.fromlong(2097152 << SHIFT)
  279. d = f2.tofloat()
  280. assert d == float(2097152 << SHIFT)
  281. def test_tofloat_precision(self):
  282. assert rbigint.fromlong(0).tofloat() == 0.0
  283. for sign in [1, -1]:
  284. for p in xrange(100):
  285. x = long(2**p * (2**53 + 1) + 1) * sign
  286. y = long(2**p * (2**53+ 2)) * sign
  287. rx = rbigint.fromlong(x)
  288. rxf = rx.tofloat()
  289. assert rxf == float(y)
  290. assert rbigint.fromfloat(rxf).tolong() == y
  291. #
  292. x = long(2**p * (2**53 + 1)) * sign
  293. y = long(2**p * 2**53) * sign
  294. rx = rbigint.fromlong(x)
  295. rxf = rx.tofloat()
  296. assert rxf == float(y)
  297. assert rbigint.fromfloat(rxf).tolong() == y
  298. def test_fromfloat(self):
  299. x = 1234567890.1234567890
  300. f1 = rbigint.fromfloat(x)
  301. y = f1.tofloat()
  302. assert f1.tolong() == long(x)
  303. # check overflow
  304. #x = 12345.6789e10000000000000000000000000000
  305. # XXX don't use such consts. marshal doesn't handle them right.
  306. x = 12345.6789e200
  307. x *= x
  308. assert py.test.raises(OverflowError, rbigint.fromfloat, x)
  309. assert py.test.raises(ValueError, rbigint.fromfloat, NAN)
  310. #
  311. f1 = rbigint.fromfloat(9007199254740991.0)
  312. assert f1.tolong() == 9007199254740991
  313. null = rbigint.fromfloat(-0.0)
  314. assert null.int_eq(0)
  315. def test_eq(self):
  316. x = 5858393919192332223L
  317. y = 585839391919233111223311112332L
  318. f1 = rbigint.fromlong(x)
  319. f2 = rbigint.fromlong(-x)
  320. f3 = rbigint.fromlong(y)
  321. assert f1.eq(f1)
  322. assert f2.eq(f2)
  323. assert f3.eq(f3)
  324. assert not f1.eq(f2)
  325. assert not f1.eq(f3)
  326. def test_eq_fastpath(self):
  327. x = 1234
  328. y = 1234
  329. f1 = rbigint.fromint(x)
  330. f2 = rbigint.fromint(y)
  331. assert f1.eq(f2)
  332. def test_lt(self):
  333. val = [0, 0x111111111111, 0x111111111112, 0x111111111112FFFF]
  334. for x in gen_signs(val):
  335. for y in gen_signs(val):
  336. f1 = rbigint.fromlong(x)
  337. f2 = rbigint.fromlong(y)
  338. assert (x < y) == f1.lt(f2)
  339. def test_int_comparison(self):
  340. for x in gen_signs(long_vals):
  341. for y in gen_signs([0, 1, 0x11111111, 0x11111112, 8888, sys.maxint, 2 ** 19, 2 ** 18 - 1]):
  342. f1 = rbigint.fromlong(x)
  343. assert (x < y) == f1.int_lt(y)
  344. assert (x <= y) == f1.int_le(y)
  345. assert (x > y) == f1.int_gt(y)
  346. assert (x >= y) == f1.int_ge(y)
  347. assert (x == y) == f1.int_eq(y)
  348. assert (x != y) == f1.int_ne(y)
  349. def test_order(self):
  350. f6 = rbigint.fromint(6)
  351. f7 = rbigint.fromint(7)
  352. assert (f6.lt(f6), f6.lt(f7), f7.lt(f6)) == (0,1,0)
  353. assert (f6.le(f6), f6.le(f7), f7.le(f6)) == (1,1,0)
  354. assert (f6.gt(f6), f6.gt(f7), f7.gt(f6)) == (0,0,1)
  355. assert (f6.ge(f6), f6.ge(f7), f7.ge(f6)) == (1,0,1)
  356. def test_int_order(self):
  357. f6 = rbigint.fromint(6)
  358. f7 = rbigint.fromint(7)
  359. assert (f6.int_lt(6), f6.int_lt(7), f7.int_lt(6)) == (0,1,0)
  360. assert (f6.int_le(6), f6.int_le(7), f7.int_le(6)) == (1,1,0)
  361. assert (f6.int_gt(6), f6.int_gt(7), f7.int_gt(6)) == (0,0,1)
  362. assert (f6.int_ge(6), f6.int_ge(7), f7.int_ge(6)) == (1,0,1)
  363. def test_int_conversion(self):
  364. f1 = rbigint.fromlong(12332)
  365. f2 = rbigint.fromint(12332)
  366. assert f2.tolong() == f1.tolong()
  367. assert f2.toint()
  368. assert rbigint.fromlong(42).tolong() == 42
  369. assert rbigint.fromlong(-42).tolong() == -42
  370. u = f2.touint()
  371. assert u == 12332
  372. assert type(u) is r_uint
  373. def test_conversions(self):
  374. for v in (0, 1, -1, sys.maxint, -sys.maxint-1):
  375. assert rbigint.fromlong(long(v)).tolong() == long(v)
  376. l = rbigint.fromint(v)
  377. assert l.toint() == v
  378. if v >= 0:
  379. u = l.touint()
  380. assert u == v
  381. assert type(u) is r_uint
  382. else:
  383. py.test.raises(ValueError, l.touint)
  384. toobig_lv1 = rbigint.fromlong(sys.maxint+1)
  385. assert toobig_lv1.tolong() == sys.maxint+1
  386. toobig_lv2 = rbigint.fromlong(sys.maxint+2)
  387. assert toobig_lv2.tolong() == sys.maxint+2
  388. toobig_lv3 = rbigint.fromlong(-sys.maxint-2)
  389. assert toobig_lv3.tolong() == -sys.maxint-2
  390. for lv in (toobig_lv1, toobig_lv2, toobig_lv3):
  391. py.test.raises(OverflowError, lv.toint)
  392. lmaxuint = rbigint.fromlong(2*sys.maxint+1)
  393. toobig_lv4 = rbigint.fromlong(2*sys.maxint+2)
  394. u = lmaxuint.touint()
  395. assert u == 2*sys.maxint+1
  396. py.test.raises(ValueError, toobig_lv3.touint)
  397. py.test.raises(OverflowError, toobig_lv4.touint)
  398. def test_pow_lll(self):
  399. x = 10L
  400. y = 2L
  401. z = 13L
  402. f1 = rbigint.fromlong(x)
  403. f2 = rbigint.fromlong(y)
  404. f3 = rbigint.fromlong(z)
  405. v = f1.pow(f2, f3)
  406. assert v.tolong() == pow(x, y, z)
  407. f3n = f3.neg()
  408. v = f1.pow(f2, f3n)
  409. assert v.tolong() == pow(x, y, -z)
  410. #
  411. f1, f2, f3 = [rbigint.fromlong(i)
  412. for i in (10L, -1L, 42L)]
  413. py.test.raises(TypeError, f1.pow, f2, f3)
  414. f1, f2, f3 = [rbigint.fromlong(i)
  415. for i in (10L, 5L, 0L)]
  416. py.test.raises(ValueError, f1.pow, f2, f3)
  417. #
  418. MAX = 1E20
  419. x = long(random() * MAX) + 1
  420. y = long(random() * MAX) + 1
  421. z = long(random() * MAX) + 1
  422. f1 = rbigint.fromlong(x)
  423. f2 = rbigint.fromlong(y)
  424. f3 = rbigint.fromlong(z)
  425. print f1
  426. print f2
  427. print f3
  428. v = f1.pow(f2, f3)
  429. print '--->', v
  430. assert v.tolong() == pow(x, y, z)
  431. def test_pow_lll_bug(self):
  432. two = rbigint.fromint(2)
  433. t = rbigint.fromlong(2655689964083835493447941032762343136647965588635159615997220691002017799304)
  434. for n, expected in [(37, 9), (1291, 931), (67889, 39464)]:
  435. v = two.pow(t, rbigint.fromint(n))
  436. assert v.toint() == expected
  437. #
  438. # more tests, comparing against CPython's answer
  439. enabled = sample(range(5*32), 10)
  440. for i in range(5*32):
  441. t = t.mul(two) # add one random bit
  442. if random() >= 0.5:
  443. t = t.add(rbigint.fromint(1))
  444. if i not in enabled:
  445. continue # don't take forever
  446. n = randint(1, sys.maxint)
  447. v = two.pow(t, rbigint.fromint(n))
  448. assert v.toint() == pow(2, t.tolong(), n)
  449. def test_pow_lll_bug2(self):
  450. x = rbigint.fromlong(2)
  451. y = rbigint.fromlong(5100894665148900058249470019412564146962964987365857466751243988156579407594163282788332839328303748028644825680244165072186950517295679131100799612871613064597)
  452. z = rbigint.fromlong(538564)
  453. expected = rbigint.fromlong(163464)
  454. got = x.pow(y, z)
  455. assert got.eq(expected)
  456. def test_pow_lln(self):
  457. x = 10L
  458. y = 2L
  459. f1 = rbigint.fromlong(x)
  460. f2 = rbigint.fromlong(y)
  461. v = f1.pow(f2)
  462. assert v.tolong() == x ** y
  463. def test_normalize(self):
  464. f1 = bigint([1, 0], 1)
  465. f1._normalize()
  466. assert f1.size == 1
  467. f0 = bigint([0], 0)
  468. assert f1.sub(f1).eq(f0)
  469. def test_invert(self):
  470. x = 3 ** 40
  471. f1 = rbigint.fromlong(x)
  472. f2 = rbigint.fromlong(-x)
  473. r1 = f1.invert()
  474. r2 = f2.invert()
  475. assert r1.tolong() == -(x + 1)
  476. assert r2.tolong() == -(-x + 1)
  477. def test_shift(self):
  478. negative = -23
  479. masks_list = [int((1 << i) - 1) for i in range(1, r_uint.BITS-1)]
  480. for x in gen_signs([3L ** 30L, 5L ** 20L, 7 ** 300, 0L, 1L]):
  481. f1 = rbigint.fromlong(x)
  482. py.test.raises(ValueError, f1.lshift, negative)
  483. py.test.raises(ValueError, f1.rshift, negative)
  484. for y in [0L, 1L, 32L, 2304L, 11233L, 3 ** 9]:
  485. res1 = f1.lshift(int(y)).tolong()
  486. res2 = f1.rshift(int(y)).tolong()
  487. assert res1 == x << y
  488. assert res2 == x >> y
  489. for mask in masks_list:
  490. res3 = f1.abs_rshift_and_mask(r_ulonglong(y), mask)
  491. assert res3 == (abs(x) >> y) & mask
  492. def test_from_list_n_bits(self):
  493. for x in ([3L ** 30L, 5L ** 20L, 7 ** 300] +
  494. [1L << i for i in range(130)] +
  495. [(1L << i) - 1L for i in range(130)]):
  496. for nbits in range(1, SHIFT+1):
  497. mask = (1 << nbits) - 1
  498. lst = []
  499. got = x
  500. while got > 0:
  501. lst.append(int(got & mask))
  502. got >>= nbits
  503. f1 = rbigint.from_list_n_bits(lst, nbits)
  504. assert f1.tolong() == x
  505. def test_bitwise(self):
  506. for x in gen_signs([0, 1, 5, 11, 42, 43, 3 ** 30]):
  507. for y in gen_signs([0, 1, 5, 11, 42, 43, 3 ** 30, 3 ** 31]):
  508. lx = rbigint.fromlong(x)
  509. ly = rbigint.fromlong(y)
  510. for mod in "xor and_ or_".split():
  511. res1 = getattr(lx, mod)(ly).tolong()
  512. res2 = getattr(operator, mod)(x, y)
  513. assert res1 == res2
  514. def test_int_bitwise(self):
  515. for x in gen_signs([0, 1, 5, 11, 42, 43, 2 ** 30]):
  516. for y in gen_signs([0, 1, 5, 11, 42, 43, 3 ** 30, 2 ** 31]):
  517. if y != intmask(y):
  518. continue # skip 'y' too large for 32-bit
  519. lx = rbigint.fromlong(x)
  520. for mod in "xor and_ or_".split():
  521. res1 = getattr(lx, 'int_' + mod)(y).tolong()
  522. res2 = getattr(operator, mod)(x, y)
  523. assert res1 == res2
  524. def test_mul_eq_shift(self):
  525. p2 = rbigint.fromlong(1).lshift(63)
  526. f1 = rbigint.fromlong(0).lshift(63)
  527. f2 = rbigint.fromlong(0).mul(p2)
  528. assert f1.eq(f2)
  529. def test_tostring(self):
  530. z = rbigint.fromlong(0)
  531. assert z.str() == '0'
  532. assert z.repr() == '0L'
  533. assert z.hex() == '0x0L'
  534. assert z.oct() == '0L'
  535. x = rbigint.fromlong(-18471379832321)
  536. assert x.str() == '-18471379832321'
  537. assert x.repr() == '-18471379832321L'
  538. assert x.hex() == '-0x10ccb4088e01L'
  539. assert x.oct() == '-0414626402107001L'
  540. assert x.format('.!') == (
  541. '-!....!!..!!..!.!!.!......!...!...!!!........!')
  542. assert x.format('abcdefghijkl', '<<', '>>') == '-<<cakdkgdijffjf>>'
  543. x = rbigint.fromlong(-18471379832321000000000000000000000000000000000000000000)
  544. assert x.str() == '-18471379832321000000000000000000000000000000000000000000'
  545. assert x.repr() == '-18471379832321000000000000000000000000000000000000000000L'
  546. assert x.hex() == '-0xc0d9a6f41fbcf1718b618443d45516a051e40000000000L'
  547. assert x.oct() == '-014033151572037571705614266060420752125055201217100000000000000L'
  548. def test_format_caching(self):
  549. big = rbigint.fromlong(2 ** 1000)
  550. res1 = big.str()
  551. oldpow = rbigint.__dict__['pow']
  552. rbigint.pow = None
  553. # make sure pow is not used the second time
  554. try:
  555. res2 = big.str()
  556. assert res2 == res1
  557. finally:
  558. rbigint.pow = oldpow
  559. def test_overzelous_assertion(self):
  560. a = rbigint.fromlong(-1<<10000)
  561. b = rbigint.fromlong(-1<<3000)
  562. assert a.mul(b).tolong() == (-1<<10000)*(-1<<3000)
  563. def test_bit_length(self):
  564. assert rbigint.fromlong(0).bit_length() == 0
  565. assert rbigint.fromlong(1).bit_length() == 1
  566. assert rbigint.fromlong(2).bit_length() == 2
  567. assert rbigint.fromlong(3).bit_length() == 2
  568. assert rbigint.fromlong(4).bit_length() == 3
  569. assert rbigint.fromlong(-3).bit_length() == 2
  570. assert rbigint.fromlong(-4).bit_length() == 3
  571. assert rbigint.fromlong(1<<40).bit_length() == 41
  572. def test_hash(self):
  573. for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  574. sys.maxint-3, sys.maxint-2, sys.maxint-1, sys.maxint,
  575. ] + [randint(0, sys.maxint) for _ in range(100)]:
  576. # hash of machine-sized integers
  577. assert rbigint.fromint(i).hash() == i
  578. # hash of negative machine-sized integers
  579. assert rbigint.fromint(-i-1).hash() == -i-1
  580. #
  581. for i in range(200):
  582. # hash of large integers: should be equal to the hash of the
  583. # integer reduced modulo 2**64-1, to make decimal.py happy
  584. x = randint(0, sys.maxint**5)
  585. y = x % (2**64-1)
  586. assert rbigint.fromlong(x).hash() == rbigint.fromlong(y).hash()
  587. assert rbigint.fromlong(-x).hash() == rbigint.fromlong(-y).hash()
  588. def test_log(self):
  589. from rpython.rlib.rfloat import ulps_check
  590. for op in long_vals:
  591. if not op:
  592. continue
  593. for base in [0, 2, 4, 8, 16, 10, math.e]:
  594. l = rbigint.fromlong(op).log(base)
  595. if base:
  596. assert ulps_check(l, math.log(op, base)) is None
  597. else:
  598. assert ulps_check(l, math.log(op)) is None
  599. class TestInternalFunctions(object):
  600. def test__inplace_divrem1(self):
  601. # signs are not handled in the helpers!
  602. for x, y in [(1238585838347L, 3), (1234123412311231L, 1231231), (99, 100)]:
  603. if y > MASK:
  604. continue
  605. f1 = rbigint.fromlong(x)
  606. f2 = y
  607. remainder = lobj._inplace_divrem1(f1, f1, f2)
  608. assert (f1.tolong(), remainder) == divmod(x, y)
  609. out = bigint([99, 99], 1)
  610. remainder = lobj._inplace_divrem1(out, out, 100)
  611. def test__divrem1(self):
  612. # signs are not handled in the helpers!
  613. x = 1238585838347L
  614. y = 3
  615. f1 = rbigint.fromlong(x)
  616. f2 = y
  617. div, rem = lobj._divrem1(f1, f2)
  618. assert (div.tolong(), rem) == divmod(x, y)
  619. def test__muladd1(self):
  620. x = 1238585838347L
  621. y = 3
  622. z = 42
  623. f1 = rbigint.fromlong(x)
  624. f2 = y
  625. f3 = z
  626. prod = lobj._muladd1(f1, f2, f3)
  627. assert prod.tolong() == x * y + z
  628. def test__x_divrem(self):
  629. x = 12345678901234567890L
  630. for i in range(100):
  631. y = long(randint(1, 1 << 60))
  632. y <<= 60
  633. y += randint(1, 1 << 60)
  634. if y > x:
  635. x <<= 100
  636. f1 = rbigint.fromlong(x)
  637. f2 = rbigint.fromlong(y)
  638. div, rem = lobj._x_divrem(f1, f2)
  639. _div, _rem = divmod(x, y)
  640. assert div.tolong() == _div
  641. assert rem.tolong() == _rem
  642. def test__x_divrem2(self):
  643. Rx = 1 << 130
  644. Rx2 = 1 << 150
  645. Ry = 1 << 127
  646. Ry2 = 1<< 150
  647. for i in range(10):
  648. x = long(randint(Rx, Rx2))
  649. y = long(randint(Ry, Ry2))
  650. f1 = rbigint.fromlong(x)
  651. f2 = rbigint.fromlong(y)
  652. div, rem = lobj._x_divrem(f1, f2)
  653. _div, _rem = divmod(x, y)
  654. assert div.tolong() == _div
  655. assert rem.tolong() == _rem
  656. def test_divmod(self):
  657. x = 12345678901234567890L
  658. for i in range(100):
  659. y = long(randint(0, 1 << 60))
  660. y <<= 60
  661. y += randint(0, 1 << 60)
  662. for sx, sy in (1, 1), (1, -1), (-1, -1), (-1, 1):
  663. sx *= x
  664. sy *= y
  665. f1 = rbigint.fromlong(sx)
  666. f2 = rbigint.fromlong(sy)
  667. div, rem = f1.divmod(f2)
  668. _div, _rem = divmod(sx, sy)
  669. assert div.tolong() == _div
  670. assert rem.tolong() == _rem
  671. # testing Karatsuba stuff
  672. def test__v_iadd(self):
  673. f1 = bigint([lobj.MASK] * 10, 1)
  674. f2 = bigint([1], 1)
  675. carry = lobj._v_iadd(f1, 1, len(f1._digits)-1, f2, 1)
  676. assert carry == 1
  677. assert f1.tolong() == lobj.MASK
  678. def test__v_isub(self):
  679. f1 = bigint([lobj.MASK] + [0] * 9 + [1], 1)
  680. f2 = bigint([1], 1)
  681. borrow = lobj._v_isub(f1, 1, len(f1._digits)-1, f2, 1)
  682. assert borrow == 0
  683. assert f1.tolong() == (1 << lobj.SHIFT) ** 10 - 1
  684. def test__kmul_split(self):
  685. split = 5
  686. diglo = [0] * split
  687. dighi = [lobj.MASK] * split
  688. f1 = bigint(diglo + dighi, 1)
  689. hi, lo = lobj._kmul_split(f1, split)
  690. assert lo._digits == [_store_digit(0)]
  691. assert hi._digits == map(_store_digit, dighi)
  692. def test__k_mul(self):
  693. digs = KARATSUBA_CUTOFF * 5
  694. f1 = bigint([lobj.MASK] * digs, 1)
  695. f2 = lobj._x_add(f1, bigint([1], 1))
  696. ret = lobj._k_mul(f1, f2)
  697. assert ret.tolong() == f1.tolong() * f2.tolong()
  698. def test__k_lopsided_mul(self):
  699. digs_a = KARATSUBA_CUTOFF + 3
  700. digs_b = 3 * digs_a
  701. f1 = bigint([lobj.MASK] * digs_a, 1)
  702. f2 = bigint([lobj.MASK] * digs_b, 1)
  703. ret = lobj._k_lopsided_mul(f1, f2)
  704. assert ret.tolong() == f1.tolong() * f2.tolong()
  705. def test_longlong(self):
  706. max = 1L << (r_longlong.BITS-1)
  707. f1 = rbigint.fromlong(max-1) # fits in r_longlong
  708. f2 = rbigint.fromlong(-max) # fits in r_longlong
  709. f3 = rbigint.fromlong(max) # overflows
  710. f4 = rbigint.fromlong(-max-1) # overflows
  711. assert f1.tolonglong() == max-1
  712. assert f2.tolonglong() == -max
  713. py.test.raises(OverflowError, f3.tolonglong)
  714. py.test.raises(OverflowError, f4.tolonglong)
  715. def test_uintmask(self):
  716. assert rbigint.fromint(-1).uintmask() == r_uint(-1)
  717. assert rbigint.fromint(0).uintmask() == r_uint(0)
  718. assert (rbigint.fromint(sys.maxint).uintmask() ==
  719. r_uint(sys.maxint))
  720. assert (rbigint.fromlong(sys.maxint+1).uintmask() ==
  721. r_uint(-sys.maxint-1))
  722. def test_ulonglongmask(self):
  723. assert rbigint.fromlong(-1).ulonglongmask() == r_ulonglong(-1)
  724. assert rbigint.fromlong(0).ulonglongmask() == r_ulonglong(0)
  725. assert (rbigint.fromlong(sys.maxint).ulonglongmask() ==
  726. r_ulonglong(sys.maxint))
  727. assert (rbigint.fromlong(9**50).ulonglongmask() ==
  728. r_ulonglong(9**50))
  729. assert (rbigint.fromlong(-9**50).ulonglongmask() ==
  730. r_ulonglong(-9**50))
  731. def test_parse_digit_string(self):
  732. from rpython.rlib.rbigint import parse_digit_string
  733. class Parser:
  734. def __init__(self, base, sign, digits):
  735. self.base = base
  736. self.sign = sign
  737. self.i = 0
  738. self._digits = digits
  739. def next_digit(self):
  740. i = self.i
  741. if i == len(self._digits):
  742. return -1
  743. self.i = i + 1
  744. return self._digits[i]
  745. def prev_digit(self):
  746. i = self.i - 1
  747. assert i >= 0
  748. self.i = i
  749. return self._digits[i]
  750. x = parse_digit_string(Parser(10, 1, [6]))
  751. assert x.eq(rbigint.fromint(6))
  752. x = parse_digit_string(Parser(10, 1, [6, 2, 3]))
  753. assert x.eq(rbigint.fromint(623))
  754. x = parse_digit_string(Parser(10, -1, [6, 2, 3]))
  755. assert x.eq(rbigint.fromint(-623))
  756. x = parse_digit_string(Parser(16, 1, [0xA, 0x4, 0xF]))
  757. assert x.eq(rbigint.fromint(0xA4F))
  758. num = 0
  759. for i in range(36):
  760. x = parse_digit_string(Parser(36, 1, range(i)))
  761. assert x.eq(rbigint.fromlong(num))
  762. num = num * 36 + i
  763. x = parse_digit_string(Parser(16, -1, range(15,-1,-1)*99))
  764. assert x.eq(rbigint.fromlong(long('-0x' + 'FEDCBA9876543210'*99, 16)))
  765. assert x.tobool() is True
  766. x = parse_digit_string(Parser(7, 1, [0, 0, 0]))
  767. assert x.tobool() is False
  768. x = parse_digit_string(Parser(7, -1, [0, 0, 0]))
  769. assert x.tobool() is False
  770. for base in [2, 4, 8, 16, 32]:
  771. for inp in [[0], [1], [1, 0], [0, 1], [1, 0, 1], [1, 0, 0, 1],
  772. [1, 0, 0, base-1, 0, 1], [base-1, 1, 0, 0, 0, 1, 0],
  773. [base-1]]:
  774. inp = inp * 97
  775. x = parse_digit_string(Parser(base, -1, inp))
  776. num = sum(inp[i] * (base ** (len(inp)-1-i))
  777. for i in range(len(inp)))
  778. assert x.eq(rbigint.fromlong(-num))
  779. BASE = 2 ** SHIFT
  780. class TestTranslatable(object):
  781. def test_square(self):
  782. def test():
  783. xlo = rbigint.fromint(1410065408)
  784. xhi = rbigint.fromint(4)
  785. x = xlo.or_(xhi.lshift(31))
  786. y = x.mul(x)
  787. return y.str()
  788. res = interpret(test, [])
  789. assert "".join(res.chars) == test()
  790. def test_add(self):
  791. x = rbigint.fromint(-2147483647)
  792. y = rbigint.fromint(-1)
  793. z = rbigint.fromint(-2147483648)
  794. def test():
  795. return x.add(y).eq(z)
  796. assert test()
  797. res = interpret(test, [])
  798. assert res
  799. def test_args_from_rarith_int(self):
  800. from rpython.rtyper.tool.rfficache import platform
  801. from rpython.rlib.rarithmetic import r_int
  802. from rpython.rtyper.lltypesystem.rffi import r_int_real
  803. classlist = platform.numbertype_to_rclass.values()
  804. fnlist = []
  805. for r in classlist:
  806. if r in (r_int, r_int_real): # and also r_longlong on 64-bit
  807. continue
  808. if r is int:
  809. mask = sys.maxint*2+1
  810. signed = True
  811. else:
  812. mask = r.MASK
  813. signed = r.SIGNED
  814. values = [0, -1, mask>>1, -(mask>>1)-1]
  815. if not signed:
  816. values = [x & mask for x in values]
  817. values = [r(x) for x in values]
  818. def fn(i):
  819. n = rbigint.fromrarith_int(values[i])
  820. return n.str()
  821. for i in range(len(values)):
  822. res = fn(i)
  823. assert res == str(long(values[i]))
  824. res = interpret(fn, [i])
  825. assert ''.join(res.chars) == str(long(values[i]))
  826. def test_truediv_overflow(self):
  827. overflowing = 2**1024 - 2**(1024-53-1)
  828. op1 = rbigint.fromlong(overflowing)
  829. def fn():
  830. try:
  831. return op1.truediv(rbigint.fromint(1))
  832. except OverflowError:
  833. return -42.0
  834. res = interpret(fn, [])
  835. assert res == -42.0
  836. def test_frombytes(self):
  837. bigint = rbigint.frombytes('', byteorder='big', signed=True)
  838. assert bigint.tolong() == 0
  839. s = "\xFF\x12\x34\x56"
  840. bigint = rbigint.frombytes(s, byteorder="big", signed=False)
  841. assert bigint.tolong() == 0xFF123456
  842. bigint = rbigint.frombytes(s, byteorder="little", signed=False)
  843. assert bigint.tolong() == 0x563412FF
  844. s = "\xFF\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\xFF"
  845. bigint = rbigint.frombytes(s, byteorder="big", signed=False)
  846. assert s == bigint.tobytes(16, byteorder="big", signed=False)
  847. py.test.raises(InvalidEndiannessError, bigint.frombytes, '\xFF', 'foo',
  848. signed=True)
  849. bigint = rbigint.frombytes('\x82', byteorder='big', signed=True)
  850. assert bigint.tolong() == -126
  851. def test_tobytes(self):
  852. assert rbigint.fromint(0).tobytes(1, 'big', signed=True) == '\x00'
  853. assert rbigint.fromint(1).tobytes(2, 'big', signed=True) == '\x00\x01'
  854. py.test.raises(OverflowError, rbigint.fromint(255).tobytes, 1, 'big', signed=True)
  855. assert rbigint.fromint(-129).tobytes(2, 'big', signed=True) == '\xff\x7f'
  856. assert rbigint.fromint(-129).tobytes(2, 'little', signed=True) == '\x7f\xff'
  857. assert rbigint.fromint(65535).tobytes(3, 'big', signed=True) == '\x00\xff\xff'
  858. assert rbigint.fromint(-65536).tobytes(3, 'little', signed=True) == '\x00\x00\xff'
  859. assert rbigint.fromint(65535).tobytes(2, 'big', signed=False) == '\xff\xff'
  860. assert rbigint.fromint(-8388608).tobytes(3, 'little', signed=True) == '\x00\x00\x80'
  861. i = rbigint.fromint(-8388608)
  862. py.test.raises(InvalidEndiannessError, i.tobytes, 3, 'foo', signed=True)
  863. py.test.raises(InvalidSignednessError, i.tobytes, 3, 'little', signed=False)
  864. py.test.raises(OverflowError, i.tobytes, 2, 'little', signed=True)
  865. @given(strategies.binary(), strategies.booleans(), strategies.booleans())
  866. def test_frombytes_tobytes_hypothesis(self, s, big, signed):
  867. # check the roundtrip from binary strings to bigints and back
  868. byteorder = 'big' if big else 'little'
  869. bigint = rbigint.frombytes(s, byteorder=byteorder, signed=signed)
  870. t = bigint.tobytes(len(s), byteorder=byteorder, signed=signed)
  871. assert s == t
  872. class TestTranslated(StandaloneTests):
  873. def test_gcc_4_9(self):
  874. MIN = -sys.maxint-1
  875. def entry_point(argv):
  876. print rbigint.fromint(MIN+1)._digits
  877. print rbigint.fromint(MIN)._digits
  878. return 0
  879. t, cbuilder = self.compile(entry_point)
  880. data = cbuilder.cmdexec('hi there')
  881. assert data == '[%d]\n[0, 1]\n' % sys.maxint