chiark / gitweb /
Add some simple bitwise operations so that Perl can use them.
[catacomb] / mp-arith.c
1 /* -*-c-*-
2  *
3  * $Id: mp-arith.c,v 1.10 2001/04/03 19:36:05 mdw Exp $
4  *
5  * Basic arithmetic on multiprecision integers
6  *
7  * (c) 1999 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of Catacomb.
13  *
14  * Catacomb is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  * 
19  * Catacomb is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  * 
24  * You should have received a copy of the GNU Library General Public
25  * License along with Catacomb; if not, write to the Free
26  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27  * MA 02111-1307, USA.
28  */
29
30 /*----- Revision history --------------------------------------------------* 
31  *
32  * $Log: mp-arith.c,v $
33  * Revision 1.10  2001/04/03 19:36:05  mdw
34  * Add some simple bitwise operations so that Perl can use them.
35  *
36  * Revision 1.9  2000/10/08 15:48:35  mdw
37  * Rename Karatsuba constants now that we have @gfx_kmul@ too.
38  *
39  * Revision 1.8  2000/10/08 12:02:21  mdw
40  * Use @MP_EQ@ instead of @MP_CMP@.
41  *
42  * Revision 1.7  2000/06/22 19:02:53  mdw
43  * New function @mp_odd@ to extract powers of two from an integer.  This is
44  * common code from the Rabin-Miller test, RSA key recovery and modular
45  * square-root extraction.
46  *
47  * Revision 1.6  2000/06/17 11:45:09  mdw
48  * Major memory management overhaul.  Added arena support.  Use the secure
49  * arena for secret integers.  Replace and improve the MP management macros
50  * (e.g., replace MP_MODIFY by MP_DEST).
51  *
52  * Revision 1.5  1999/12/22 15:54:41  mdw
53  * Adjust Karatsuba parameters.  Calculate destination size better.
54  *
55  * Revision 1.4  1999/12/13 15:35:16  mdw
56  * Slightly different rules on memory allocation.
57  *
58  * Revision 1.3  1999/12/11 10:57:43  mdw
59  * Karatsuba squaring algorithm.
60  *
61  * Revision 1.2  1999/12/10 23:18:39  mdw
62  * Change interface for suggested destinations.
63  *
64  * Revision 1.1  1999/11/17 18:02:16  mdw
65  * New multiprecision integer arithmetic suite.
66  *
67  */
68
69 /*----- Header files ------------------------------------------------------*/
70
71 #include "mp.h"
72
73 /*----- Macros ------------------------------------------------------------*/
74
75 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
76
77 /*----- Main code ---------------------------------------------------------*/
78
79 /* --- @mp_2c@ --- *
80  *
81  * Arguments:   @mp *a@ = source
82  *
83  * Returns:     Result, @a@ converted to two's complement notation.
84  */
85
86 mp *mp_2c(mp *d, mp *a)
87 {
88   if (!(a->f & MP_NEG))
89     return (MP_COPY(a));
90
91   MP_DEST(d, MP_LEN(a), a->f);
92   mpx_2c(d->v, d->vl, a->v, a->vl);
93   d->f = a->f & MP_BURN;
94   MP_SHRINK(d);
95   return (d);
96 }
97
98 /* --- @mp_sm@ --- *
99  *
100  * Arguments:   @mp *d@ = destination
101  *              @mp *a@ = source
102  *
103  * Returns:     Result, @a@ converted to the native signed-magnitude
104  *              notation.
105  */
106
107 mp *mp_sm(mp *d, mp *a)
108 {
109   if (!MP_LEN(a) || a->vl[-1] < MPW_MAX / 2)
110     return (MP_COPY(a));
111
112   MP_DEST(d, MP_LEN(a), a->f);
113   mpx_2c(d->v, d->vl, a->v, a->vl);
114   d->f = (a->f & (MP_BURN | MP_NEG)) ^ MP_NEG;
115   MP_SHRINK(d);
116   return (d);  
117 }
118
119 /* --- @mp_lsl@ --- *
120  *
121  * Arguments:   @mp *d@ = destination
122  *              @mp *a@ = source
123  *              @size_t n@ = number of bits to move
124  *
125  * Returns:     Result, @a@ shifted left by @n@.
126  */
127
128 mp *mp_lsl(mp *d, mp *a, size_t n)
129 {
130   MP_DEST(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS, a->f);
131   mpx_lsl(d->v, d->vl, a->v, a->vl, n);
132   d->f = a->f & (MP_NEG | MP_BURN);
133   MP_SHRINK(d);
134   return (d);
135 }
136
137 /* --- @mp_lsr@ --- *
138  *
139  * Arguments:   @mp *d@ = destination
140  *              @mp *a@ = source
141  *              @size_t n@ = number of bits to move
142  *
143  * Returns:     Result, @a@ shifted left by @n@.
144  */
145
146 mp *mp_lsr(mp *d, mp *a, size_t n)
147 {
148   MP_DEST(d, MP_LEN(a), a->f);
149   mpx_lsr(d->v, d->vl, a->v, a->vl, n);
150   d->f = a->f & (MP_NEG | MP_BURN);
151   MP_SHRINK(d);
152   return (d);
153 }
154
155 /* --- @mp_eq@ --- *
156  *
157  * Arguments:   @const mp *a, *b@ = two numbers
158  *
159  * Returns:     Nonzero if the numbers are equal.
160  */
161
162 int mp_eq(const mp *a, const mp *b) { return (MP_EQ(a, b)); }
163
164 /* --- @mp_cmp@ --- *
165  *
166  * Arguments:   @const mp *a, *b@ = two numbers
167  *
168  * Returns:     Less than, equal to or greater than zero, according to
169  *              whether @a@ is less than, equal to or greater than @b@.
170  */
171
172 int mp_cmp(const mp *a, const mp *b)
173 {
174   if (!((a->f ^ b->f) & MP_NEG))
175     return (mpx_ucmp(a->v, a->vl, b->v, b->vl));
176   else if (a->f & MP_NEG)
177     return (-1);
178   else
179     return (+1);
180 }
181
182 /* --- @mpx_and@, @mpx_or@, @mpx_xor@, @mpx_not@ --- *
183  *
184  * Arguments:   @mp *d@ = destination
185  *              @mp *a, *b@ = sources
186  *
187  * Returns:     The result of the obvious bitwise operation.
188  */
189
190 #define MP_BITBINOP(name)                                               \
191                                                                         \
192 mp *mp_##name(mp *d, mp *a, mp *b)                                      \
193 {                                                                       \
194   MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)), a->f | b->f);                   \
195   mpx_##name(d->v, d->vl, a->v, a->vl, b->v, b->vl);                    \
196   d->f = (a->f | b->f) & MP_BURN;                                       \
197   MP_SHRINK(d);                                                         \
198   return (d);                                                           \
199 }
200
201 MP_BITBINOP(and)
202 MP_BITBINOP(or)
203 MP_BITBINOP(xor)
204
205 mp *mp_not(mp *d, mp *a)
206 {
207   MP_DEST(d, MP_LEN(a), a->f);
208   mpx_not(d->v, d->vl, a->v, a->vl);
209   d->f = a->f & MP_BURN;
210   MP_SHRINK(d);
211   return (d);
212 }
213
214 /* --- @mp_add@ --- *
215  *
216  * Arguments:   @mp *d@ = destination
217  *              @mp *a, *b@ = sources
218  *
219  * Returns:     Result, @a@ added to @b@.
220  */
221
222 mp *mp_add(mp *d, mp *a, mp *b)
223 {
224   MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
225   if (!((a->f ^ b->f) & MP_NEG))
226     mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
227   else {
228     if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
229       mp *t = a; a = b; b = t;
230     }
231     mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
232   }
233   d->f = ((a->f | b->f) & MP_BURN) | (a->f & MP_NEG);
234   MP_SHRINK(d);
235   return (d);
236 }
237
238 /* --- @mp_sub@ --- *
239  *
240  * Arguments:   @mp *d@ = destination
241  *              @mp *a, *b@ = sources
242  *
243  * Returns:     Result, @b@ subtracted from @a@.
244  */
245
246 mp *mp_sub(mp *d, mp *a, mp *b)
247 {
248   unsigned sgn = 0;
249   MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
250   if ((a->f ^ b->f) & MP_NEG)
251     mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
252   else {
253     if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
254       mp *t = a; a = b; b = t;
255       sgn = MP_NEG;
256     }
257     mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
258   }
259   d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ sgn) & MP_NEG);
260   MP_SHRINK(d);
261   return (d);
262 }
263
264 /* --- @mp_mul@ --- *
265  *
266  * Arguments:   @mp *d@ = destination
267  *              @mp *a, *b@ = sources
268  *
269  * Returns:     Result, @a@ multiplied by @b@.
270  */
271
272 mp *mp_mul(mp *d, mp *a, mp *b)
273 {
274   a = MP_COPY(a);
275   b = MP_COPY(b);
276
277   if (MP_LEN(a) <= MPK_THRESH || MP_LEN(b) <= MPK_THRESH) {
278     MP_DEST(d, MP_LEN(a) + MP_LEN(b), a->f | b->f | MP_UNDEF);
279     mpx_umul(d->v, d->vl, a->v, a->vl, b->v, b->vl);
280   } else {
281     size_t m = 2 * MAX(MP_LEN(a), MP_LEN(b)) + 2;
282     mpw *s;
283     MP_DEST(d, m, a->f | b->f | MP_UNDEF);
284     m += MPK_SLOP;
285     s = mpalloc(d->a, m);
286     mpx_kmul(d->v, d->vl, a->v, a->vl, b->v, b->vl, s, s + m);
287     mpfree(d->a, s);
288   }
289
290   d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
291   MP_SHRINK(d);
292   MP_DROP(a);
293   MP_DROP(b);
294   return (d);
295 }
296
297 /* --- @mp_sqr@ --- *
298  *
299  * Arguments:   @mp *d@ = destination
300  *              @mp *a@ = source
301  *
302  * Returns:     Result, @a@ squared.
303  */
304
305 mp *mp_sqr(mp *d, mp *a)
306 {
307   size_t m = MP_LEN(a);
308
309   a = MP_COPY(a);
310   MP_DEST(d, 2 * m + 2, a->f | MP_UNDEF);
311   if (m > MPK_THRESH) {
312     mpw *s;
313     m = 2 * (m + 1) + MPK_SLOP;
314     s = mpalloc(d->a, m);
315     mpx_ksqr(d->v, d->vl, a->v, a->vl, s, s + m);
316     mpfree(d->a, s);
317   } else 
318     mpx_usqr(d->v, d->vl, a->v, a->vl);
319   d->f = a->f & MP_BURN;
320   MP_SHRINK(d);
321   MP_DROP(a);
322   return (d);
323 }
324
325 /* --- @mp_div@ --- *
326  *
327  * Arguments:   @mp **qq, **rr@ = destination, quotient and remainder
328  *              @mp *a, *b@ = sources
329  *
330  * Use:         Calculates the quotient and remainder when @a@ is divided by
331  *              @b@.  The destinations @*qq@ and @*rr@ must be distinct.
332  *              Either of @qq@ or @rr@ may be null to indicate that the
333  *              result is irrelevant.  (Discarding both results is silly.)
334  *              There is a performance advantage if @a == *rr@.
335  *
336  *              The behaviour when @a@ and @b@ have the same sign is
337  *              straightforward.  When the signs differ, this implementation
338  *              chooses @r@ to have the same sign as @b@, rather than the
339  *              more normal choice that the remainder has the same sign as
340  *              the dividend.  This makes modular arithmetic a little more
341  *              straightforward.
342  */
343
344 void mp_div(mp **qq, mp **rr, mp *a, mp *b)
345  {
346   mp *r = rr ? *rr : MP_NEW;
347   mp *q = qq ? *qq : MP_NEW;
348   mpw *sv, *svl;
349
350   /* --- Set the remainder up right --- *
351    *
352    * Just in case the divisor is larger, be able to cope with this.  It's not
353    * important in @mpx_udiv@, but it is here because of the sign correction.
354    */
355
356   b = MP_COPY(b);
357   a = MP_COPY(a);
358   if (r)
359     MP_DROP(r);
360   r = a;
361   MP_DEST(r, MP_LEN(a) + 2, a->f | b->f);
362
363   /* --- Fix up the quotient too --- */
364
365   r = MP_COPY(r);
366   MP_DEST(q, MP_LEN(r), r->f | MP_UNDEF);
367   MP_DROP(r);
368
369   /* --- Set up some temporary workspace --- */
370
371   {
372     size_t rq = MP_LEN(b) + 1;
373     sv = mpalloc(r->a, rq);
374     svl = sv + rq;
375   }
376
377   /* --- Perform the calculation --- */
378
379   mpx_udiv(q->v, q->vl, r->v, r->vl, b->v, b->vl, sv, svl);
380
381   /* --- Sort out the sign of the results --- *
382    *
383    * If the signs of the arguments differ, and the remainder is nonzero, I
384    * must add one to the absolute value of the quotient and subtract the
385    * remainder from @b@.
386    */
387
388   q->f = ((r->f | b->f) & MP_BURN) | ((r->f ^ b->f) & MP_NEG);
389   if (q->f & MP_NEG) {
390     mpw *v;
391     for (v = r->v; v < r->vl; v++) {
392       if (*v) {
393         MPX_UADDN(q->v, q->vl, 1);
394         mpx_usub(r->v, r->vl, b->v, b->vl, r->v, r->vl);
395         break;
396       }
397     }
398   }
399
400   r->f = ((r->f | b->f) & MP_BURN) | (b->f & MP_NEG);
401
402   /* --- Store the return values --- */
403
404   mpfree(r->a, sv);
405   MP_DROP(b);
406
407   if (!qq)
408     MP_DROP(q);
409   else {
410     MP_SHRINK(q);
411     *qq = q;
412   }
413
414   if (!rr)
415     MP_DROP(r);
416   else {
417     MP_SHRINK(r);
418     *rr = r;
419   }
420 }
421
422 /* --- @mp_odd@ --- *
423  *
424  * Arguments:   @mp *d@ = pointer to destination integer
425  *              @mp *m@ = pointer to source integer
426  *              @size_t *s@ = where to store the power of 2
427  *
428  * Returns:     An odd integer integer %$t$% such that %$m = 2^s t$%.
429  *
430  * Use:         Computes a power of two and an odd integer which, when
431  *              multiplied, give a specified result.  This sort of thing is
432  *              useful in number theory quite often.
433  */
434
435 mp *mp_odd(mp *d, mp *m, size_t *s)
436 {
437   size_t ss = 0;
438   const mpw *v, *vl;
439
440   v = m->v;
441   vl = m->vl;
442   for (; !*v && v < vl; v++)
443     ss += MPW_BITS;
444   if (v >= vl)
445     ss = 0;
446   else {
447     mpw x = *v;
448     mpw mask = MPW_MAX;
449     unsigned z = MPW_BITS / 2;
450
451     while (z) {
452       mask >>= z;
453       if (!(x & mask)) {
454         x >>= z;
455         ss += z;
456       }
457       z >>= 1;
458     }
459   }
460
461   *s = ss;
462   return (mp_lsr(d, m, ss));
463 }
464
465 /*----- Test rig ----------------------------------------------------------*/
466
467 #ifdef TEST_RIG
468
469 static int verify(const char *op, mp *expect, mp *result, mp *a, mp *b)
470 {
471   if (!MP_EQ(expect, result)) {
472     fprintf(stderr, "\n*** %s failed", op);
473     fputs("\n*** a      = ", stderr); mp_writefile(a, stderr, 10);
474     fputs("\n*** b      = ", stderr); mp_writefile(b, stderr, 10);
475     fputs("\n*** result = ", stderr); mp_writefile(result, stderr, 10);
476     fputs("\n*** expect = ", stderr); mp_writefile(expect, stderr, 10);
477     fputc('\n', stderr);
478     return (0);
479   }
480   return (1);
481 }
482
483 #define RIG(name, op)                                                   \
484   static int t##name(dstr *v)                                           \
485   {                                                                     \
486     mp *a = *(mp **)v[0].buf;                                           \
487     mpw n = *(int *)v[1].buf;                                           \
488     mp b;                                                               \
489     mp *r = *(mp **)v[2].buf;                                           \
490     mp *c = op(MP_NEW, a, n);                                           \
491     int ok;                                                             \
492     mp_build(&b, &n, &n + 1);                                           \
493     ok = verify(#name, r, c, a, &b);                                    \
494     mp_drop(a); mp_drop(c); mp_drop(r);                                 \
495     assert(mparena_count(MPARENA_GLOBAL) == 0);                         \
496     return (ok);                                                        \
497   }
498
499 RIG(lsl, mp_lsl)
500 RIG(lsr, mp_lsr)
501
502 #undef RIG
503
504 #define RIG(name, op)                                                   \
505   static int t##name(dstr *v)                                           \
506   {                                                                     \
507     mp *a = *(mp **)v[0].buf;                                           \
508     mp *b = *(mp **)v[1].buf;                                           \
509     mp *r = *(mp **)v[2].buf;                                           \
510     mp *c = op(MP_NEW, a, b);                                           \
511     int ok = verify(#name, r, c, a, b);                                 \
512     mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r);                     \
513     assert(mparena_count(MPARENA_GLOBAL) == 0);                         \
514     return (ok);                                                        \
515   }
516
517 RIG(add, mp_add)
518 RIG(sub, mp_sub)
519 RIG(mul, mp_mul)
520
521 #undef RIG
522
523 static int tdiv(dstr *v)
524 {
525   mp *a = *(mp **)v[0].buf;
526   mp *b = *(mp **)v[1].buf;
527   mp *q = *(mp **)v[2].buf;
528   mp *r = *(mp **)v[3].buf;
529   mp *c = MP_NEW, *d = MP_NEW;
530   int ok = 1;
531   mp_div(&c, &d, a, b);
532   ok &= verify("div(quotient)", q, c, a, b);
533   ok &= verify("div(remainder)", r, d, a, b);
534   mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(d); mp_drop(r); mp_drop(q);
535   assert(mparena_count(MPARENA_GLOBAL) == 0);
536   return (ok);
537 }
538
539 static int todd(dstr *v)
540 {
541   mp *a = *(mp **)v[0].buf;
542   size_t rs = *(uint32 *)v[1].buf;
543   mp *rt = *(mp **)v[2].buf;
544   int ok = 1;
545   mp *t;
546   size_t s;
547   t = mp_odd(MP_NEW, a, &s);
548   if (s != rs || !MP_EQ(t, rt)) {
549     ok = 0;
550     fprintf(stderr, "\n*** odd failed");
551     fputs("\n*** a  = ", stderr); mp_writefile(a, stderr, 10);
552     fprintf(stderr, "\n*** s  = %lu", (unsigned long)s);
553     fputs("\n*** t  = ", stderr); mp_writefile(t, stderr, 10);
554     fprintf(stderr, "\n*** rs = %lu", (unsigned long)rs);
555     fputs("\n*** rt = ", stderr); mp_writefile(rt, stderr, 10);
556     fputc('\n', stderr);
557   }
558   mp_drop(a);
559   mp_drop(rt);
560   mp_drop(t);
561   return (ok);
562 }
563
564 static test_chunk tests[] = {
565   { "lsl", tlsl, { &type_mp, &type_mp, &type_mp, 0 } },
566   { "lsr", tlsr, { &type_mp, &type_mp, &type_mp, 0 } },
567   { "add", tadd, { &type_mp, &type_mp, &type_mp, 0 } },
568   { "sub", tsub, { &type_mp, &type_mp, &type_mp, 0 } },
569   { "mul", tmul, { &type_mp, &type_mp, &type_mp, 0 } },
570   { "div", tdiv, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
571   { "odd", todd, { &type_mp, &type_uint32, &type_mp, 0 } },
572   { 0, 0, { 0 } },
573 };
574
575 int main(int argc, char *argv[])
576 {
577   sub_init();
578   test_run(argc, argv, tests, SRCDIR "/tests/mp");
579   return (0);
580 }
581
582 #endif
583
584 /*----- That's all, folks -------------------------------------------------*/