Bump actions/upload-artifacts version
[libtommath.git] / mp_fread.c
blob53c35e8223ff93b5879672a38f4c005547e3fe15
1 #include "tommath_private.h"
2 #ifdef MP_FREAD_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 #ifndef MP_NO_FILE
7 /* read a bigint from a file stream in ASCII */
8 mp_err mp_fread(mp_int *a, int radix, FILE *stream)
10 mp_err err;
11 mp_sign sign = MP_ZPOS;
12 int ch;
14 /* make sure the radix is ok */
15 if ((radix < 2) || (radix > 64)) {
16 return MP_VAL;
19 /* if first digit is - then set negative */
20 ch = fgetc(stream);
21 if (ch == (int)'-') {
22 sign = MP_NEG;
23 ch = fgetc(stream);
26 /* no digits, return error */
27 if (ch == EOF) {
28 return MP_ERR;
31 /* clear a */
32 mp_zero(a);
34 do {
35 uint8_t y;
36 unsigned pos;
37 ch = (radix <= 36) ? MP_TOUPPER(ch) : ch;
38 pos = (unsigned)(ch - (int)'+');
39 if (MP_RADIX_MAP_REVERSE_SIZE <= pos) {
40 break;
43 y = s_mp_radix_map_reverse[pos];
45 if (y >= radix) {
46 break;
49 /* shift up and add */
50 if ((err = mp_mul_d(a, (mp_digit)radix, a)) != MP_OKAY) {
51 return err;
53 if ((err = mp_add_d(a, y, a)) != MP_OKAY) {
54 return err;
56 } while ((ch = fgetc(stream)) != EOF);
58 if (!mp_iszero(a)) {
59 a->sign = sign;
62 return MP_OKAY;
64 #endif
66 #endif