chiark / gitweb /
Fix bug dividing small things by large ones.
[catacomb] / mp-arith.c
1 /* -*-c-*-
2  *
3  * $Id: mp-arith.c,v 1.16.2.1 2003/06/10 13:21:10 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.16.2.1  2003/06/10 13:21:10  mdw
34  * Fix bug dividing small things by large ones.
35  *
36  * Revision 1.16  2003/05/16 09:09:24  mdw
37  * Fix @mp_lsl2c@.  Turns out to be surprisingly tricky.
38  *
39  * Revision 1.15  2002/10/19 17:56:50  mdw
40  * Fix bit operations.  Test them (a bit) better.
41  *
42  * Revision 1.14  2002/10/15 19:18:31  mdw
43  * New operation to negate numbers.
44  *
45  * Revision 1.13  2002/10/15 00:19:40  mdw
46  * Bit setting and clearing functions.
47  *
48  * Revision 1.12  2002/10/09 00:36:03  mdw
49  * Fix bounds on workspace for Karatsuba operations.
50  *
51  * Revision 1.11  2002/10/06 22:52:50  mdw
52  * Pile of changes for supporting two's complement properly.
53  *
54  * Revision 1.10  2001/04/03 19:36:05  mdw
55  * Add some simple bitwise operations so that Perl can use them.
56  *
57  * Revision 1.9  2000/10/08 15:48:35  mdw
58  * Rename Karatsuba constants now that we have @gfx_kmul@ too.
59  *
60  * Revision 1.8  2000/10/08 12:02:21  mdw
61  * Use @MP_EQ@ instead of @MP_CMP@.
62  *
63  * Revision 1.7  2000/06/22 19:02:53  mdw
64  * New function @mp_odd@ to extract powers of two from an integer.  This is
65  * common code from the Rabin-Miller test, RSA key recovery and modular
66  * square-root extraction.
67  *
68  * Revision 1.6  2000/06/17 11:45:09  mdw
69  * Major memory management overhaul.  Added arena support.  Use the secure
70  * arena for secret integers.  Replace and improve the MP management macros
71  * (e.g., replace MP_MODIFY by MP_DEST).
72  *
73  * Revision 1.5  1999/12/22 15:54:41  mdw
74  * Adjust Karatsuba parameters.  Calculate destination size better.
75  *
76  * Revision 1.4  1999/12/13 15:35:16  mdw
77  * Slightly different rules on memory allocation.
78  *
79  * Revision 1.3  1999/12/11 10:57:43  mdw
80  * Karatsuba squaring algorithm.
81  *
82  * Revision 1.2  1999/12/10 23:18:39  mdw
83  * Change interface for suggested destinations.
84  *
85  * Revision 1.1  1999/11/17 18:02:16  mdw
86  * New multiprecision integer arithmetic suite.
87  *
88  */
89
90 /*----- Header files ------------------------------------------------------*/
91
92 #include "mp.h"
93
94 /*----- Macros ------------------------------------------------------------*/
95
96 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
97
98 /*----- Main code ---------------------------------------------------------*/
99
100 /* --- @mp_lsl@, @mp_lslc@, @mp_lsr@ --- *
101  *
102  * Arguments:   @mp *d@ = destination
103  *              @mp *a@ = source
104  *              @size_t n@ = number of bits to move
105  *
106  * Returns:     Result, @a@ shifted left or right by @n@.
107  *
108  * Use:         Bitwise shift operators.  @mp_lslc@ fills the bits introduced
109  *              on the right with ones instead of zeroes: it's used
110  *              internally by @mp_lsl2c@, though it may be useful on its
111  *              own.
112  */
113
114 mp *mp_lsl(mp *d, mp *a, size_t n)
115 {
116   MP_DEST(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS, a->f);
117   mpx_lsl(d->v, d->vl, a->v, a->vl, n);
118   d->f = a->f & (MP_NEG | MP_BURN);
119   MP_SHRINK(d);
120   return (d);
121 }
122
123 mp *mp_lslc(mp *d, mp *a, size_t n)
124 {
125   MP_DEST(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS, a->f);
126   mpx_lslc(d->v, d->vl, a->v, a->vl, n);
127   d->f = a->f & (MP_NEG | MP_BURN);
128   MP_SHRINK(d);
129   return (d);
130 }
131
132 mp *mp_lsr(mp *d, mp *a, size_t n)
133 {
134   MP_DEST(d, MP_LEN(a), a->f);
135   mpx_lsr(d->v, d->vl, a->v, a->vl, n);
136   d->f = a->f & (MP_NEG | MP_BURN);
137   MP_SHRINK(d);
138   return (d);
139 }
140
141 /* --- @mp_lsl2c@, @mp_lsr2c@ --- *
142  *
143  * Arguments:   @mp *d@ = destination
144  *              @mp *a@ = source
145  *              @size_t n@ = number of bits to move
146  *
147  * Returns:     Result, @a@ shifted left or right by @n@.  Handles the
148  *              pretence of sign-extension for negative numbers.
149  */
150
151 mp *mp_lsl2c(mp *d, mp *a, size_t n)
152 {
153   if (!(a->f & MP_NEG))
154     return (mp_lsl(d, a, n));
155   d = mp_not2c(d, a);
156   d = mp_lslc(d, d, n);
157   d = mp_not2c(d, d);
158   return (d);
159 }
160
161 mp *mp_lsr2c(mp *d, mp *a, size_t n)
162 {
163   if (!(a->f & MP_NEG))
164     return (mp_lsr(d, a, n));
165   d = mp_not2c(d, a);
166   d = mp_lsr(d, d, n);
167   d = mp_not2c(d, d);
168   return (d);
169 }
170
171 /* --- @mp_testbit@ --- *
172  *
173  * Arguments:   @mp *x@ = a large integer
174  *              @unsigned long n@ = which bit to test
175  *
176  * Returns:     Nonzero if the bit is set, zero if not.
177  */
178
179 int mp_testbit(mp *x, unsigned long n)
180 {
181   if (n > MPW_BITS * MP_LEN(x))
182     return (0);
183   return ((x->v[n/MPW_BITS] >> n%MPW_BITS) & 1u);
184 }
185
186 /* --- @mp_testbit2c@ --- *
187  *
188  * Arguments:   @mp *x@ = a large integer
189  *              @unsigned long n@ = which bit to test
190  *
191  * Returns:     Nonzero if the bit is set, zero if not.  Fakes up two's
192  *              complement representation.
193  */
194
195 int mp_testbit2c(mp *x, unsigned long n)
196 {
197   int r;
198   if (!(x->f & MP_NEG))
199     return (mp_testbit(x, n));
200   x = mp_not2c(MP_NEW, x);
201   r = !mp_testbit(x, n);
202   MP_DROP(x);
203   return (r);
204 }
205
206 /* --- @mp_setbit@, @mp_clearbit@ --- *
207  *
208  * Arguments:   @mp *d@ = a destination
209  *              @mp *x@ = a large integer
210  *              @unsigned long n@ = which bit to modify
211  *
212  * Returns:     The argument @x@, with the appropriate bit set or cleared.
213  */
214
215 mp *mp_setbit(mp *d, mp *x, unsigned long n)
216 {
217   size_t rq;
218
219   rq = n + MPW_BITS; rq -= rq % MPW_BITS;
220   if (d != x) {
221     if (d) MP_DROP(d);
222     d = MP_COPY(x);
223   }
224   MP_DEST(d, rq, x->f & (MP_NEG | MP_BURN));
225   d->v[n/MPW_BITS] |= 1 << n%MPW_BITS;
226   return (d);
227 }
228
229 mp *mp_clearbit(mp *d, mp *x, unsigned long n)
230 {
231   size_t rq;
232
233   rq = n + MPW_BITS; rq -= rq % MPW_BITS;
234   if (d != x) {
235     if (d) MP_DROP(d);
236     d = MP_COPY(x);
237   }
238   MP_DEST(d, rq, x->f & (MP_NEG | MP_BURN));
239   d->v[n/MPW_BITS] &= ~(1 << n%MPW_BITS);
240   return (d);
241 }
242
243 /* --- @mp_setbit2c@, @mp_clearbit2c@ --- *
244  *
245  * Arguments:   @mp *d@ = a destination
246  *              @mp *x@ = a large integer
247  *              @unsigned long n@ = which bit to modify
248  *
249  * Returns:     The argument @x@, with the appropriate bit set or cleared.
250  *              Fakes up two's complement representation.
251  */
252
253 mp *mp_setbit2c(mp *d, mp *x, unsigned long n)
254 {
255   if (!(x->f & MP_NEG))
256     return mp_setbit(d, x, n);
257   d = mp_not2c(d, x);
258   d = mp_clearbit(d, d, n);
259   d = mp_not2c(d, d);
260   return (d);
261 }
262
263 mp *mp_clearbit2c(mp *d, mp *x, unsigned long n)
264 {
265   if (!(x->f & MP_NEG))
266     return mp_clearbit(d, x, n);
267   d = mp_not2c(d, x);
268   d = mp_setbit(d, d, n);
269   d = mp_not2c(d, d);
270   return (d);
271 }
272
273 /* --- @mp_eq@ --- *
274  *
275  * Arguments:   @const mp *a, *b@ = two numbers
276  *
277  * Returns:     Nonzero if the numbers are equal.
278  */
279
280 int mp_eq(const mp *a, const mp *b) { return (MP_EQ(a, b)); }
281
282 /* --- @mp_cmp@ --- *
283  *
284  * Arguments:   @const mp *a, *b@ = two numbers
285  *
286  * Returns:     Less than, equal to or greater than zero, according to
287  *              whether @a@ is less than, equal to or greater than @b@.
288  */
289
290 int mp_cmp(const mp *a, const mp *b)
291 {
292   if (!((a->f ^ b->f) & MP_NEG))
293     return (mpx_ucmp(a->v, a->vl, b->v, b->vl));
294   else if (a->f & MP_NEG)
295     return (-1);
296   else
297     return (+1);
298 }
299
300 /* --- @mp_neg@ --- *
301  *
302  * Arguments:   @mp *d@ = destination
303  *              @mp *a@ = argument
304  *
305  * Returns:     The negation of the argument.
306  *
307  * Use:         Negates its argument.
308  */
309
310 mp *mp_neg(mp *d, mp *a)
311 {
312   /* --- Surprising amounts of messing about required --- */
313
314   MP_SHRINK(a);
315   MP_COPY(a);
316   if (d)
317     MP_DROP(d);
318   if (a->v == a->vl)
319     return (a);
320   MP_DEST(a, MP_LEN(a), a->f);
321   a->f ^= MP_NEG;
322   return (a);
323 }
324
325 /* --- @mp_bitop@ --- *
326  *
327  * Arguments:   @mp *d@ = destination
328  *              @mp *a, *b@ = sources
329  *
330  * Returns:     The result of the given bitwise operation.  These functions
331  *              don't handle negative numbers at all sensibly.  For that, use
332  *              the @...2c@ variants.  The functions are named after the
333  *              truth tables they generate:
334  *
335  *                      a:      0011
336  *                      b:      0101
337  *                      @mpx_bitXXXX@
338  */
339
340 #define MP_BITBINOP(string)                                             \
341                                                                         \
342 mp *mp_bit##string(mp *d, mp *a, mp *b)                                 \
343 {                                                                       \
344   MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)), (a->f | b->f) & ~MP_NEG);       \
345   mpx_bit##string(d->v, d->vl, a->v, a->vl, b->v, b->vl);               \
346   d->f = (a->f | b->f) & MP_BURN;                                       \
347   MP_SHRINK(d);                                                         \
348   return (d);                                                           \
349 }
350
351 MPX_DOBIN(MP_BITBINOP)
352
353 /* --- @mp_not@ --- *
354  *
355  * Arguments:   @mp *d@ = destination
356  *              @mp *a@ = source
357  *
358  * Returns:     The bitwise complement of the source.
359  */ 
360
361 mp *mp_not(mp *d, mp *a)
362 {
363   MP_DEST(d, MP_LEN(a), a->f);
364   mpx_not(d->v, d->vl, a->v, a->vl);
365   d->f = a->f & MP_BURN;
366   MP_SHRINK(d);
367   return (d);
368 }
369
370 /* --- @mp_bitop2c@ --- *
371  *
372  * Arguments:   @mp *d@ = destination
373  *              @mp *a, *b@ = sources
374  *
375  * Returns:     The result of the given bitwise operation.  Negative numbers
376  *              are treated as two's complement, sign-extended infinitely to
377  *              the left.  The functions are named after the truth tables
378  *              they generate:
379  *
380  *                      a:      0011
381  *                      b:      0101
382  *                      @mpx_bitXXXX@
383  */
384
385 /* --- How this actually works --- *
386  *
387  * The two arguments are inverted (with a sign-swap) if they're currently
388  * negative.  This means that we end up using a different function (one which
389  * reinverts as we go) for the main operation.  Also, if the sign would be
390  * negative at the end, we preinvert the output and then invert again with a
391  * sign-swap.
392  *
393  * Start with:                  wxyz      WXYZ
394  * If @a@ negative:             yzwx  or  YZWX
395  * If @b@ negative:             xwzy      XWZY
396  * If both negative:            zyxw      ZYXW
397  */
398
399 #define MP_BIT2CBINOP(n, base, an, bn, abn, p_base, p_an, p_bn, p_abn)  \
400                                                                         \
401 mp *mp_bit##n##2c(mp *d, mp *a, mp *b)                                  \
402 {                                                                       \
403   if (!((a->f | b->f) & MP_NEG)) {      /* Both positive */             \
404     d = mp_bit##base(d, a, b);                                          \
405     p_base                                                              \
406   } else if (!(b->f & MP_NEG)) {        /* Only @b@ positive */         \
407     MP_COPY(b);                                                         \
408     d = mp_not2c(d, a);                                                 \
409     d = mp_bit##an(d, d, b);                                            \
410     MP_DROP(b);                                                         \
411     p_an                                                                \
412   } else if (!(a->f & MP_NEG)) {        /* Only @a@ positive */         \
413     MP_COPY(a);                                                         \
414     d = mp_not2c(d, b);                                                 \
415     d = mp_bit##bn(d, a, d);                                            \
416     MP_DROP(a);                                                         \
417     p_bn                                                                \
418   } else {                              /* Both negative */             \
419     mp *t = mp_not2c(MP_NEW, a);                                        \
420     mp *d = mp_not2c(d, b);                                             \
421     d = mp_bit##abn(d, t, d);                                           \
422     MP_DROP(t);                                                         \
423     p_abn                                                               \
424   }                                                                     \
425   return (d);                                                           \
426 }                                                                       \
427
428 #define NEG d = mp_not2c(d, d);
429 #define POS
430 MP_BIT2CBINOP(0000, 0000, 0000, 0000, 0000, POS, POS, POS, POS)
431 MP_BIT2CBINOP(0001, 0001, 0100, 0010, 0111, POS, POS, POS, NEG)
432 MP_BIT2CBINOP(0010, 0010, 0111, 0001, 0100, POS, NEG, POS, POS)
433 MP_BIT2CBINOP(0011, 0011, 0011, 0011, 0011, POS, NEG, POS, NEG)
434 MP_BIT2CBINOP(0100, 0100, 0001, 0111, 0010, POS, POS, NEG, POS)
435 MP_BIT2CBINOP(0101, 0101, 0101, 0101, 0101, POS, POS, NEG, NEG)
436 MP_BIT2CBINOP(0110, 0110, 0110, 0110, 0110, POS, NEG, NEG, POS)
437 MP_BIT2CBINOP(0111, 0111, 0010, 0100, 0001, POS, NEG, NEG, NEG)
438 MP_BIT2CBINOP(1000, 0111, 0010, 0100, 0001, NEG, POS, POS, POS)
439 MP_BIT2CBINOP(1001, 0110, 0110, 0110, 0110, NEG, POS, POS, NEG)
440 MP_BIT2CBINOP(1010, 0101, 0101, 0101, 0101, NEG, NEG, POS, POS)
441 MP_BIT2CBINOP(1011, 0100, 0001, 0111, 0010, NEG, NEG, POS, NEG)
442 MP_BIT2CBINOP(1100, 0011, 0011, 0011, 0011, NEG, POS, NEG, POS)
443 MP_BIT2CBINOP(1101, 0010, 0111, 0001, 0100, NEG, POS, NEG, NEG)
444 MP_BIT2CBINOP(1110, 0001, 0100, 0010, 0111, NEG, NEG, NEG, POS)
445 MP_BIT2CBINOP(1111, 0000, 0000, 0000, 0000, NEG, NEG, NEG, NEG)
446 #undef NEG
447 #undef POS
448
449 /* --- @mp_not2c@ --- *
450  *
451  * Arguments:   @mp *d@ = destination
452  *              @mp *a@ = source
453  *
454  * Returns:     The sign-extended complement of the argument.
455  */
456
457 mp *mp_not2c(mp *d, mp *a)
458 {
459   mpw one = 1;
460
461   MP_DEST(d, MP_LEN(a) + 1, a->f);
462   if (d == a) {
463     if (a->f & MP_NEG)
464       MPX_USUBN(d->v, d->vl, 1);
465     else
466       MPX_UADDN(d->v, d->vl, 1);
467   } else {
468     if (a->f & MP_NEG)
469       mpx_usub(d->v, d->vl, a->v, a->vl, &one, &one + 1);
470     else
471       mpx_uadd(d->v, d->vl, a->v, a->vl, &one, &one + 1);
472   }
473   d->f = (a->f & (MP_NEG | MP_BURN)) ^ MP_NEG;
474   MP_SHRINK(d);
475   return (d);
476 }
477
478 /* --- @mp_add@ --- *
479  *
480  * Arguments:   @mp *d@ = destination
481  *              @mp *a, *b@ = sources
482  *
483  * Returns:     Result, @a@ added to @b@.
484  */
485
486 mp *mp_add(mp *d, mp *a, mp *b)
487 {
488   MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
489   if (!((a->f ^ b->f) & MP_NEG))
490     mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
491   else {
492     if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
493       mp *t = a; a = b; b = t;
494     }
495     mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
496   }
497   d->f = ((a->f | b->f) & MP_BURN) | (a->f & MP_NEG);
498   MP_SHRINK(d);
499   return (d);
500 }
501
502 /* --- @mp_sub@ --- *
503  *
504  * Arguments:   @mp *d@ = destination
505  *              @mp *a, *b@ = sources
506  *
507  * Returns:     Result, @b@ subtracted from @a@.
508  */
509
510 mp *mp_sub(mp *d, mp *a, mp *b)
511 {
512   unsigned sgn = 0;
513   MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
514   if ((a->f ^ b->f) & MP_NEG)
515     mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
516   else {
517     if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
518       mp *t = a; a = b; b = t;
519       sgn = MP_NEG;
520     }
521     mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
522   }
523   d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ sgn) & MP_NEG);
524   MP_SHRINK(d);
525   return (d);
526 }
527
528 /* --- @mp_mul@ --- *
529  *
530  * Arguments:   @mp *d@ = destination
531  *              @mp *a, *b@ = sources
532  *
533  * Returns:     Result, @a@ multiplied by @b@.
534  */
535
536 mp *mp_mul(mp *d, mp *a, mp *b)
537 {
538   a = MP_COPY(a);
539   b = MP_COPY(b);
540
541   if (MP_LEN(a) <= MPK_THRESH || MP_LEN(b) <= MPK_THRESH) {
542     MP_DEST(d, MP_LEN(a) + MP_LEN(b), a->f | b->f | MP_UNDEF);
543     mpx_umul(d->v, d->vl, a->v, a->vl, b->v, b->vl);
544   } else {
545     size_t m = MAX(MP_LEN(a), MP_LEN(b));
546     mpw *s;
547     MP_DEST(d, 3 * m, a->f | b->f | MP_UNDEF);
548     s = mpalloc(d->a, 5 * m);
549     mpx_kmul(d->v, d->vl, a->v, a->vl, b->v, b->vl, s, s + 5 * m);
550     mpfree(d->a, s);
551   }
552
553   d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
554   MP_SHRINK(d);
555   MP_DROP(a);
556   MP_DROP(b);
557   return (d);
558 }
559
560 /* --- @mp_sqr@ --- *
561  *
562  * Arguments:   @mp *d@ = destination
563  *              @mp *a@ = source
564  *
565  * Returns:     Result, @a@ squared.
566  */
567
568 mp *mp_sqr(mp *d, mp *a)
569 {
570   size_t m = MP_LEN(a);
571
572   a = MP_COPY(a);
573   if (m > MPK_THRESH) {
574     mpw *s;
575     MP_DEST(d, 3 * m, a->f | MP_UNDEF);
576     s = mpalloc(d->a, 5 * m);
577     mpx_ksqr(d->v, d->vl, a->v, a->vl, s, s + 5 * m);
578     mpfree(d->a, s);
579   } else {
580     MP_DEST(d, 2 * m + 2, a->f | MP_UNDEF);
581     mpx_usqr(d->v, d->vl, a->v, a->vl);
582   }
583   d->f = a->f & MP_BURN;
584   MP_SHRINK(d);
585   MP_DROP(a);
586   return (d);
587 }
588
589 /* --- @mp_div@ --- *
590  *
591  * Arguments:   @mp **qq, **rr@ = destination, quotient and remainder
592  *              @mp *a, *b@ = sources
593  *
594  * Use:         Calculates the quotient and remainder when @a@ is divided by
595  *              @b@.  The destinations @*qq@ and @*rr@ must be distinct.
596  *              Either of @qq@ or @rr@ may be null to indicate that the
597  *              result is irrelevant.  (Discarding both results is silly.)
598  *              There is a performance advantage if @a == *rr@.
599  *
600  *              The behaviour when @a@ and @b@ have the same sign is
601  *              straightforward.  When the signs differ, this implementation
602  *              chooses @r@ to have the same sign as @b@, rather than the
603  *              more normal choice that the remainder has the same sign as
604  *              the dividend.  This makes modular arithmetic a little more
605  *              straightforward.
606  */
607
608 void mp_div(mp **qq, mp **rr, mp *a, mp *b)
609  {
610   mp *r = rr ? *rr : MP_NEW;
611   mp *q = qq ? *qq : MP_NEW;
612   mpw *sv, *svl;
613
614   /* --- Set the remainder up right --- *
615    *
616    * Just in case the divisor is larger, be able to cope with this.  It's not
617    * important in @mpx_udiv@, but it is here because of the sign correction.
618    */
619
620   b = MP_COPY(b);
621   a = MP_COPY(a);
622   if (r)
623     MP_DROP(r);
624   r = a;
625   MP_DEST(r, MP_LEN(b) + 2, a->f | b->f);
626
627   /* --- Fix up the quotient too --- */
628
629   r = MP_COPY(r);
630   MP_DEST(q, MP_LEN(r), r->f | MP_UNDEF);
631   MP_DROP(r);
632
633   /* --- Set up some temporary workspace --- */
634
635   {
636     size_t rq = MP_LEN(b) + 1;
637     sv = mpalloc(r->a, rq);
638     svl = sv + rq;
639   }
640
641   /* --- Perform the calculation --- */
642
643   mpx_udiv(q->v, q->vl, r->v, r->vl, b->v, b->vl, sv, svl);
644
645   /* --- Sort out the sign of the results --- *
646    *
647    * If the signs of the arguments differ, and the remainder is nonzero, I
648    * must add one to the absolute value of the quotient and subtract the
649    * remainder from @b@.
650    */
651
652   q->f = ((r->f | b->f) & MP_BURN) | ((r->f ^ b->f) & MP_NEG);
653   if (q->f & MP_NEG) {
654     mpw *v;
655     for (v = r->v; v < r->vl; v++) {
656       if (*v) {
657         MPX_UADDN(q->v, q->vl, 1);
658         mpx_usub(r->v, r->vl, b->v, b->vl, r->v, r->vl);
659         break;
660       }
661     }
662   }
663
664   r->f = ((r->f | b->f) & MP_BURN) | (b->f & MP_NEG);
665
666   /* --- Store the return values --- */
667
668   mpfree(r->a, sv);
669   MP_DROP(b);
670
671   if (!qq)
672     MP_DROP(q);
673   else {
674     MP_SHRINK(q);
675     *qq = q;
676   }
677
678   if (!rr)
679     MP_DROP(r);
680   else {
681     MP_SHRINK(r);
682     *rr = r;
683   }
684 }
685
686 /* --- @mp_odd@ --- *
687  *
688  * Arguments:   @mp *d@ = pointer to destination integer
689  *              @mp *m@ = pointer to source integer
690  *              @size_t *s@ = where to store the power of 2
691  *
692  * Returns:     An odd integer integer %$t$% such that %$m = 2^s t$%.
693  *
694  * Use:         Computes a power of two and an odd integer which, when
695  *              multiplied, give a specified result.  This sort of thing is
696  *              useful in number theory quite often.
697  */
698
699 mp *mp_odd(mp *d, mp *m, size_t *s)
700 {
701   size_t ss = 0;
702   const mpw *v, *vl;
703
704   v = m->v;
705   vl = m->vl;
706   for (; !*v && v < vl; v++)
707     ss += MPW_BITS;
708   if (v >= vl)
709     ss = 0;
710   else {
711     mpw x = *v;
712     mpw mask = MPW_MAX;
713     unsigned z = MPW_BITS / 2;
714
715     while (z) {
716       mask >>= z;
717       if (!(x & mask)) {
718         x >>= z;
719         ss += z;
720       }
721       z >>= 1;
722     }
723   }
724
725   *s = ss;
726   return (mp_lsr(d, m, ss));
727 }
728
729 /*----- Test rig ----------------------------------------------------------*/
730
731 #ifdef TEST_RIG
732
733 static int verify(const char *op, mp *expect, mp *result, mp *a, mp *b)
734 {
735   if (!MP_EQ(expect, result)) {
736     fprintf(stderr, "\n*** %s failed", op);
737     fputs("\n*** a      = ", stderr); mp_writefile(a, stderr, 10);
738     fputs("\n*** b      = ", stderr); mp_writefile(b, stderr, 10);
739     fputs("\n*** result = ", stderr); mp_writefile(result, stderr, 10);
740     fputs("\n*** expect = ", stderr); mp_writefile(expect, stderr, 10);
741     fputc('\n', stderr);
742     return (0);
743   }
744   return (1);
745 }
746
747 #define RIG(name, op)                                                   \
748   static int t##name(dstr *v)                                           \
749   {                                                                     \
750     mp *a = *(mp **)v[0].buf;                                           \
751     mpw n = *(int *)v[1].buf;                                           \
752     mp b;                                                               \
753     mp *r = *(mp **)v[2].buf;                                           \
754     mp *c = op(MP_NEW, a, n);                                           \
755     int ok;                                                             \
756     mp_build(&b, &n, &n + 1);                                           \
757     ok = verify(#name, r, c, a, &b);                                    \
758     mp_drop(a); mp_drop(c); mp_drop(r);                                 \
759     assert(mparena_count(MPARENA_GLOBAL) == 0);                         \
760     return (ok);                                                        \
761   }
762
763 RIG(lsl, mp_lsl)
764 RIG(lsr, mp_lsr)
765 RIG(lsl2c, mp_lsl2c)
766 RIG(lsr2c, mp_lsr2c)
767
768 #undef RIG
769
770 #define RIG(name, op)                                                   \
771   static int t##name(dstr *v)                                           \
772   {                                                                     \
773     mp *a = *(mp **)v[0].buf;                                           \
774     mp *b = *(mp **)v[1].buf;                                           \
775     mp *r = *(mp **)v[2].buf;                                           \
776     mp *c = op(MP_NEW, a, b);                                           \
777     int ok = verify(#name, r, c, a, b);                                 \
778     mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r);                     \
779     assert(mparena_count(MPARENA_GLOBAL) == 0);                         \
780     return (ok);                                                        \
781   }
782
783 RIG(add, mp_add)
784 RIG(sub, mp_sub)
785 RIG(mul, mp_mul)
786
787 #undef RIG
788
789 static int tdiv(dstr *v)
790 {
791   mp *a = *(mp **)v[0].buf;
792   mp *b = *(mp **)v[1].buf;
793   mp *q = *(mp **)v[2].buf;
794   mp *r = *(mp **)v[3].buf;
795   mp *c = MP_NEW, *d = MP_NEW;
796   int ok = 1;
797   mp_div(&c, &d, a, b);
798   ok &= verify("div(quotient)", q, c, a, b);
799   ok &= verify("div(remainder)", r, d, a, b);
800   mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(d); mp_drop(r); mp_drop(q);
801   assert(mparena_count(MPARENA_GLOBAL) == 0);
802   return (ok);
803 }
804
805 static int tbin(dstr *v)
806 {
807   static mp *(*fn[])(mp *, mp *, mp *) = {
808 #define DO(string) mp_bit##string##2c, 
809 MPX_DOBIN(DO)
810 #undef DO
811   };
812   int ok = 1;
813   unsigned op = 0;
814   mp *a = *(mp **)v[1].buf;
815   mp *b = *(mp **)v[2].buf;
816   mp *r = *(mp **)v[3].buf;
817   mp *c;
818     
819   if (strcmp(v[0].buf, "and") == 0) op = 1;
820   else if (strcmp(v[0].buf, "or") == 0) op = 7;
821   else if (strcmp(v[0].buf, "nand") == 0) op = 14;
822   else if (strcmp(v[0].buf, "nor") == 0) op = 8;
823   else if (strcmp(v[0].buf, "xor") == 0) op = 6;
824   else {
825     char *p = v[0].buf;
826     while (*p) {
827       op <<= 1;
828       if (*p++ == '1')
829         op |= 1;
830     }
831   }
832
833   c = fn[op](MP_NEW, a, b);
834   ok = verify(v[0].buf, r, c, a, b);
835   mp_drop(a); mp_drop(b); mp_drop(r); mp_drop(c);
836   assert(mparena_count(MPARENA_GLOBAL) == 0);
837   return (ok);
838 }
839
840 static int tset(dstr *v)
841 {
842   mp *a = *(mp **)v[0].buf;
843   unsigned long n = *(unsigned long *)v[1].buf;
844   mp *r = *(mp **)v[2].buf;
845   mp *c;
846   int ok = 1;
847
848   c = mp_setbit2c(MP_NEW, a, n);
849   if (!MP_EQ(c, r)) {
850     ok = 0;
851     fprintf(stderr, "\n***setbit (set) failed");
852     fputs("\n*** a  = ", stderr); mp_writefile(a, stderr, 16);
853     fprintf(stderr, "\n*** n  = %lu", n);
854     fputs("\n*** r  = ", stderr); mp_writefile(r, stderr, 16);
855     fputs("\n*** c = ", stderr); mp_writefile(c, stderr, 16);
856     fputc('\n', stderr);
857   }
858   if (!mp_testbit2c(r, n)) {
859     ok = 0;
860     fprintf(stderr, "\n***setbit (test) failed");
861     fprintf(stderr, "\n*** n  = %lu", n);
862     fputs("\n*** r  = ", stderr); mp_writefile(r, stderr, 16);
863     fputc('\n', stderr);
864   }
865   mp_drop(a);
866   mp_drop(r);
867   mp_drop(c);
868   assert(mparena_count(MPARENA_GLOBAL) == 0);
869   return (ok);
870 }
871
872 static int tclr(dstr *v)
873 {
874   mp *a = *(mp **)v[0].buf;
875   unsigned long n = *(unsigned long *)v[1].buf;
876   mp *r = *(mp **)v[2].buf;
877   mp *c;
878   int ok = 1;
879
880   c = mp_clearbit2c(MP_NEW, a, n);
881   if (!MP_EQ(c, r)) {
882     ok = 0;
883     fprintf(stderr, "\n***clrbit (set) failed");
884     fputs("\n*** a  = ", stderr); mp_writefile(a, stderr, 16);
885     fprintf(stderr, "\n*** n  = %lu", n);
886     fputs("\n*** r  = ", stderr); mp_writefile(r, stderr, 16);
887     fputs("\n*** c = ", stderr); mp_writefile(c, stderr, 16);
888     fputc('\n', stderr);
889   }
890   if (mp_testbit2c(r, n)) {
891     ok = 0;
892     fprintf(stderr, "\n***clrbit (test) failed");
893     fprintf(stderr, "\n*** n  = %lu", n);
894     fputs("\n*** r  = ", stderr); mp_writefile(r, stderr, 16);
895     fputc('\n', stderr);
896   }
897   mp_drop(a);
898   mp_drop(c);
899   mp_drop(r);
900   assert(mparena_count(MPARENA_GLOBAL) == 0);
901   return (ok);
902 }
903
904 static int tneg(dstr *v)
905 {
906   mp *a = *(mp **)v[0].buf;
907   mp *r = *(mp **)v[1].buf;
908   int ok = 1;
909   mp *n = mp_neg(MP_NEW, a);
910   if (!MP_EQ(r, n)) {
911     ok = 0;
912     fprintf(stderr, "\n*** neg failed\n");
913     fputs("\n*** a  = ", stderr); mp_writefile(a, stderr, 10);
914     fputs("\n*** r  = ", stderr); mp_writefile(r, stderr, 10);
915     fputs("\n*** n  = ", stderr); mp_writefile(n, stderr, 10);
916     fputc('\n', stderr);
917   }
918   mp_drop(n);
919   n = mp_neg(a, a);
920   if (!MP_EQ(r, n)) {
921     ok = 0;
922     fprintf(stderr, "\n*** neg failed\n");
923     fputs("\n*** a* = ", stderr); mp_writefile(a, stderr, 10);
924     fputs("\n*** r  = ", stderr); mp_writefile(r, stderr, 10);
925     fputs("\n*** n  = ", stderr); mp_writefile(n, stderr, 10);
926     fputc('\n', stderr);
927   }
928   mp_drop(a);
929   mp_drop(r);
930   assert(mparena_count(MPARENA_GLOBAL) == 0);
931   return (ok);  
932 }
933
934 static int todd(dstr *v)
935 {
936   mp *a = *(mp **)v[0].buf;
937   size_t rs = *(uint32 *)v[1].buf;
938   mp *rt = *(mp **)v[2].buf;
939   int ok = 1;
940   mp *t;
941   size_t s;
942   t = mp_odd(MP_NEW, a, &s);
943   if (s != rs || !MP_EQ(t, rt)) {
944     ok = 0;
945     fprintf(stderr, "\n*** odd failed");
946     fputs("\n*** a  = ", stderr); mp_writefile(a, stderr, 10);
947     fprintf(stderr, "\n*** s  = %lu", (unsigned long)s);
948     fputs("\n*** t  = ", stderr); mp_writefile(t, stderr, 10);
949     fprintf(stderr, "\n*** rs = %lu", (unsigned long)rs);
950     fputs("\n*** rt = ", stderr); mp_writefile(rt, stderr, 10);
951     fputc('\n', stderr);
952   }
953   mp_drop(a);
954   mp_drop(rt);
955   mp_drop(t);
956   assert(mparena_count(MPARENA_GLOBAL) == 0);
957   return (ok);
958 }
959
960 static test_chunk tests[] = {
961   { "lsl", tlsl, { &type_mp, &type_int, &type_mp, 0 } },
962   { "lsr", tlsr, { &type_mp, &type_int, &type_mp, 0 } },
963   { "lsl2c", tlsl2c, { &type_mp, &type_int, &type_mp, 0 } },
964   { "lsr2c", tlsr2c, { &type_mp, &type_int, &type_mp, 0 } },
965   { "setbit", tset, { &type_mp, &type_ulong, &type_mp, 0 } },
966   { "clrbit", tclr, { &type_mp, &type_ulong, &type_mp, 0 } },
967   { "add", tadd, { &type_mp, &type_mp, &type_mp, 0 } },
968   { "sub", tsub, { &type_mp, &type_mp, &type_mp, 0 } },
969   { "mul", tmul, { &type_mp, &type_mp, &type_mp, 0 } },
970   { "div", tdiv, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
971   { "bin2c", tbin, { &type_string, &type_mp, &type_mp, &type_mp, 0 } },
972   { "odd", todd, { &type_mp, &type_uint32, &type_mp, 0 } },
973   { "neg", tneg, { &type_mp, &type_mp, 0 } },
974   { 0, 0, { 0 } },
975 };
976
977 int main(int argc, char *argv[])
978 {
979   sub_init();
980   test_run(argc, argv, tests, SRCDIR "/tests/mp");
981   return (0);
982 }
983
984 #endif
985
986 /*----- That's all, folks -------------------------------------------------*/