1 /*	$NetBSD: bn_s_mp_add.c,v 1.1.1.1 2011/04/13 18:14:55 elric Exp $	*/
2 
3 #include <tommath.h>
4 #ifdef BN_S_MP_ADD_C
5 /* LibTomMath, multiple-precision integer library -- Tom St Denis
6  *
7  * LibTomMath is a library that provides multiple-precision
8  * integer arithmetic as well as number theoretic functionality.
9  *
10  * The library was designed directly after the MPI library by
11  * Michael Fromberger but has been written from scratch with
12  * additional optimizations in place.
13  *
14  * The library is free for all purposes without any express
15  * guarantee it works.
16  *
17  * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
18  */
19 
20 /* low level addition, based on HAC pp.594, Algorithm 14.7 */
21 int
22 s_mp_add (mp_int * a, mp_int * b, mp_int * c)
23 {
24   mp_int *x;
25   int     olduse, res, min, max;
26 
27   /* find sizes, we let |a| <= |b| which means we have to sort
28    * them.  "x" will point to the input with the most digits
29    */
30   if (a->used > b->used) {
31     min = b->used;
32     max = a->used;
33     x = a;
34   } else {
35     min = a->used;
36     max = b->used;
37     x = b;
38   }
39 
40   /* init result */
41   if (c->alloc < max + 1) {
42     if ((res = mp_grow (c, max + 1)) != MP_OKAY) {
43       return res;
44     }
45   }
46 
47   /* get old used digit count and set new one */
48   olduse = c->used;
49   c->used = max + 1;
50 
51   {
52     register mp_digit u, *tmpa, *tmpb, *tmpc;
53     register int i;
54 
55     /* alias for digit pointers */
56 
57     /* first input */
58     tmpa = a->dp;
59 
60     /* second input */
61     tmpb = b->dp;
62 
63     /* destination */
64     tmpc = c->dp;
65 
66     /* zero the carry */
67     u = 0;
68     for (i = 0; i < min; i++) {
69       /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
70       *tmpc = *tmpa++ + *tmpb++ + u;
71 
72       /* U = carry bit of T[i] */
73       u = *tmpc >> ((mp_digit)DIGIT_BIT);
74 
75       /* take away carry bit from T[i] */
76       *tmpc++ &= MP_MASK;
77     }
78 
79     /* now copy higher words if any, that is in A+B
80      * if A or B has more digits add those in
81      */
82     if (min != max) {
83       for (; i < max; i++) {
84         /* T[i] = X[i] + U */
85         *tmpc = x->dp[i] + u;
86 
87         /* U = carry bit of T[i] */
88         u = *tmpc >> ((mp_digit)DIGIT_BIT);
89 
90         /* take away carry bit from T[i] */
91         *tmpc++ &= MP_MASK;
92       }
93     }
94 
95     /* add carry */
96     *tmpc++ = u;
97 
98     /* clear digits above oldused */
99     for (i = c->used; i < olduse; i++) {
100       *tmpc++ = 0;
101     }
102   }
103 
104   mp_clamp (c);
105   return MP_OKAY;
106 }
107 #endif
108 
109 /* Source: /cvs/libtom/libtommath/bn_s_mp_add.c,v */
110 /* Revision: 1.4 */
111 /* Date: 2006/12/28 01:25:13 */
112