Import gmp-4.3.1
[dragonfly.git] / contrib / gmp / mpf / 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 1996, 2000, 2001, 2002, 2005 Free Software Foundation, Inc.
5
6 This file is part of the GNU MP Library.
7
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
12
13 The GNU MP Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16 License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
20
21 #include <stdio.h>
22 #include <ctype.h>
23 #include "gmp.h"
24 #include "gmp-impl.h"
25
26 size_t
27 mpf_inp_str (mpf_ptr rop, FILE *stream, int base)
28 {
29   char *str;
30   size_t alloc_size, str_size;
31   int c;
32   int res;
33   size_t nread;
34
35   if (stream == 0)
36     stream = stdin;
37
38   alloc_size = 100;
39   str = (char *) (*__gmp_allocate_func) (alloc_size);
40   str_size = 0;
41   nread = 0;
42
43   /* Skip whitespace.  */
44   do
45     {
46       c = getc (stream);
47       nread++;
48     }
49   while (isspace (c));
50
51   for (;;)
52     {
53       if (str_size >= alloc_size)
54         {
55           size_t old_alloc_size = alloc_size;
56           alloc_size = alloc_size * 3 / 2;
57           str = (char *) (*__gmp_reallocate_func) (str, old_alloc_size, alloc_size);
58         }
59       if (c == EOF || isspace (c))
60         break;
61       str[str_size++] = c;
62       c = getc (stream);
63     }
64   ungetc (c, stream);
65   nread--;
66
67   if (str_size >= alloc_size)
68     {
69       size_t old_alloc_size = alloc_size;
70       alloc_size = alloc_size * 3 / 2;
71       str = (char *) (*__gmp_reallocate_func) (str, old_alloc_size, alloc_size);
72     }
73   str[str_size] = 0;
74
75   res = mpf_set_str (rop, str, base);
76   (*__gmp_free_func) (str, alloc_size);
77
78   if (res == -1)
79     return 0;                   /* error */
80
81   return str_size + nread;
82 }