Merge pull request #578 from PX4/fix_mp_prime_strong_lucas_lefridge_compilation
[libtommath.git] / mp_grow.c
blob551d1a3bc1f5bee1ca5f8c65e225182d1436f139
1 #include "tommath_private.h"
2 #ifdef MP_GROW_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* grow as required */
7 mp_err mp_grow(mp_int *a, int size)
9 if (size < 0) {
10 return MP_VAL;
13 /* if the alloc size is smaller alloc more ram */
14 if (a->alloc < size) {
15 mp_digit *dp;
17 if (size > MP_MAX_DIGIT_COUNT) {
18 return MP_OVF;
21 /* reallocate the array a->dp
23 * We store the return in a temporary variable
24 * in case the operation failed we don't want
25 * to overwrite the dp member of a.
27 dp = (mp_digit *) MP_REALLOC(a->dp,
28 (size_t)a->alloc * sizeof(mp_digit),
29 (size_t)size * sizeof(mp_digit));
30 if (dp == NULL) {
31 /* reallocation failed but "a" is still valid [can be freed] */
32 return MP_MEM;
35 /* reallocation succeeded so set a->dp */
36 a->dp = dp;
38 /* zero excess digits */
39 s_mp_zero_digs(a->dp + a->alloc, size - a->alloc);
40 a->alloc = size;
42 return MP_OKAY;
44 #endif