OILS / mycpp / examples / test_integers.py View on Github | oilshell.org

75 lines, 43 significant
1#!/usr/bin/env python2
2"""
3integers.py
4"""
5from __future__ import print_function
6
7import os
8from mycpp import mops
9from mycpp.mylib import log
10
11from typing import cast
12
13
14def run_tests():
15 # type: () -> None
16
17 a = 3 + 2
18 print('a = %d' % a)
19
20 # the way to write 1 << 31
21 i1 = mops.LShift(mops.BigInt(1), mops.BigInt(31))
22 i2 = mops.Add(i1, i1)
23 i3 = mops.Add(i2, i1)
24
25 # TODO: %d or %ld doesn't work, and won't work when it becomes arbitrary
26 # size
27 print('i1 = %s' % mops.ToStr(i1))
28 print('i2 = %s' % mops.ToStr(i2))
29 print('i3 = %s' % mops.ToStr(i3))
30 print('')
31
32 # This overflows an int64_t
33 i4 = mops.LShift(mops.BigInt(1), mops.BigInt(63))
34 #print('i4 = %s' % mops.ToStr(i4))
35
36 # Max positive (2 ^ (N-1)) - 1
37 x = mops.LShift(mops.BigInt(1), mops.BigInt(62))
38 y = mops.Sub(x, mops.BigInt(1))
39 max_positive = mops.Add(x, y)
40 print('max_positive = %s' % mops.ToStr(max_positive))
41
42 # Max negative -2 ^ (N-1)
43 z = mops.Sub(mops.BigInt(0), x)
44 max_negative = mops.Sub(z, x)
45 print('max_negative = %s' % mops.ToStr(max_negative))
46
47 # Round trip from string
48 s1 = mops.ToStr(max_negative)
49 print('max_negative string = %s' % s1)
50
51 ok, max_negative2 = mops.FromStr2(s1)
52 print('max_negative2 = %s' % mops.ToStr(max_negative2))
53 if ok:
54 print('ok')
55
56 if mops.Equal(max_negative, max_negative2):
57 print('round trip equal')
58
59 big = mops.IntWiden(a)
60 print('big = %s' % mops.ToStr(big))
61 small = mops.BigTruncate(big)
62 print('small = %d' % small)
63
64
65def run_benchmarks():
66 # type: () -> None
67 pass
68
69
70if __name__ == '__main__':
71 if os.getenv('BENCHMARK'):
72 log('Benchmarking...')
73 run_benchmarks()
74 else:
75 run_tests()