Debian Codegraph @

pypy/module/cpyext/pystrtod.py

raw symbols SCIP
1 import errno
2 from pypy.interpreter.error import oefmt
3 from pypy.module.cpyext.api import cpython_api, INTP_real
4 from pypy.module.cpyext.pyobject import PyObject
5 from rpython.rlib import rdtoa
6 from rpython.rlib import rfloat
7 from rpython.rlib import rposix, jit
8 from rpython.rlib.rarithmetic import intmask
9 from rpython.rtyper.lltypesystem import lltype
10 from rpython.rtyper.lltypesystem import rffi
11
12
13 # from pystrtod.h
14 # PyOS_double_to_string's "type", if non-NULL, will be set to one of:
15 Py_DTST_FINITE = 0
16 Py_DTST_INFINITE = 1
17 Py_DTST_NAN = 2
18
19 # Match the "type" back to values in CPython
20 DOUBLE_TO_STRING_TYPES_MAP = {
21 rfloat.DIST_FINITE: Py_DTST_FINITE,
22 rfloat.DIST_INFINITY: Py_DTST_INFINITE,
23 rfloat.DIST_NAN: Py_DTST_NAN
24 }
25
26 @cpython_api([rffi.CONST_CCHARP, rffi.CCHARPP, PyObject], rffi.DOUBLE, error=-1.0)
27 @jit.dont_look_inside # direct use of _get_errno()
28 def PyOS_string_to_double(space, s, endptr, w_overflow_exception):
29 """Convert a string s to a double, raising a Python
30 exception on failure. The set of accepted strings corresponds to
31 the set of strings accepted by Python's float() constructor,
32 except that s must not have leading or trailing whitespace.
33 The conversion is independent of the current locale.
34
35 If endptr is NULL, convert the whole string. Raise
36 ValueError and return -1.0 if the string is not a valid
37 representation of a floating-point number.
38
39 If endptr is not NULL, convert as much of the string as
40 possible and set *endptr to point to the first unconverted
41 character. If no initial segment of the string is the valid
42 representation of a floating-point number, set *endptr to point
43 to the beginning of the string, raise ValueError, and return
44 -1.0.
45
46 If s represents a value that is too large to store in a float
47 (for example, "1e500" is such a string on many platforms) then
48 if overflow_exception is NULL return Py_HUGE_VAL (with
49 an appropriate sign) and don't set any exception. Otherwise,
50 overflow_exception must point to a Python exception object;
51 raise that exception and return -1.0. In both cases, set
52 *endptr to point to the first character after the converted value.
53
54 If any other error occurs during the conversion (for example an
55 out-of-memory error), set the appropriate Python exception and
56 return -1.0.
57 """
58 user_endptr = True
59 try:
60 if not endptr:
61 endptr = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
62 user_endptr = False
63 result = rdtoa.dg_strtod(s, endptr)
64 endpos = (rffi.cast(lltype.Signed, endptr[0]) -
65 rffi.cast(lltype.Signed, s))
66 if endpos != 0 and not user_endptr and endptr[0][0] != '\0':
67 # Not all of s was converted
68 raise oefmt(space.w_ValueError,
69 "could not convert string to float: '%s'",
70 rffi.constcharp2str(s))
71 elif endpos == 0:
72 low = rffi.constcharp2str(s).lower()
73 sz = 0
74 if len(low) < 3:
75 pass
76 elif low[0] == '-':
77 if low.startswith('-infinity'):
78 result = -rfloat.INFINITY
79 sz = len("-infinity")
80 elif low.startswith("-inf"):
81 result = -rfloat.INFINITY
82 sz = 4
83 elif low.startswith("-nan"):
84 result = -rfloat.NAN
85 sz = 4
86 elif low[0] == '+':
87 if low.startswith("+infinity"):
88 result = rfloat.INFINITY
89 sz = len("+infinity")
90 elif low.startswith("+inf"):
91 result = rfloat.INFINITY
92 sz = 4
93 elif low.startswith("+nan"):
94 result = rfloat.NAN
95 sz = 4
96 elif low.startswith("infinity"):
97 result = rfloat.INFINITY
98 sz = len("infinity")
99 elif low.startswith("inf"):
100 result = rfloat.INFINITY
101 sz = 3
102 elif low.startswith("nan"):
103 result = rfloat.NAN
104 sz = 3
105 # result is set to 0.0 for a parse_error in dtoa.c
106 # if it changed, we must have sucessfully converted
107 if result != 0.0:
108 if not user_endptr and sz != len(low):
109 # Not all of s was converted
110 raise oefmt(space.w_ValueError,
111 "could not convert string to float: '%s'",
112 rffi.constcharp2str(s))
113 if endptr:
114 endptr[0] = rffi.cast(rffi.CCHARP, rffi.ptradd(s, sz))
115 return result
116 raise oefmt(space.w_ValueError,
117 "invalid input at position %d", endpos)
118 err = rffi.cast(lltype.Signed, rposix._get_errno())
119 if err == errno.ERANGE:
120 if w_overflow_exception is None:
121 if result > 0:
122 return rfloat.INFINITY
123 else:
124 return -rfloat.INFINITY
125 else:
126 rposix._set_errno(rffi.cast(rffi.INT, 0))
127 raise oefmt(w_overflow_exception, "value too large")
128 return result
129 finally:
130 if not user_endptr:
131 lltype.free(endptr, flavor='raw')
132
133 @cpython_api([rffi.DOUBLE, lltype.Char, rffi.INT_real, rffi.INT_real, INTP_real], rffi.CCHARP)
134 def PyOS_double_to_string(space, val, format_code, precision, flags, ptype):
135 """Convert a double val to a string using supplied
136 format_code, precision, and flags.
137
138 format_code must be one of 'e', 'E', 'f', 'F',
139 'g', 'G' or 'r'. For 'r', the supplied precision
140 must be 0 and is ignored. The 'r' format code specifies the
141 standard repr() format.
142
143 flags can be zero or more of the values Py_DTSF_SIGN,
144 Py_DTSF_ADD_DOT_0, or Py_DTSF_ALT, or-ed together:
145
146 Py_DTSF_SIGN means to always precede the returned string with a sign
147 character, even if val is non-negative.
148
149 Py_DTSF_ADD_DOT_0 means to ensure that the returned string will not look
150 like an integer.
151
152 Py_DTSF_ALT means to apply "alternate" formatting rules. See the
153 documentation for the PyOS_snprintf() '#' specifier for
154 details.
155
156 If ptype is non-NULL, then the value it points to will be set to one of
157 Py_DTST_FINITE, Py_DTST_INFINITE, or Py_DTST_NAN, signifying that
158 val is a finite number, an infinite number, or not a number, respectively.
159
160 The return value is a pointer to buffer with the converted string or
161 NULL if the conversion failed. The caller is responsible for freeing the
162 returned string by calling PyMem_Free().
163 """
164 buffer, rtype = rfloat.double_to_string(val, format_code,
165 intmask(precision),
166 intmask(flags))
167 if ptype != lltype.nullptr(INTP_real.TO):
168 ptype[0] = rffi.cast(rffi.INT_real, DOUBLE_TO_STRING_TYPES_MAP[rtype])
169 bufp = rffi.str2charp(buffer)
170 return bufp