142
|
1 #include <tommath.h> |
|
2 #ifdef BN_MP_SUB_D_C |
2
|
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis |
|
4 * |
|
5 * LibTomMath is a library that provides multiple-precision |
|
6 * integer arithmetic as well as number theoretic functionality. |
|
7 * |
|
8 * The library was designed directly after the MPI library by |
|
9 * Michael Fromberger but has been written from scratch with |
|
10 * additional optimizations in place. |
|
11 * |
|
12 * The library is free for all purposes without any express |
|
13 * guarantee it works. |
|
14 * |
|
15 * Tom St Denis, [email protected], http://math.libtomcrypt.org |
|
16 */ |
|
17 |
|
18 /* single digit subtraction */ |
|
19 int |
|
20 mp_sub_d (mp_int * a, mp_digit b, mp_int * c) |
|
21 { |
|
22 mp_digit *tmpa, *tmpc, mu; |
|
23 int res, ix, oldused; |
|
24 |
|
25 /* grow c as required */ |
|
26 if (c->alloc < a->used + 1) { |
|
27 if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) { |
|
28 return res; |
|
29 } |
|
30 } |
|
31 |
|
32 /* if a is negative just do an unsigned |
|
33 * addition [with fudged signs] |
|
34 */ |
|
35 if (a->sign == MP_NEG) { |
|
36 a->sign = MP_ZPOS; |
|
37 res = mp_add_d(a, b, c); |
|
38 a->sign = c->sign = MP_NEG; |
|
39 return res; |
|
40 } |
|
41 |
|
42 /* setup regs */ |
|
43 oldused = c->used; |
|
44 tmpa = a->dp; |
|
45 tmpc = c->dp; |
|
46 |
|
47 /* if a <= b simply fix the single digit */ |
|
48 if ((a->used == 1 && a->dp[0] <= b) || a->used == 0) { |
|
49 if (a->used == 1) { |
|
50 *tmpc++ = b - *tmpa; |
|
51 } else { |
|
52 *tmpc++ = b; |
|
53 } |
|
54 ix = 1; |
|
55 |
|
56 /* negative/1digit */ |
|
57 c->sign = MP_NEG; |
|
58 c->used = 1; |
|
59 } else { |
|
60 /* positive/size */ |
|
61 c->sign = MP_ZPOS; |
|
62 c->used = a->used; |
|
63 |
|
64 /* subtract first digit */ |
|
65 *tmpc = *tmpa++ - b; |
|
66 mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1); |
|
67 *tmpc++ &= MP_MASK; |
|
68 |
|
69 /* handle rest of the digits */ |
|
70 for (ix = 1; ix < a->used; ix++) { |
|
71 *tmpc = *tmpa++ - mu; |
|
72 mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1); |
|
73 *tmpc++ &= MP_MASK; |
|
74 } |
|
75 } |
|
76 |
|
77 /* zero excess digits */ |
|
78 while (ix++ < oldused) { |
|
79 *tmpc++ = 0; |
|
80 } |
|
81 mp_clamp(c); |
|
82 return MP_OKAY; |
|
83 } |
|
84 |
142
|
85 #endif |