1
|
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis |
|
2 * |
|
3 * LibTomMath is a library that provides multiple-precision |
|
4 * integer arithmetic as well as number theoretic functionality. |
|
5 * |
|
6 * The library was 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, [email protected], http://math.libtomcrypt.org |
|
14 */ |
|
15 #include <tommath.h> |
|
16 |
|
17 /* single digit addition */ |
|
18 int |
|
19 mp_add_d (mp_int * a, mp_digit b, mp_int * c) |
|
20 { |
|
21 int res, ix, oldused; |
|
22 mp_digit *tmpa, *tmpc, mu; |
|
23 |
|
24 /* grow c as required */ |
|
25 if (c->alloc < a->used + 1) { |
|
26 if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) { |
|
27 return res; |
|
28 } |
|
29 } |
|
30 |
|
31 /* if a is negative and |a| >= b, call c = |a| - b */ |
|
32 if (a->sign == MP_NEG && (a->used > 1 || a->dp[0] >= b)) { |
|
33 /* temporarily fix sign of a */ |
|
34 a->sign = MP_ZPOS; |
|
35 |
|
36 /* c = |a| - b */ |
|
37 res = mp_sub_d(a, b, c); |
|
38 |
|
39 /* fix sign */ |
|
40 a->sign = c->sign = MP_NEG; |
|
41 |
|
42 return res; |
|
43 } |
|
44 |
|
45 /* old number of used digits in c */ |
|
46 oldused = c->used; |
|
47 |
|
48 /* sign always positive */ |
|
49 c->sign = MP_ZPOS; |
|
50 |
|
51 /* source alias */ |
|
52 tmpa = a->dp; |
|
53 |
|
54 /* destination alias */ |
|
55 tmpc = c->dp; |
|
56 |
|
57 /* if a is positive */ |
|
58 if (a->sign == MP_ZPOS) { |
|
59 /* add digit, after this we're propagating |
|
60 * the carry. |
|
61 */ |
|
62 *tmpc = *tmpa++ + b; |
|
63 mu = *tmpc >> DIGIT_BIT; |
|
64 *tmpc++ &= MP_MASK; |
|
65 |
|
66 /* now handle rest of the digits */ |
|
67 for (ix = 1; ix < a->used; ix++) { |
|
68 *tmpc = *tmpa++ + mu; |
|
69 mu = *tmpc >> DIGIT_BIT; |
|
70 *tmpc++ &= MP_MASK; |
|
71 } |
|
72 /* set final carry */ |
|
73 ix++; |
|
74 *tmpc++ = mu; |
|
75 |
|
76 /* setup size */ |
|
77 c->used = a->used + 1; |
|
78 } else { |
|
79 /* a was negative and |a| < b */ |
|
80 c->used = 1; |
|
81 |
|
82 /* the result is a single digit */ |
|
83 if (a->used == 1) { |
|
84 *tmpc++ = b - a->dp[0]; |
|
85 } else { |
|
86 *tmpc++ = b; |
|
87 } |
|
88 |
|
89 /* setup count so the clearing of oldused |
|
90 * can fall through correctly |
|
91 */ |
|
92 ix = 1; |
|
93 } |
|
94 |
|
95 /* now zero to oldused */ |
|
96 while (ix++ < oldused) { |
|
97 *tmpc++ = 0; |
|
98 } |
|
99 mp_clamp(c); |
|
100 |
|
101 return MP_OKAY; |
|
102 } |
|
103 |