1 /* $NetBSD: bn_mp_sub_d.c,v 1.1.1.2 2014/04/24 12:45:31 pettai Exp $ */
2
3 #include <tommath.h>
4 #ifdef BN_MP_SUB_D_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 /* single digit subtraction */
21 int
mp_sub_d(mp_int * a,mp_digit b,mp_int * c)22 mp_sub_d (mp_int * a, mp_digit b, mp_int * c)
23 {
24 mp_digit *tmpa, *tmpc, mu;
25 int res, ix, oldused;
26
27 /* grow c as required */
28 if (c->alloc < a->used + 1) {
29 if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) {
30 return res;
31 }
32 }
33
34 /* if a is negative just do an unsigned
35 * addition [with fudged signs]
36 */
37 if (a->sign == MP_NEG) {
38 a->sign = MP_ZPOS;
39 res = mp_add_d(a, b, c);
40 a->sign = c->sign = MP_NEG;
41
42 /* clamp */
43 mp_clamp(c);
44
45 return res;
46 }
47
48 /* setup regs */
49 oldused = c->used;
50 tmpa = a->dp;
51 tmpc = c->dp;
52
53 /* if a <= b simply fix the single digit */
54 if ((a->used == 1 && a->dp[0] <= b) || a->used == 0) {
55 if (a->used == 1) {
56 *tmpc++ = b - *tmpa;
57 } else {
58 *tmpc++ = b;
59 }
60 ix = 1;
61
62 /* negative/1digit */
63 c->sign = MP_NEG;
64 c->used = 1;
65 } else {
66 /* positive/size */
67 c->sign = MP_ZPOS;
68 c->used = a->used;
69
70 /* subtract first digit */
71 *tmpc = *tmpa++ - b;
72 mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
73 *tmpc++ &= MP_MASK;
74
75 /* handle rest of the digits */
76 for (ix = 1; ix < a->used; ix++) {
77 *tmpc = *tmpa++ - mu;
78 mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
79 *tmpc++ &= MP_MASK;
80 }
81 }
82
83 /* zero excess digits */
84 while (ix++ < oldused) {
85 *tmpc++ = 0;
86 }
87 mp_clamp(c);
88 return MP_OKAY;
89 }
90
91 #endif
92
93 /* Source: /cvs/libtom/libtommath/bn_mp_sub_d.c,v */
94 /* Revision: 1.6 */
95 /* Date: 2006/12/28 01:25:13 */
96