Merge pull request #578 from PX4/fix_mp_prime_strong_lucas_lefridge_compilation
[libtommath.git] / mp_add_d.c
blobc57a80db308a56d6034a6067822810c0aaf09554
1 #include "tommath_private.h"
2 #ifdef MP_ADD_D_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* single digit addition */
7 mp_err mp_add_d(const mp_int *a, mp_digit b, mp_int *c)
9 mp_err err;
10 int oldused;
12 /* fast path for a == c */
13 if (a == c) {
14 if (!mp_isneg(c) &&
15 !mp_iszero(c) &&
16 ((c->dp[0] + b) < MP_DIGIT_MAX)) {
17 c->dp[0] += b;
18 return MP_OKAY;
20 if (mp_isneg(c) &&
21 (c->dp[0] > b)) {
22 c->dp[0] -= b;
23 return MP_OKAY;
27 /* grow c as required */
28 if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
29 return err;
32 /* if a is negative and |a| >= b, call c = |a| - b */
33 if (mp_isneg(a) && ((a->used > 1) || (a->dp[0] >= b))) {
34 mp_int a_ = *a;
35 /* temporarily fix sign of a */
36 a_.sign = MP_ZPOS;
38 /* c = |a| - b */
39 err = mp_sub_d(&a_, b, c);
41 /* fix sign */
42 c->sign = MP_NEG;
44 /* clamp */
45 mp_clamp(c);
47 return err;
50 /* old number of used digits in c */
51 oldused = c->used;
53 /* if a is positive */
54 if (!mp_isneg(a)) {
55 /* add digits, mu is carry */
56 int i;
57 mp_digit mu = b;
58 for (i = 0; i < a->used; i++) {
59 c->dp[i] = a->dp[i] + mu;
60 mu = c->dp[i] >> MP_DIGIT_BIT;
61 c->dp[i] &= MP_MASK;
63 /* set final carry */
64 c->dp[i] = mu;
66 /* setup size */
67 c->used = a->used + 1;
68 } else {
69 /* a was negative and |a| < b */
70 c->used = 1;
72 /* the result is a single digit */
73 c->dp[0] = (a->used == 1) ? b - a->dp[0] : b;
76 /* sign always positive */
77 c->sign = MP_ZPOS;
79 /* now zero to oldused */
80 s_mp_zero_digs(c->dp + c->used, oldused - c->used);
81 mp_clamp(c);
83 return MP_OKAY;
86 #endif