-
Notifications
You must be signed in to change notification settings - Fork 56
/
uint256.go
1363 lines (1204 loc) · 35 KB
/
uint256.go
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
// uint256: Fixed size 256-bit math library
// Copyright 2018-2020 uint256 Authors
// SPDX-License-Identifier: BSD-3-Clause
// Package math provides integer math utilities.
package uint256
import (
"encoding/binary"
"math"
"math/big"
"math/bits"
)
// Int is represented as an array of 4 uint64, in little-endian order,
// so that Int[3] is the most significant, and Int[0] is the least significant
type Int [4]uint64
// NewInt returns a new initialized Int.
func NewInt(val uint64) *Int {
z := &Int{}
z.SetUint64(val)
return z
}
// SetBytes interprets buf as the bytes of a big-endian unsigned
// integer, sets z to that value, and returns z.
// If buf is larger than 32 bytes, the last 32 bytes is used. This operation
// is semantically equivalent to `FromBig(new(big.Int).SetBytes(buf))`
func (z *Int) SetBytes(buf []byte) *Int {
switch l := len(buf); l {
case 0:
z.Clear()
case 1:
z.SetBytes1(buf)
case 2:
z.SetBytes2(buf)
case 3:
z.SetBytes3(buf)
case 4:
z.SetBytes4(buf)
case 5:
z.SetBytes5(buf)
case 6:
z.SetBytes6(buf)
case 7:
z.SetBytes7(buf)
case 8:
z.SetBytes8(buf)
case 9:
z.SetBytes9(buf)
case 10:
z.SetBytes10(buf)
case 11:
z.SetBytes11(buf)
case 12:
z.SetBytes12(buf)
case 13:
z.SetBytes13(buf)
case 14:
z.SetBytes14(buf)
case 15:
z.SetBytes15(buf)
case 16:
z.SetBytes16(buf)
case 17:
z.SetBytes17(buf)
case 18:
z.SetBytes18(buf)
case 19:
z.SetBytes19(buf)
case 20:
z.SetBytes20(buf)
case 21:
z.SetBytes21(buf)
case 22:
z.SetBytes22(buf)
case 23:
z.SetBytes23(buf)
case 24:
z.SetBytes24(buf)
case 25:
z.SetBytes25(buf)
case 26:
z.SetBytes26(buf)
case 27:
z.SetBytes27(buf)
case 28:
z.SetBytes28(buf)
case 29:
z.SetBytes29(buf)
case 30:
z.SetBytes30(buf)
case 31:
z.SetBytes31(buf)
default:
z.SetBytes32(buf[l-32:])
}
return z
}
// Bytes32 returns the value of z as a 32-byte big-endian array.
func (z *Int) Bytes32() [32]byte {
// The PutUint64()s are inlined and we get 4x (load, bswap, store) instructions.
var b [32]byte
binary.BigEndian.PutUint64(b[0:8], z[3])
binary.BigEndian.PutUint64(b[8:16], z[2])
binary.BigEndian.PutUint64(b[16:24], z[1])
binary.BigEndian.PutUint64(b[24:32], z[0])
return b
}
// Bytes20 returns the value of z as a 20-byte big-endian array.
func (z *Int) Bytes20() [20]byte {
var b [20]byte
// The PutUint*()s are inlined and we get 3x (load, bswap, store) instructions.
binary.BigEndian.PutUint32(b[0:4], uint32(z[2]))
binary.BigEndian.PutUint64(b[4:12], z[1])
binary.BigEndian.PutUint64(b[12:20], z[0])
return b
}
// Bytes returns the value of z as a big-endian byte slice.
func (z *Int) Bytes() []byte {
b := z.Bytes32()
return b[32-z.ByteLen():]
}
// WriteToSlice writes the content of z into the given byteslice.
// If dest is larger than 32 bytes, z will fill the first parts, and leave
// the end untouched.
// OBS! If dest is smaller than 32 bytes, only the end parts of z will be used
// for filling the array, making it useful for filling an Address object
func (z *Int) WriteToSlice(dest []byte) {
// ensure 32 bytes
// A too large buffer. Fill last 32 bytes
end := len(dest) - 1
if end > 31 {
end = 31
}
for i := 0; i <= end; i++ {
dest[end-i] = byte(z[i/8] >> uint64(8*(i%8)))
}
}
// WriteToArray32 writes all 32 bytes of z to the destination array, including zero-bytes
func (z *Int) WriteToArray32(dest *[32]byte) {
for i := 0; i < 32; i++ {
dest[31-i] = byte(z[i/8] >> uint64(8*(i%8)))
}
}
// WriteToArray20 writes the last 20 bytes of z to the destination array, including zero-bytes
func (z *Int) WriteToArray20(dest *[20]byte) {
for i := 0; i < 20; i++ {
dest[19-i] = byte(z[i/8] >> uint64(8*(i%8)))
}
}
// Uint64 returns the lower 64-bits of z
func (z *Int) Uint64() uint64 {
return z[0]
}
// Uint64WithOverflow returns the lower 64-bits of z and bool whether overflow occurred
func (z *Int) Uint64WithOverflow() (uint64, bool) {
return z[0], (z[1] | z[2] | z[3]) != 0
}
// Clone creates a new Int identical to z
func (z *Int) Clone() *Int {
return &Int{z[0], z[1], z[2], z[3]}
}
// Add sets z to the sum x+y
func (z *Int) Add(x, y *Int) *Int {
var carry uint64
z[0], carry = bits.Add64(x[0], y[0], 0)
z[1], carry = bits.Add64(x[1], y[1], carry)
z[2], carry = bits.Add64(x[2], y[2], carry)
z[3], _ = bits.Add64(x[3], y[3], carry)
return z
}
// AddOverflow sets z to the sum x+y, and returns z and whether overflow occurred
func (z *Int) AddOverflow(x, y *Int) (*Int, bool) {
var carry uint64
z[0], carry = bits.Add64(x[0], y[0], 0)
z[1], carry = bits.Add64(x[1], y[1], carry)
z[2], carry = bits.Add64(x[2], y[2], carry)
z[3], carry = bits.Add64(x[3], y[3], carry)
return z, carry != 0
}
// AddMod sets z to the sum ( x+y ) mod m, and returns z.
// If m == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Int) AddMod(x, y, m *Int) *Int {
// Fast path for m >= 2^192, with x and y at most slightly bigger than m.
// This is always the case when x and y are already reduced modulo such m.
if (m[3] != 0) && (x[3] <= m[3]) && (y[3] <= m[3]) {
var (
gteC1 uint64
gteC2 uint64
tmpX Int
tmpY Int
res Int
)
// reduce x/y modulo m if they are gte m
tmpX[0], gteC1 = bits.Sub64(x[0], m[0], gteC1)
tmpX[1], gteC1 = bits.Sub64(x[1], m[1], gteC1)
tmpX[2], gteC1 = bits.Sub64(x[2], m[2], gteC1)
tmpX[3], gteC1 = bits.Sub64(x[3], m[3], gteC1)
tmpY[0], gteC2 = bits.Sub64(y[0], m[0], gteC2)
tmpY[1], gteC2 = bits.Sub64(y[1], m[1], gteC2)
tmpY[2], gteC2 = bits.Sub64(y[2], m[2], gteC2)
tmpY[3], gteC2 = bits.Sub64(y[3], m[3], gteC2)
if gteC1 == 0 {
x = &tmpX
}
if gteC2 == 0 {
y = &tmpY
}
var (
c1 uint64
c2 uint64
tmp Int
)
res[0], c1 = bits.Add64(x[0], y[0], c1)
res[1], c1 = bits.Add64(x[1], y[1], c1)
res[2], c1 = bits.Add64(x[2], y[2], c1)
res[3], c1 = bits.Add64(x[3], y[3], c1)
tmp[0], c2 = bits.Sub64(res[0], m[0], c2)
tmp[1], c2 = bits.Sub64(res[1], m[1], c2)
tmp[2], c2 = bits.Sub64(res[2], m[2], c2)
tmp[3], c2 = bits.Sub64(res[3], m[3], c2)
// final sub was unnecessary
if c1 == 0 && c2 != 0 {
return z.Set(&res)
}
return z.Set(&tmp)
}
if m.IsZero() {
return z.Clear()
}
if z == m { // z is an alias for m and will be overwritten by AddOverflow before m is read
m = m.Clone()
}
if _, overflow := z.AddOverflow(x, y); overflow {
sum := [5]uint64{z[0], z[1], z[2], z[3], 1}
var quot [5]uint64
var rem Int
udivrem(quot[:], sum[:], m, &rem)
return z.Set(&rem)
}
return z.Mod(z, m)
}
// AddUint64 sets z to x + y, where y is a uint64, and returns z
func (z *Int) AddUint64(x *Int, y uint64) *Int {
var carry uint64
z[0], carry = bits.Add64(x[0], y, 0)
z[1], carry = bits.Add64(x[1], 0, carry)
z[2], carry = bits.Add64(x[2], 0, carry)
z[3], _ = bits.Add64(x[3], 0, carry)
return z
}
// PaddedBytes encodes a Int as a 0-padded byte slice. The length
// of the slice is at least n bytes.
// Example, z =1, n = 20 => [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]
func (z *Int) PaddedBytes(n int) []byte {
b := make([]byte, n)
for i := 0; i < 32 && i < n; i++ {
b[n-1-i] = byte(z[i/8] >> uint64(8*(i%8)))
}
return b
}
// SubUint64 set z to the difference x - y, where y is a uint64, and returns z
func (z *Int) SubUint64(x *Int, y uint64) *Int {
var carry uint64
z[0], carry = bits.Sub64(x[0], y, carry)
z[1], carry = bits.Sub64(x[1], 0, carry)
z[2], carry = bits.Sub64(x[2], 0, carry)
z[3], _ = bits.Sub64(x[3], 0, carry)
return z
}
// SubOverflow sets z to the difference x-y and returns z and true if the operation underflowed
func (z *Int) SubOverflow(x, y *Int) (*Int, bool) {
var carry uint64
z[0], carry = bits.Sub64(x[0], y[0], 0)
z[1], carry = bits.Sub64(x[1], y[1], carry)
z[2], carry = bits.Sub64(x[2], y[2], carry)
z[3], carry = bits.Sub64(x[3], y[3], carry)
return z, carry != 0
}
// Sub sets z to the difference x-y
func (z *Int) Sub(x, y *Int) *Int {
var carry uint64
z[0], carry = bits.Sub64(x[0], y[0], 0)
z[1], carry = bits.Sub64(x[1], y[1], carry)
z[2], carry = bits.Sub64(x[2], y[2], carry)
z[3], _ = bits.Sub64(x[3], y[3], carry)
return z
}
// umulStep computes (hi * 2^64 + lo) = z + (x * y) + carry.
func umulStep(z, x, y, carry uint64) (hi, lo uint64) {
hi, lo = bits.Mul64(x, y)
lo, carry = bits.Add64(lo, carry, 0)
hi, _ = bits.Add64(hi, 0, carry)
lo, carry = bits.Add64(lo, z, 0)
hi, _ = bits.Add64(hi, 0, carry)
return hi, lo
}
// umulHop computes (hi * 2^64 + lo) = z + (x * y)
func umulHop(z, x, y uint64) (hi, lo uint64) {
hi, lo = bits.Mul64(x, y)
lo, carry := bits.Add64(lo, z, 0)
hi, _ = bits.Add64(hi, 0, carry)
return hi, lo
}
// umul computes full 256 x 256 -> 512 multiplication.
func umul(x, y *Int, res *[8]uint64) {
var (
carry, carry4, carry5, carry6 uint64
res1, res2, res3, res4, res5 uint64
)
carry, res[0] = bits.Mul64(x[0], y[0])
carry, res1 = umulHop(carry, x[1], y[0])
carry, res2 = umulHop(carry, x[2], y[0])
carry4, res3 = umulHop(carry, x[3], y[0])
carry, res[1] = umulHop(res1, x[0], y[1])
carry, res2 = umulStep(res2, x[1], y[1], carry)
carry, res3 = umulStep(res3, x[2], y[1], carry)
carry5, res4 = umulStep(carry4, x[3], y[1], carry)
carry, res[2] = umulHop(res2, x[0], y[2])
carry, res3 = umulStep(res3, x[1], y[2], carry)
carry, res4 = umulStep(res4, x[2], y[2], carry)
carry6, res5 = umulStep(carry5, x[3], y[2], carry)
carry, res[3] = umulHop(res3, x[0], y[3])
carry, res[4] = umulStep(res4, x[1], y[3], carry)
carry, res[5] = umulStep(res5, x[2], y[3], carry)
res[7], res[6] = umulStep(carry6, x[3], y[3], carry)
}
// Mul sets z to the product x*y
func (z *Int) Mul(x, y *Int) *Int {
var (
carry0, carry1, carry2 uint64
res1, res2 uint64
x0, x1, x2, x3 = x[0], x[1], x[2], x[3]
y0, y1, y2, y3 = y[0], y[1], y[2], y[3]
)
carry0, z[0] = bits.Mul64(x0, y0)
carry0, res1 = umulHop(carry0, x1, y0)
carry0, res2 = umulHop(carry0, x2, y0)
carry1, z[1] = umulHop(res1, x0, y1)
carry1, res2 = umulStep(res2, x1, y1, carry1)
carry2, z[2] = umulHop(res2, x0, y2)
z[3] = x3*y0 + x2*y1 + x0*y3 + x1*y2 + carry0 + carry1 + carry2
return z
}
// MulOverflow sets z to the product x*y, and returns z and whether overflow occurred
func (z *Int) MulOverflow(x, y *Int) (*Int, bool) {
var p [8]uint64
umul(x, y, &p)
copy(z[:], p[:4])
return z, (p[4] | p[5] | p[6] | p[7]) != 0
}
func (z *Int) squared() {
var (
carry0, carry1, carry2 uint64
res0, res1, res2, res3 uint64
)
carry0, res0 = bits.Mul64(z[0], z[0])
carry0, res1 = umulHop(carry0, z[0], z[1])
carry0, res2 = umulHop(carry0, z[0], z[2])
carry1, res1 = umulHop(res1, z[0], z[1])
carry1, res2 = umulStep(res2, z[1], z[1], carry1)
carry2, res2 = umulHop(res2, z[0], z[2])
res3 = 2*(z[0]*z[3]+z[1]*z[2]) + carry0 + carry1 + carry2
z[0], z[1], z[2], z[3] = res0, res1, res2, res3
}
// isBitSet returns true if bit n-th is set, where n = 0 is LSB.
// The n must be <= 255.
func (z *Int) isBitSet(n uint) bool {
return (z[n/64] & (1 << (n % 64))) != 0
}
// addTo computes x += y.
// Requires len(x) >= len(y) > 0.
func addTo(x, y []uint64) uint64 {
var carry uint64
_ = x[len(y)-1] // bounds check hint to compiler; see golang.org/issue/14808
for i := 0; i < len(y); i++ {
x[i], carry = bits.Add64(x[i], y[i], carry)
}
return carry
}
// subMulTo computes x -= y * multiplier.
// Requires len(x) >= len(y) > 0.
func subMulTo(x, y []uint64, multiplier uint64) uint64 {
var borrow uint64
_ = x[len(y)-1] // bounds check hint to compiler; see golang.org/issue/14808
for i := 0; i < len(y); i++ {
s, carry1 := bits.Sub64(x[i], borrow, 0)
ph, pl := bits.Mul64(y[i], multiplier)
t, carry2 := bits.Sub64(s, pl, 0)
x[i] = t
borrow = ph + carry1 + carry2
}
return borrow
}
// udivremBy1 divides u by single normalized word d and produces both quotient and remainder.
// The quotient is stored in provided quot.
func udivremBy1(quot, u []uint64, d uint64) (rem uint64) {
reciprocal := reciprocal2by1(d)
rem = u[len(u)-1] // Set the top word as remainder.
for j := len(u) - 2; j >= 0; j-- {
quot[j], rem = udivrem2by1(rem, u[j], d, reciprocal)
}
return rem
}
// udivremKnuth implements the division of u by normalized multiple word d from the Knuth's division algorithm.
// The quotient is stored in provided quot - len(u)-len(d) words.
// Updates u to contain the remainder - len(d) words.
func udivremKnuth(quot, u, d []uint64) {
dh := d[len(d)-1]
dl := d[len(d)-2]
reciprocal := reciprocal2by1(dh)
for j := len(u) - len(d) - 1; j >= 0; j-- {
u2 := u[j+len(d)]
u1 := u[j+len(d)-1]
u0 := u[j+len(d)-2]
var qhat, rhat uint64
if u2 >= dh { // Division overflows.
qhat = ^uint64(0)
// TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case).
} else {
qhat, rhat = udivrem2by1(u2, u1, dh, reciprocal)
ph, pl := bits.Mul64(qhat, dl)
if ph > rhat || (ph == rhat && pl > u0) {
qhat--
// TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case).
}
}
// Multiply and subtract.
borrow := subMulTo(u[j:], d, qhat)
u[j+len(d)] = u2 - borrow
if u2 < borrow { // Too much subtracted, add back.
qhat--
u[j+len(d)] += addTo(u[j:], d)
}
quot[j] = qhat // Store quotient digit.
}
}
// udivrem divides u by d and produces both quotient and remainder.
// The quotient is stored in provided quot - len(u)-len(d)+1 words.
// It loosely follows the Knuth's division algorithm (sometimes referenced as "schoolbook" division) using 64-bit words.
// See Knuth, Volume 2, section 4.3.1, Algorithm D.
func udivrem(quot, u []uint64, d, rem *Int) {
var dLen int
for i := len(d) - 1; i >= 0; i-- {
if d[i] != 0 {
dLen = i + 1
break
}
}
shift := uint(bits.LeadingZeros64(d[dLen-1]))
var dnStorage Int
dn := dnStorage[:dLen]
for i := dLen - 1; i > 0; i-- {
dn[i] = (d[i] << shift) | (d[i-1] >> (64 - shift))
}
dn[0] = d[0] << shift
var uLen int
for i := len(u) - 1; i >= 0; i-- {
if u[i] != 0 {
uLen = i + 1
break
}
}
if uLen < dLen {
if rem != nil {
copy(rem[:], u)
}
return
}
var unStorage [9]uint64
un := unStorage[:uLen+1]
un[uLen] = u[uLen-1] >> (64 - shift)
for i := uLen - 1; i > 0; i-- {
un[i] = (u[i] << shift) | (u[i-1] >> (64 - shift))
}
un[0] = u[0] << shift
// TODO: Skip the highest word of numerator if not significant.
if dLen == 1 {
r := udivremBy1(quot, un, dn[0])
if rem != nil {
rem.SetUint64(r >> shift)
}
return
}
udivremKnuth(quot, un, dn)
if rem != nil {
for i := 0; i < dLen-1; i++ {
rem[i] = (un[i] >> shift) | (un[i+1] << (64 - shift))
}
rem[dLen-1] = un[dLen-1] >> shift
}
}
// Div sets z to the quotient x/y for returns z.
// If y == 0, z is set to 0
func (z *Int) Div(x, y *Int) *Int {
if y.IsZero() || y.Gt(x) {
return z.Clear()
}
if x.Eq(y) {
return z.SetOne()
}
// Shortcut some cases
if x.IsUint64() {
return z.SetUint64(x.Uint64() / y.Uint64())
}
// At this point, we know
// x/y ; x > y > 0
var quot Int
udivrem(quot[:], x[:], y, nil)
return z.Set(")
}
// Mod sets z to the modulus x%y for y != 0 and returns z.
// If y == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Int) Mod(x, y *Int) *Int {
if y.IsZero() || x.Eq(y) {
return z.Clear()
}
if x.Lt(y) {
return z.Set(x)
}
// At this point:
// x != 0
// y != 0
// x > y
// Shortcut trivial case
if x.IsUint64() {
return z.SetUint64(x.Uint64() % y.Uint64())
}
var quot, rem Int
udivrem(quot[:], x[:], y, &rem)
return z.Set(&rem)
}
// DivMod sets z to the quotient x div y and m to the modulus x mod y and returns the pair (z, m) for y != 0.
// If y == 0, both z and m are set to 0 (OBS: differs from the big.Int)
func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
if z == m {
// We return both z and m as results, if they are aliased, we have to
// un-alias them to be able to return separate results.
m = new(Int).Set(m)
}
if y.IsZero() {
return z.Clear(), m.Clear()
}
if x.Eq(y) {
return z.SetOne(), m.Clear()
}
if x.Lt(y) {
m.Set(x)
return z.Clear(), m
}
// At this point:
// x != 0
// y != 0
// x > y
// Shortcut trivial case
if x.IsUint64() {
x0, y0 := x.Uint64(), y.Uint64()
return z.SetUint64(x0 / y0), m.SetUint64(x0 % y0)
}
var quot, rem Int
udivrem(quot[:], x[:], y, &rem)
return z.Set("), m.Set(&rem)
}
// SMod interprets x and y as two's complement signed integers,
// sets z to (sign x) * { abs(x) modulus abs(y) }
// If y == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Int) SMod(x, y *Int) *Int {
ys := y.Sign()
xs := x.Sign()
// abs x
if xs == -1 {
x = new(Int).Neg(x)
}
// abs y
if ys == -1 {
y = new(Int).Neg(y)
}
z.Mod(x, y)
if xs == -1 {
z.Neg(z)
}
return z
}
// MulModWithReciprocal calculates the modulo-m multiplication of x and y
// and returns z, using the reciprocal of m provided as the mu parameter.
// Use uint256.Reciprocal to calculate mu from m.
// If m == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Int) MulModWithReciprocal(x, y, m *Int, mu *[5]uint64) *Int {
if x.IsZero() || y.IsZero() || m.IsZero() {
return z.Clear()
}
var p [8]uint64
umul(x, y, &p)
if m[3] != 0 {
return z.reduce4(&p, m, mu)
}
var (
pl Int
ph Int
)
pl[0], pl[1], pl[2], pl[3] = p[0], p[1], p[2], p[3]
ph[0], ph[1], ph[2], ph[3] = p[4], p[5], p[6], p[7]
// If the multiplication is within 256 bits use Mod().
if ph.IsZero() {
return z.Mod(&pl, m)
}
var quot [8]uint64
var rem Int
udivrem(quot[:], p[:], m, &rem)
return z.Set(&rem)
}
// MulMod calculates the modulo-m multiplication of x and y and
// returns z.
// If m == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Int) MulMod(x, y, m *Int) *Int {
if x.IsZero() || y.IsZero() || m.IsZero() {
return z.Clear()
}
var p [8]uint64
umul(x, y, &p)
if m[3] != 0 {
mu := Reciprocal(m)
return z.reduce4(&p, m, &mu)
}
var (
pl Int
ph Int
)
pl[0], pl[1], pl[2], pl[3] = p[0], p[1], p[2], p[3]
ph[0], ph[1], ph[2], ph[3] = p[4], p[5], p[6], p[7]
// If the multiplication is within 256 bits use Mod().
if ph.IsZero() {
return z.Mod(&pl, m)
}
var quot [8]uint64
var rem Int
udivrem(quot[:], p[:], m, &rem)
return z.Set(&rem)
}
// MulDivOverflow calculates (x*y)/d with full precision, returns z and whether overflow occurred in multiply process (result does not fit to 256-bit).
// computes 512-bit multiplication and 512 by 256 division.
func (z *Int) MulDivOverflow(x, y, d *Int) (*Int, bool) {
if x.IsZero() || y.IsZero() || d.IsZero() {
return z.Clear(), false
}
var p [8]uint64
umul(x, y, &p)
var quot [8]uint64
udivrem(quot[:], p[:], d, nil)
z[0], z[1], z[2], z[3] = quot[0], quot[1], quot[2], quot[3]
return z, (quot[4] | quot[5] | quot[6] | quot[7]) != 0
}
// Abs interprets x as a two's complement signed number,
// and sets z to the absolute value
//
// Abs(0) = 0
// Abs(1) = 1
// Abs(2**255) = -2**255
// Abs(2**256-1) = -1
func (z *Int) Abs(x *Int) *Int {
if x[3] < 0x8000000000000000 {
return z.Set(x)
}
return z.Sub(new(Int), x)
}
// Neg returns -x mod 2**256.
func (z *Int) Neg(x *Int) *Int {
return z.Sub(new(Int), x)
}
// SDiv interprets n and d as two's complement signed integers,
// does a signed division on the two operands and sets z to the result.
// If d == 0, z is set to 0
func (z *Int) SDiv(n, d *Int) *Int {
if n.Sign() > 0 {
if d.Sign() > 0 {
// pos / pos
z.Div(n, d)
return z
} else {
// pos / neg
z.Div(n, new(Int).Neg(d))
return z.Neg(z)
}
}
if d.Sign() < 0 {
// neg / neg
z.Div(new(Int).Neg(n), new(Int).Neg(d))
return z
}
// neg / pos
z.Div(new(Int).Neg(n), d)
return z.Neg(z)
}
// Sign returns:
//
// -1 if z < 0
// 0 if z == 0
// +1 if z > 0
//
// Where z is interpreted as a two's complement signed number
func (z *Int) Sign() int {
if z.IsZero() {
return 0
}
if z[3] < 0x8000000000000000 {
return 1
}
return -1
}
// BitLen returns the number of bits required to represent z
func (z *Int) BitLen() int {
switch {
case z[3] != 0:
return 192 + bits.Len64(z[3])
case z[2] != 0:
return 128 + bits.Len64(z[2])
case z[1] != 0:
return 64 + bits.Len64(z[1])
default:
return bits.Len64(z[0])
}
}
// ByteLen returns the number of bytes required to represent z
func (z *Int) ByteLen() int {
return (z.BitLen() + 7) / 8
}
func (z *Int) lsh64(x *Int) *Int {
z[3], z[2], z[1], z[0] = x[2], x[1], x[0], 0
return z
}
func (z *Int) lsh128(x *Int) *Int {
z[3], z[2], z[1], z[0] = x[1], x[0], 0, 0
return z
}
func (z *Int) lsh192(x *Int) *Int {
z[3], z[2], z[1], z[0] = x[0], 0, 0, 0
return z
}
func (z *Int) rsh64(x *Int) *Int {
z[3], z[2], z[1], z[0] = 0, x[3], x[2], x[1]
return z
}
func (z *Int) rsh128(x *Int) *Int {
z[3], z[2], z[1], z[0] = 0, 0, x[3], x[2]
return z
}
func (z *Int) rsh192(x *Int) *Int {
z[3], z[2], z[1], z[0] = 0, 0, 0, x[3]
return z
}
func (z *Int) srsh64(x *Int) *Int {
z[3], z[2], z[1], z[0] = math.MaxUint64, x[3], x[2], x[1]
return z
}
func (z *Int) srsh128(x *Int) *Int {
z[3], z[2], z[1], z[0] = math.MaxUint64, math.MaxUint64, x[3], x[2]
return z
}
func (z *Int) srsh192(x *Int) *Int {
z[3], z[2], z[1], z[0] = math.MaxUint64, math.MaxUint64, math.MaxUint64, x[3]
return z
}
// Not sets z = ^x and returns z.
func (z *Int) Not(x *Int) *Int {
z[3], z[2], z[1], z[0] = ^x[3], ^x[2], ^x[1], ^x[0]
return z
}
// Gt returns true if z > x
func (z *Int) Gt(x *Int) bool {
return x.Lt(z)
}
// Slt interprets z and x as signed integers, and returns
// true if z < x
func (z *Int) Slt(x *Int) bool {
zSign := z.Sign()
xSign := x.Sign()
switch {
case zSign >= 0 && xSign < 0:
return false
case zSign < 0 && xSign >= 0:
return true
default:
return z.Lt(x)
}
}
// Sgt interprets z and x as signed integers, and returns
// true if z > x
func (z *Int) Sgt(x *Int) bool {
zSign := z.Sign()
xSign := x.Sign()
switch {
case zSign >= 0 && xSign < 0:
return true
case zSign < 0 && xSign >= 0:
return false
default:
return z.Gt(x)
}
}
// Lt returns true if z < x
func (z *Int) Lt(x *Int) bool {
// z < x <=> z - x < 0 i.e. when subtraction overflows.
_, carry := bits.Sub64(z[0], x[0], 0)
_, carry = bits.Sub64(z[1], x[1], carry)
_, carry = bits.Sub64(z[2], x[2], carry)
_, carry = bits.Sub64(z[3], x[3], carry)
return carry != 0
}
// SetUint64 sets z to the value x
func (z *Int) SetUint64(x uint64) *Int {
z[3], z[2], z[1], z[0] = 0, 0, 0, x
return z
}
// Eq returns true if z == x
func (z *Int) Eq(x *Int) bool {
return (z[0] == x[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3])
}
// Cmp compares z and x and returns:
//
// -1 if z < x
// 0 if z == x
// +1 if z > x
func (z *Int) Cmp(x *Int) (r int) {
// z < x <=> z - x < 0 i.e. when subtraction overflows.
d0, carry := bits.Sub64(z[0], x[0], 0)
d1, carry := bits.Sub64(z[1], x[1], carry)
d2, carry := bits.Sub64(z[2], x[2], carry)
d3, carry := bits.Sub64(z[3], x[3], carry)
if carry == 1 {
return -1
}
if d0|d1|d2|d3 == 0 {
return 0
}
return 1
}
// CmpUint64 compares z and x and returns:
//
// -1 if z < x
// 0 if z == x
// +1 if z > x
func (z *Int) CmpUint64(x uint64) int {
if z[0] > x || (z[1]|z[2]|z[3]) != 0 {
return 1
}
if z[0] == x {
return 0
}
return -1
}
// CmpBig compares z and x and returns:
//
// -1 if z < x
// 0 if z == x
// +1 if z > x
func (z *Int) CmpBig(x *big.Int) (r int) {
// If x is negative, it's surely smaller (z > x)
if x.Sign() == -1 {
return 1
}
y := new(Int)
if y.SetFromBig(x) { // overflow
// z < x
return -1
}
return z.Cmp(y)
}
// LtUint64 returns true if z is smaller than n
func (z *Int) LtUint64(n uint64) bool {
return z[0] < n && (z[1]|z[2]|z[3]) == 0
}
// GtUint64 returns true if z is larger than n
func (z *Int) GtUint64(n uint64) bool {
return z[0] > n || (z[1]|z[2]|z[3]) != 0
}
// IsUint64 reports whether z can be represented as a uint64.
func (z *Int) IsUint64() bool {
return (z[1] | z[2] | z[3]) == 0
}