-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathmp_sub_d.c
78 lines (64 loc) · 1.66 KB
/
mp_sub_d.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "tommath_private.h"
#ifdef MP_SUB_D_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
/* single digit subtraction */
mp_err mp_sub_d(const mp_int *a, mp_digit b, mp_int *c)
{
mp_err err;
int oldused;
/* fast path for a == c */
if (a == c) {
if ((c->sign == MP_NEG) &&
((c->dp[0] + b) < MP_DIGIT_MAX)) {
c->dp[0] += b;
return MP_OKAY;
}
if ((c->sign == MP_ZPOS) &&
(c->dp[0] > b)) {
c->dp[0] -= b;
return MP_OKAY;
}
}
/* grow c as required */
if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
return err;
}
/* if a is negative just do an unsigned
* addition [with fudged signs]
*/
if (a->sign == MP_NEG) {
mp_int a_ = *a;
a_.sign = MP_ZPOS;
err = mp_add_d(&a_, b, c);
c->sign = MP_NEG;
/* clamp */
mp_clamp(c);
return err;
}
oldused = c->used;
/* if a <= b simply fix the single digit */
if (((a->used == 1) && (a->dp[0] <= b)) || mp_iszero(a)) {
c->dp[0] = (a->used == 1) ? b - a->dp[0] : b;
/* negative/1digit */
c->sign = MP_NEG;
c->used = 1;
} else {
int i;
mp_digit mu = b;
/* positive/size */
c->sign = MP_ZPOS;
c->used = a->used;
/* subtract digits, mu is carry */
for (i = 0; i < a->used; i++) {
c->dp[i] = a->dp[i] - mu;
mu = c->dp[i] >> (MP_SIZEOF_BITS(mp_digit) - 1u);
c->dp[i] &= MP_MASK;
}
}
/* zero excess digits */
s_mp_zero_digs(c->dp + c->used, oldused - c->used);
mp_clamp(c);
return MP_OKAY;
}
#endif