Commit c91c1ba2b109e0487c7825ef26e173a075f47611

Daniel Mendler 2019-10-24T21:32:31

rework mp_add_d and mp_sub_d

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 */