Import mpc-1.0.1 to new vendor branch
[dragonfly.git] / contrib / mpc / src / strtoc.c
1 /* mpc_strtoc -- Read a complex number from a string.
2
3 Copyright (C) 2009, 2010, 2011 INRIA
4
5 This file is part of GNU MPC.
6
7 GNU MPC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU Lesser General Public License as published by the
9 Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
11
12 GNU MPC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
15 more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with this program. If not, see http://www.gnu.org/licenses/ .
19 */
20
21 #include <string.h>
22 #include <ctype.h>
23 #include "mpc-impl.h"
24
25 static void
26 skip_whitespace (const char **p)
27 {
28    /* TODO: This function had better be inlined, but it is unclear whether
29       the hassle to get this implemented across all platforms is worth it. */
30    while (isspace ((unsigned char) **p))
31       (*p)++;
32 }
33
34 int
35 mpc_strtoc (mpc_ptr rop, const char *nptr, char **endptr, int base, mpc_rnd_t rnd)
36 {
37    const char *p;
38    char *end;
39    int bracketed = 0;
40
41    int inex_re = 0, inex_im = 0;
42
43    if (nptr == NULL || base > 36 || base == 1)
44      goto error;
45
46    p = nptr;
47    skip_whitespace (&p);
48
49    if (*p == '('){
50       bracketed = 1;
51       ++p;
52    }
53
54    inex_re = mpfr_strtofr (mpc_realref(rop), p, &end, base, MPC_RND_RE (rnd));
55    if (end == p)
56       goto error;
57    p = end;
58
59    if (!bracketed)
60      inex_im = mpfr_set_ui (mpc_imagref (rop), 0ul, GMP_RNDN);
61    else {
62      if (!isspace ((unsigned char)*p))
63          goto error;
64
65       skip_whitespace (&p);
66
67       inex_im = mpfr_strtofr (mpc_imagref(rop), p, &end, base, MPC_RND_IM (rnd));
68       if (end == p)
69          goto error;
70       p = end;
71
72       skip_whitespace (&p);
73       if (*p != ')')
74          goto error;
75
76       p++;
77    }
78
79    if (endptr != NULL)
80      *endptr = (char*) p;
81    return MPC_INEX (inex_re, inex_im);
82
83 error:
84    if (endptr != NULL)
85      *endptr = (char*) nptr;
86    mpfr_set_nan (mpc_realref (rop));
87    mpfr_set_nan (mpc_imagref (rop));
88    return -1;
89 }