18bf9042af8097f2b7798b1f7d1e54820de65002
[bcm963xx.git] / userapps / opensource / sshd / libtommath / bn_mp_div_2d.c
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
2  *
3  * LibTomMath is library that provides for multiple-precision
4  * integer arithmetic as well as number theoretic functionality.
5  *
6  * The library is designed directly after the MPI library by
7  * Michael Fromberger but has been written from scratch with
8  * additional optimizations in place.
9  *
10  * The library is free for all purposes without any express
11  * guarantee it works.
12  *
13  * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
14  */
15 #include <tommath.h>
16
17 /* shift right by a certain bit count (store quotient in c, optional remainder in d) */
18 int
19 mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
20 {
21   mp_digit D, r, rr;
22   int     x, res;
23   mp_int  t;
24
25
26   /* if the shift count is <= 0 then we do no work */
27   if (b <= 0) {
28     res = mp_copy (a, c);
29     if (d != NULL) {
30       mp_zero (d);
31     }
32     return res;
33   }
34
35   if ((res = mp_init (&t)) != MP_OKAY) {
36     return res;
37   }
38
39   /* get the remainder */
40   if (d != NULL) {
41     if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
42       mp_clear (&t);
43       return res;
44     }
45   }
46
47   /* copy */
48   if ((res = mp_copy (a, c)) != MP_OKAY) {
49     mp_clear (&t);
50     return res;
51   }
52
53   /* shift by as many digits in the bit count */
54   if (b >= (int)DIGIT_BIT) {
55     mp_rshd (c, b / DIGIT_BIT);
56   }
57
58   /* shift any bit count < DIGIT_BIT */
59   D = (mp_digit) (b % DIGIT_BIT);
60   if (D != 0) {
61     register mp_digit *tmpc, mask;
62
63     /* mask */
64     mask = (((mp_digit)1) << D) - 1;
65
66     /* alias */
67     tmpc = c->dp + (c->used - 1);
68
69     /* carry */
70     r = 0;
71     for (x = c->used - 1; x >= 0; x--) {
72       /* get the lower  bits of this word in a temp */
73       rr = *tmpc & mask;
74
75       /* shift the current word and mix in the carry bits from the previous word */
76       *tmpc = (*tmpc >> D) | (r << (DIGIT_BIT - D));
77       --tmpc;
78
79       /* set the carry to the carry bits of the current word found above */
80       r = rr;
81     }
82   }
83   mp_clamp (c);
84   if (d != NULL) {
85     mp_exch (&t, d);
86   }
87   mp_clear (&t);
88   return MP_OKAY;
89 }