-
Notifications
You must be signed in to change notification settings - Fork 6
/
ZInt.cs
4748 lines (4468 loc) · 105 KB
/
ZInt.cs
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
/*
* Copyright (c) 2017 Thomas Pornin <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Security.Cryptography;
using System.Text;
namespace BigInt {
/*
* A custom "big integer" implementation. It internally uses an array
* of 32-bit integers, that encode the integer in little-endian convention,
* using two's complement for negative integers.
*
* Apart from the array, a single 32-bit field is also present, which
* encodes the sign. When the value is small (it fits on 32 bits), then
* the array pointer is null, and the value is in the 32-bit field.
* Since ZInt is a struct, this means that computations using ZInt do
* not entail any dynamic (GC-based) memory allocation as long as the
* value fits on 32 bits. This makes it substantially faster than usual
* "big integer" implementations (including .NET's implementation, since
* version 4.0) when values are small.
*
* Instances are immutable, and thus can be used as if they were
* "plain integers".
*
* None of this code is "constant-time". As such, ZInt should be
* considered unsuitable to implementations of cryptographic algorithms.
*/
public struct ZInt : IComparable, IComparable<ZInt>, IEquatable<ZInt> {
/*
* CONVENTIONS:
*
* If varray == null, then "small" contains the integer value.
*
* If varray != null, then it contains the value, in little-endian
* convention (least significant word comes first) and of
* minimal encoded length (i.e. "trimmed"). Two's complement is
* used for negative values. "small" is then -1 or 0, depending
* on whether the value is negative or not.
*
* Note that the trimmed value does not always include the sign
* bit.
*
* If the integer value is in the range of values which can be
* represented in an "int", then magn is null. There is no allowed
* overlap between the two kinds of encodings.
*
* Default value thus encodes the integer zero.
*/
readonly int small;
readonly uint[] varray;
/*
* The value -1.
*/
public static ZInt MinusOne {
get { return new ZInt(-1, null); }
}
/*
* The value 0.
*/
public static ZInt Zero {
get { return new ZInt(0, null); }
}
/*
* The value 1.
*/
public static ZInt One {
get { return new ZInt(1, null); }
}
/*
* The value 2.
*/
public static ZInt Two {
get { return new ZInt(2, null); }
}
/*
* Internal constructor which assumes that the provided values are
* correct and normalized.
*/
private ZInt(int small, uint[] varray)
{
this.small = small;
this.varray = varray;
#if DEBUG
if (varray != null) {
if (small != -1 && small != 0) {
throw new Exception(
"Bad sign encoding: " + small);
}
if (varray.Length == 0) {
throw new Exception("Empty varray");
}
if (Length(small, varray) != varray.Length) {
throw new Exception("Untrimmed varray");
}
if (varray.Length == 1) {
/*
* If there was room for a sign bit, then
* the "small" encoding should have been used.
*/
if (((varray[0] ^ (uint)small) >> 31) == 0) {
throw new Exception(
"suboptimal encoding");
}
}
}
#endif
}
/*
* Main internal build method. This method normalizes the encoding
* ("small" encoding is used when possible; otherwise, the varray
* is trimmed and the sign is normalized to -1 or 0).
*
* If "varray" is null, then the small value is used. Otherwise,
* only the sign bit (most significant bit) of "small" is used,
* and that value is normalized; the array is trimmed. If the
* small encoding then becomes applicable, then it is used.
*/
private static ZInt Make(int small, uint[] varray)
{
if (varray == null) {
return new ZInt(small, null);
}
small >>= 31;
int n = Length(small, varray);
if (n == 1 && (((varray[0] ^ (uint)small) >> 31) == 0)) {
small = (int)varray[0];
varray = null;
} else {
/*
* Note: if n == 0 then the value is -1 or 0, and
* "small" already contains the correct value;
* Trim() will then return null, which is appropriate.
*/
varray = Trim(small, varray, n);
}
return new ZInt(small, varray);
}
/*
* Create an instance from a signed 32-bit integer.
*/
public ZInt(int val)
{
small = val;
varray = null;
}
/*
* Create an instance from an unsigned 32-bit integer.
*/
public ZInt(uint val)
{
small = (int)val;
if (small < 0) {
small = 0;
varray = new uint[1] { val };
} else {
varray = null;
}
}
/*
* Create an instance from a signed 64-bit integer.
*/
public ZInt(long val)
{
small = (int)val;
if ((long)small == val) {
varray = null;
} else {
ulong uval = (ulong)val;
uint w0 = (uint)uval;
uint w1 = (uint)(uval >> 32);
if (w1 == 0) {
small = 0;
varray = new uint[1] { w0 };
} else if (w1 == 0xFFFFFFFF) {
small = -1;
varray = new uint[1] { w0 };
} else {
small = (int)w1 >> 31;
varray = new uint[2] { w0, w1 };
}
}
}
/*
* Create an instance from an unsigned 64-bit integer.
*/
public ZInt(ulong val)
{
if (val <= 0x7FFFFFFF) {
small = (int)val;
varray = null;
} else {
small = 0;
uint w0 = (uint)val;
uint w1 = (uint)(val >> 32);
if (w1 == 0) {
varray = new uint[1] { w0 };
} else {
varray = new uint[2] { w0, w1 };
}
}
}
/*
* Create a ZInt instance for an integer expressed as an array
* of 32-bit integers (unsigned little-endian convention), with
* a specific number of value bits.
*/
public static ZInt Make(uint[] words, int numBits)
{
if (numBits == 0) {
return Zero;
}
int n = (numBits + 31) >> 5;
int kb = numBits & 31;
uint[] m = new uint[n];
Array.Copy(words, 0, m, 0, n);
if (kb > 0) {
m[n - 1] &= ~((uint)0xFFFFFFFF << kb);
}
return Make(0, m);
}
/*
* Create a ZInt instance for an integer expressed as an array
* of 64-bit integers (unsigned little-endian convention), with
* a specific number of value bits.
*/
public static ZInt Make(ulong[] words, int numBits)
{
if (numBits == 0) {
return Zero;
}
int kw = (numBits + 63) >> 6;
int kb = numBits & 63;
int n = kw * 2;
uint[] m = new uint[n];
if (kb != 0) {
ulong z = words[kw - 1]
& ~((ulong)0xFFFFFFFFFFFFFFFF << kb);
m[n - 1] = (uint)(z >> 32);
m[n - 2] = (uint)z;
kw --;
n -= 2;
}
for (int i = kw - 1, j = n - 2; i >= 0; i --, j -= 2) {
ulong z = words[i];
m[j + 0] = (uint)z;
m[j + 1] = (uint)(z >> 32);
}
return Make(0, m);
}
/*
* Test whether this value is 0.
*/
public bool IsZero {
get {
return small == 0 && varray == null;
}
}
/*
* Test whether this value is 1.
*/
public bool IsOne {
get {
return small == 1;
}
}
/*
* Test whether this value is even.
*/
public bool IsEven {
get {
uint w = (varray == null) ? (uint)small : varray[0];
return (w & 1) == 0;
}
}
/*
* Test whether this value is a power of 2. Note that 1 is a power
* of 2 (but 0 is not). For negative values, false is returned.
*/
public bool IsPowerOfTwo {
get {
if (small < 0) {
return false;
}
if (varray == null) {
return small != 0 && (small & -small) == small;
}
int n = varray.Length;
int z = (int)varray[n - 1];
if ((z & -z) != z) {
return false;
}
for (int i = n - 2; i >= 0; i --) {
if (varray[i] != 0) {
return false;
}
}
return true;
}
}
/*
* Get the sign of this value as an integer (-1 for negative
* values, 1 for positive, 0 for zero).
*/
public int Sign {
get {
if (varray == null) {
if (small < 0) {
return -1;
} else if (small == 0) {
return 0;
} else {
return 1;
}
} else {
return small | 1;
}
}
}
/*
* Test whether this value would fit in an 'int'.
*/
public bool IsInt {
get {
return varray == null;
}
}
/*
* Test whether this value would fit in a "long".
*/
public bool IsLong {
get {
if (varray == null) {
return true;
}
int n = varray.Length;
if (n == 1) {
return true;
} else if (n == 2) {
return ((int)varray[1] >> 31) == small;
} else {
return false;
}
}
}
/*
* Get the length of the value in bits. This is the minimal number
* of bits of the two's complement representation of the value,
* excluding the sign bit; thus, both 0 and -1 have bit length 0.
*/
public int BitLength {
get {
if (varray == null) {
if (small < 0) {
return 32 - LeadingZeros(~(uint)small);
} else {
return 32 - LeadingZeros((uint)small);
}
} else {
int n = varray.Length;
int bl = n << 5;
uint w = varray[n - 1];
if (small < 0) {
return bl - LeadingZeros(~w);
} else {
return bl - LeadingZeros(w);
}
}
}
}
/*
* Test whether the specified bit has value 1 or 0 ("true" is
* returned if the bit has value 1). Note that for negative values,
* two's complement representation is assumed.
*/
public bool TestBit(int n)
{
if (n < 0) {
throw new ArgumentOutOfRangeException();
}
if (varray == null) {
if (n >= 32) {
return small < 0;
} else {
return (((uint)small >> n) & (uint)1) != 0;
}
} else {
int nw = n >> 5;
if (nw >= varray.Length) {
return small != 0;
}
int nb = n & 31;
return ((varray[nw] >> nb) & (uint)1) != 0;
}
}
/*
* Copy some bits from this instance to the provided array. Bits
* are copied in little-endian order. First bit to be copied is
* bit at index "off", and exactly "num" bits are copied. This
* method modifies only the minimum number of destination words
* (i.e. the first "(num+31)/32" words, exactly). Remaining bits
* in the last touched word are set to 0.
*/
public void CopyBits(int off, int num, uint[] dest)
{
CopyBits(off, num, dest, 0);
}
public void CopyBits(int off, int num, uint[] dest, int destOff)
{
if (off < 0 || num < 0) {
throw new ArgumentOutOfRangeException();
}
if (num == 0) {
return;
}
ZInt x = this;
if (off > 0) {
x >>= off;
}
int kw = num >> 5;
int kb = num & 31;
uint hmask = ~((uint)0xFFFFFFFF << kb);
if (x.varray == null) {
if (kw == 0) {
dest[destOff] = (uint)x.small & hmask;
} else {
uint iw = (uint)(x.small >> 31);
dest[destOff] = (uint)x.small;
for (int i = 1; i < kw; i ++) {
dest[destOff + i] = iw;
}
if (kb > 0) {
dest[destOff + kw] = iw & hmask;
}
}
} else {
int n = x.varray.Length;
if (kw <= n) {
Array.Copy(x.varray, 0, dest, destOff, kw);
} else {
Array.Copy(x.varray, 0, dest, destOff, n);
for (int i = n; i < kw; i ++) {
dest[destOff + i] = (uint)x.small;
}
}
if (kb > 0) {
uint last;
if (kw < n) {
last = x.varray[kw] & hmask;
} else {
last = (uint)x.small & hmask;
}
dest[destOff + kw] = last;
}
}
}
/*
* Copy some bits from this instance to the provided array. Bits
* are copied in little-endian order. First bit to be copied is
* bit at index "off", and exactly "num" bits are copied. This
* method modifies only the minimum number of destination words
* (i.e. the first "(num+63)/64" words, exactly). Remaining bits
* in the last touched word are set to 0.
*/
public void CopyBits(int off, int num, ulong[] dest)
{
CopyBits(off, num, dest, 0);
}
public void CopyBits(int off, int num, ulong[] dest, int destOff)
{
if (off < 0 || num < 0) {
throw new ArgumentOutOfRangeException();
}
if (num == 0) {
return;
}
ZInt x = this;
if (off > 0) {
x >>= off;
}
int kw = num >> 6;
int kb = num & 63;
ulong hmask = ~((ulong)0xFFFFFFFFFFFFFFFF << kb);
long xs = (long)x.small;
if (x.varray == null) {
if (kw == 0) {
dest[destOff] = (ulong)xs & hmask;
} else {
ulong iw = (ulong)(xs >> 31);
dest[destOff] = (ulong)xs;
for (int i = 1; i < kw; i ++) {
dest[destOff + i] = iw;
}
if (kb > 0) {
dest[destOff + kw] = iw & hmask;
}
}
} else {
int n = x.varray.Length;
uint iw = (uint)x.small;
int j = 0;
for (int i = 0; i < kw; i ++, j += 2) {
uint w0 = (j < n) ? x.varray[j] : iw;
uint w1 = ((j + 1) < n) ? x.varray[j + 1] : iw;
dest[destOff + i] =
(ulong)w0 | ((ulong)w1 << 32);
}
if (kb > 0) {
uint w0 = (j < n) ? x.varray[j] : iw;
uint w1 = ((j + 1) < n) ? x.varray[j + 1] : iw;
ulong last = (ulong)w0 | ((ulong)w1 << 32);
dest[destOff + kw] = last & hmask;
}
}
}
/*
* Extract a 32-bit word at a given offset (counted in bits).
* This function is equivalent to right-shifting the value by
* "off" bits, then returning the low 32 bits (however, this
* function may be more efficient).
*/
public uint GetWord(int off)
{
if (off < 0) {
throw new ArgumentOutOfRangeException();
}
if (varray == null) {
int x = small;
if (off >= 32) {
off = 31;
}
return (uint)(x >> off);
}
int n = varray.Length;
int kw = off >> 5;
if (kw >= n) {
return (uint)small;
}
int kb = off & 31;
if (kb == 0) {
return varray[kw];
} else {
uint hi;
if (kw == n - 1) {
hi = (uint)small;
} else {
hi = varray[kw + 1];
}
uint lo = varray[kw];
return (lo >> kb) | (hi << (32 - kb));
}
}
/*
* Extract a 64-bit word at a given offset (counted in bits).
* This function is equivalent to right-shifting the value by
* "off" bits, then returning the low 64 bits (however, this
* function may be more efficient).
*/
public ulong GetWord64(int off)
{
if (off < 0) {
throw new ArgumentOutOfRangeException();
}
if (varray == null) {
int x = small;
if (off >= 32) {
off = 31;
}
return (ulong)(x >> off);
}
int n = varray.Length;
int kw = off >> 5;
if (kw >= n) {
return (ulong)small;
}
int kb = off & 31;
if (kb == 0) {
if (kw == (n - 1)) {
return (ulong)varray[kw]
| ((ulong)small << 32);
} else {
return (ulong)varray[kw]
| ((ulong)varray[kw + 1] << 32);
}
} else {
uint v0, v1, v2;
if (kw == (n - 1)) {
v0 = varray[kw];
v1 = (uint)small;
v2 = (uint)small;
} else if (kw == (n - 2)) {
v0 = varray[kw];
v1 = varray[kw + 1];
v2 = (uint)small;
} else {
v0 = varray[kw];
v1 = varray[kw + 1];
v2 = varray[kw + 2];
}
uint lo = (v0 >> kb) | (v1 << (32 - kb));
uint hi = (v1 >> kb) | (v2 << (32 - kb));
return (ulong)lo | ((ulong)hi << 32);
}
}
/*
* Convert this value to an 'int', using silent truncation if
* the value does not fit.
*/
public int ToInt {
get {
return (varray == null) ? small : (int)varray[0];
}
}
/*
* Convert this value to an 'uint', using silent truncation if
* the value does not fit.
*/
public uint ToUInt {
get {
return (varray == null) ? (uint)small : varray[0];
}
}
/*
* Convert this value to a 'long', using silent truncation if
* the value does not fit.
*/
public long ToLong {
get {
return (long)ToULong;
}
}
/*
* Convert this value to an 'ulong', using silent truncation if
* the value does not fit.
*/
public ulong ToULong {
get {
if (varray == null) {
return (ulong)small;
} else if (varray.Length == 1) {
uint iw = (uint)small;
return (ulong)varray[0] | ((ulong)iw << 32);
} else {
return (ulong)varray[0]
| ((ulong)varray[1] << 32);
}
}
}
/*
* Get the actual length of a varray encoding: this is the minimal
* length, in words, needed to encode the value. The value sign
* is provided as a negative or non-negative integer, and the
* encoding of minimal length does not necessarily include a
* sign bit. The value 0 is returned when the array encodes 0
* or -1 (depending on sign).
*/
static int Length(int sign, uint[] m)
{
if (m == null) {
return 0;
}
uint sw = (uint)(sign >> 31);
int n = m.Length;
while (n > 0 && m[n - 1] == sw) {
n --;
}
return n;
}
/*
* Trim an encoding to its minimal encoded length. If the provided
* array is already of minimal length, it is returned unchanged.
*/
static uint[] Trim(int sign, uint[] m)
{
int n = Length(sign, m);
if (n == 0) {
return null;
} else if (n < m.Length) {
uint[] mt = new uint[n];
Array.Copy(m, 0, mt, 0, n);
return mt;
} else {
return m;
}
}
/*
* Trim or extend a value to the provided length. The returned
* array will have the length specified as "n" (if n == 0, then
* null is returned). If the source array already has the right
* size, then it is returned unchanged.
*/
static uint[] Trim(int sign, uint[] m, int n)
{
if (n == 0) {
return null;
} else if (m == null) {
m = new uint[n];
if (sign < 0) {
Fill(0xFFFFFFFF, m);
}
return m;
}
int ct = m.Length;
if (ct < n) {
uint[] r = new uint[n];
Array.Copy(m, 0, r, 0, ct);
return r;
} else if (ct == n) {
return m;
} else {
uint[] r = new uint[n];
Array.Copy(m, 0, r, 0, n);
if (sign < 0) {
Fill(0xFFFFFFFF, r, ct, n - ct);
}
return r;
}
}
static void Fill(uint val, uint[] buf)
{
Fill(val, buf, 0, buf.Length);
}
static void Fill(uint val, uint[] buf, int off, int len)
{
while (len -- > 0) {
buf[off ++] = val;
}
}
// =================================================================
/*
* Utility methods.
*
* The methods whose name begins with "Mutate" modify the array
* they are given as first parameter; the other methods instantiate
* a new array.
*
* As a rule, untrimmed arrays are accepted as input, and output
* may be untrimmed as well.
*/
/*
* Count the number of leading zeros for a 32-bit value (number of
* consecutive zeros, starting with the most significant bit). This
* value is between 0 (for a value equal to 2^31 or greater) and
* 32 (for zero).
*/
static int LeadingZeros(uint v)
{
if (v == 0) {
return 32;
}
int n = 0;
if (v > 0xFFFF) { v >>= 16; } else { n += 16; }
if (v > 0x00FF) { v >>= 8; } else { n += 8; }
if (v > 0x000F) { v >>= 4; } else { n += 4; }
if (v > 0x0003) { v >>= 2; } else { n += 2; }
if (v <= 0x0001) { n ++; }
return n;
}
/*
* Duplicate the provided magnitude array. No attempt is made at
* trimming. The source array MUST NOT be null.
*/
static uint[] Dup(uint[] m)
{
uint[] r = new uint[m.Length];
Array.Copy(m, 0, r, 0, m.Length);
return r;
}
/*
* Increment the provided array. If there is a resulting carry,
* then "true" is returned, "false" otherwise. The array MUST
* NOT be null.
*/
static bool MutateIncr(uint[] x)
{
int n = x.Length;
for (int i = 0; i < n; i ++) {
uint w = x[i] + 1;
x[i] = w;
if (w != 0) {
return false;
}
}
return true;
}
/*
* Decrement the provided array. If there is a resulting carry,
* then "true" is returned, "false" otherwise. The array MUST
* NOT be null.
*/
static bool MutateDecr(uint[] x)
{
int n = x.Length;
for (int i = 0; i < n; i ++) {
uint w = x[i];
x[i] = w - 1;
if (w != 0) {
return false;
}
}
return true;
}
/*
* Multiply a[] with b[] (unsigned multiplication).
*/
static uint[] Mul(uint[] a, uint[] b)
{
// TODO: use Karatsuba when operands are large.
int na = Length(0, a);
int nb = Length(0, b);
if (na == 0 || nb == 0) {
return null;
}
uint[] r = new uint[na + nb];
for (int i = 0; i < na; i ++) {
ulong ma = a[i];
ulong carry = 0;
for (int j = 0; j < nb; j ++) {
ulong mb = (ulong)b[j];
ulong mr = (ulong)r[i + j];
ulong w = ma * mb + mr + carry;
r[i + j] = (uint)w;
carry = w >> 32;
}
r[i + nb] = (uint)carry;
}
return r;
}
/*
* Get the sign and magnitude of an integer. The sign is
* normalized to -1 (negative) or 0 (positive or zero). The
* magnitude is an array of length at least 1, containing the
* absolute value of this integer; if possible, the varray
* is reused (hence, the magnitude array MUST NOT be altered).
*/
static void ToAbs(ZInt x, out int sign, out uint[] magn)
{
if (x.small < 0) {
sign = -1;
x = -x;
} else {
sign = 0;
}
magn = x.varray;
if (magn == null) {
magn = new uint[1] { (uint)x.small };
}
}
/*
* Compare two integers, yielding -1, 0 or 1.
*/
static int Compare(int a, int b)
{
if (a < b) {
return -1;
} else if (a == b) {
return 0;
} else {
return 1;
}
}
/*
* Compare a[] with b[] (unsigned). Returned value is 1 if a[]
* is greater than b[], 0 if they are equal, -1 otherwise.
*/
static int Compare(uint[] a, uint[] b)
{
int ka = Length(0, a);
int kb = Length(0, b);
if (ka < kb) {
return -1;
} else if (ka == kb) {
while (ka > 0) {
ka --;
uint wa = a[ka];
uint wb = b[ka];
if (wa < wb) {
return -1;
} else if (wa > wb) {
return 1;
}
}
return 0;
} else {
return 1;
}
}
/*
* Add b[] to a[] (unsigned). a[] is modified "in place". Only
* n words of a[] are modified. Moreover, the value of
* b[] which is added is left-shifted: words b[0]...b[n-1] are
* added to a[k]...a[k+n-1]. The final carry is returned ("true"
* for 1, "false" for 0). Neither a nor b may be null.
*/
static bool MutateAdd(uint[] a, int n, uint[] b, int k)
{
bool carry = false;
for (int i = 0; i < n; i ++) {
uint wa = a[i + k];
uint wb = b[i];
uint wc = wa + wb;
if (carry) {
wc ++;
carry = wa >= wc;
} else {
carry = wa > wc;
}
a[i + k] = wc;
}
return carry;
}
/*
* Substract b[] from a[] (unsigned). a[] is modified "in
* place". Only n words of a[] are modified. Words
* b[0]...b[n-1] are subtracted from a[k]...a[k+n-1]. The final
* carry is returned ("true" for -1, "false" for 0). Neither a
* nor b may be null.
*/
static bool MutateSub(uint[] a, int n, uint[] b, int k)
{
bool carry = false;
for (int i = 0; i < n; i ++) {
uint wa = a[i + k];
uint wb = b[i];
uint wc = wa - wb;
if (carry) {
wc --;
carry = wa <= wc;