rework mp_add_d and mp_sub_d
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
diff --git a/mp_add_d.c b/mp_add_d.c
index cd0d47a..4508cc8 100644
--- a/mp_add_d.c
+++ b/mp_add_d.c
@@ -11,12 +11,18 @@ mp_err mp_add_d(const mp_int *a, mp_digit b, mp_int *c)
mp_digit *tmpa, *tmpc;
/* fast path for a == c */
- if (a == c &&
- !mp_iszero(c) &&
- c->sign == MP_ZPOS &&
- c->dp[0] + b < MP_DIGIT_MAX) {
- c->dp[0] += b;
- return MP_OKAY;
+ if (a == c) {
+ if ((c->sign == MP_ZPOS) &&
+ !mp_iszero(c) &&
+ ((c->dp[0] + b) < MP_DIGIT_MAX)) {
+ c->dp[0] += b;
+ return MP_OKAY;
+ }
+ if ((c->sign == MP_NEG) &&
+ (c->dp[0] > b)) {
+ c->dp[0] -= b;
+ return MP_OKAY;
+ }
}
/* grow c as required */
diff --git a/mp_sub_d.c b/mp_sub_d.c
index e453d36..96a747c 100644
--- a/mp_sub_d.c
+++ b/mp_sub_d.c
@@ -11,12 +11,17 @@ mp_err mp_sub_d(const mp_int *a, mp_digit b, mp_int *c)
int ix, oldused;
/* fast path for a == c */
- if (a == c &&
- !mp_iszero(c) &&
- c->sign == MP_ZPOS &&
- c->dp[0] > b) {
- c->dp[0] -= b;
- return MP_OKAY;
+ 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 */