Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / libgmp / 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 (C) 1996 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 Library General Public License as published by
10 the Free Software Foundation; either version 2 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 Library General Public
16 License for more details.
17
18 You should have received a copy of the GNU Library General Public License
19 along with the GNU MP Library; see the file COPYING.LIB.  If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21 MA 02111-1307, USA. */
22
23 #include <stdio.h>
24 #include <ctype.h>
25 #include "gmp.h"
26 #include "gmp-impl.h"
27
28 size_t
29 #if __STDC__
30 mpf_inp_str (mpf_ptr rop, FILE *stream, int base)
31 #else
32 mpf_inp_str (rop, stream, base)
33      mpf_ptr rop;
34      FILE *stream;
35      int base;
36 #endif
37 {
38   char *str;
39   size_t alloc_size, str_size;
40   int c;
41   size_t retval;
42   size_t nread;
43
44   if (stream == 0)
45     stream = stdin;
46
47   alloc_size = 100;
48   str = (char *) (*_mp_allocate_func) (alloc_size);
49   str_size = 0;
50   nread = 0;
51
52   /* Skip whitespace.  */
53   do
54     {
55       c = getc (stream);
56       nread++;
57     }
58   while (isspace (c));
59
60   for (;;)
61     {
62       if (str_size >= alloc_size)
63         {
64           size_t old_alloc_size = alloc_size;
65           alloc_size = alloc_size * 3 / 2;
66           str = (char *) (*_mp_reallocate_func) (str, old_alloc_size, alloc_size);
67         }
68       if (c == EOF || isspace (c))
69         break;
70       str[str_size++] = c;
71       c = getc (stream);
72     }
73   ungetc (c, stream);
74
75   if (str_size >= alloc_size)
76     {
77       size_t old_alloc_size = alloc_size;
78       alloc_size = alloc_size * 3 / 2;
79       str = (char *) (*_mp_reallocate_func) (str, old_alloc_size, alloc_size);
80     }
81   str[str_size] = 0;
82
83   retval = mpf_set_str (rop, str, base);
84   if (retval == -1)
85     return 0;                   /* error */
86
87   (*_mp_free_func) (str, alloc_size);
88   return str_size + nread;
89 }