chiark / gitweb /
(mpx_udiv): Fix bug in quotient digit estimation.
[catacomb] / mpx.c
1 /* -*-c-*-
2  *
3  * $Id: mpx.c,v 1.8 2000/06/25 12:59:02 mdw Exp $
4  *
5  * Low-level multiprecision arithmetic
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: mpx.c,v $
33  * Revision 1.8  2000/06/25 12:59:02  mdw
34  * (mpx_udiv): Fix bug in quotient digit estimation.
35  *
36  * Revision 1.7  1999/12/22 15:49:07  mdw
37  * New function for division by a small integer.
38  *
39  * Revision 1.6  1999/11/20 22:43:44  mdw
40  * Integrate testing for MPX routines.
41  *
42  * Revision 1.5  1999/11/20 22:23:27  mdw
43  * Add function versions of some low-level macros with wider use.
44  *
45  * Revision 1.4  1999/11/17 18:04:09  mdw
46  * Add two's-complement functionality.  Improve mpx_udiv a little by
47  * performing the multiplication of the divisor by q with the subtraction
48  * from r.
49  *
50  * Revision 1.3  1999/11/13 01:57:31  mdw
51  * Remove stray debugging code.
52  *
53  * Revision 1.2  1999/11/13 01:50:59  mdw
54  * Multiprecision routines finished and tested.
55  *
56  * Revision 1.1  1999/09/03 08:41:12  mdw
57  * Initial import.
58  *
59  */
60
61 /*----- Header files ------------------------------------------------------*/
62
63 #include <assert.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67
68 #include <mLib/bits.h>
69
70 #include "mptypes.h"
71 #include "mpx.h"
72
73 /*----- Loading and storing -----------------------------------------------*/
74
75 /* --- @mpx_storel@ --- *
76  *
77  * Arguments:   @const mpw *v, *vl@ = base and limit of source vector
78  *              @void *pp@ = pointer to octet array
79  *              @size_t sz@ = size of octet array
80  *
81  * Returns:     ---
82  *
83  * Use:         Stores an MP in an octet array, least significant octet
84  *              first.  High-end octets are silently discarded if there
85  *              isn't enough space for them.
86  */
87
88 void mpx_storel(const mpw *v, const mpw *vl, void *pp, size_t sz)
89 {
90   mpw n, w = 0;
91   octet *p = pp, *q = p + sz;
92   unsigned bits = 0;
93
94   while (p < q) {
95     if (bits < 8) {
96       if (v >= vl) {
97         *p++ = U8(w);
98         break;
99       }
100       n = *v++;
101       *p++ = U8(w | n << bits);
102       w = n >> (8 - bits);
103       bits += MPW_BITS - 8;
104     } else {
105       *p++ = U8(w);
106       w >>= 8;
107       bits -= 8;
108     }
109   }
110   memset(p, 0, q - p);
111 }
112
113 /* --- @mpx_loadl@ --- *
114  *
115  * Arguments:   @mpw *v, *vl@ = base and limit of destination vector
116  *              @const void *pp@ = pointer to octet array
117  *              @size_t sz@ = size of octet array
118  *
119  * Returns:     ---
120  *
121  * Use:         Loads an MP in an octet array, least significant octet
122  *              first.  High-end octets are ignored if there isn't enough
123  *              space for them.
124  */
125
126 void mpx_loadl(mpw *v, mpw *vl, const void *pp, size_t sz)
127 {
128   unsigned n;
129   mpw w = 0;
130   const octet *p = pp, *q = p + sz;
131   unsigned bits = 0;
132
133   if (v >= vl)
134     return;
135   while (p < q) {
136     n = U8(*p++);
137     w |= n << bits;
138     bits += 8;
139     if (bits >= MPW_BITS) {
140       *v++ = MPW(w);
141       w = n >> (MPW_BITS - bits + 8);
142       bits -= MPW_BITS;
143       if (v >= vl)
144         return;
145     }
146   }
147   *v++ = w;
148   MPX_ZERO(v, vl);
149 }
150
151 /* --- @mpx_storeb@ --- *
152  *
153  * Arguments:   @const mpw *v, *vl@ = base and limit of source vector
154  *              @void *pp@ = pointer to octet array
155  *              @size_t sz@ = size of octet array
156  *
157  * Returns:     ---
158  *
159  * Use:         Stores an MP in an octet array, most significant octet
160  *              first.  High-end octets are silently discarded if there
161  *              isn't enough space for them.
162  */
163
164 void mpx_storeb(const mpw *v, const mpw *vl, void *pp, size_t sz)
165 {
166   mpw n, w = 0;
167   octet *p = pp, *q = p + sz;
168   unsigned bits = 0;
169
170   while (q > p) {
171     if (bits < 8) {
172       if (v >= vl) {
173         *--q = U8(w);
174         break;
175       }
176       n = *v++;
177       *--q = U8(w | n << bits);
178       w = n >> (8 - bits);
179       bits += MPW_BITS - 8;
180     } else {
181       *--q = U8(w);
182       w >>= 8;
183       bits -= 8;
184     }
185   }
186   memset(p, 0, q - p);
187 }
188
189 /* --- @mpx_loadb@ --- *
190  *
191  * Arguments:   @mpw *v, *vl@ = base and limit of destination vector
192  *              @const void *pp@ = pointer to octet array
193  *              @size_t sz@ = size of octet array
194  *
195  * Returns:     ---
196  *
197  * Use:         Loads an MP in an octet array, most significant octet
198  *              first.  High-end octets are ignored if there isn't enough
199  *              space for them.
200  */
201
202 void mpx_loadb(mpw *v, mpw *vl, const void *pp, size_t sz)
203 {
204   unsigned n;
205   mpw w = 0;
206   const octet *p = pp, *q = p + sz;
207   unsigned bits = 0;
208
209   if (v >= vl)
210     return;
211   while (q > p) {
212     n = U8(*--q);
213     w |= n << bits;
214     bits += 8;
215     if (bits >= MPW_BITS) {
216       *v++ = MPW(w);
217       w = n >> (MPW_BITS - bits + 8);
218       bits -= MPW_BITS;
219       if (v >= vl)
220         return;
221     }
222   }
223   *v++ = w;
224   MPX_ZERO(v, vl);
225 }
226
227 /*----- Logical shifting --------------------------------------------------*/
228
229 /* --- @mpx_lsl@ --- *
230  *
231  * Arguments:   @mpw *dv, *dvl@ = destination vector base and limit
232  *              @const mpw *av, *avl@ = source vector base and limit
233  *              @size_t n@ = number of bit positions to shift by
234  *
235  * Returns:     ---
236  *
237  * Use:         Performs a logical shift left operation on an integer.
238  */
239
240 void mpx_lsl(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl, size_t n)
241 {
242   size_t nw;
243   unsigned nb;
244
245   /* --- Trivial special case --- */
246
247   if (n == 0)
248     MPX_COPY(dv, dvl, av, avl);
249
250   /* --- Single bit shifting --- */
251
252   else if (n == 1) {
253     mpw w = 0;
254     while (av < avl) {
255       mpw t;
256       if (dv >= dvl)
257         goto done;
258       t = *av++;
259       *dv++ = MPW((t << 1) | w);
260       w = t >> (MPW_BITS - 1);
261     }
262     if (dv >= dvl)
263       goto done;
264     *dv++ = MPW(w);
265     MPX_ZERO(dv, dvl);
266     goto done;
267   }
268
269   /* --- Break out word and bit shifts for more sophisticated work --- */
270         
271   nw = n / MPW_BITS;
272   nb = n % MPW_BITS;
273
274   /* --- Handle a shift by a multiple of the word size --- */
275
276   if (nb == 0) {
277     MPX_COPY(dv + nw, dvl, av, avl);
278     memset(dv, 0, MPWS(nw));
279   }
280
281   /* --- And finally the difficult case --- *
282    *
283    * This is a little convoluted, because I have to start from the end and
284    * work backwards to avoid overwriting the source, if they're both the same
285    * block of memory.
286    */
287
288   else {
289     mpw w;
290     size_t nr = MPW_BITS - nb;
291     size_t dvn = dvl - dv;
292     size_t avn = avl - av;
293
294     if (dvn <= nw) {
295       MPX_ZERO(dv, dvl);
296       goto done;
297     }
298
299     if (dvn > avn + nw) {
300       size_t off = avn + nw + 1;
301       MPX_ZERO(dv + off, dvl);
302       dvl = dv + off;
303       w = 0;
304     } else {
305       avl = av + dvn - nw;
306       w = *--avl << nb;
307     }
308
309     while (avl > av) {
310       mpw t = *--avl;
311       *--dvl = (t >> nr) | w;
312       w = t << nb;
313     }
314
315     *--dvl = w;
316     MPX_ZERO(dv, dvl);
317   }
318
319 done:;
320 }
321
322 /* --- @mpx_lsr@ --- *
323  *
324  * Arguments:   @mpw *dv, *dvl@ = destination vector base and limit
325  *              @const mpw *av, *avl@ = source vector base and limit
326  *              @size_t n@ = number of bit positions to shift by
327  *
328  * Returns:     ---
329  *
330  * Use:         Performs a logical shift right operation on an integer.
331  */
332
333 void mpx_lsr(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl, size_t n)
334 {
335   size_t nw;
336   unsigned nb;
337
338   /* --- Trivial special case --- */
339
340   if (n == 0)
341     MPX_COPY(dv, dvl, av, avl);
342
343   /* --- Single bit shifting --- */
344
345   else if (n == 1) {
346     mpw w = *av++ >> 1;
347     while (av < avl) {
348       mpw t;
349       if (dv >= dvl)
350         goto done;
351       t = *av++;
352       *dv++ = MPW((t << (MPW_BITS - 1)) | w);
353       w = t >> 1;
354     }
355     if (dv >= dvl)
356       goto done;
357     *dv++ = MPW(w);
358     MPX_ZERO(dv, dvl);
359     goto done;
360   }
361
362   /* --- Break out word and bit shifts for more sophisticated work --- */
363
364   nw = n / MPW_BITS;
365   nb = n % MPW_BITS;
366
367   /* --- Handle a shift by a multiple of the word size --- */
368
369   if (nb == 0)
370     MPX_COPY(dv, dvl, av + nw, avl);
371
372   /* --- And finally the difficult case --- */
373
374   else {
375     mpw w;
376     size_t nr = MPW_BITS - nb;
377
378     av += nw;
379     w = *av++;
380     while (av < avl) {
381       mpw t;
382       if (dv >= dvl)
383         goto done;
384       t = *av++;
385       *dv++ = MPW((w >> nb) | (t << nr));
386       w = t;
387     }
388     if (dv < dvl) {
389       *dv++ = MPW(w >> nb);
390       MPX_ZERO(dv, dvl);
391     }
392   }
393
394 done:;
395 }
396
397 /*----- Unsigned arithmetic -----------------------------------------------*/
398
399 /* --- @mpx_2c@ --- *
400  *
401  * Arguments:   @mpw *dv, *dvl@ = destination vector
402  *              @const mpw *v, *vl@ = source vector
403  *
404  * Returns:     ---
405  *
406  * Use:         Calculates the two's complement of @v@.
407  */
408
409 void mpx_2c(mpw *dv, mpw *dvl, const mpw *v, const mpw *vl)
410 {
411   mpw c = 0;
412   while (dv < dvl && v < vl)
413     *dv++ = c = MPW(~*v++);
414   if (dv < dvl) {
415     if (c > MPW_MAX / 2)
416       c = MPW(~0);
417     while (dv < dvl)
418       *dv++ = c;
419   }
420   MPX_UADDN(dv, dvl, 1);
421 }
422
423 /* --- @mpx_ucmp@ --- *
424  *
425  * Arguments:   @const mpw *av, *avl@ = first argument vector base and limit
426  *              @const mpw *bv, *bvl@ = second argument vector base and limit
427  *
428  * Returns:     Less than, equal to, or greater than zero depending on
429  *              whether @a@ is less than, equal to or greater than @b@,
430  *              respectively.
431  *
432  * Use:         Performs an unsigned integer comparison.
433  */
434
435 int mpx_ucmp(const mpw *av, const mpw *avl, const mpw *bv, const mpw *bvl)
436 {
437   MPX_SHRINK(av, avl);
438   MPX_SHRINK(bv, bvl);
439
440   if (avl - av > bvl - bv)
441     return (+1);
442   else if (avl - av < bvl - bv)
443     return (-1);
444   else while (avl > av) {
445     mpw a = *--avl, b = *--bvl;
446     if (a > b)
447       return (+1);
448     else if (a < b)
449       return (-1);
450   }
451   return (0);
452 }
453   
454 /* --- @mpx_uadd@ --- *
455  *
456  * Arguments:   @mpw *dv, *dvl@ = destination vector base and limit
457  *              @const mpw *av, *avl@ = first addend vector base and limit
458  *              @const mpw *bv, *bvl@ = second addend vector base and limit
459  *
460  * Returns:     ---
461  *
462  * Use:         Performs unsigned integer addition.  If the result overflows
463  *              the destination vector, high-order bits are discarded.  This
464  *              means that two's complement addition happens more or less for
465  *              free, although that's more a side-effect than anything else.
466  *              The result vector may be equal to either or both source
467  *              vectors, but may not otherwise overlap them.
468  */
469
470 void mpx_uadd(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl,
471               const mpw *bv, const mpw *bvl)
472 {
473   mpw c = 0;
474
475   while (av < avl || bv < bvl) {
476     mpw a, b;
477     mpd x;
478     if (dv >= dvl)
479       return;
480     a = (av < avl) ? *av++ : 0;
481     b = (bv < bvl) ? *bv++ : 0;
482     x = (mpd)a + (mpd)b + c;
483     *dv++ = MPW(x);
484     c = x >> MPW_BITS;
485   }
486   if (dv < dvl) {
487     *dv++ = c;
488     MPX_ZERO(dv, dvl);
489   }
490 }
491
492 /* --- @mpx_uaddn@ --- *
493  *
494  * Arguments:   @mpw *dv, *dvl@ = source and destination base and limit
495  *              @mpw n@ = other addend
496  *
497  * Returns:     ---
498  *
499  * Use:         Adds a small integer to a multiprecision number.
500  */
501
502 void mpx_uaddn(mpw *dv, mpw *dvl, mpw n) { MPX_UADDN(dv, dvl, n); }
503
504 /* --- @mpx_usub@ --- *
505  *
506  * Arguments:   @mpw *dv, *dvl@ = destination vector base and limit
507  *              @const mpw *av, *avl@ = first argument vector base and limit
508  *              @const mpw *bv, *bvl@ = second argument vector base and limit
509  *
510  * Returns:     ---
511  *
512  * Use:         Performs unsigned integer subtraction.  If the result
513  *              overflows the destination vector, high-order bits are
514  *              discarded.  This means that two's complement subtraction
515  *              happens more or less for free, althuogh that's more a side-
516  *              effect than anything else.  The result vector may be equal to
517  *              either or both source vectors, but may not otherwise overlap
518  *              them.
519  */
520
521 void mpx_usub(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl,
522               const mpw *bv, const mpw *bvl)
523 {
524   mpw c = 0;
525
526   while (av < avl || bv < bvl) {
527     mpw a, b;
528     mpd x;
529     if (dv >= dvl)
530       return;
531     a = (av < avl) ? *av++ : 0;
532     b = (bv < bvl) ? *bv++ : 0;
533     x = (mpd)a - (mpd)b - c;
534     *dv++ = MPW(x);
535     if (x >> MPW_BITS)
536       c = 1;
537     else
538       c = 0;
539   }
540   if (c)
541     c = MPW_MAX;
542   while (dv < dvl)
543     *dv++ = c;
544 }
545
546 /* --- @mpx_usubn@ --- *
547  *
548  * Arguments:   @mpw *dv, *dvl@ = source and destination base and limit
549  *              @n@ = subtrahend
550  *
551  * Returns:     ---
552  *
553  * Use:         Subtracts a small integer from a multiprecision number.
554  */
555
556 void mpx_usubn(mpw *dv, mpw *dvl, mpw n) { MPX_USUBN(dv, dvl, n); }
557
558 /* --- @mpx_umul@ --- *
559  *
560  * Arguments:   @mpw *dv, *dvl@ = destination vector base and limit
561  *              @const mpw *av, *avl@ = multiplicand vector base and limit
562  *              @const mpw *bv, *bvl@ = multiplier vector base and limit
563  *
564  * Returns:     ---
565  *
566  * Use:         Performs unsigned integer multiplication.  If the result
567  *              overflows the desination vector, high-order bits are
568  *              discarded.  The result vector may not overlap the argument
569  *              vectors in any way.
570  */
571
572 void mpx_umul(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl,
573               const mpw *bv, const mpw *bvl)
574 {
575   /* --- This is probably worthwhile on a multiply --- */
576
577   MPX_SHRINK(av, avl);
578   MPX_SHRINK(bv, bvl);
579
580   /* --- Deal with a multiply by zero --- */
581   
582   if (bv == bvl) {
583     MPX_ZERO(dv, dvl);
584     return;
585   }
586
587   /* --- Do the initial multiply and initialize the accumulator --- */
588
589   MPX_UMULN(dv, dvl, av, avl, *bv++);
590
591   /* --- Do the remaining multiply/accumulates --- */
592
593   while (dv < dvl && bv < bvl) {
594     mpw m = *bv++;
595     mpw c = 0;
596     const mpw *avv = av;
597     mpw *dvv = ++dv;
598
599     while (avv < avl) {
600       mpd x;
601       if (dvv >= dvl)
602         goto next;
603       x = (mpd)*dvv + (mpd)m * (mpd)*avv++ + c;
604       *dvv++ = MPW(x);
605       c = x >> MPW_BITS;
606     }
607     MPX_UADDN(dvv, dvl, c);
608   next:;
609   }
610 }
611
612 /* --- @mpx_umuln@ --- *
613  *
614  * Arguments:   @mpw *dv, *dvl@ = destination vector base and limit
615  *              @const mpw *av, *avl@ = multiplicand vector base and limit
616  *              @mpw m@ = multiplier
617  *
618  * Returns:     ---
619  *
620  * Use:         Multiplies a multiprecision integer by a single-word value.
621  *              The destination and source may be equal.  The destination
622  *              is completely cleared after use.
623  */
624
625 void mpx_umuln(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl, mpw m)
626 {
627   MPX_UMULN(dv, dvl, av, avl, m);
628 }
629
630 /* --- @mpx_umlan@ --- *
631  *
632  * Arguments:   @mpw *dv, *dvl@ = destination/accumulator base and limit
633  *              @const mpw *av, *avl@ = multiplicand vector base and limit
634  *              @mpw m@ = multiplier
635  *
636  * Returns:     ---
637  *
638  * Use:         Multiplies a multiprecision integer by a single-word value
639  *              and adds the result to an accumulator.
640  */
641
642 void mpx_umlan(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl, mpw m)
643 {
644   MPX_UMLAN(dv, dvl, av, avl, m);
645 }
646
647 /* --- @mpx_usqr@ --- *
648  *
649  * Arguments:   @mpw *dv, *dvl@ = destination vector base and limit
650  *              @const mpw *av, *av@ = source vector base and limit
651  *
652  * Returns:     ---
653  *
654  * Use:         Performs unsigned integer squaring.  The result vector must
655  *              not overlap the source vector in any way.
656  */
657
658 void mpx_usqr(mpw *dv, mpw *dvl, const mpw *av, const mpw *avl)
659 {
660   MPX_ZERO(dv, dvl);
661
662   /* --- Main loop --- */
663
664   while (av < avl) {
665     const mpw *avv = av;
666     mpw *dvv = dv;
667     mpw a = *av;
668     mpd c;
669
670     /* --- Stop if I've run out of destination --- */
671
672     if (dvv >= dvl)
673       break;
674
675     /* --- Work out the square at this point in the proceedings --- */
676
677     {
678       mpd x = (mpd)a * (mpd)a + *dvv;
679       *dvv++ = MPW(x);
680       c = MPW(x >> MPW_BITS);
681     }
682
683     /* --- Now fix up the rest of the vector upwards --- */
684
685     avv++;
686     while (dvv < dvl && avv < avl) {
687       mpd x = (mpd)a * (mpd)*avv++;
688       mpd y = ((x << 1) & MPW_MAX) + c + *dvv;
689       c = (x >> (MPW_BITS - 1)) + (y >> MPW_BITS);
690       *dvv++ = MPW(y);
691     }
692     while (dvv < dvl && c) {
693       mpd x = c + *dvv;
694       *dvv++ = MPW(x);
695       c = x >> MPW_BITS;
696     }
697
698     /* --- Get ready for the next round --- */
699
700     av++;
701     dv += 2;
702   }
703 }
704
705 /* --- @mpx_udiv@ --- *
706  *
707  * Arguments:   @mpw *qv, *qvl@ = quotient vector base and limit
708  *              @mpw *rv, *rvl@ = dividend/remainder vector base and limit
709  *              @const mpw *dv, *dvl@ = divisor vector base and limit
710  *              @mpw *sv, *svl@ = scratch workspace
711  *
712  * Returns:     ---
713  *
714  * Use:         Performs unsigned integer division.  If the result overflows
715  *              the quotient vector, high-order bits are discarded.  (Clearly
716  *              the remainder vector can't overflow.)  The various vectors
717  *              may not overlap in any way.  Yes, I know it's a bit odd
718  *              requiring the dividend to be in the result position but it
719  *              does make some sense really.  The remainder must have
720  *              headroom for at least two extra words.  The scratch space
721  *              must be at least one word larger than the divisor.
722  */
723
724 void mpx_udiv(mpw *qv, mpw *qvl, mpw *rv, mpw *rvl,
725               const mpw *dv, const mpw *dvl,
726               mpw *sv, mpw *svl)
727 {
728   unsigned norm = 0;
729   size_t scale;
730   mpw d, dd;
731
732   /* --- Initialize the quotient --- */
733
734   MPX_ZERO(qv, qvl);
735
736   /* --- Perform some sanity checks --- */
737
738   MPX_SHRINK(dv, dvl);
739   assert(((void)"division by zero in mpx_udiv", dv < dvl));
740
741   /* --- Normalize the divisor --- *
742    *
743    * The algorithm requires that the divisor be at least two digits long.
744    * This is easy to fix.
745    */
746
747   {
748     unsigned b;
749
750     d = dvl[-1];
751     for (b = MPW_BITS / 2; b; b >>= 1) {
752       if (d < (MPW_MAX >> b)) {
753         d <<= b;
754         norm += b;
755       }
756     }
757     if (dv + 1 == dvl)
758       norm += MPW_BITS;
759   }
760
761   /* --- Normalize the dividend/remainder to match --- */
762
763   if (norm) {
764     mpx_lsl(rv, rvl, rv, rvl, norm);
765     mpx_lsl(sv, svl, dv, dvl, norm);
766     dv = sv;
767     dvl = svl;
768     MPX_SHRINK(dv, dvl);
769   }
770
771   MPX_SHRINK(rv, rvl);
772   d = dvl[-1];
773   dd = dvl[-2];
774
775   /* --- Work out the relative scales --- */
776
777   {
778     size_t rvn = rvl - rv;
779     size_t dvn = dvl - dv;
780
781     /* --- If the divisor is clearly larger, notice this --- */
782
783     if (dvn > rvn) {
784       mpx_lsr(rv, rvl, rv, rvl, norm);
785       return;
786     }
787
788     scale = rvn - dvn;
789   }
790
791   /* --- Calculate the most significant quotient digit --- *
792    *
793    * Because the divisor has its top bit set, this can only happen once.  The
794    * pointer arithmetic is a little contorted, to make sure that the
795    * behaviour is defined.
796    */
797
798   if (MPX_UCMP(rv + scale, rvl, >=, dv, dvl)) {
799     mpx_usub(rv + scale, rvl, rv + scale, rvl, dv, dvl);
800     if (qvl - qv > scale)
801       qv[scale] = 1;
802   }
803
804   /* --- Now for the main loop --- */
805
806   {
807     mpw *rvv = rvl - 2;
808
809     while (scale) {
810       mpw q;
811       mpd rh;
812
813       /* --- Get an estimate for the next quotient digit --- */
814
815       mpw r = rvv[1];
816       mpw rr = rvv[0];
817       mpw rrr = *--rvv;
818
819       scale--;
820       rh = ((mpd)r << MPW_BITS) | rr;
821       if (r == d)
822         q = MPW_MAX;
823       else
824         q = MPW(rh / d);
825
826       /* --- Refine the estimate --- */
827
828       {
829         mpd yh = (mpd)d * q;
830         mpd yy = (mpd)dd * q;
831         mpw yl;
832
833         if (yy > MPW_MAX)
834           yh += yy >> MPW_BITS;
835         yl = MPW(yy);
836
837         while (yh > rh || (yh == rh && yl > rrr)) {
838           q--;
839           yh -= d;
840           if (yl < dd)
841             yh--;
842           yl -= dd;
843         }
844       }
845
846       /* --- Remove a chunk from the dividend --- */
847
848       {
849         mpw *svv;
850         const mpw *dvv;
851         mpw mc = 0, sc = 0;
852
853         /* --- Calculate the size of the chunk --- *
854          *
855          * This does the whole job of calculating @r >> scale - qd@.
856          */
857
858         for (svv = rv + scale, dvv = dv;
859              dvv < dvl && svv < rvl;
860              svv++, dvv++) {
861           mpd x = (mpd)*dvv * (mpd)q + mc;
862           mc = x >> MPW_BITS;
863           x = (mpd)*svv - MPW(x) - sc;
864           *svv = MPW(x);
865           if (x >> MPW_BITS)
866             sc = 1;
867           else
868             sc = 0;
869         }
870
871         if (svv < rvl) {
872           mpd x = (mpd)*svv - mc - sc;
873           *svv++ = MPW(x);
874           if (x >> MPW_BITS)
875             sc = MPW_MAX;
876           else
877             sc = 0;
878           while (svv < rvl)
879             *svv++ = sc;
880         }
881
882         /* --- Fix if the quotient was too large --- *
883          *
884          * This doesn't seem to happen very often.
885          */
886
887         if (rvl[-1] > MPW_MAX / 2) {
888           mpx_uadd(rv + scale, rvl, rv + scale, rvl, dv, dvl);
889           q--;
890         }
891       }
892
893       /* --- Done for another iteration --- */
894
895       if (qvl - qv > scale)
896         qv[scale] = q;
897       r = rr;
898       rr = rrr;
899     }
900   }
901
902   /* --- Now fiddle with unnormalizing and things --- */
903
904   mpx_lsr(rv, rvl, rv, rvl, norm);
905 }
906
907 /* --- @mpx_udivn@ --- *
908  *
909  * Arguments:   @mpw *qv, *qvl@ = storage for the quotient (may overlap
910  *                      dividend)
911  *              @const mpw *rv, *rvl@ = dividend
912  *              @mpw d@ = single-precision divisor
913  *
914  * Returns:     Remainder after divison.
915  *
916  * Use:         Performs a single-precision division operation.
917  */
918
919 mpw mpx_udivn(mpw *qv, mpw *qvl, const mpw *rv, const mpw *rvl, mpw d)
920 {
921   size_t i;
922   size_t ql = qvl - qv;
923   mpd r = 0;
924
925   i = rvl - rv;
926   while (i > 0) {
927     i--;
928     r = (r << MPW_BITS) | rv[i];
929     if (i < ql)
930       qv[i] = r / d;
931     r %= d;
932   }
933   return (MPW(r));
934 }
935
936 /*----- Test rig ----------------------------------------------------------*/
937
938 #ifdef TEST_RIG
939
940 #include <mLib/alloc.h>
941 #include <mLib/dstr.h>
942 #include <mLib/quis.h>
943 #include <mLib/testrig.h>
944
945 #include "mpscan.h"
946
947 #define ALLOC(v, vl, sz) do {                                           \
948   size_t _sz = (sz);                                                    \
949   mpw *_vv = xmalloc(MPWS(_sz));                                        \
950   mpw *_vvl = _vv + _sz;                                                \
951   (v) = _vv;                                                            \
952   (vl) = _vvl;                                                          \
953 } while (0)
954
955 #define LOAD(v, vl, d) do {                                             \
956   const dstr *_d = (d);                                                 \
957   mpw *_v, *_vl;                                                        \
958   ALLOC(_v, _vl, MPW_RQ(_d->len));                                      \
959   mpx_loadb(_v, _vl, _d->buf, _d->len);                                 \
960   (v) = _v;                                                             \
961   (vl) = _vl;                                                           \
962 } while (0)
963
964 #define MAX(x, y) ((x) > (y) ? (x) : (y))
965   
966 static void dumpbits(const char *msg, const void *pp, size_t sz)
967 {
968   const octet *p = pp;
969   fputs(msg, stderr);
970   for (; sz; sz--)
971     fprintf(stderr, " %02x", *p++);
972   fputc('\n', stderr);
973 }
974
975 static void dumpmp(const char *msg, const mpw *v, const mpw *vl)
976 {
977   fputs(msg, stderr);
978   MPX_SHRINK(v, vl);
979   while (v < vl)
980     fprintf(stderr, " %08lx", (unsigned long)*--vl);
981   fputc('\n', stderr);
982 }
983
984 static int chkscan(const mpw *v, const mpw *vl,
985                    const void *pp, size_t sz, int step)
986 {
987   mpscan mps;
988   const octet *p = pp;
989   unsigned bit = 0;
990   int ok = 1;
991
992   mpscan_initx(&mps, v, vl);
993   while (sz) {
994     unsigned x = *p;
995     int i;
996     p += step;
997     for (i = 0; i < 8 && MPSCAN_STEP(&mps); i++) {
998       if (MPSCAN_BIT(&mps) != (x & 1)) {
999         fprintf(stderr,
1000                 "\n*** error, step %i, bit %u, expected %u, found %u\n",
1001                 step, bit, x & 1, MPSCAN_BIT(&mps));
1002         ok = 0;
1003       }
1004       x >>= 1;
1005       bit++;
1006     }
1007     sz--;
1008   }
1009
1010   return (ok);
1011 }
1012
1013 static int loadstore(dstr *v)
1014 {
1015   dstr d = DSTR_INIT;
1016   size_t sz = MPW_RQ(v->len) * 2, diff;
1017   mpw *m, *ml;
1018   int ok = 1;
1019
1020   dstr_ensure(&d, v->len);
1021   m = xmalloc(MPWS(sz));
1022
1023   for (diff = 0; diff < sz; diff += 5) {
1024     size_t oct;
1025
1026     ml = m + sz - diff;
1027
1028     mpx_loadl(m, ml, v->buf, v->len);
1029     if (!chkscan(m, ml, v->buf, v->len, +1))
1030       ok = 0;
1031     MPX_OCTETS(oct, m, ml);
1032     mpx_storel(m, ml, d.buf, d.sz);
1033     if (memcmp(d.buf, v->buf, oct) != 0) {
1034       dumpbits("\n*** storel failed", d.buf, d.sz);
1035       ok = 0;
1036     }
1037
1038     mpx_loadb(m, ml, v->buf, v->len);
1039     if (!chkscan(m, ml, v->buf + v->len - 1, v->len, -1))
1040       ok = 0;
1041     MPX_OCTETS(oct, m, ml);
1042     mpx_storeb(m, ml, d.buf, d.sz);
1043     if (memcmp(d.buf + d.sz - oct, v->buf + v->len - oct, oct) != 0) {
1044       dumpbits("\n*** storeb failed", d.buf, d.sz);
1045       ok = 0;
1046     }
1047   }
1048
1049   if (!ok)
1050     dumpbits("input data", v->buf, v->len);
1051
1052   free(m);
1053   dstr_destroy(&d);
1054   return (ok);
1055 }
1056
1057 static int lsl(dstr *v)
1058 {
1059   mpw *a, *al;
1060   int n = *(int *)v[1].buf;
1061   mpw *c, *cl;
1062   mpw *d, *dl;
1063   int ok = 1;
1064
1065   LOAD(a, al, &v[0]);
1066   LOAD(c, cl, &v[2]);
1067   ALLOC(d, dl, al - a + (n + MPW_BITS - 1) / MPW_BITS);
1068
1069   mpx_lsl(d, dl, a, al, n);
1070   if (MPX_UCMP(d, dl, !=, c, cl)) {
1071     fprintf(stderr, "\n*** lsl(%i) failed\n", n);
1072     dumpmp("       a", a, al);
1073     dumpmp("expected", c, cl);
1074     dumpmp("  result", d, dl);
1075     ok = 0;
1076   }
1077
1078   free(a); free(c); free(d);
1079   return (ok);
1080 }
1081
1082 static int lsr(dstr *v)
1083 {
1084   mpw *a, *al;
1085   int n = *(int *)v[1].buf;
1086   mpw *c, *cl;
1087   mpw *d, *dl;
1088   int ok = 1;
1089
1090   LOAD(a, al, &v[0]);
1091   LOAD(c, cl, &v[2]);
1092   ALLOC(d, dl, al - a + (n + MPW_BITS - 1) / MPW_BITS + 1);
1093
1094   mpx_lsr(d, dl, a, al, n);
1095   if (MPX_UCMP(d, dl, !=, c, cl)) {
1096     fprintf(stderr, "\n*** lsr(%i) failed\n", n);
1097     dumpmp("       a", a, al);
1098     dumpmp("expected", c, cl);
1099     dumpmp("  result", d, dl);
1100     ok = 0;
1101   }
1102
1103   free(a); free(c); free(d);
1104   return (ok);
1105 }
1106
1107 static int uadd(dstr *v)
1108 {
1109   mpw *a, *al;
1110   mpw *b, *bl;
1111   mpw *c, *cl;
1112   mpw *d, *dl;
1113   int ok = 1;
1114
1115   LOAD(a, al, &v[0]);
1116   LOAD(b, bl, &v[1]);
1117   LOAD(c, cl, &v[2]);
1118   ALLOC(d, dl, MAX(al - a, bl - b) + 1);
1119
1120   mpx_uadd(d, dl, a, al, b, bl);
1121   if (MPX_UCMP(d, dl, !=, c, cl)) {
1122     fprintf(stderr, "\n*** uadd failed\n");
1123     dumpmp("       a", a, al);
1124     dumpmp("       b", b, bl);
1125     dumpmp("expected", c, cl);
1126     dumpmp("  result", d, dl);
1127     ok = 0;
1128   }
1129
1130   free(a); free(b); free(c); free(d);
1131   return (ok);
1132 }
1133
1134 static int usub(dstr *v)
1135 {
1136   mpw *a, *al;
1137   mpw *b, *bl;
1138   mpw *c, *cl;
1139   mpw *d, *dl;
1140   int ok = 1;
1141
1142   LOAD(a, al, &v[0]);
1143   LOAD(b, bl, &v[1]);
1144   LOAD(c, cl, &v[2]);
1145   ALLOC(d, dl, al - a);
1146
1147   mpx_usub(d, dl, a, al, b, bl);
1148   if (MPX_UCMP(d, dl, !=, c, cl)) {
1149     fprintf(stderr, "\n*** usub failed\n");
1150     dumpmp("       a", a, al);
1151     dumpmp("       b", b, bl);
1152     dumpmp("expected", c, cl);
1153     dumpmp("  result", d, dl);
1154     ok = 0;
1155   }
1156
1157   free(a); free(b); free(c); free(d);
1158   return (ok);
1159 }
1160
1161 static int umul(dstr *v)
1162 {
1163   mpw *a, *al;
1164   mpw *b, *bl;
1165   mpw *c, *cl;
1166   mpw *d, *dl;
1167   int ok = 1;
1168
1169   LOAD(a, al, &v[0]);
1170   LOAD(b, bl, &v[1]);
1171   LOAD(c, cl, &v[2]);
1172   ALLOC(d, dl, (al - a) + (bl - b));
1173
1174   mpx_umul(d, dl, a, al, b, bl);
1175   if (MPX_UCMP(d, dl, !=, c, cl)) {
1176     fprintf(stderr, "\n*** umul failed\n");
1177     dumpmp("       a", a, al);
1178     dumpmp("       b", b, bl);
1179     dumpmp("expected", c, cl);
1180     dumpmp("  result", d, dl);
1181     ok = 0;
1182   }
1183
1184   free(a); free(b); free(c); free(d);
1185   return (ok);
1186 }
1187
1188 static int usqr(dstr *v)
1189 {
1190   mpw *a, *al;
1191   mpw *c, *cl;
1192   mpw *d, *dl;
1193   int ok = 1;
1194
1195   LOAD(a, al, &v[0]);
1196   LOAD(c, cl, &v[1]);
1197   ALLOC(d, dl, 2 * (al - a));
1198
1199   mpx_usqr(d, dl, a, al);
1200   if (MPX_UCMP(d, dl, !=, c, cl)) {
1201     fprintf(stderr, "\n*** usqr failed\n");
1202     dumpmp("       a", a, al);
1203     dumpmp("expected", c, cl);
1204     dumpmp("  result", d, dl);
1205     ok = 0;
1206   }
1207
1208   free(a); free(c); free(d);
1209   return (ok);
1210 }
1211
1212 static int udiv(dstr *v)
1213 {
1214   mpw *a, *al;
1215   mpw *b, *bl;
1216   mpw *q, *ql;
1217   mpw *r, *rl;
1218   mpw *qq, *qql;
1219   mpw *s, *sl;
1220   int ok = 1;
1221
1222   ALLOC(a, al, MPW_RQ(v[0].len) + 2); mpx_loadb(a, al, v[0].buf, v[0].len);
1223   LOAD(b, bl, &v[1]);
1224   LOAD(q, ql, &v[2]);
1225   LOAD(r, rl, &v[3]);
1226   ALLOC(qq, qql, al - a);
1227   ALLOC(s, sl, (bl - b) + 1);
1228
1229   mpx_udiv(qq, qql, a, al, b, bl, s, sl);
1230   if (MPX_UCMP(qq, qql, !=, q, ql) ||
1231       MPX_UCMP(a, al, !=, r, rl)) {
1232     fprintf(stderr, "\n*** udiv failed\n");
1233     dumpmp(" divisor", b, bl);
1234     dumpmp("expect r", r, rl);
1235     dumpmp("result r", a, al);
1236     dumpmp("expect q", q, ql);
1237     dumpmp("result q", qq, qql);
1238     ok = 0;
1239   }
1240
1241   free(a); free(b); free(r); free(q); free(s); free(qq);
1242   return (ok);
1243 }
1244
1245 static test_chunk defs[] = {
1246   { "load-store", loadstore, { &type_hex, 0 } },
1247   { "lsl", lsl, { &type_hex, &type_int, &type_hex, 0 } },
1248   { "lsr", lsr, { &type_hex, &type_int, &type_hex, 0 } },
1249   { "uadd", uadd, { &type_hex, &type_hex, &type_hex, 0 } },
1250   { "usub", usub, { &type_hex, &type_hex, &type_hex, 0 } },
1251   { "umul", umul, { &type_hex, &type_hex, &type_hex, 0 } },
1252   { "usqr", usqr, { &type_hex, &type_hex, 0 } },
1253   { "udiv", udiv, { &type_hex, &type_hex, &type_hex, &type_hex, 0 } },
1254   { 0, 0, { 0 } }
1255 };
1256
1257 int main(int argc, char *argv[])
1258 {
1259   test_run(argc, argv, defs, SRCDIR"/tests/mpx");
1260   return (0);
1261 }
1262
1263
1264 #endif
1265
1266 /*----- That's all, folks -------------------------------------------------*/