forked from creachadair/imath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imath.c
2782 lines (2169 loc) · 69.4 KB
/
imath.c
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
/*
Name: imath.c
Purpose: Arbitrary precision integer arithmetic routines.
Author: M. J. Fromberger
Copyright (C) 2002-2007 Michael J. Fromberger, All Rights Reserved.
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.
*/
#include "imath.h"
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
const mp_result MP_OK = 0; /* no error, all is well */
const mp_result MP_FALSE = 0; /* boolean false */
const mp_result MP_TRUE = -1; /* boolean true */
const mp_result MP_MEMORY = -2; /* out of memory */
const mp_result MP_RANGE = -3; /* argument out of range */
const mp_result MP_UNDEF = -4; /* result undefined */
const mp_result MP_TRUNC = -5; /* output truncated */
const mp_result MP_BADARG = -6; /* invalid null argument */
const mp_result MP_MINERR = -6;
const mp_sign MP_NEG = 1; /* value is strictly negative */
const mp_sign MP_ZPOS = 0; /* value is non-negative */
static const char *const s_unknown_err = "unknown result code";
static const char *const s_error_msg[] = {
"error code 0", "boolean true",
"out of memory", "argument out of range",
"result undefined", "output truncated",
"invalid argument", NULL,
};
/* The ith entry of this table gives the value of log_i(2).
An integer value n requires ceil(log_i(n)) digits to be represented
in base i. Since it is easy to compute lg(n), by counting bits, we
can compute log_i(n) = lg(n) * log_i(2).
The use of this table eliminates a dependency upon linkage against
the standard math libraries.
If MP_MAX_RADIX is increased, this table should be expanded too.
*/
static const double s_log2[] = {
0.000000000, 0.000000000, 1.000000000, 0.630929754, /* (D)(D) 2 3 */
0.500000000, 0.430676558, 0.386852807, 0.356207187, /* 4 5 6 7 */
0.333333333, 0.315464877, 0.301029996, 0.289064826, /* 8 9 10 11 */
0.278942946, 0.270238154, 0.262649535, 0.255958025, /* 12 13 14 15 */
0.250000000, 0.244650542, 0.239812467, 0.235408913, /* 16 17 18 19 */
0.231378213, 0.227670249, 0.224243824, 0.221064729, /* 20 21 22 23 */
0.218104292, 0.215338279, 0.212746054, 0.210309918, /* 24 25 26 27 */
0.208014598, 0.205846832, 0.203795047, 0.201849087, /* 28 29 30 31 */
0.200000000, 0.198239863, 0.196561632, 0.194959022, /* 32 33 34 35 */
0.193426404, /* 36 */
};
/* Return the number of digits needed to represent a static value */
#define MP_VALUE_DIGITS(V) \
((sizeof(V) + (sizeof(mp_digit) - 1)) / sizeof(mp_digit))
/* Round precision P to nearest word boundary */
static inline mp_size s_round_prec(mp_size P) { return 2 * ((P + 1) / 2); }
/* Set array P of S digits to zero */
static inline void ZERO(mp_digit *P, mp_size S) {
mp_size i__ = S * sizeof(mp_digit);
mp_digit *p__ = P;
memset(p__, 0, i__);
}
/* Copy S digits from array P to array Q */
static inline void COPY(mp_digit *P, mp_digit *Q, mp_size S) {
mp_size i__ = S * sizeof(mp_digit);
mp_digit *p__ = P;
mp_digit *q__ = Q;
memcpy(q__, p__, i__);
}
/* Reverse N elements of unsigned char in A. */
static inline void REV(unsigned char *A, int N) {
unsigned char *u_ = A;
unsigned char *v_ = u_ + N - 1;
while (u_ < v_) {
unsigned char xch = *u_;
*u_++ = *v_;
*v_-- = xch;
}
}
/* Strip leading zeroes from z_ in-place. */
static inline void CLAMP(mp_int z_) {
mp_size uz_ = MP_USED(z_);
mp_digit *dz_ = MP_DIGITS(z_) + uz_ - 1;
while (uz_ > 1 && (*dz_-- == 0)) --uz_;
z_->used = uz_;
}
/* Select min/max. */
static inline int MIN(int A, int B) { return (B < A ? B : A); }
static inline mp_size MAX(mp_size A, mp_size B) { return (B > A ? B : A); }
/* Exchange lvalues A and B of type T, e.g.
SWAP(int, x, y) where x and y are variables of type int. */
#define SWAP(T, A, B) \
do { \
T t_ = (A); \
A = (B); \
B = t_; \
} while (0)
/* Declare a block of N temporary mpz_t values.
These values are initialized to zero.
You must add CLEANUP_TEMP() at the end of the function.
Use TEMP(i) to access a pointer to the ith value.
*/
#define DECLARE_TEMP(N) \
struct { \
mpz_t value[(N)]; \
int len; \
mp_result err; \
} temp_ = { \
.len = (N), \
.err = MP_OK, \
}; \
do { \
for (int i = 0; i < temp_.len; i++) { \
mp_int_init(TEMP(i)); \
} \
} while (0)
/* Clear all allocated temp values. */
#define CLEANUP_TEMP() \
CLEANUP: \
do { \
for (int i = 0; i < temp_.len; i++) { \
mp_int_clear(TEMP(i)); \
} \
if (temp_.err != MP_OK) { \
return temp_.err; \
} \
} while (0)
/* A pointer to the kth temp value. */
#define TEMP(K) (temp_.value + (K))
/* Evaluate E, an expression of type mp_result expected to return MP_OK. If
the value is not MP_OK, the error is cached and control resumes at the
cleanup handler, which returns it.
*/
#define REQUIRE(E) \
do { \
temp_.err = (E); \
if (temp_.err != MP_OK) goto CLEANUP; \
} while (0)
/* Compare value to zero. */
static inline int CMPZ(mp_int Z) {
if (Z->used == 1 && Z->digits[0] == 0) return 0;
return (Z->sign == MP_NEG) ? -1 : 1;
}
static inline mp_word UPPER_HALF(mp_word W) { return (W >> MP_DIGIT_BIT); }
static inline mp_digit LOWER_HALF(mp_word W) { return (mp_digit)(W); }
/* Report whether the highest-order bit of W is 1. */
static inline bool HIGH_BIT_SET(mp_word W) {
return (W >> (MP_WORD_BIT - 1)) != 0;
}
/* Report whether adding W + V will carry out. */
static inline bool ADD_WILL_OVERFLOW(mp_word W, mp_word V) {
return ((MP_WORD_MAX - V) < W);
}
/* Default number of digits allocated to a new mp_int */
static mp_size default_precision = 8;
void mp_int_default_precision(mp_size size) {
assert(size > 0);
default_precision = size;
}
/* Minimum number of digits to invoke recursive multiply */
static mp_size multiply_threshold = 32;
void mp_int_multiply_threshold(mp_size thresh) {
assert(thresh >= sizeof(mp_word));
multiply_threshold = thresh;
}
/* Allocate a buffer of (at least) num digits, or return
NULL if that couldn't be done. */
static mp_digit *s_alloc(mp_size num);
/* Release a buffer of digits allocated by s_alloc(). */
static void s_free(void *ptr);
/* Insure that z has at least min digits allocated, resizing if
necessary. Returns true if successful, false if out of memory. */
static bool s_pad(mp_int z, mp_size min);
/* Ensure Z has at least N digits allocated. */
static inline mp_result GROW(mp_int Z, mp_size N) {
return s_pad(Z, N) ? MP_OK : MP_MEMORY;
}
/* Fill in a "fake" mp_int on the stack with a given value */
static void s_fake(mp_int z, mp_small value, mp_digit vbuf[]);
static void s_ufake(mp_int z, mp_usmall value, mp_digit vbuf[]);
/* Compare two runs of digits of given length, returns <0, 0, >0 */
static int s_cdig(mp_digit *da, mp_digit *db, mp_size len);
/* Pack the unsigned digits of v into array t */
static int s_uvpack(mp_usmall v, mp_digit t[]);
/* Compare magnitudes of a and b, returns <0, 0, >0 */
static int s_ucmp(mp_int a, mp_int b);
/* Compare magnitudes of a and v, returns <0, 0, >0 */
static int s_vcmp(mp_int a, mp_small v);
static int s_uvcmp(mp_int a, mp_usmall uv);
/* Unsigned magnitude addition; assumes dc is big enough.
Carry out is returned (no memory allocated). */
static mp_digit s_uadd(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a,
mp_size size_b);
/* Unsigned magnitude subtraction. Assumes dc is big enough. */
static void s_usub(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a,
mp_size size_b);
/* Unsigned recursive multiplication. Assumes dc is big enough. */
static int s_kmul(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a,
mp_size size_b);
/* Unsigned magnitude multiplication. Assumes dc is big enough. */
static void s_umul(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a,
mp_size size_b);
/* Unsigned recursive squaring. Assumes dc is big enough. */
static int s_ksqr(mp_digit *da, mp_digit *dc, mp_size size_a);
/* Unsigned magnitude squaring. Assumes dc is big enough. */
static void s_usqr(mp_digit *da, mp_digit *dc, mp_size size_a);
/* Single digit addition. Assumes a is big enough. */
static void s_dadd(mp_int a, mp_digit b);
/* Single digit multiplication. Assumes a is big enough. */
static void s_dmul(mp_int a, mp_digit b);
/* Single digit multiplication on buffers; assumes dc is big enough. */
static void s_dbmul(mp_digit *da, mp_digit b, mp_digit *dc, mp_size size_a);
/* Single digit division. Replaces a with the quotient,
returns the remainder. */
static mp_digit s_ddiv(mp_int a, mp_digit b);
/* Quick division by a power of 2, replaces z (no allocation) */
static void s_qdiv(mp_int z, mp_size p2);
/* Quick remainder by a power of 2, replaces z (no allocation) */
static void s_qmod(mp_int z, mp_size p2);
/* Quick multiplication by a power of 2, replaces z.
Allocates if necessary; returns false in case this fails. */
static int s_qmul(mp_int z, mp_size p2);
/* Quick subtraction from a power of 2, replaces z.
Allocates if necessary; returns false in case this fails. */
static int s_qsub(mp_int z, mp_size p2);
/* Return maximum k such that 2^k divides z. */
static int s_dp2k(mp_int z);
/* Return k >= 0 such that z = 2^k, or -1 if there is no such k. */
static int s_isp2(mp_int z);
/* Set z to 2^k. May allocate; returns false in case this fails. */
static int s_2expt(mp_int z, mp_small k);
/* Normalize a and b for division, returns normalization constant */
static int s_norm(mp_int a, mp_int b);
/* Compute constant mu for Barrett reduction, given modulus m, result
replaces z, m is untouched. */
static mp_result s_brmu(mp_int z, mp_int m);
/* Reduce a modulo m, using Barrett's algorithm. */
static int s_reduce(mp_int x, mp_int m, mp_int mu, mp_int q1, mp_int q2);
/* Modular exponentiation, using Barrett reduction */
static mp_result s_embar(mp_int a, mp_int b, mp_int m, mp_int mu, mp_int c);
/* Unsigned magnitude division. Assumes |a| > |b|. Allocates temporaries;
overwrites a with quotient, b with remainder. */
static mp_result s_udiv_knuth(mp_int a, mp_int b);
/* Compute the number of digits in radix r required to represent the given
value. Does not account for sign flags, terminators, etc. */
static int s_outlen(mp_int z, mp_size r);
/* Guess how many digits of precision will be needed to represent a radix r
value of the specified number of digits. Returns a value guaranteed to be
no smaller than the actual number required. */
static mp_size s_inlen(int len, mp_size r);
/* Convert a character to a digit value in radix r, or
-1 if out of range */
static int s_ch2val(char c, int r);
/* Convert a digit value to a character */
static char s_val2ch(int v, int caps);
/* Take 2's complement of a buffer in place */
static void s_2comp(unsigned char *buf, int len);
/* Convert a value to binary, ignoring sign. On input, *limpos is the bound on
how many bytes should be written to buf; on output, *limpos is set to the
number of bytes actually written. */
static mp_result s_tobin(mp_int z, unsigned char *buf, int *limpos, int pad);
/* Multiply X by Y into Z, ignoring signs. Requires that Z have enough storage
preallocated to hold the result. */
static inline void UMUL(mp_int X, mp_int Y, mp_int Z) {
mp_size ua_ = MP_USED(X);
mp_size ub_ = MP_USED(Y);
mp_size o_ = ua_ + ub_;
ZERO(MP_DIGITS(Z), o_);
(void)s_kmul(MP_DIGITS(X), MP_DIGITS(Y), MP_DIGITS(Z), ua_, ub_);
Z->used = o_;
CLAMP(Z);
}
/* Square X into Z. Requires that Z have enough storage to hold the result. */
static inline void USQR(mp_int X, mp_int Z) {
mp_size ua_ = MP_USED(X);
mp_size o_ = ua_ + ua_;
ZERO(MP_DIGITS(Z), o_);
(void)s_ksqr(MP_DIGITS(X), MP_DIGITS(Z), ua_);
Z->used = o_;
CLAMP(Z);
}
mp_result mp_int_init(mp_int z) {
if (z == NULL) return MP_BADARG;
z->single = 0;
z->digits = &(z->single);
z->alloc = 1;
z->used = 1;
z->sign = MP_ZPOS;
return MP_OK;
}
mp_int mp_int_alloc(void) {
mp_int out = malloc(sizeof(mpz_t));
if (out != NULL) mp_int_init(out);
return out;
}
mp_result mp_int_init_size(mp_int z, mp_size prec) {
assert(z != NULL);
if (prec == 0) {
prec = default_precision;
} else if (prec == 1) {
return mp_int_init(z);
} else {
prec = s_round_prec(prec);
}
z->digits = s_alloc(prec);
if (MP_DIGITS(z) == NULL) return MP_MEMORY;
z->digits[0] = 0;
z->used = 1;
z->alloc = prec;
z->sign = MP_ZPOS;
return MP_OK;
}
mp_result mp_int_init_copy(mp_int z, mp_int old) {
assert(z != NULL && old != NULL);
mp_size uold = MP_USED(old);
if (uold == 1) {
mp_int_init(z);
} else {
mp_size target = MAX(uold, default_precision);
mp_result res = mp_int_init_size(z, target);
if (res != MP_OK) return res;
}
z->used = uold;
z->sign = old->sign;
COPY(MP_DIGITS(old), MP_DIGITS(z), uold);
return MP_OK;
}
mp_result mp_int_init_value(mp_int z, mp_small value) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(value)];
s_fake(&vtmp, value, vbuf);
return mp_int_init_copy(z, &vtmp);
}
mp_result mp_int_init_uvalue(mp_int z, mp_usmall uvalue) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(uvalue)];
s_ufake(&vtmp, uvalue, vbuf);
return mp_int_init_copy(z, &vtmp);
}
mp_result mp_int_set_value(mp_int z, mp_small value) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(value)];
s_fake(&vtmp, value, vbuf);
return mp_int_copy(&vtmp, z);
}
mp_result mp_int_set_uvalue(mp_int z, mp_usmall uvalue) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(uvalue)];
s_ufake(&vtmp, uvalue, vbuf);
return mp_int_copy(&vtmp, z);
}
void mp_int_clear(mp_int z) {
if (z == NULL) return;
if (MP_DIGITS(z) != NULL) {
if (MP_DIGITS(z) != &(z->single)) s_free(MP_DIGITS(z));
z->digits = NULL;
}
}
void mp_int_free(mp_int z) {
assert(z != NULL);
mp_int_clear(z);
free(z); /* note: NOT s_free() */
}
mp_result mp_int_copy(mp_int a, mp_int c) {
assert(a != NULL && c != NULL);
if (a != c) {
mp_size ua = MP_USED(a);
mp_digit *da, *dc;
if (!s_pad(c, ua)) return MP_MEMORY;
da = MP_DIGITS(a);
dc = MP_DIGITS(c);
COPY(da, dc, ua);
c->used = ua;
c->sign = a->sign;
}
return MP_OK;
}
void mp_int_swap(mp_int a, mp_int c) {
if (a != c) {
mpz_t tmp = *a;
*a = *c;
*c = tmp;
if (MP_DIGITS(a) == &(c->single)) a->digits = &(a->single);
if (MP_DIGITS(c) == &(a->single)) c->digits = &(c->single);
}
}
void mp_int_zero(mp_int z) {
assert(z != NULL);
z->digits[0] = 0;
z->used = 1;
z->sign = MP_ZPOS;
}
mp_result mp_int_abs(mp_int a, mp_int c) {
assert(a != NULL && c != NULL);
mp_result res;
if ((res = mp_int_copy(a, c)) != MP_OK) return res;
c->sign = MP_ZPOS;
return MP_OK;
}
mp_result mp_int_neg(mp_int a, mp_int c) {
assert(a != NULL && c != NULL);
mp_result res;
if ((res = mp_int_copy(a, c)) != MP_OK) return res;
if (CMPZ(c) != 0) c->sign = 1 - MP_SIGN(a);
return MP_OK;
}
mp_result mp_int_add(mp_int a, mp_int b, mp_int c) {
assert(a != NULL && b != NULL && c != NULL);
mp_size ua = MP_USED(a);
mp_size ub = MP_USED(b);
mp_size max = MAX(ua, ub);
if (MP_SIGN(a) == MP_SIGN(b)) {
/* Same sign -- add magnitudes, preserve sign of addends */
if (!s_pad(c, max)) return MP_MEMORY;
mp_digit carry = s_uadd(MP_DIGITS(a), MP_DIGITS(b), MP_DIGITS(c), ua, ub);
mp_size uc = max;
if (carry) {
if (!s_pad(c, max + 1)) return MP_MEMORY;
c->digits[max] = carry;
++uc;
}
c->used = uc;
c->sign = a->sign;
} else {
/* Different signs -- subtract magnitudes, preserve sign of greater */
int cmp = s_ucmp(a, b); /* magnitude comparison, sign ignored */
/* Set x to max(a, b), y to min(a, b) to simplify later code.
A special case yields zero for equal magnitudes.
*/
mp_int x, y;
if (cmp == 0) {
mp_int_zero(c);
return MP_OK;
} else if (cmp < 0) {
x = b;
y = a;
} else {
x = a;
y = b;
}
if (!s_pad(c, MP_USED(x))) return MP_MEMORY;
/* Subtract smaller from larger */
s_usub(MP_DIGITS(x), MP_DIGITS(y), MP_DIGITS(c), MP_USED(x), MP_USED(y));
c->used = x->used;
CLAMP(c);
/* Give result the sign of the larger */
c->sign = x->sign;
}
return MP_OK;
}
mp_result mp_int_add_value(mp_int a, mp_small value, mp_int c) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(value)];
s_fake(&vtmp, value, vbuf);
return mp_int_add(a, &vtmp, c);
}
mp_result mp_int_sub(mp_int a, mp_int b, mp_int c) {
assert(a != NULL && b != NULL && c != NULL);
mp_size ua = MP_USED(a);
mp_size ub = MP_USED(b);
mp_size max = MAX(ua, ub);
if (MP_SIGN(a) != MP_SIGN(b)) {
/* Different signs -- add magnitudes and keep sign of a */
if (!s_pad(c, max)) return MP_MEMORY;
mp_digit carry = s_uadd(MP_DIGITS(a), MP_DIGITS(b), MP_DIGITS(c), ua, ub);
mp_size uc = max;
if (carry) {
if (!s_pad(c, max + 1)) return MP_MEMORY;
c->digits[max] = carry;
++uc;
}
c->used = uc;
c->sign = a->sign;
} else {
/* Same signs -- subtract magnitudes */
if (!s_pad(c, max)) return MP_MEMORY;
mp_int x, y;
mp_sign osign;
int cmp = s_ucmp(a, b);
if (cmp >= 0) {
x = a;
y = b;
osign = MP_ZPOS;
} else {
x = b;
y = a;
osign = MP_NEG;
}
if (MP_SIGN(a) == MP_NEG && cmp != 0) osign = 1 - osign;
s_usub(MP_DIGITS(x), MP_DIGITS(y), MP_DIGITS(c), MP_USED(x), MP_USED(y));
c->used = x->used;
CLAMP(c);
c->sign = osign;
}
return MP_OK;
}
mp_result mp_int_sub_value(mp_int a, mp_small value, mp_int c) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(value)];
s_fake(&vtmp, value, vbuf);
return mp_int_sub(a, &vtmp, c);
}
mp_result mp_int_mul(mp_int a, mp_int b, mp_int c) {
assert(a != NULL && b != NULL && c != NULL);
/* If either input is zero, we can shortcut multiplication */
if (mp_int_compare_zero(a) == 0 || mp_int_compare_zero(b) == 0) {
mp_int_zero(c);
return MP_OK;
}
/* Output is positive if inputs have same sign, otherwise negative */
mp_sign osign = (MP_SIGN(a) == MP_SIGN(b)) ? MP_ZPOS : MP_NEG;
/* If the output is not identical to any of the inputs, we'll write the
results directly; otherwise, allocate a temporary space. */
mp_size ua = MP_USED(a);
mp_size ub = MP_USED(b);
mp_size osize = MAX(ua, ub);
osize = 4 * ((osize + 1) / 2);
mp_digit *out;
mp_size p = 0;
if (c == a || c == b) {
p = MAX(s_round_prec(osize), default_precision);
if ((out = s_alloc(p)) == NULL) return MP_MEMORY;
} else {
if (!s_pad(c, osize)) return MP_MEMORY;
out = MP_DIGITS(c);
}
ZERO(out, osize);
if (!s_kmul(MP_DIGITS(a), MP_DIGITS(b), out, ua, ub)) return MP_MEMORY;
/* If we allocated a new buffer, get rid of whatever memory c was already
using, and fix up its fields to reflect that.
*/
if (out != MP_DIGITS(c)) {
if ((void *)MP_DIGITS(c) != (void *)c) s_free(MP_DIGITS(c));
c->digits = out;
c->alloc = p;
}
c->used = osize; /* might not be true, but we'll fix it ... */
CLAMP(c); /* ... right here */
c->sign = osign;
return MP_OK;
}
mp_result mp_int_mul_value(mp_int a, mp_small value, mp_int c) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(value)];
s_fake(&vtmp, value, vbuf);
return mp_int_mul(a, &vtmp, c);
}
mp_result mp_int_mul_pow2(mp_int a, mp_small p2, mp_int c) {
assert(a != NULL && c != NULL && p2 >= 0);
mp_result res = mp_int_copy(a, c);
if (res != MP_OK) return res;
if (s_qmul(c, (mp_size)p2)) {
return MP_OK;
} else {
return MP_MEMORY;
}
}
mp_result mp_int_sqr(mp_int a, mp_int c) {
assert(a != NULL && c != NULL);
/* Get a temporary buffer big enough to hold the result */
mp_size osize = (mp_size)4 * ((MP_USED(a) + 1) / 2);
mp_size p = 0;
mp_digit *out;
if (a == c) {
p = s_round_prec(osize);
p = MAX(p, default_precision);
if ((out = s_alloc(p)) == NULL) return MP_MEMORY;
} else {
if (!s_pad(c, osize)) return MP_MEMORY;
out = MP_DIGITS(c);
}
ZERO(out, osize);
s_ksqr(MP_DIGITS(a), out, MP_USED(a));
/* Get rid of whatever memory c was already using, and fix up its fields to
reflect the new digit array it's using
*/
if (out != MP_DIGITS(c)) {
if ((void *)MP_DIGITS(c) != (void *)c) s_free(MP_DIGITS(c));
c->digits = out;
c->alloc = p;
}
c->used = osize; /* might not be true, but we'll fix it ... */
CLAMP(c); /* ... right here */
c->sign = MP_ZPOS;
return MP_OK;
}
mp_result mp_int_div(mp_int a, mp_int b, mp_int q, mp_int r) {
assert(a != NULL && b != NULL && q != r);
int cmp;
mp_result res = MP_OK;
mp_int qout, rout;
mp_sign sa = MP_SIGN(a);
mp_sign sb = MP_SIGN(b);
if (CMPZ(b) == 0) {
return MP_UNDEF;
} else if ((cmp = s_ucmp(a, b)) < 0) {
/* If |a| < |b|, no division is required:
q = 0, r = a
*/
if (r && (res = mp_int_copy(a, r)) != MP_OK) return res;
if (q) mp_int_zero(q);
return MP_OK;
} else if (cmp == 0) {
/* If |a| = |b|, no division is required:
q = 1 or -1, r = 0
*/
if (r) mp_int_zero(r);
if (q) {
mp_int_zero(q);
q->digits[0] = 1;
if (sa != sb) q->sign = MP_NEG;
}
return MP_OK;
}
/* When |a| > |b|, real division is required. We need someplace to store
quotient and remainder, but q and r are allowed to be NULL or to overlap
with the inputs.
*/
DECLARE_TEMP(2);
int lg;
if ((lg = s_isp2(b)) < 0) {
if (q && b != q) {
REQUIRE(mp_int_copy(a, q));
qout = q;
} else {
REQUIRE(mp_int_copy(a, TEMP(0)));
qout = TEMP(0);
}
if (r && a != r) {
REQUIRE(mp_int_copy(b, r));
rout = r;
} else {
REQUIRE(mp_int_copy(b, TEMP(1)));
rout = TEMP(1);
}
REQUIRE(s_udiv_knuth(qout, rout));
} else {
if (q) REQUIRE(mp_int_copy(a, q));
if (r) REQUIRE(mp_int_copy(a, r));
if (q) s_qdiv(q, (mp_size)lg);
qout = q;
if (r) s_qmod(r, (mp_size)lg);
rout = r;
}
/* Recompute signs for output */
if (rout) {
rout->sign = sa;
if (CMPZ(rout) == 0) rout->sign = MP_ZPOS;
}
if (qout) {
qout->sign = (sa == sb) ? MP_ZPOS : MP_NEG;
if (CMPZ(qout) == 0) qout->sign = MP_ZPOS;
}
if (q) REQUIRE(mp_int_copy(qout, q));
if (r) REQUIRE(mp_int_copy(rout, r));
CLEANUP_TEMP();
return res;
}
mp_result mp_int_mod(mp_int a, mp_int m, mp_int c) {
DECLARE_TEMP(1);
mp_int out = (m == c) ? TEMP(0) : c;
REQUIRE(mp_int_div(a, m, NULL, out));
if (CMPZ(out) < 0) {
REQUIRE(mp_int_add(out, m, c));
} else {
REQUIRE(mp_int_copy(out, c));
}
CLEANUP_TEMP();
return MP_OK;
}
mp_result mp_int_div_value(mp_int a, mp_small value, mp_int q, mp_small *r) {
mpz_t vtmp;
mp_digit vbuf[MP_VALUE_DIGITS(value)];
s_fake(&vtmp, value, vbuf);
DECLARE_TEMP(1);
REQUIRE(mp_int_div(a, &vtmp, q, TEMP(0)));
if (r) (void)mp_int_to_int(TEMP(0), r); /* can't fail */
CLEANUP_TEMP();
return MP_OK;
}
mp_result mp_int_div_pow2(mp_int a, mp_small p2, mp_int q, mp_int r) {
assert(a != NULL && p2 >= 0 && q != r);
mp_result res = MP_OK;
if (q != NULL && (res = mp_int_copy(a, q)) == MP_OK) {
s_qdiv(q, (mp_size)p2);
}
if (res == MP_OK && r != NULL && (res = mp_int_copy(a, r)) == MP_OK) {
s_qmod(r, (mp_size)p2);
}
return res;
}
mp_result mp_int_expt(mp_int a, mp_small b, mp_int c) {
assert(c != NULL);
if (b < 0) return MP_RANGE;
DECLARE_TEMP(1);
REQUIRE(mp_int_copy(a, TEMP(0)));
(void)mp_int_set_value(c, 1);
unsigned int v = labs(b);
while (v != 0) {
if (v & 1) {
REQUIRE(mp_int_mul(c, TEMP(0), c));
}
v >>= 1;
if (v == 0) break;
REQUIRE(mp_int_sqr(TEMP(0), TEMP(0)));
}
CLEANUP_TEMP();
return MP_OK;
}
mp_result mp_int_expt_value(mp_small a, mp_small b, mp_int c) {
assert(c != NULL);
if (b < 0) return MP_RANGE;
DECLARE_TEMP(1);
REQUIRE(mp_int_set_value(TEMP(0), a));
(void)mp_int_set_value(c, 1);
unsigned int v = labs(b);
while (v != 0) {
if (v & 1) {
REQUIRE(mp_int_mul(c, TEMP(0), c));
}
v >>= 1;
if (v == 0) break;
REQUIRE(mp_int_sqr(TEMP(0), TEMP(0)));
}
CLEANUP_TEMP();
return MP_OK;
}
mp_result mp_int_expt_full(mp_int a, mp_int b, mp_int c) {
assert(a != NULL && b != NULL && c != NULL);
if (MP_SIGN(b) == MP_NEG) return MP_RANGE;
DECLARE_TEMP(1);
REQUIRE(mp_int_copy(a, TEMP(0)));
(void)mp_int_set_value(c, 1);
for (unsigned ix = 0; ix < MP_USED(b); ++ix) {
mp_digit d = b->digits[ix];
for (unsigned jx = 0; jx < MP_DIGIT_BIT; ++jx) {
if (d & 1) {
REQUIRE(mp_int_mul(c, TEMP(0), c));
}
d >>= 1;
if (d == 0 && ix + 1 == MP_USED(b)) break;
REQUIRE(mp_int_sqr(TEMP(0), TEMP(0)));
}
}
CLEANUP_TEMP();
return MP_OK;
}
int mp_int_compare(mp_int a, mp_int b) {
assert(a != NULL && b != NULL);
mp_sign sa = MP_SIGN(a);
if (sa == MP_SIGN(b)) {
int cmp = s_ucmp(a, b);
/* If they're both zero or positive, the normal comparison applies; if both
negative, the sense is reversed. */
if (sa == MP_ZPOS) {
return cmp;
} else {
return -cmp;
}
} else if (sa == MP_ZPOS) {
return 1;
} else {
return -1;
}
}
int mp_int_compare_unsigned(mp_int a, mp_int b) {
assert(a != NULL && b != NULL);