Merge pull request #578 from PX4/fix_mp_prime_strong_lucas_lefridge_compilation
[libtommath.git] / mp_mul_d.c
blob2585055430ebd6c934f1c976d8f4300224669fc8
1 #include "tommath_private.h"
2 #ifdef MP_MUL_D_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* multiply by a digit */
7 mp_err mp_mul_d(const mp_int *a, mp_digit b, mp_int *c)
9 mp_digit u;
10 mp_err err;
11 int ix, oldused;
13 if (b == 1u) {
14 return mp_copy(a, c);
17 /* power of two ? */
18 if (MP_HAS(MP_MUL_2) && (b == 2u)) {
19 return mp_mul_2(a, c);
21 if (MP_HAS(MP_MUL_2D) && MP_IS_2EXPT(b)) {
22 ix = 1;
23 while ((ix < MP_DIGIT_BIT) && (b != (((mp_digit)1)<<ix))) {
24 ix++;
26 return mp_mul_2d(a, ix, c);
29 /* make sure c is big enough to hold a*b */
30 if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
31 return err;
34 /* get the original destinations used count */
35 oldused = c->used;
37 /* set the sign */
38 c->sign = a->sign;
40 /* zero carry */
41 u = 0;
43 /* compute columns */
44 for (ix = 0; ix < a->used; ix++) {
45 /* compute product and carry sum for this term */
46 mp_word r = (mp_word)u + ((mp_word)a->dp[ix] * (mp_word)b);
48 /* mask off higher bits to get a single digit */
49 c->dp[ix] = (mp_digit)(r & (mp_word)MP_MASK);
51 /* send carry into next iteration */
52 u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
55 /* store final carry [if any] and increment ix offset */
56 c->dp[ix] = u;
58 /* set used count */
59 c->used = a->used + 1;
61 /* now zero digits above the top */
62 s_mp_zero_digs(c->dp + c->used, oldused - c->used);
64 mp_clamp(c);
66 return MP_OKAY;
68 #endif