forked from edubart/lua-bint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bint.lua
1652 lines (1525 loc) · 45.6 KB
/
bint.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[--
lua-bint - v0.4.1 - 17/Aug/2021
Eduardo Bart - [email protected]
https://github.com/edubart/lua-bint
Small portable arbitrary-precision integer arithmetic library in pure Lua for
computing with large integers.
Different from most arbitrary-precision integer libraries in pure Lua out there this one
uses an array of lua integers as underlying data-type in its implementation instead of
using strings or large tables, this make it efficient for working with fixed width integers
and to make bitwise operations.
## Design goals
The main design goal of this library is to be small, correct, self contained and use few
resources while retaining acceptable performance and feature completeness.
The library is designed to follow recent Lua integer semantics, this means that
integer overflow warps around,
signed integers are implemented using two-complement arithmetic rules,
integer division operations rounds towards minus infinity,
any mixed operations with float numbers promotes the value to a float,
and the usual division/power operation always promotes to floats.
The library is designed to be possible to work with only unsigned integer arithmetic
when using the proper methods.
All the lua arithmetic operators (+, -, *, //, /, %) and bitwise operators (&, |, ~, <<, >>)
are implemented as metamethods.
The integer size must be fixed in advance and the library is designed to be more efficient when
working with integers of sizes between 64-4096 bits. If you need to work with really huge numbers
without size restrictions then use another library. This choice has been made to have more efficiency
in that specific size range.
## Usage
First on you should require the bint file including how many bits the bint module will work with,
by calling the returned function from the require, for example:
```lua
local bint = require 'bint'(1024)
```
For more information about its arguments see @{newmodule}.
Then when you need create a bint, you can use one of the following functions:
* @{bint.fromuinteger} (convert from lua integers, but read as unsigned integer)
* @{bint.frominteger} (convert from lua integers, preserving the sign)
* @{bint.frombase} (convert from arbitrary bases, like hexadecimal)
* @{bint.trunc} (convert from lua numbers, truncating the fractional part)
* @{bint.new} (convert from anything, asserts on invalid integers)
* @{bint.tobint} (convert from anything, returns nil on invalid integers)
* @{bint.parse} (convert from anything, returns a lua number as fallback)
* @{bint.zero}
* @{bint.one}
* `bint`
You can also call `bint` as it is an alias to `bint.new`.
In doubt use @{bint.new} to create a new bint.
Then you can use all the usual lua numeric operations on it,
all the arithmetic metamethods are implemented.
When you are done computing and need to get the result,
get the output from one of the following functions:
* @{bint.touinteger} (convert to a lua integer, wraps around as an unsigned integer)
* @{bint.tointeger} (convert to a lua integer, wraps around, preserves the sign)
* @{bint.tonumber} (convert to lua float, losing precision)
* @{bint.tobase} (convert to a string in any base)
* @{bint.__tostring} (convert to a string in base 10)
To output a very large integer with no loss you probably want to use @{bint.tobase}
or call `tostring` to get a string representation.
## Precautions
All library functions can be mixed with lua numbers,
this makes easy to mix operations between bints and lua numbers,
however the user should take care in some situations:
* Don't mix integers and float operations if you want to work with integers only.
* Don't use the regular equal operator ('==') to compare values from this library,
unless you know in advance that both values are of the same primitive type,
otherwise it will always return false, use @{bint.eq} to be safe.
* Don't pass fractional numbers to functions that an integer is expected
* Don't mix operations between bint classes with different sizes as this is not supported, this
will throw assertions.
* Remember that casting back to lua integers or numbers precision can be lost.
* For dividing while preserving integers use the @{bint.__idiv} (the '//' operator).
* For doing power operation preserving integers use the @{bint.ipow} function.
* Configure the proper integer size you intend to work with, otherwise large integers may wrap around.
]]
-- Returns number of bits of the internal lua integer type.
local function luainteger_bitsize()
local n, i = -1, 0
repeat
n, i = n >> 16, i + 16
until n==0
return i
end
local math_type = math.type
local math_floor = math.floor
local math_abs = math.abs
local math_ceil = math.ceil
local math_modf = math.modf
local math_mininteger = math.mininteger
local math_maxinteger = math.maxinteger
local math_max = math.max
local math_min = math.min
local string_format = string.format
local table_insert = table.insert
local table_concat = table.concat
local memo = {}
--- Create a new bint module representing integers of the desired bit size.
-- This is the returned function when `require 'bint'` is called.
-- @function newmodule
-- @param bits Number of bits for the integer representation, must be multiple of wordbits and
-- at least 64.
-- @param[opt] wordbits Number of the bits for the internal word,
-- defaults to half of Lua's integer size.
local function newmodule(bits, wordbits)
local intbits = luainteger_bitsize()
bits = bits or 256
wordbits = wordbits or (intbits // 2)
-- Memoize bint modules
local memoindex = bits * 64 + wordbits
if memo[memoindex] then
return memo[memoindex]
end
-- Validate
assert(bits % wordbits == 0, 'bitsize is not multiple of word bitsize')
assert(2*wordbits <= intbits, 'word bitsize must be half of the lua integer bitsize')
assert(bits >= 64, 'bitsize must be >= 64')
-- Create bint module
local bint = {}
bint.__index = bint
--- Number of bits representing a bint instance.
bint.bits = bits
-- Constants used internally
local BINT_BITS = bits
local BINT_WORDBITS = wordbits
local BINT_SIZE = BINT_BITS // BINT_WORDBITS
local BINT_WORDMAX = (1 << BINT_WORDBITS) - 1
local BINT_WORDMSB = (1 << (BINT_WORDBITS - 1))
local BINT_MATHMININTEGER, BINT_MATHMAXINTEGER
local BINT_MININTEGER
--- Create a new bint with 0 value.
function bint.zero()
local x = setmetatable({}, bint)
for i=1,BINT_SIZE do
x[i] = 0
end
return x
end
local bint_zero = bint.zero
--- Create a new bint with 1 value.
function bint.one()
local x = setmetatable({}, bint)
x[1] = 1
for i=2,BINT_SIZE do
x[i] = 0
end
return x
end
local bint_one = bint.one
-- Convert a value to a lua integer without losing precision.
local function tointeger(x)
x = tonumber(x)
local ty = math_type(x)
if ty == 'float' then
local floorx = math_floor(x)
if floorx == x then
x = floorx
ty = math_type(x)
end
end
if ty == 'integer' then
return x
end
end
--- Create a bint from an unsigned integer.
-- Treats signed integers as an unsigned integer.
-- @param x A value to initialize from convertible to a lua integer.
-- @return A new bint or nil in case the input cannot be represented by an integer.
-- @see bint.frominteger
function bint.fromuinteger(x)
x = tointeger(x)
if x then
if x == 1 then
return bint_one()
elseif x == 0 then
return bint_zero()
end
local n = setmetatable({}, bint)
for i=1,BINT_SIZE do
n[i] = x & BINT_WORDMAX
x = x >> BINT_WORDBITS
end
return n
end
end
local bint_fromuinteger = bint.fromuinteger
--- Create a bint from a signed integer.
-- @param x A value to initialize from convertible to a lua integer.
-- @return A new bint or nil in case the input cannot be represented by an integer.
-- @see bint.fromuinteger
function bint.frominteger(x)
x = tointeger(x)
if x then
if x == 1 then
return bint_one()
elseif x == 0 then
return bint_zero()
end
local neg = false
if x < 0 then
x = math_abs(x)
neg = true
end
local n = setmetatable({}, bint)
for i=1,BINT_SIZE do
n[i] = x & BINT_WORDMAX
x = x >> BINT_WORDBITS
end
if neg then
n:_unm()
end
return n
end
end
local bint_frominteger = bint.frominteger
local basesteps = {}
-- Compute the read step for frombase function
local function getbasestep(base)
local step = basesteps[base]
if step then
return step
end
step = 0
local dmax = 1
local limit = math_maxinteger // base
repeat
step = step + 1
dmax = dmax * base
until dmax >= limit
basesteps[base] = step
return step
end
-- Compute power with lua integers.
local function ipow(y, x, n)
if n == 1 then
return y * x
elseif n & 1 == 0 then --even
return ipow(y, x * x, n // 2)
end
return ipow(x * y, x * x, (n-1) // 2)
end
--- Create a bint from a string of the desired base.
-- @param s The string to be converted from,
-- must have only alphanumeric and '+-' characters.
-- @param[opt] base Base that the number is represented, defaults to 10.
-- Must be at least 2 and at most 36.
-- @return A new bint or nil in case the conversion failed.
function bint.frombase(s, base)
if type(s) ~= 'string' then
return
end
base = base or 10
if not (base >= 2 and base <= 36) then
-- number base is too large
return
end
local step = getbasestep(base)
if #s < step then
-- string is small, use tonumber (faster)
return bint_frominteger(tonumber(s, base))
end
local sign, int = s:lower():match('^([+-]?)(%w+)$')
if not (sign and int) then
-- invalid integer string representation
return
end
local n = bint_zero()
for i=1,#int,step do
local part = int:sub(i,i+step-1)
local d = tonumber(part, base)
if not d then
-- invalid integer string representation
return
end
if i > 1 then
n = n * ipow(1, base, #part)
end
if d ~= 0 then
n:_add(d)
end
end
if sign == '-' then
n:_unm()
end
return n
end
local bint_frombase = bint.frombase
--- Create a new bint from a value.
-- @param x A value convertible to a bint (string, number or another bint).
-- @return A new bint, guaranteed to be a new reference in case needed.
-- @raise An assert is thrown in case x is not convertible to a bint.
-- @see bint.tobint
-- @see bint.parse
function bint.new(x)
if getmetatable(x) ~= bint then
local ty = type(x)
if ty == 'number' then
return bint_frominteger(x)
elseif ty == 'string' then
return bint_frombase(x, 10)
end
error('value cannot be represented by a bint')
end
-- return a clone
local n = setmetatable({}, bint)
for i=1,BINT_SIZE do
n[i] = x[i]
end
return n
end
local bint_new = bint.new
--- Convert a value to a bint if possible.
-- @param x A value to be converted (string, number or another bint).
-- @param[opt] clone A boolean that tells if a new bint reference should be returned.
-- Defaults to false.
-- @return A bint or nil in case the conversion failed.
-- @see bint.new
-- @see bint.parse
function bint.tobint(x, clone)
if getmetatable(x) == bint then
if not clone then
return x
end
-- return a clone
local n = setmetatable({}, bint)
for i=1,BINT_SIZE do
n[i] = x[i]
end
return n
end
local ty = type(x)
if ty == 'number' then
return bint_frominteger(x)
elseif ty == 'string' then
return bint_frombase(x, 10)
end
end
local tobint = bint.tobint
--- Convert a value to a bint if possible otherwise to a lua number.
-- Useful to prepare values that you are unsure if it's going to be an integer or float.
-- @param x A value to be converted (string, number or another bint).
-- @param[opt] clone A boolean that tells if a new bint reference should be returned.
-- Defaults to false.
-- @return A bint or a lua number or nil in case the conversion failed.
-- @see bint.new
-- @see bint.tobint
function bint.parse(x, clone)
local i = tobint(x, clone)
if i then
return i
end
return tonumber(x)
end
local bint_parse = bint.parse
--- Convert a bint to an unsigned integer.
-- Note that large unsigned integers may be represented as negatives in lua integers.
-- Note that lua cannot represent values larger than 64 bits,
-- in that case integer values wrap around.
-- @param x A bint or a number to be converted into an unsigned integer.
-- @return An integer or nil in case the input cannot be represented by an integer.
-- @see bint.tointeger
function bint.touinteger(x)
if getmetatable(x) == bint then
local n = 0
for i=1,BINT_SIZE do
n = n | (x[i] << (BINT_WORDBITS * (i - 1)))
end
return n
end
return tointeger(x)
end
--- Convert a bint to a signed integer.
-- It works by taking absolute values then applying the sign bit in case needed.
-- Note that lua cannot represent values larger than 64 bits,
-- in that case integer values wrap around.
-- @param x A bint or value to be converted into an unsigned integer.
-- @return An integer or nil in case the input cannot be represented by an integer.
-- @see bint.touinteger
function bint.tointeger(x)
if getmetatable(x) == bint then
local n = 0
local neg = x:isneg()
if neg then
x = -x
end
for i=1,BINT_SIZE do
n = n | (x[i] << (BINT_WORDBITS * (i - 1)))
end
if neg then
n = -n
end
return n
end
return tointeger(x)
end
local bint_tointeger = bint.tointeger
local function bint_assert_tointeger(x)
x = bint_tointeger(x)
if not x then
error('value has no integer representation')
end
return x
end
--- Convert a bint to a lua float in case integer would wrap around or lua integer otherwise.
-- Different from @{bint.tointeger} the operation does not wrap around integers,
-- but digits precision are lost in the process of converting to a float.
-- @param x A bint or value to be converted into a lua number.
-- @return A lua number or nil in case the input cannot be represented by a number.
-- @see bint.tointeger
function bint.tonumber(x)
if getmetatable(x) == bint then
if x <= BINT_MATHMAXINTEGER and x >= BINT_MATHMININTEGER then
return x:tointeger()
end
return tonumber(tostring(x))
end
return tonumber(x)
end
local bint_tonumber = bint.tonumber
-- Compute base letters to use in bint.tobase
local BASE_LETTERS = {}
do
for i=1,36 do
BASE_LETTERS[i-1] = ('0123456789abcdefghijklmnopqrstuvwxyz'):sub(i,i)
end
end
--- Convert a bint to a string in the desired base.
-- @param x The bint to be converted from.
-- @param[opt] base Base to be represented, defaults to 10.
-- Must be at least 2 and at most 36.
-- @param[opt] unsigned Whether to output as an unsigned integer.
-- Defaults to false for base 10 and true for others.
-- When unsigned is false the symbol '-' is prepended in negative values.
-- @return A string representing the input.
-- @raise An assert is thrown in case the base is invalid.
function bint.tobase(x, base, unsigned)
x = tobint(x)
if not x then
-- x is a fractional float or something else
return
end
base = base or 10
if not (base >= 2 and base <= 36) then
-- number base is too large
return
end
if unsigned == nil then
unsigned = base ~= 10
end
local isxneg = x:isneg()
if (base == 10 and not unsigned) or (base == 16 and unsigned and not isxneg) then
if x <= BINT_MATHMAXINTEGER and x >= BINT_MATHMININTEGER then
-- integer is small, use tostring or string.format (faster)
local n = x:tointeger()
if base == 10 then
return tostring(n)
elseif unsigned then
return string_format('%x', n)
end
end
end
local ss = {}
local neg = not unsigned and isxneg
x = neg and x:abs() or bint_new(x)
local xiszero = x:iszero()
if xiszero then
return '0'
end
-- calculate basepow
local step = 0
local basepow = 1
local limit = (BINT_WORDMSB - 1) // base
repeat
step = step + 1
basepow = basepow * base
until basepow >= limit
-- serialize base digits
local size = BINT_SIZE
local xd, carry, d
repeat
-- single word division
carry = 0
xiszero = true
for i=size,1,-1 do
carry = carry | x[i]
d, xd = carry // basepow, carry % basepow
if xiszero and d ~= 0 then
size = i
xiszero = false
end
x[i] = d
carry = xd << BINT_WORDBITS
end
-- digit division
for _=1,step do
xd, d = xd // base, xd % base
if xiszero and xd == 0 and d == 0 then
-- stop on leading zeros
break
end
table_insert(ss, 1, BASE_LETTERS[d])
end
until xiszero
if neg then
table_insert(ss, 1, '-')
end
return table_concat(ss)
end
local function bint_assert_convert(x)
return assert(tobint(x), 'value has not integer representation')
end
--- Check if a number is 0 considering bints.
-- @param x A bint or a lua number.
function bint.iszero(x)
if getmetatable(x) == bint then
for i=1,BINT_SIZE do
if x[i] ~= 0 then
return false
end
end
return true
end
return x == 0
end
--- Check if a number is 1 considering bints.
-- @param x A bint or a lua number.
function bint.isone(x)
if getmetatable(x) == bint then
if x[1] ~= 1 then
return false
end
for i=2,BINT_SIZE do
if x[i] ~= 0 then
return false
end
end
return true
end
return x == 1
end
--- Check if a number is -1 considering bints.
-- @param x A bint or a lua number.
function bint.isminusone(x)
if getmetatable(x) == bint then
for i=1,BINT_SIZE do
if x[i] ~= BINT_WORDMAX then
return false
end
end
return true
end
return x == -1
end
local bint_isminusone = bint.isminusone
--- Check if the input is a bint.
-- @param x Any lua value.
function bint.isbint(x)
return getmetatable(x) == bint
end
--- Check if the input is a lua integer or a bint.
-- @param x Any lua value.
function bint.isintegral(x)
return getmetatable(x) == bint or math_type(x) == 'integer'
end
--- Check if the input is a bint or a lua number.
-- @param x Any lua value.
function bint.isnumeric(x)
return getmetatable(x) == bint or type(x) == 'number'
end
--- Get the number type of the input (bint, integer or float).
-- @param x Any lua value.
-- @return Returns "bint" for bints, "integer" for lua integers,
-- "float" from lua floats or nil otherwise.
function bint.type(x)
if getmetatable(x) == bint then
return 'bint'
end
return math_type(x)
end
--- Check if a number is negative considering bints.
-- Zero is guaranteed to never be negative for bints.
-- @param x A bint or a lua number.
function bint.isneg(x)
if getmetatable(x) == bint then
return x[BINT_SIZE] & BINT_WORDMSB ~= 0
end
return x < 0
end
local bint_isneg = bint.isneg
--- Check if a number is positive considering bints.
-- @param x A bint or a lua number.
function bint.ispos(x)
if getmetatable(x) == bint then
return not x:isneg() and not x:iszero()
end
return x > 0
end
--- Check if a number is even considering bints.
-- @param x A bint or a lua number.
function bint.iseven(x)
if getmetatable(x) == bint then
return x[1] & 1 == 0
end
return math_abs(x) % 2 == 0
end
--- Check if a number is odd considering bints.
-- @param x A bint or a lua number.
function bint.isodd(x)
if getmetatable(x) == bint then
return x[1] & 1 == 1
end
return math_abs(x) % 2 == 1
end
--- Create a new bint with the maximum possible integer value.
function bint.maxinteger()
local x = setmetatable({}, bint)
for i=1,BINT_SIZE-1 do
x[i] = BINT_WORDMAX
end
x[BINT_SIZE] = BINT_WORDMAX ~ BINT_WORDMSB
return x
end
--- Create a new bint with the minimum possible integer value.
function bint.mininteger()
local x = setmetatable({}, bint)
for i=1,BINT_SIZE-1 do
x[i] = 0
end
x[BINT_SIZE] = BINT_WORDMSB
return x
end
--- Bitwise left shift a bint in one bit (in-place).
function bint:_shlone()
local wordbitsm1 = BINT_WORDBITS - 1
for i=BINT_SIZE,2,-1 do
self[i] = ((self[i] << 1) | (self[i-1] >> wordbitsm1)) & BINT_WORDMAX
end
self[1] = (self[1] << 1) & BINT_WORDMAX
return self
end
--- Bitwise right shift a bint in one bit (in-place).
function bint:_shrone()
local wordbitsm1 = BINT_WORDBITS - 1
for i=1,BINT_SIZE-1 do
self[i] = ((self[i] >> 1) | (self[i+1] << wordbitsm1)) & BINT_WORDMAX
end
self[BINT_SIZE] = self[BINT_SIZE] >> 1
return self
end
-- Bitwise left shift words of a bint (in-place). Used only internally.
function bint:_shlwords(n)
for i=BINT_SIZE,n+1,-1 do
self[i] = self[i - n]
end
for i=1,n do
self[i] = 0
end
return self
end
-- Bitwise right shift words of a bint (in-place). Used only internally.
function bint:_shrwords(n)
if n < BINT_SIZE then
for i=1,BINT_SIZE-n do
self[i] = self[i + n]
end
for i=BINT_SIZE-n+1,BINT_SIZE do
self[i] = 0
end
else
for i=1,BINT_SIZE do
self[i] = 0
end
end
return self
end
--- Increment a bint by one (in-place).
function bint:_inc()
for i=1,BINT_SIZE do
local tmp = self[i]
local v = (tmp + 1) & BINT_WORDMAX
self[i] = v
if v > tmp then
break
end
end
return self
end
--- Increment a number by one considering bints.
-- @param x A bint or a lua number to increment.
function bint.inc(x)
local ix = tobint(x, true)
if ix then
return ix:_inc()
end
return x + 1
end
--- Decrement a bint by one (in-place).
function bint:_dec()
for i=1,BINT_SIZE do
local tmp = self[i]
local v = (tmp - 1) & BINT_WORDMAX
self[i] = v
if not (v > tmp) then
break
end
end
return self
end
--- Decrement a number by one considering bints.
-- @param x A bint or a lua number to decrement.
function bint.dec(x)
local ix = tobint(x, true)
if ix then
return ix:_dec()
end
return x - 1
end
--- Assign a bint to a new value (in-place).
-- @param y A value to be copied from.
-- @raise Asserts in case inputs are not convertible to integers.
function bint:_assign(y)
y = bint_assert_convert(y)
for i=1,BINT_SIZE do
self[i] = y[i]
end
return self
end
--- Take absolute of a bint (in-place).
function bint:_abs()
if self:isneg() then
self:_unm()
end
return self
end
--- Take absolute of a number considering bints.
-- @param x A bint or a lua number to take the absolute.
function bint.abs(x)
local ix = tobint(x, true)
if ix then
return ix:_abs()
end
return math_abs(x)
end
local bint_abs = bint.abs
--- Take the floor of a number considering bints.
-- @param x A bint or a lua number to perform the floor operation.
function bint.floor(x)
if getmetatable(x) == bint then
return bint_new(x)
end
return bint_new(math_floor(tonumber(x)))
end
--- Take ceil of a number considering bints.
-- @param x A bint or a lua number to perform the ceil operation.
function bint.ceil(x)
if getmetatable(x) == bint then
return bint_new(x)
end
return bint_new(math_ceil(tonumber(x)))
end
--- Wrap around bits of an integer (discarding left bits) considering bints.
-- @param x A bint or a lua integer.
-- @param y Number of right bits to preserve.
function bint.bwrap(x, y)
x = bint_assert_convert(x)
if y <= 0 then
return bint_zero()
elseif y < BINT_BITS then
return x & (bint_one() << y):_dec()
end
return bint_new(x)
end
--- Rotate left integer x by y bits considering bints.
-- @param x A bint or a lua integer.
-- @param y Number of bits to rotate.
function bint.brol(x, y)
x, y = bint_assert_convert(x), bint_assert_tointeger(y)
if y > 0 then
return (x << y) | (x >> (BINT_BITS - y))
elseif y < 0 then
if y ~= math_mininteger then
return x:bror(-y)
else
x:bror(-(y+1))
x:bror(1)
end
end
return x
end
--- Rotate right integer x by y bits considering bints.
-- @param x A bint or a lua integer.
-- @param y Number of bits to rotate.
function bint.bror(x, y)
x, y = bint_assert_convert(x), bint_assert_tointeger(y)
if y > 0 then
return (x >> y) | (x << (BINT_BITS - y))
elseif y < 0 then
if y ~= math_mininteger then
return x:brol(-y)
else
x:brol(-(y+1))
x:brol(1)
end
end
return x
end
--- Truncate a number to a bint.
-- Floats numbers are truncated, that is, the fractional port is discarded.
-- @param x A number to truncate.
-- @return A new bint or nil in case the input does not fit in a bint or is not a number.
function bint.trunc(x)
if getmetatable(x) ~= bint then
x = tonumber(x)
if x then
local ty = math_type(x)
if ty == 'float' then
-- truncate to integer
x = math_modf(x)
end
return bint_frominteger(x)
end
return
end
return bint_new(x)
end
--- Take maximum between two numbers considering bints.
-- @param x A bint or lua number to compare.
-- @param y A bint or lua number to compare.
-- @return A bint or a lua number. Guarantees to return a new bint for integer values.
function bint.max(x, y)
local ix, iy = tobint(x), tobint(y)
if ix and iy then
return bint_new(ix > iy and ix or iy)
end
return bint_parse(math_max(x, y))
end
--- Take minimum between two numbers considering bints.
-- @param x A bint or lua number to compare.
-- @param y A bint or lua number to compare.
-- @return A bint or a lua number. Guarantees to return a new bint for integer values.
function bint.min(x, y)
local ix, iy = tobint(x), tobint(y)
if ix and iy then
return bint_new(ix < iy and ix or iy)
end
return bint_parse(math_min(x, y))
end
--- Add an integer to a bint (in-place).
-- @param y An integer to be added.
-- @raise Asserts in case inputs are not convertible to integers.
function bint:_add(y)
y = bint_assert_convert(y)
local carry = 0
for i=1,BINT_SIZE do
local tmp = self[i] + y[i] + carry
carry = tmp >> BINT_WORDBITS
self[i] = tmp & BINT_WORDMAX
end
return self
end
--- Add two numbers considering bints.
-- @param x A bint or a lua number to be added.
-- @param y A bint or a lua number to be added.
function bint.__add(x, y)
local ix, iy = tobint(x), tobint(y)
if ix and iy then
local z = setmetatable({}, bint)
local carry = 0
for i=1,BINT_SIZE do
local tmp = ix[i] + iy[i] + carry
carry = tmp >> BINT_WORDBITS
z[i] = tmp & BINT_WORDMAX
end
return z
end
return bint_tonumber(x) + bint_tonumber(y)
end
--- Subtract an integer from a bint (in-place).
-- @param y An integer to subtract.
-- @raise Asserts in case inputs are not convertible to integers.
function bint:_sub(y)
y = bint_assert_convert(y)
local borrow = 0
local wordmaxp1 = BINT_WORDMAX + 1
for i=1,BINT_SIZE do
local res = self[i] + wordmaxp1 - y[i] - borrow
self[i] = res & BINT_WORDMAX
borrow = (res >> BINT_WORDBITS) ~ 1
end
return self
end
--- Subtract two numbers considering bints.
-- @param x A bint or a lua number to be subtracted from.
-- @param y A bint or a lua number to subtract.
function bint.__sub(x, y)
local ix, iy = tobint(x), tobint(y)
if ix and iy then
local z = setmetatable({}, bint)
local borrow = 0
local wordmaxp1 = BINT_WORDMAX + 1
for i=1,BINT_SIZE do
local res = ix[i] + wordmaxp1 - iy[i] - borrow
z[i] = res & BINT_WORDMAX
borrow = (res >> BINT_WORDBITS) ~ 1
end
return z
end
return bint_tonumber(x) - bint_tonumber(y)
end
--- Multiply two numbers considering bints.
-- @param x A bint or a lua number to multiply.
-- @param y A bint or a lua number to multiply.
function bint.__mul(x, y)
local ix, iy = tobint(x), tobint(y)