/src/dropbear/libtommath/bn_s_mp_sub.c
Line | Count | Source (jump to first uncovered line) |
1 | | #include "tommath_private.h" |
2 | | #ifdef BN_S_MP_SUB_C |
3 | | /* LibTomMath, multiple-precision integer library -- Tom St Denis */ |
4 | | /* SPDX-License-Identifier: Unlicense */ |
5 | | |
6 | | /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */ |
7 | | mp_err s_mp_sub(const mp_int *a, const mp_int *b, mp_int *c) |
8 | 4.08M | { |
9 | 4.08M | int olduse, min, max; |
10 | 4.08M | mp_err err; |
11 | | |
12 | | /* find sizes */ |
13 | 4.08M | min = b->used; |
14 | 4.08M | max = a->used; |
15 | | |
16 | | /* init result */ |
17 | 4.08M | if (c->alloc < max) { |
18 | 42 | if ((err = mp_grow(c, max)) != MP_OKAY) { |
19 | 0 | return err; |
20 | 0 | } |
21 | 42 | } |
22 | 4.08M | olduse = c->used; |
23 | 4.08M | c->used = max; |
24 | | |
25 | 4.08M | { |
26 | 4.08M | mp_digit u, *tmpa, *tmpb, *tmpc; |
27 | 4.08M | int i; |
28 | | |
29 | | /* alias for digit pointers */ |
30 | 4.08M | tmpa = a->dp; |
31 | 4.08M | tmpb = b->dp; |
32 | 4.08M | tmpc = c->dp; |
33 | | |
34 | | /* set carry to zero */ |
35 | 4.08M | u = 0; |
36 | 96.1M | for (i = 0; i < min; i++) { |
37 | | /* T[i] = A[i] - B[i] - U */ |
38 | 92.1M | *tmpc = (*tmpa++ - *tmpb++) - u; |
39 | | |
40 | | /* U = carry bit of T[i] |
41 | | * Note this saves performing an AND operation since |
42 | | * if a carry does occur it will propagate all the way to the |
43 | | * MSB. As a result a single shift is enough to get the carry |
44 | | */ |
45 | 92.1M | u = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u); |
46 | | |
47 | | /* Clear carry from T[i] */ |
48 | 92.1M | *tmpc++ &= MP_MASK; |
49 | 92.1M | } |
50 | | |
51 | | /* now copy higher words if any, e.g. if A has more digits than B */ |
52 | 41.5M | for (; i < max; i++) { |
53 | | /* T[i] = A[i] - U */ |
54 | 37.4M | *tmpc = *tmpa++ - u; |
55 | | |
56 | | /* U = carry bit of T[i] */ |
57 | 37.4M | u = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u); |
58 | | |
59 | | /* Clear carry from T[i] */ |
60 | 37.4M | *tmpc++ &= MP_MASK; |
61 | 37.4M | } |
62 | | |
63 | | /* clear digits above used (since we may not have grown result above) */ |
64 | 4.08M | MP_ZERO_DIGITS(tmpc, olduse - c->used); |
65 | 4.08M | } |
66 | | |
67 | 4.08M | mp_clamp(c); |
68 | 4.08M | return MP_OKAY; |
69 | 4.08M | } |
70 | | |
71 | | #endif |