Bump actions/upload-artifacts version
[libtommath.git] / mp_reduce.c
blobb6fae55ccf0b1db2da499c07ddea76713e9c3210
1 #include "tommath_private.h"
2 #ifdef MP_REDUCE_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* reduces x mod m, assumes 0 < x < m**2, mu is
7 * precomputed via mp_reduce_setup.
8 * From HAC pp.604 Algorithm 14.42
9 */
10 mp_err mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu)
12 mp_int q;
13 mp_err err;
14 int um = m->used;
16 /* q = x */
17 if ((err = mp_init_copy(&q, x)) != MP_OKAY) {
18 return err;
21 /* q1 = x / b**(k-1) */
22 mp_rshd(&q, um - 1);
24 /* according to HAC this optimization is ok */
25 if ((mp_digit)um > ((mp_digit)1 << (MP_DIGIT_BIT - 1))) {
26 if ((err = mp_mul(&q, mu, &q)) != MP_OKAY) {
27 goto LBL_ERR;
29 } else if (MP_HAS(S_MP_MUL_HIGH)) {
30 if ((err = s_mp_mul_high(&q, mu, &q, um)) != MP_OKAY) {
31 goto LBL_ERR;
33 } else if (MP_HAS(S_MP_MUL_HIGH_COMBA)) {
34 if ((err = s_mp_mul_high_comba(&q, mu, &q, um)) != MP_OKAY) {
35 goto LBL_ERR;
37 } else {
38 err = MP_VAL;
39 goto LBL_ERR;
42 /* q3 = q2 / b**(k+1) */
43 mp_rshd(&q, um + 1);
45 /* x = x mod b**(k+1), quick (no division) */
46 if ((err = mp_mod_2d(x, MP_DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
47 goto LBL_ERR;
50 /* q = q * m mod b**(k+1), quick (no division) */
51 if ((err = s_mp_mul(&q, m, &q, um + 1)) != MP_OKAY) {
52 goto LBL_ERR;
55 /* x = x - q */
56 if ((err = mp_sub(x, &q, x)) != MP_OKAY) {
57 goto LBL_ERR;
60 /* If x < 0, add b**(k+1) to it */
61 if (mp_cmp_d(x, 0uL) == MP_LT) {
62 mp_set(&q, 1uL);
63 if ((err = mp_lshd(&q, um + 1)) != MP_OKAY) {
64 goto LBL_ERR;
66 if ((err = mp_add(x, &q, x)) != MP_OKAY) {
67 goto LBL_ERR;
71 /* Back off if it's too big */
72 while (mp_cmp(x, m) != MP_LT) {
73 if ((err = s_mp_sub(x, m, x)) != MP_OKAY) {
74 goto LBL_ERR;
78 LBL_ERR:
79 mp_clear(&q);
81 return err;
83 #endif