handle EOF condition in mp_fread, fix #163
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
diff --git a/bn_mp_fread.c b/bn_mp_fread.c
index bbb59a5..04a1316 100644
--- a/bn_mp_fread.c
+++ b/bn_mp_fread.c
@@ -9,14 +9,9 @@ mp_err mp_fread(mp_int *a, int radix, FILE *stream)
{
mp_err err;
mp_sign neg;
- int ch, y;
- unsigned pos;
-
- /* clear a */
- mp_zero(a);
/* if first digit is - then set negative */
- ch = fgetc(stream);
+ int ch = fgetc(stream);
if (ch == (int)'-') {
neg = MP_NEG;
ch = fgetc(stream);
@@ -24,8 +19,17 @@ mp_err mp_fread(mp_int *a, int radix, FILE *stream)
neg = MP_ZPOS;
}
- for (;;) {
- pos = (unsigned)(ch - (int)'(');
+ /* no digits, return error */
+ if (ch == EOF) {
+ return MP_ERR;
+ }
+
+ /* clear a */
+ mp_zero(a);
+
+ do {
+ int y;
+ unsigned pos = (unsigned)(ch - (int)'(');
if (mp_s_rmap_reverse_sz < pos) {
break;
}
@@ -43,10 +47,9 @@ mp_err mp_fread(mp_int *a, int radix, FILE *stream)
if ((err = mp_add_d(a, (mp_digit)y, a)) != MP_OKAY) {
return err;
}
+ } while ((ch = fgetc(stream)) != EOF);
- ch = fgetc(stream);
- }
- if (mp_cmp_d(a, 0uL) != MP_EQ) {
+ if (!mp_iszero(a)) {
a->sign = neg;
}
diff --git a/tommath_class.h b/tommath_class.h
index f102f1c..d51c7f8 100644
--- a/tommath_class.h
+++ b/tommath_class.h
@@ -398,7 +398,7 @@
# define BN_MP_ZERO_C
# define BN_MP_MUL_D_C
# define BN_MP_ADD_D_C
-# define BN_MP_CMP_D_C
+# define BN_MP_ISZERO_C
#endif
#if defined(BN_MP_FWRITE_C)