Import mpfr-2.4.1
[dragonfly.git] / contrib / mpfr / inp_str.c
1 /* mpf_inp_str(dest_float, stream, base) -- Input a number in base
2    BASE from stdio stream STREAM and store the result in DEST_FLOAT.
3
4 Copyright 1999, 2001, 2002, 2004, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5 Contributed by the Arenaire and Cacao projects, INRIA.
6 (Copied from GMP, file mpf/inp_str.c)
7
8 This file is part of the GNU MPFR Library.
9
10 The GNU MPFR Library is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 2.1 of the License, or (at your
13 option) any later version.
14
15 The GNU MPFR Library is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
18 License for more details.
19
20 You should have received a copy of the GNU Lesser General Public License
21 along with the GNU MPFR Library; see the file COPYING.LIB.  If not, write to
22 the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
23 MA 02110-1301, USA. */
24
25 #include <ctype.h>
26
27 #include "mpfr-impl.h"
28
29 size_t
30 mpfr_inp_str (mpfr_ptr rop, FILE *stream, int base, mp_rnd_t rnd_mode)
31 {
32   unsigned char *str;
33   size_t alloc_size, str_size;
34   int c;
35   int retval;
36   size_t nread;
37
38   MPFR_CLEAR_FLAGS(rop);
39   if (stream == NULL)
40     stream = stdin;
41
42   alloc_size = 100;
43   str = (unsigned char *) (*__gmp_allocate_func) (alloc_size);
44   str_size = 0;
45   nread = 0;
46
47   /* Skip whitespace.  */
48   do
49     {
50       c = getc (stream);
51       nread++;
52     }
53   while (isspace (c));
54
55   /* number of characters read is nread */
56
57   for (;;)
58     {
59       if (str_size >= alloc_size)
60         {
61           size_t old_alloc_size = alloc_size;
62           alloc_size = alloc_size * 3 / 2;
63           str = (unsigned char *)
64             (*__gmp_reallocate_func) (str, old_alloc_size, alloc_size);
65         }
66       if (c == EOF || isspace (c))
67         break;
68       str[str_size++] = (unsigned char) c;
69       c = getc (stream);
70     }
71   ungetc (c, stream);
72
73   /* number of characters read is nread + str_size - 1 */
74
75   /* we can exit the for loop only by the break instruction,
76      then necessarily str_size >= alloc_size was checked, so
77      now str_size < alloc_size */
78
79   str[str_size] = '\0';
80
81   retval = mpfr_set_str (rop, (char *) str, base, rnd_mode);
82   (*__gmp_free_func) (str, alloc_size);
83
84   if (retval == -1)
85     return 0;                   /* error */
86
87  return str_size + nread - 1;
88 }