Merge pull request #578 from PX4/fix_mp_prime_strong_lucas_lefridge_compilation
[libtommath.git] / mp_rand.c
blob19364755a37d6cc65a634e6518d6a13d8fce5393
1 #include "tommath_private.h"
2 #ifdef MP_RAND_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 mp_err mp_rand(mp_int *a, int digits)
8 int i;
9 mp_err err;
11 mp_zero(a);
13 if (digits <= 0) {
14 return MP_OKAY;
17 if ((err = mp_grow(a, digits)) != MP_OKAY) {
18 return err;
21 if ((err = s_mp_rand_source(a->dp, (size_t)digits * sizeof(mp_digit))) != MP_OKAY) {
22 return err;
25 /* TODO: We ensure that the highest digit is nonzero. Should this be removed? */
26 while ((a->dp[digits - 1] & MP_MASK) == 0u) {
27 if ((err = s_mp_rand_source(a->dp + digits - 1, sizeof(mp_digit))) != MP_OKAY) {
28 return err;
32 a->used = digits;
33 for (i = 0; i < digits; ++i) {
34 a->dp[i] &= MP_MASK;
37 return MP_OKAY;
39 #endif