Debian Codegraph @

libtommath/bn_mp_mul_2d.c

raw
1 #include "tommath_private.h"
2 #ifdef BN_MP_MUL_2D_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
5
6 /* shift left by a certain bit count */
7 mp_err mp_mul_2d(const mp_int *a, int b, mp_int *c)
8 {
9 mp_digit d;
10 mp_err err;
11
12 if (b < 0) {
13 return MP_VAL;
14 }
15
16 /* copy */
17 if (a != c) {
18 if ((err = mp_copy(a, c)) != MP_OKAY) {
19 return err;
20 }
21 }
22
23 if (c->alloc < (c->used + (b / MP_DIGIT_BIT) + 1)) {
24 if ((err = mp_grow(c, c->used + (b / MP_DIGIT_BIT) + 1)) != MP_OKAY) {
25 return err;
26 }
27 }
28
29 /* shift by as many digits in the bit count */
30 if (b >= MP_DIGIT_BIT) {
31 if ((err = mp_lshd(c, b / MP_DIGIT_BIT)) != MP_OKAY) {
32 return err;
33 }
34 }
35
36 /* shift any bit count < MP_DIGIT_BIT */
37 d = (mp_digit)(b % MP_DIGIT_BIT);
38 if (d != 0u) {
39 mp_digit *tmpc, shift, mask, r, rr;
40 int x;
41
42 /* bitmask for carries */
43 mask = ((mp_digit)1 << d) - (mp_digit)1;
44
45 /* shift for msbs */
46 shift = (mp_digit)MP_DIGIT_BIT - d;
47
48 /* alias */
49 tmpc = c->dp;
50
51 /* carry */
52 r = 0;
53 for (x = 0; x < c->used; x++) {
54 /* get the higher bits of the current word */
55 rr = (*tmpc >> shift) & mask;
56
57 /* shift the current word and OR in the carry */
58 *tmpc = ((*tmpc << d) | r) & MP_MASK;
59 ++tmpc;
60
61 /* set the carry to the carry bits of the current word */
62 r = rr;
63 }
64
65 /* set final carry */
66 if (r != 0u) {
67 c->dp[(c->used)++] = r;
68 }
69 }
70 mp_clamp(c);
71 return MP_OKAY;
72 }
73 #endif