comparison bn_mp_sub_d.c @ 2:86e0b50a9b58 libtommath-orig ltm-0.30-orig

ltm 0.30 orig import
author Matt Johnston <matt@ucc.asn.au>
date Mon, 31 May 2004 18:25:22 +0000
parents
children d29b64170cf0
comparison
equal deleted inserted replaced
-1:000000000000 2:86e0b50a9b58
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 subtraction */
18 int
19 mp_sub_d (mp_int * a, mp_digit b, mp_int * c)
20 {
21 mp_digit *tmpa, *tmpc, mu;
22 int res, ix, oldused;
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 just do an unsigned
32 * addition [with fudged signs]
33 */
34 if (a->sign == MP_NEG) {
35 a->sign = MP_ZPOS;
36 res = mp_add_d(a, b, c);
37 a->sign = c->sign = MP_NEG;
38 return res;
39 }
40
41 /* setup regs */
42 oldused = c->used;
43 tmpa = a->dp;
44 tmpc = c->dp;
45
46 /* if a <= b simply fix the single digit */
47 if ((a->used == 1 && a->dp[0] <= b) || a->used == 0) {
48 if (a->used == 1) {
49 *tmpc++ = b - *tmpa;
50 } else {
51 *tmpc++ = b;
52 }
53 ix = 1;
54
55 /* negative/1digit */
56 c->sign = MP_NEG;
57 c->used = 1;
58 } else {
59 /* positive/size */
60 c->sign = MP_ZPOS;
61 c->used = a->used;
62
63 /* subtract first digit */
64 *tmpc = *tmpa++ - b;
65 mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
66 *tmpc++ &= MP_MASK;
67
68 /* handle rest of the digits */
69 for (ix = 1; ix < a->used; ix++) {
70 *tmpc = *tmpa++ - mu;
71 mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
72 *tmpc++ &= MP_MASK;
73 }
74 }
75
76 /* zero excess digits */
77 while (ix++ < oldused) {
78 *tmpc++ = 0;
79 }
80 mp_clamp(c);
81 return MP_OKAY;
82 }
83