-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathb9.c
More file actions
1619 lines (1444 loc) · 40.9 KB
/
Copy pathb9.c
File metadata and controls
1619 lines (1444 loc) · 40.9 KB
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
#include <stdlib.h>
#include <string.h>
#include "b9.h"
/* Use schoolbook multiplication below this many limbs (must be >= 3). */
#define B9_KARATSUBA_THRESHOLD 400
/******************************************************************************/
/* Internal allocation helpers. */
/******************************************************************************/
/* Internal allocations cannot propagate failure through the b9 interface. */
static void* b9_xmalloc(size_t count, size_t size)
{
void *p;
if (size != 0 && count > (size_t)MAX_SIZET / size)
croak("internal: b9 allocation too large");
p = malloc(count * size);
if (p == 0 && count != 0 && size != 0)
croak("internal: b9 allocation failed");
return p;
}
static void* b9_xcalloc(size_t count, size_t size)
{
void *p;
if (size != 0 && count > (size_t)MAX_SIZET / size)
croak("internal: b9 allocation too large");
p = calloc(count, size);
if (p == 0 && count != 0 && size != 0)
croak("internal: b9 allocation failed");
return p;
}
static void* b9_xrealloc(void *ptr, size_t count, size_t size)
{
void *p;
if (size != 0 && count > (size_t)MAX_SIZET / size)
croak("internal: b9 allocation too large");
p = realloc(ptr, count * size);
if (p == 0 && count != 0 && size != 0)
croak("internal: b9 allocation failed");
return p;
}
void b9_free(b9_t *x)
{
if (x->d != (b9limb_t*)x->d_small) free(x->d);
b9_init(x);
}
void b9_neg(b9_t *x)
{
x->neg = x->n == 0 ? 0 : !x->neg;
}
/******************************************************************************/
/* Base-10^N arithmetic. */
/******************************************************************************/
void b9_ensure(b9_t *x, uint32_t need)
{
b9limb_t *newd;
if (x->alloc >= need) return;
if (x->d == (b9limb_t*)x->d_small) {
newd = (b9limb_t*)b9_xmalloc((size_t)need, sizeof(b9limb_t));
if (x->n) memcpy(newd, x->d_small, x->n * sizeof(b9limb_t));
} else {
newd = (b9limb_t*)b9_xrealloc(x->d, (size_t)need,
sizeof(b9limb_t));
}
x->d = newd;
x->alloc = need;
}
/* Exchange two b9_t values, correctly handling inline storage. */
void b9_swap(b9_t *a, b9_t *b)
{
int a_inline = (a->d == (b9limb_t*)a->d_small);
int b_inline = (b->d == (b9limb_t*)b->d_small);
b9limb_t small[B9_INLINE_LIMBS];
b9limb_t *d;
b9_t *t;
uint32_t an, bn, alloc, n;
int aneg, bneg, neg;
if (a_inline && b_inline) {
an = a->n; aneg = a->neg;
bn = b->n; bneg = b->neg;
if (an) memcpy(small, a->d, (size_t)an * sizeof(b9limb_t));
if (bn) memcpy(a->d, b->d, (size_t)bn * sizeof(b9limb_t));
if (an) memcpy(b->d, small, (size_t)an * sizeof(b9limb_t));
a->n = bn; a->neg = bneg;
b->n = an; b->neg = aneg;
return;
}
if (!a_inline && !b_inline) {
d = a->d; a->d = b->d; b->d = d;
alloc = a->alloc; a->alloc = b->alloc; b->alloc = alloc;
n = a->n; a->n = b->n; b->n = n;
neg = a->neg; a->neg = b->neg; b->neg = neg;
return;
}
/* Put the inline value in a and the heap value in b. */
if (!a_inline) { t = a; a = b; b = t; }
an = a->n; aneg = a->neg;
if (an) memcpy(small, a->d, (size_t)an * sizeof(b9limb_t));
a->d = b->d; a->alloc = b->alloc; a->n = b->n; a->neg = b->neg;
b->d = (b9limb_t*)b->d_small;
b->alloc = B9_INLINE_LIMBS; b->n = an; b->neg = aneg;
if (an) memcpy(b->d, small, (size_t)an * sizeof(b9limb_t));
}
/* Free dst, move src into dst. src is blanked. */
void b9_move(b9_t *dst, b9_t *src)
{
b9_free(dst);
if (src->d == (b9limb_t*)src->d_small) {
if (src->n)
memcpy(dst->d, src->d, (size_t)src->n * sizeof(b9limb_t));
} else {
dst->d = src->d;
dst->alloc = src->alloc;
}
dst->n = src->n;
dst->neg = src->neg;
b9_init(src);
}
/* Copy src into an initialized dst. src is unchanged. */
void b9_set(b9_t *dst, const b9_t *src)
{
if (dst != src) {
b9_ensure(dst, src->n);
if (src->n) memcpy(dst->d, src->d, src->n * sizeof(b9limb_t));
dst->n = src->n;
dst->neg = src->neg;
}
}
/* Exact length in decimal digits including possible sign character */
STRLEN b9_length(const b9_t *x)
{
STRLEN digits;
uint32_t v;
if (x->n == 0)
return 1;
digits = (STRLEN)(x->n - 1) * B9_DIGS;
v = x->d[x->n - 1];
do { digits++; v /= 10; } while (v > 0);
return digits + (x->neg ? 1 : 0);
}
/* Set x from a signed decimal string (may have leading sign and/or zeros). */
void b9_set_str(b9_t *x, const char *s, STRLEN len)
{
int neg;
uint32_t nlimbs;
STRLEN pos;
neg = (len > 0 && s[0] == '-');
if (len > 0 && (s[0] == '-' || s[0] == '+')) { s++; len--; }
while (len > 1 && s[0] == '0') { s++; len--; }
if (len == 0 || (len == 1 && s[0] == '0')) { x->n = 0; x->neg = 0; return; }
nlimbs = (uint32_t)B9_NLIMBS(len);
b9_ensure(x, nlimbs);
x->n = 0;
pos = len;
while (pos > 0) {
STRLEN start = (pos > (STRLEN)B9_DIGS) ? pos - B9_DIGS : 0;
STRLEN i;
uint32_t v = 0;
for (i = start; i < pos; i++)
v = v * 10 + (uint32_t)(s[i] - '0');
x->d[x->n++] = (b9limb_t)v;
pos = start;
}
x->neg = neg;
}
void b9_init_set_str(b9_t *x, const char *s, STRLEN len)
{
b9_init(x);
b9_set_str(x, s, len);
}
/* Write x to buf as a signed decimal string (no NUL).
* buf must have at least x->n * B9_DIGS + 2 bytes.
* Returns string length. */
STRLEN b9_get_str(char *buf, const b9_t *x)
{
STRLEN pos = 0;
uint32_t i;
if (x->n == 0) { buf[0] = '0'; return 1; }
if (x->neg) buf[pos++] = '-';
{ /* Most-significant limb: no leading zeros */
char tmp[12];
uint32_t v = x->d[x->n - 1];
STRLEN j = (STRLEN)B9_DIGS;
do { tmp[--j] = '0' + (char)(v % 10); v /= 10; } while (v > 0);
while (j < (STRLEN)B9_DIGS) buf[pos++] = tmp[j++];
}
/* Remaining limbs: exactly B9_DIGS digits, zero-padded */
for (i = x->n - 1; i-- > 0; ) {
char tmp[12];
uint32_t v = x->d[i];
STRLEN j = (STRLEN)B9_DIGS;
while (j > 0) { tmp[--j] = '0' + (char)(v % 10); v /= 10; }
memcpy(buf + pos, tmp, (size_t)B9_DIGS);
pos += (STRLEN)B9_DIGS;
}
return pos;
}
/* Set x from an unsigned machine word. */
void b9_set_uv(b9_t *x, UV v)
{
uint32_t n = 0;
b9_ensure(x, (uint32_t)B9_NLIMBS(B9_UV_DEC_DIGS));
x->neg = 0;
if (v == 0) { x->n = 0; return; }
while (v > 0) { x->d[n++] = (b9limb_t)((UV)(v % B9_BASE)); v /= (UV)B9_BASE; }
x->n = n;
}
void b9_init_set_uv(b9_t *x, UV v)
{
b9_init(x);
b9_set_uv(x, v);
}
/* Set x from an unsigned accumulator value. */
static void b9_set_acc(b9_t *x, b9acc_t v)
{
uint32_t n = 0;
b9_ensure(x, (uint32_t)B9_NLIMBS(B9_ACC_DEC_DIGS));
x->neg = 0;
if (v == 0) { x->n = 0; return; }
while (v > 0) { x->d[n++] = (b9limb_t)(v % B9_BASE); v /= B9_BASE; }
x->n = n;
}
/* Convert b9 to u32, no size check. */
MAYBE_UNUSED static uint32_t b9_get_u32(const b9_t *x)
{
uint32_t i, v;
for (v = 0, i = x->n; i-- > 0; )
v = v * B9_BASE + (uint32_t)x->d[i];
return v;
}
#if HAVE_UINT64
static bool b9_get_u32_checked(uint32_t *result, const b9_t *x)
{
uint64_t v = 0;
uint32_t i;
if (x->n > (uint32_t)B9_NLIMBS(10)) return 0;
for (i = x->n; i-- > 0; )
v = v * B9_BASE + x->d[i];
if (v > UINT32_MAX) return 0;
*result = (uint32_t)v;
return 1;
}
#endif
/* Convert b9 to UV, no size check. [n * B9_DIGS < sizeof(UV)*3] */
UV b9_get_uv(const b9_t* x) {
UV v = 0;
uint32_t i;
for (i = x->n; i-- > 0; )
v = v * (UV)B9_BASE + (UV)x->d[i];
return v;
}
/* Simpler helpers */
static void b9_init_set_acc(b9_t *x, b9acc_t v)
{ b9_init(x); b9_set_acc(x,v); }
void b9_init_set(b9_t *x, const b9_t *y)
{
b9_init(x);
b9_set(x, y);
}
/* Signed comparison. Returns -1, 0, or 1. */
int b9_cmp(const b9_t *a, const b9_t *b)
{
uint32_t i;
int gt;
if (a->n == 0 && b->n == 0) return 0;
if (a->neg != b->neg) return a->neg ? -1 : 1;
if (a->n != b->n) {
gt = (a->n > b->n) ? 1 : -1;
return a->neg ? -gt : gt;
}
for (i = a->n; i-- > 0; ) {
if (a->d[i] != b->d[i]) {
gt = (a->d[i] > b->d[i]) ? 1 : -1;
return a->neg ? -gt : gt;
}
}
return 0;
}
/*--- Unsigned-magnitude helpers (raw limb arrays, no alloc) ---*/
static int b9mag_cmp(const b9limb_t *a, uint32_t na,
const b9limb_t *b, uint32_t nb)
{
uint32_t i;
if (na != nb) return (na > nb) ? 1 : -1;
for (i = na; i-- > 0; )
if (a[i] != b[i]) return (a[i] > b[i]) ? 1 : -1;
return 0;
}
/* out = |a| + |b|. out needs max(na,nb)+1 limbs. Returns limb count. */
static uint32_t b9mag_add(b9limb_t *out,
const b9limb_t *a, uint32_t na,
const b9limb_t *b, uint32_t nb)
{
uint32_t i, rn;
b9acc_t carry = 0;
if (na < nb) {
const b9limb_t *t = a; uint32_t tn = na;
a = b; na = nb; b = t; nb = tn;
}
rn = na;
for (i = 0; i < nb; i++) {
b9acc_t s = (b9acc_t)a[i] + b[i] + carry;
out[i] = (b9limb_t)(s % B9_BASE);
carry = s / B9_BASE;
}
for (; i < na; i++) {
b9acc_t s = (b9acc_t)a[i] + carry;
out[i] = (b9limb_t)(s % B9_BASE);
carry = s / B9_BASE;
}
if (carry) out[rn++] = (b9limb_t)carry;
return rn;
}
/* out = |a| - |b| (|a| >= |b| required).
* out needs na limbs. Returns significant limb count. */
static uint32_t b9mag_sub(b9limb_t *out,
const b9limb_t *a, uint32_t na,
const b9limb_t *b, uint32_t nb)
{
uint32_t i, rn;
int borrow = 0;
for (i = 0; i < nb; i++) {
b9acc_t bi_b = (b9acc_t)b[i] + borrow;
if ((b9acc_t)a[i] >= bi_b) {
out[i] = (b9limb_t)((b9acc_t)a[i] - bi_b);
borrow = 0;
} else {
out[i] = (b9limb_t)(B9_BASE + (b9acc_t)a[i] - bi_b);
borrow = 1;
}
}
for (; i < na; i++) {
if (!borrow) { out[i] = a[i]; }
else if (a[i]) { out[i] = a[i] - 1; borrow = 0; }
else { out[i] = (b9limb_t)(B9_BASE - 1); }
}
rn = na;
while (rn > 1 && out[rn-1] == 0) rn--;
return rn;
}
/* out = a + b (signed). out may alias a or b. */
void b9_add(b9_t *out, const b9_t *a, const b9_t *b)
{
int cmp, use_tmp;
b9limb_t *dst;
uint32_t need, rn;
if (a->n == 0) {
b9_set(out, b);
return;
}
if (b->n == 0) {
b9_set(out, a);
return;
}
use_tmp = (out->d == a->d || out->d == b->d);
if (a->neg == b->neg) {
need = (a->n > b->n ? a->n : b->n) + 1;
if (use_tmp) {
dst = (b9limb_t*)b9_xmalloc(need, sizeof(b9limb_t));
} else {
b9_ensure(out, need);
dst = out->d;
}
rn = b9mag_add(dst, a->d, a->n, b->d, b->n);
out->neg = a->neg;
} else {
cmp = b9mag_cmp(a->d, a->n, b->d, b->n);
if (cmp == 0) { out->n = 0; out->neg = 0; return; }
need = (cmp > 0) ? a->n : b->n;
if (use_tmp) {
dst = (b9limb_t*)b9_xmalloc(need, sizeof(b9limb_t));
} else {
b9_ensure(out, need);
dst = out->d;
}
if (cmp > 0) {
rn = b9mag_sub(dst, a->d, a->n, b->d, b->n);
out->neg = a->neg;
} else {
rn = b9mag_sub(dst, b->d, b->n, a->d, a->n);
out->neg = b->neg;
}
}
if (use_tmp) {
b9_ensure(out, rn);
memcpy(out->d, dst, rn * sizeof(b9limb_t));
free(dst);
}
out->n = rn;
if (out->n == 0) out->neg = 0;
}
#if 0
/* out = a - b (signed). out may alias a or b. */
static void b9_sub(b9_t *out, const b9_t *a, const b9_t *b)
{
b9_t nb;
nb.d = b->d; nb.alloc = b->alloc; nb.n = b->n; nb.neg = b->neg;
b9_neg(&nb);
b9_add(out, a, &nb);
}
#endif
void b9_add_u32(b9_t *out, const b9_t *a, uint32_t v)
{
b9acc_t carry;
uint32_t i, need;
if (v == 0) {
b9_set(out, a);
return;
}
if (a->neg) {
b9_t b;
b9_init_set_uv(&b, v);
b9_add(out, a, &b);
b9_free(&b);
return;
}
need = a->n + (uint32_t)B9_NLIMBS(B9_UV_DEC_DIGS);
b9_ensure(out, need);
if (out != a && a->n)
memcpy(out->d, a->d, a->n * sizeof(b9limb_t));
carry = v;
i = 0;
while (carry) {
b9acc_t s = carry;
if (i < a->n) s += out->d[i];
out->d[i++] = (b9limb_t)(s % B9_BASE);
carry = s / B9_BASE;
}
out->n = (a->n > i) ? a->n : i;
out->neg = 0;
}
void b9_add_uv(b9_t *out, const b9_t *a, UV v)
{
if (v <= (UV)UINT32_MAX) {
b9_add_u32(out, a, (uint32_t)v);
} else {
b9_t b;
b9_init_set_uv(&b, v);
b9_add(out, a, &b);
b9_free(&b);
}
}
/* out = a * b (signed). Every multiplication path permits out to alias
* either input. */
/* Keep common schoolbook products and Karatsuba leaves off the heap without
* making a 4 KiB stack array when b9acc_t is uint64_t. */
#define B9_MUL_STACK_LIMBS 448
/* Multiply a magnitude by one limb. out may alias a. */
static void b9_mul_limb_abs(b9_t *out, const b9_t *a, b9limb_t v)
{
b9acc_t carry = 0;
uint32_t i;
if (v == 0 || a->n == 0) {
out->n = 0;
out->neg = 0;
return;
}
if (v == 1) {
b9_set(out, a);
out->neg = 0;
return;
}
if (a->n == UINT32_MAX)
croak("internal: b9 multiplication too large");
b9_ensure(out, a->n + 1);
for (i = 0; i < a->n; i++) {
b9acc_t product = (b9acc_t)a->d[i] * v + carry;
out->d[i] = (b9limb_t)(product % B9_BASE);
carry = product / B9_BASE;
}
out->n = a->n;
if (carry != 0) out->d[out->n++] = (b9limb_t)carry;
out->neg = 0;
}
/* All input limbs are consumed before out is resized or written. */
static void b9_mul_schoolbook(b9_t *out, const b9_t *a, const b9_t *b)
{
uint32_t i, j, rn;
b9acc_t stack_acc[B9_MUL_STACK_LIMBS + 1];
b9acc_t *acc;
if (a->n == 0 || b->n == 0) { out->n = 0; out->neg = 0; return; }
rn = a->n + b->n;
if (rn <= B9_MUL_STACK_LIMBS) {
acc = stack_acc;
memset(acc, 0, (rn + 1) * sizeof(b9acc_t));
} else {
acc = (b9acc_t*)b9_xcalloc((size_t)rn + 1, sizeof(b9acc_t));
}
for (i = 0; i < a->n; i++) {
if (a->d[i] == 0) continue;
for (j = 0; j < b->n; j++)
acc[i + j] += (b9acc_t)a->d[i] * b->d[j];
/* Per-row carry flush: only needed for base 10^4 (32-bit uint32_t acc).
* With uint64_t (base 10^6) overflow needs 18M products/position. */
#if !HAVE_UINT128 && !HAVE_UINT64
for (j = i; j <= i + b->n && j < rn; j++) {
acc[j + 1] += acc[j] / B9_BASE;
acc[j] %= B9_BASE;
}
#endif
}
/* a->d and b->d fully consumed; safe to resize out even if aliased */
b9_ensure(out, rn);
for (i = 0; i < rn; i++) {
acc[i + 1] += acc[i] / B9_BASE;
acc[i] %= B9_BASE;
out->d[i] = (b9limb_t)acc[i];
}
if (acc != stack_acc) free(acc);
while (rn > 0 && out->d[rn-1] == 0) rn--;
out->n = rn;
out->neg = 0;
}
/* Make a read-only, non-owning view of a limb range. The view must not be
* passed as an output or to b9_free. */
static void b9_init_slice_view(b9_t *view, const b9_t *a,
uint32_t start, uint32_t len)
{
b9_init(view);
if (start >= a->n) return;
if (len > a->n-start) len = a->n-start;
view->d = a->d + start;
view->alloc = len;
view->n = len;
while (view->n > 0 && view->d[view->n-1] == 0) view->n--;
}
/* Initialize a temporary using its fixed-capacity portion of a work buffer. */
static void b9_init_work(b9_t *x, b9limb_t **next, uint32_t capacity)
{
x->d = *next;
x->alloc = capacity;
x->n = 0;
x->neg = 0;
*next += capacity;
}
static void b9_add_work_size(size_t *total, uint32_t capacity)
{
if (*total > (size_t)MAX_SIZET - (size_t)capacity)
croak("internal: b9 Karatsuba workspace too large");
*total += capacity;
}
/* Subtract |b| from nonnegative a in place. */
static void b9_sub_abs_inplace(b9_t *a, const b9_t *b)
{
MPUassert(!a->neg && !b->neg &&
b9mag_cmp(a->d, a->n, b->d, b->n) >= 0,
"b9 Karatsuba subtraction underflow");
a->n = b9mag_sub(a->d, a->d, a->n, b->d, b->n);
if (a->n == 1 && a->d[0] == 0) a->n = 0;
a->neg = 0;
}
/* Add x at a whole-limb offset into an allocated, zero-padded result. */
static void b9_add_shifted(b9_t *out, uint32_t outn,
const b9_t *x, uint32_t offset)
{
uint32_t carry = 0, i, pos;
MPUassert(offset <= outn && x->n <= outn-offset,
"b9 Karatsuba result overflow");
for (i = 0; i < x->n; i++) {
b9acc_t sum = (b9acc_t)out->d[offset+i] + x->d[i] + carry;
if (sum >= B9_BASE) {
out->d[offset+i] = (b9limb_t)(sum - B9_BASE);
carry = 1;
} else {
out->d[offset+i] = (b9limb_t)sum;
carry = 0;
}
}
pos = offset + x->n;
while (carry != 0) {
b9acc_t sum;
MPUassert(pos < outn, "b9 Karatsuba carry overflow");
sum = (b9acc_t)out->d[pos] + carry;
if (sum >= B9_BASE) {
out->d[pos++] = (b9limb_t)(sum - B9_BASE);
} else {
out->d[pos++] = (b9limb_t)sum;
carry = 0;
}
}
}
static void b9_mul_abs(b9_t *out, const b9_t *a, const b9_t *b);
static void b9_mul_karatsuba(b9_t *out, const b9_t *a, const b9_t *b)
{
b9_t a0, a1, b0, b1, asum, bsum, z0, z1, z2;
uint32_t an = a->n, bn = b->n;
uint32_t maxn = an > bn ? an : bn;
uint32_t split = maxn >> 1;
uint32_t rn = an + bn;
uint32_t a0cap = an < split ? an : split;
uint32_t b0cap = bn < split ? bn : split;
uint32_t a1cap = an-a0cap;
uint32_t b1cap = bn-b0cap;
uint32_t asumcap = (a0cap > a1cap ? a0cap : a1cap) + 1;
uint32_t bsumcap = (b0cap > b1cap ? b0cap : b1cap) + 1;
uint32_t z0cap = a0cap + b0cap;
uint32_t z1cap = asumcap + bsumcap;
uint32_t z2cap = a1cap + b1cap;
size_t worklimbs = 0;
b9limb_t *work, *next;
b9_add_work_size(&worklimbs, asumcap);
b9_add_work_size(&worklimbs, bsumcap);
b9_add_work_size(&worklimbs, z0cap);
b9_add_work_size(&worklimbs, z1cap);
b9_add_work_size(&worklimbs, z2cap);
work = (b9limb_t*)b9_xmalloc(worklimbs, sizeof(b9limb_t));
next = work;
b9_init_work(&asum, &next, asumcap);
b9_init_work(&bsum, &next, bsumcap);
b9_init_work(&z0, &next, z0cap);
b9_init_work(&z1, &next, z1cap);
b9_init_work(&z2, &next, z2cap);
MPUassert(next == work + worklimbs,
"b9 Karatsuba workspace mismatch");
b9_init_slice_view(&a0, a, 0, split);
b9_init_slice_view(&a1, a, split, an-split);
b9_init_slice_view(&b0, b, 0, split);
b9_init_slice_view(&b1, b, split, bn-split);
b9_mul_abs(&z0, &a0, &b0);
b9_mul_abs(&z2, &a1, &b1);
b9_add(&asum, &a0, &a1);
b9_add(&bsum, &b0, &b1);
b9_mul_abs(&z1, &asum, &bsum);
b9_sub_abs_inplace(&z1, &z0);
b9_sub_abs_inplace(&z1, &z2);
b9_ensure(out, rn);
memset(out->d, 0, (size_t)rn * sizeof(b9limb_t));
b9_add_shifted(out, rn, &z0, 0);
b9_add_shifted(out, rn, &z1, split);
b9_add_shifted(out, rn, &z2, split + split);
out->n = rn;
out->neg = 0;
while (out->n > 0 && out->d[out->n-1] == 0) out->n--;
free(work);
}
static void b9_mul_abs(b9_t *out, const b9_t *a, const b9_t *b)
{
uint32_t minn = a->n < b->n ? a->n : b->n;
uint32_t maxn = a->n > b->n ? a->n : b->n;
/* Very unequal operands do not recover the extra additions and copies. */
if (minn >= B9_KARATSUBA_THRESHOLD && maxn-minn <= minn/2)
b9_mul_karatsuba(out, a, b);
else
b9_mul_schoolbook(out, a, b);
}
void b9_mul(b9_t *out, const b9_t *a, const b9_t *b)
{
const b9_t *large;
b9limb_t small;
int neg;
#if HAVE_UINT64
uint32_t small32;
#endif
if (a->n == 0 || b->n == 0) {
out->n = 0;
out->neg = 0;
return;
}
neg = a->neg != b->neg;
if (a->n == 1 || b->n == 1) {
large = a->n == 1 ? b : a;
small = a->n == 1 ? a->d[0] : b->d[0];
b9_mul_limb_abs(out, large, small);
out->neg = neg && out->n != 0;
return;
}
#if HAVE_UINT64
if (b9_get_u32_checked(&small32, a)) {
b9_mul_u32(out, b, small32);
out->neg = neg && out->n != 0;
return;
}
if (b9_get_u32_checked(&small32, b)) {
b9_mul_u32(out, a, small32);
out->neg = neg && out->n != 0;
return;
}
#endif
if (a->n > UINT32_MAX-b->n)
croak("internal: b9 multiplication too large");
b9_mul_abs(out, a, b);
out->neg = neg && out->n != 0;
}
MAYBE_UNUSED static void b9_mul_uv(b9_t *out, const b9_t *a, UV v)
{
b9_t b;
b9_init_set_uv(&b, v);
b9_mul(out, a, &b);
b9_free(&b);
}
void b9_mul_u32(b9_t *out, const b9_t *a, uint32_t v)
{
#if HAVE_UINT64
uint64_t carry = 0;
uint32_t i, need, extra = (uint32_t)B9_NLIMBS(10) + 1;
int neg = a->neg;
if (v == 0 || a->n == 0) {
out->n = 0;
out->neg = 0;
return;
}
if (a->n > UINT32_MAX-extra)
croak("internal: b9 multiplication too large");
need = a->n + extra;
b9_ensure(out, need);
for (i = 0; i < a->n; i++) {
uint64_t t = (uint64_t)a->d[i] * v + carry;
out->d[i] = (b9limb_t)(t % B9_BASE);
carry = t / B9_BASE;
}
while (carry > 0) {
out->d[i++] = (b9limb_t)(carry % B9_BASE);
carry /= B9_BASE;
}
out->n = i;
out->neg = neg;
#else
b9_mul_uv(out, a, (UV)v);
#endif
}
/* out = a^exp. out can alias a. */
void b9_pow(b9_t *out, const b9_t *a, UV exp)
{
b9_t sq, tmp;
b9_init_set(&sq, a); /* sq is a copy of a */
b9_set_uv(out, 1);
b9_init(&tmp);
while (exp > 0) {
if (exp & 1) {
b9_mul(&tmp, out, &sq);
b9_move(out, &tmp);
}
exp >>= 1;
if (exp > 0) {
b9_mul(&tmp, &sq, &sq);
b9_move(&sq, &tmp);
}
}
b9_free(&sq); b9_free(&tmp);
}
/* There are a few places that want a power of two. This wraps it. */
void b9_init_set_pow2(b9_t *x, UV k)
{
if (k < BITS_PER_WORD) {
b9_init_set_uv(x, UVCONST(1) << k);
} else {
b9_init_set_uv(x, 2);
b9_pow(x, x, k);
}
}
/* Test bit k of |x| without modifying x. */
bool b9_testbit(const b9_t *x, uint32_t k)
{
b9_t q;
bool ret;
if (b9_is_zero(x)) return 0;
if (k < 4) return ((x->d[0] >> k) & 1) != 0;
b9_init(&q);
b9_tdiv_2exp(&q, x, (UV)k);
b9_abs(&q);
ret = !b9_is_even(&q);
b9_free(&q);
return ret;
}
/* out = a * 2^bits. out may alias a. */
void b9_mul_2exp(b9_t *out, const b9_t *a, UV bits)
{
if (bits == 0) {
b9_set(out, a);
} else if (b9_is_zero(a)) {
out->n = 0;
out->neg = 0;
} else if (bits < 32) {
b9_mul_u32(out, a, UINT32_C(1) << bits);
} else if (bits == 32) {
b9_mul_u32(out, a, UINT32_C(65536));
b9_mul_u32(out, out, UINT32_C(65536));
} else {
b9_t pow2;
b9_init_set_pow2(&pow2, bits);
b9_mul(out, a, &pow2);
b9_free(&pow2);
}
}
#if HAVE_UINT64 /* 2^44 * 10^6 fits in the 64-bit accumulator. */
#define B9_TDIV_2EXP_CHUNK_BITS 44
#else /* 2^18 * 10^4 fits in the 32-bit accumulator. */
#define B9_TDIV_2EXP_CHUNK_BITS 18
#endif
/* Divide by 2^bits using one pass over the decimal limbs. The caller limits
* bits so carry * B9_BASE fits in b9acc_t. */
static b9acc_t b9_tdiv_2exp_chunk(b9_t *a, uint32_t bits)
{
b9acc_t carry = 0;
b9acc_t mask = ((b9acc_t)1 << bits) - 1;
uint32_t i;
for (i = a->n; i-- > 0; ) {
b9acc_t cur = carry * B9_BASE + a->d[i];
a->d[i] = (b9limb_t)(cur >> bits);
carry = cur & mask;
}
while (a->n > 0 && a->d[a->n-1] == 0) a->n--;
if (a->n == 0) a->neg = 0;
return carry;
}
/* Divide in place by 2^bits and report whether any discarded bit was set. */
static bool b9_tdiv_2exp_inplace(b9_t *a, UV bits)
{
bool discarded = 0;
if (bits == 1) {
discarded = !b9_is_even(a);
b9_tdiv2(a);
return discarded;
}
if (bits == 4) {
discarded = !b9_is_zero(a) && (a->d[0] & 15) != 0;
b9_tdiv16(a);
return discarded;
}
while (bits > 0 && !b9_is_zero(a)) {
uint32_t chunk = bits > B9_TDIV_2EXP_CHUNK_BITS
? B9_TDIV_2EXP_CHUNK_BITS : (uint32_t)bits;
if (b9_tdiv_2exp_chunk(a, chunk) != 0) discarded = 1;
bits -= chunk;
}
return discarded;
}
/* out = trunc(a / 2^bits). out may alias a. */
void b9_tdiv_2exp(b9_t *out, const b9_t *a, UV bits)
{
if (out != a) b9_set(out, a);
(void)b9_tdiv_2exp_inplace(out, bits);
}
/* out = floor(a / 2^bits). out may alias a. */
void b9_fdiv_2exp(b9_t *out, const b9_t *a, UV bits)
{
bool neg = b9_is_negative(a);
bool adjust;
if (out != a) b9_set(out, a);
adjust = b9_tdiv_2exp_inplace(out, bits);
if (neg && adjust) {
b9_abs(out);
b9_add_u32(out, out, 1);
b9_set_negative(out, 1);
}
}
static uint32_t b9_ctz_acc(b9acc_t v)
{
uint32_t count = 0;
MPUassert(v != 0, "b9_ctz_acc called with zero");
while (!(v & 1)) { v >>= 1; count++; }
return count;
}
/* Find the first set bit, destructively scanning x from bit zero. */
static bool b9_scan1_from_zero(uint32_t *result, b9_t *x, uint32_t limit)
{
uint32_t count = 0;
while (!b9_is_zero(x)) {
b9acc_t rem = b9_tdiv_2exp_chunk(x, B9_TDIV_2EXP_CHUNK_BITS);
if (rem != 0) {
uint32_t skip = b9_ctz_acc(rem);
if (skip > limit-count) return 0;
*result = count + skip;
return 1;
}
if (B9_TDIV_2EXP_CHUNK_BITS > limit-count) return 0;
count += B9_TDIV_2EXP_CHUNK_BITS;
}
return 0;
}
static bool b9_bitscan(uint32_t *result, const b9_t *x, uint32_t start,
bool want_one)
{
b9_t q;
uint32_t skip;
bool found;
b9_init_set(&q, x);
b9_abs(&q);
if (start != 0) b9_tdiv_2exp(&q, &q, (UV)start);
if (!want_one) b9_add_u32(&q, &q, 1);
found = b9_scan1_from_zero(&skip, &q, UINT32_MAX-start);
if (found) *result = start + skip;
b9_free(&q);
return found;
}
bool b9_bitscan0(uint32_t *result, const b9_t *x, uint32_t start)
{
return b9_bitscan(result, x, start, 0);
}
bool b9_bitscan1(uint32_t *result, const b9_t *x, uint32_t start)
{
return b9_bitscan(result, x, start, 1);
}
#if B9_DIGS == 9
#define B9_BINARY_LIMB_BITS 30
#elif B9_DIGS == 6
#define B9_BINARY_LIMB_BITS 20
#else
#define B9_BINARY_LIMB_BITS 14