pystrtod.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. /* -*- Mode: C; c-file-style: "python" -*- */
  2. #include <Python.h>
  3. #include "pycore_dtoa.h" // _Py_dg_strtod()
  4. #include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR
  5. #include <locale.h>
  6. /* Case-insensitive string match used for nan and inf detection; t should be
  7. lower-case. Returns 1 for a successful match, 0 otherwise. */
  8. static int
  9. case_insensitive_match(const char *s, const char *t)
  10. {
  11. while(*t && Py_TOLOWER(*s) == *t) {
  12. s++;
  13. t++;
  14. }
  15. return *t ? 0 : 1;
  16. }
  17. /* _Py_parse_inf_or_nan: Attempt to parse a string of the form "nan", "inf" or
  18. "infinity", with an optional leading sign of "+" or "-". On success,
  19. return the NaN or Infinity as a double and set *endptr to point just beyond
  20. the successfully parsed portion of the string. On failure, return -1.0 and
  21. set *endptr to point to the start of the string. */
  22. double
  23. _Py_parse_inf_or_nan(const char *p, char **endptr)
  24. {
  25. double retval;
  26. const char *s;
  27. int negate = 0;
  28. s = p;
  29. if (*s == '-') {
  30. negate = 1;
  31. s++;
  32. }
  33. else if (*s == '+') {
  34. s++;
  35. }
  36. if (case_insensitive_match(s, "inf")) {
  37. s += 3;
  38. if (case_insensitive_match(s, "inity"))
  39. s += 5;
  40. retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL;
  41. }
  42. else if (case_insensitive_match(s, "nan")) {
  43. s += 3;
  44. retval = negate ? -fabs(Py_NAN) : fabs(Py_NAN);
  45. }
  46. else {
  47. s = p;
  48. retval = -1.0;
  49. }
  50. *endptr = (char *)s;
  51. return retval;
  52. }
  53. /**
  54. * _PyOS_ascii_strtod:
  55. * @nptr: the string to convert to a numeric value.
  56. * @endptr: if non-%NULL, it returns the character after
  57. * the last character used in the conversion.
  58. *
  59. * Converts a string to a #gdouble value.
  60. * This function behaves like the standard strtod() function
  61. * does in the C locale. It does this without actually
  62. * changing the current locale, since that would not be
  63. * thread-safe.
  64. *
  65. * This function is typically used when reading configuration
  66. * files or other non-user input that should be locale independent.
  67. * To handle input from the user you should normally use the
  68. * locale-sensitive system strtod() function.
  69. *
  70. * If the correct value would cause overflow, plus or minus %HUGE_VAL
  71. * is returned (according to the sign of the value), and %ERANGE is
  72. * stored in %errno. If the correct value would cause underflow,
  73. * zero is returned and %ERANGE is stored in %errno.
  74. * If memory allocation fails, %ENOMEM is stored in %errno.
  75. *
  76. * This function resets %errno before calling strtod() so that
  77. * you can reliably detect overflow and underflow.
  78. *
  79. * Return value: the #gdouble value.
  80. **/
  81. #if _PY_SHORT_FLOAT_REPR == 1
  82. static double
  83. _PyOS_ascii_strtod(const char *nptr, char **endptr)
  84. {
  85. double result;
  86. _Py_SET_53BIT_PRECISION_HEADER;
  87. assert(nptr != NULL);
  88. /* Set errno to zero, so that we can distinguish zero results
  89. and underflows */
  90. errno = 0;
  91. _Py_SET_53BIT_PRECISION_START;
  92. result = _Py_dg_strtod(nptr, endptr);
  93. _Py_SET_53BIT_PRECISION_END;
  94. if (*endptr == nptr)
  95. /* string might represent an inf or nan */
  96. result = _Py_parse_inf_or_nan(nptr, endptr);
  97. return result;
  98. }
  99. #else
  100. /*
  101. Use system strtod; since strtod is locale aware, we may
  102. have to first fix the decimal separator.
  103. Note that unlike _Py_dg_strtod, the system strtod may not always give
  104. correctly rounded results.
  105. */
  106. static double
  107. _PyOS_ascii_strtod(const char *nptr, char **endptr)
  108. {
  109. char *fail_pos;
  110. double val;
  111. struct lconv *locale_data;
  112. const char *decimal_point;
  113. size_t decimal_point_len;
  114. const char *p, *decimal_point_pos;
  115. const char *end = NULL; /* Silence gcc */
  116. const char *digits_pos = NULL;
  117. int negate = 0;
  118. assert(nptr != NULL);
  119. fail_pos = NULL;
  120. locale_data = localeconv();
  121. decimal_point = locale_data->decimal_point;
  122. decimal_point_len = strlen(decimal_point);
  123. assert(decimal_point_len != 0);
  124. decimal_point_pos = NULL;
  125. /* Parse infinities and nans */
  126. val = _Py_parse_inf_or_nan(nptr, endptr);
  127. if (*endptr != nptr)
  128. return val;
  129. /* Set errno to zero, so that we can distinguish zero results
  130. and underflows */
  131. errno = 0;
  132. /* We process the optional sign manually, then pass the remainder to
  133. the system strtod. This ensures that the result of an underflow
  134. has the correct sign. (bug #1725) */
  135. p = nptr;
  136. /* Process leading sign, if present */
  137. if (*p == '-') {
  138. negate = 1;
  139. p++;
  140. }
  141. else if (*p == '+') {
  142. p++;
  143. }
  144. /* Some platform strtods accept hex floats; Python shouldn't (at the
  145. moment), so we check explicitly for strings starting with '0x'. */
  146. if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X'))
  147. goto invalid_string;
  148. /* Check that what's left begins with a digit or decimal point */
  149. if (!Py_ISDIGIT(*p) && *p != '.')
  150. goto invalid_string;
  151. digits_pos = p;
  152. if (decimal_point[0] != '.' ||
  153. decimal_point[1] != 0)
  154. {
  155. /* Look for a '.' in the input; if present, it'll need to be
  156. swapped for the current locale's decimal point before we
  157. call strtod. On the other hand, if we find the current
  158. locale's decimal point then the input is invalid. */
  159. while (Py_ISDIGIT(*p))
  160. p++;
  161. if (*p == '.')
  162. {
  163. decimal_point_pos = p++;
  164. /* locate end of number */
  165. while (Py_ISDIGIT(*p))
  166. p++;
  167. if (*p == 'e' || *p == 'E')
  168. p++;
  169. if (*p == '+' || *p == '-')
  170. p++;
  171. while (Py_ISDIGIT(*p))
  172. p++;
  173. end = p;
  174. }
  175. else if (strncmp(p, decimal_point, decimal_point_len) == 0)
  176. /* Python bug #1417699 */
  177. goto invalid_string;
  178. /* For the other cases, we need not convert the decimal
  179. point */
  180. }
  181. if (decimal_point_pos) {
  182. char *copy, *c;
  183. /* Create a copy of the input, with the '.' converted to the
  184. locale-specific decimal point */
  185. copy = (char *)PyMem_Malloc(end - digits_pos +
  186. 1 + decimal_point_len);
  187. if (copy == NULL) {
  188. *endptr = (char *)nptr;
  189. errno = ENOMEM;
  190. return val;
  191. }
  192. c = copy;
  193. memcpy(c, digits_pos, decimal_point_pos - digits_pos);
  194. c += decimal_point_pos - digits_pos;
  195. memcpy(c, decimal_point, decimal_point_len);
  196. c += decimal_point_len;
  197. memcpy(c, decimal_point_pos + 1,
  198. end - (decimal_point_pos + 1));
  199. c += end - (decimal_point_pos + 1);
  200. *c = 0;
  201. val = strtod(copy, &fail_pos);
  202. if (fail_pos)
  203. {
  204. if (fail_pos > decimal_point_pos)
  205. fail_pos = (char *)digits_pos +
  206. (fail_pos - copy) -
  207. (decimal_point_len - 1);
  208. else
  209. fail_pos = (char *)digits_pos +
  210. (fail_pos - copy);
  211. }
  212. PyMem_Free(copy);
  213. }
  214. else {
  215. val = strtod(digits_pos, &fail_pos);
  216. }
  217. if (fail_pos == digits_pos)
  218. goto invalid_string;
  219. if (negate && fail_pos != nptr)
  220. val = -val;
  221. *endptr = fail_pos;
  222. return val;
  223. invalid_string:
  224. *endptr = (char*)nptr;
  225. errno = EINVAL;
  226. return -1.0;
  227. }
  228. #endif
  229. /* PyOS_string_to_double converts a null-terminated byte string s (interpreted
  230. as a string of ASCII characters) to a float. The string should not have
  231. leading or trailing whitespace. The conversion is independent of the
  232. current locale.
  233. If endptr is NULL, try to convert the whole string. Raise ValueError and
  234. return -1.0 if the string is not a valid representation of a floating-point
  235. number.
  236. If endptr is non-NULL, try to convert as much of the string as possible.
  237. If no initial segment of the string is the valid representation of a
  238. floating-point number then *endptr is set to point to the beginning of the
  239. string, -1.0 is returned and again ValueError is raised.
  240. On overflow (e.g., when trying to convert '1e500' on an IEEE 754 machine),
  241. if overflow_exception is NULL then +-Py_HUGE_VAL is returned, and no Python
  242. exception is raised. Otherwise, overflow_exception should point to
  243. a Python exception, this exception will be raised, -1.0 will be returned,
  244. and *endptr will point just past the end of the converted value.
  245. If any other failure occurs (for example lack of memory), -1.0 is returned
  246. and the appropriate Python exception will have been set.
  247. */
  248. double
  249. PyOS_string_to_double(const char *s,
  250. char **endptr,
  251. PyObject *overflow_exception)
  252. {
  253. double x, result=-1.0;
  254. char *fail_pos;
  255. errno = 0;
  256. x = _PyOS_ascii_strtod(s, &fail_pos);
  257. if (errno == ENOMEM) {
  258. PyErr_NoMemory();
  259. fail_pos = (char *)s;
  260. }
  261. else if (!endptr && (fail_pos == s || *fail_pos != '\0'))
  262. PyErr_Format(PyExc_ValueError,
  263. "could not convert string to float: "
  264. "'%.200s'", s);
  265. else if (fail_pos == s)
  266. PyErr_Format(PyExc_ValueError,
  267. "could not convert string to float: "
  268. "'%.200s'", s);
  269. else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception)
  270. PyErr_Format(overflow_exception,
  271. "value too large to convert to float: "
  272. "'%.200s'", s);
  273. else
  274. result = x;
  275. if (endptr != NULL)
  276. *endptr = fail_pos;
  277. return result;
  278. }
  279. /* Remove underscores that follow the underscore placement rule from
  280. the string and then call the `innerfunc` function on the result.
  281. It should return a new object or NULL on exception.
  282. `what` is used for the error message emitted when underscores are detected
  283. that don't follow the rule. `arg` is an opaque pointer passed to the inner
  284. function.
  285. This is used to implement underscore-agnostic conversion for floats
  286. and complex numbers.
  287. */
  288. PyObject *
  289. _Py_string_to_number_with_underscores(
  290. const char *s, Py_ssize_t orig_len, const char *what, PyObject *obj, void *arg,
  291. PyObject *(*innerfunc)(const char *, Py_ssize_t, void *))
  292. {
  293. char prev;
  294. const char *p, *last;
  295. char *dup, *end;
  296. PyObject *result;
  297. assert(s[orig_len] == '\0');
  298. if (strchr(s, '_') == NULL) {
  299. return innerfunc(s, orig_len, arg);
  300. }
  301. dup = PyMem_Malloc(orig_len + 1);
  302. if (dup == NULL) {
  303. return PyErr_NoMemory();
  304. }
  305. end = dup;
  306. prev = '\0';
  307. last = s + orig_len;
  308. for (p = s; *p; p++) {
  309. if (*p == '_') {
  310. /* Underscores are only allowed after digits. */
  311. if (!(prev >= '0' && prev <= '9')) {
  312. goto error;
  313. }
  314. }
  315. else {
  316. *end++ = *p;
  317. /* Underscores are only allowed before digits. */
  318. if (prev == '_' && !(*p >= '0' && *p <= '9')) {
  319. goto error;
  320. }
  321. }
  322. prev = *p;
  323. }
  324. /* Underscores are not allowed at the end. */
  325. if (prev == '_') {
  326. goto error;
  327. }
  328. /* No embedded NULs allowed. */
  329. if (p != last) {
  330. goto error;
  331. }
  332. *end = '\0';
  333. result = innerfunc(dup, end - dup, arg);
  334. PyMem_Free(dup);
  335. return result;
  336. error:
  337. PyMem_Free(dup);
  338. PyErr_Format(PyExc_ValueError,
  339. "could not convert string to %s: "
  340. "%R", what, obj);
  341. return NULL;
  342. }
  343. #if _PY_SHORT_FLOAT_REPR == 0
  344. /* Given a string that may have a decimal point in the current
  345. locale, change it back to a dot. Since the string cannot get
  346. longer, no need for a maximum buffer size parameter. */
  347. Py_LOCAL_INLINE(void)
  348. change_decimal_from_locale_to_dot(char* buffer)
  349. {
  350. struct lconv *locale_data = localeconv();
  351. const char *decimal_point = locale_data->decimal_point;
  352. if (decimal_point[0] != '.' || decimal_point[1] != 0) {
  353. size_t decimal_point_len = strlen(decimal_point);
  354. if (*buffer == '+' || *buffer == '-')
  355. buffer++;
  356. while (Py_ISDIGIT(*buffer))
  357. buffer++;
  358. if (strncmp(buffer, decimal_point, decimal_point_len) == 0) {
  359. *buffer = '.';
  360. buffer++;
  361. if (decimal_point_len > 1) {
  362. /* buffer needs to get smaller */
  363. size_t rest_len = strlen(buffer +
  364. (decimal_point_len - 1));
  365. memmove(buffer,
  366. buffer + (decimal_point_len - 1),
  367. rest_len);
  368. buffer[rest_len] = 0;
  369. }
  370. }
  371. }
  372. }
  373. /* From the C99 standard, section 7.19.6:
  374. The exponent always contains at least two digits, and only as many more digits
  375. as necessary to represent the exponent.
  376. */
  377. #define MIN_EXPONENT_DIGITS 2
  378. /* Ensure that any exponent, if present, is at least MIN_EXPONENT_DIGITS
  379. in length. */
  380. Py_LOCAL_INLINE(void)
  381. ensure_minimum_exponent_length(char* buffer, size_t buf_size)
  382. {
  383. char *p = strpbrk(buffer, "eE");
  384. if (p && (*(p + 1) == '-' || *(p + 1) == '+')) {
  385. char *start = p + 2;
  386. int exponent_digit_cnt = 0;
  387. int leading_zero_cnt = 0;
  388. int in_leading_zeros = 1;
  389. int significant_digit_cnt;
  390. /* Skip over the exponent and the sign. */
  391. p += 2;
  392. /* Find the end of the exponent, keeping track of leading
  393. zeros. */
  394. while (*p && Py_ISDIGIT(*p)) {
  395. if (in_leading_zeros && *p == '0')
  396. ++leading_zero_cnt;
  397. if (*p != '0')
  398. in_leading_zeros = 0;
  399. ++p;
  400. ++exponent_digit_cnt;
  401. }
  402. significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt;
  403. if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) {
  404. /* If there are 2 exactly digits, we're done,
  405. regardless of what they contain */
  406. }
  407. else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) {
  408. int extra_zeros_cnt;
  409. /* There are more than 2 digits in the exponent. See
  410. if we can delete some of the leading zeros */
  411. if (significant_digit_cnt < MIN_EXPONENT_DIGITS)
  412. significant_digit_cnt = MIN_EXPONENT_DIGITS;
  413. extra_zeros_cnt = exponent_digit_cnt -
  414. significant_digit_cnt;
  415. /* Delete extra_zeros_cnt worth of characters from the
  416. front of the exponent */
  417. assert(extra_zeros_cnt >= 0);
  418. /* Add one to significant_digit_cnt to copy the
  419. trailing 0 byte, thus setting the length */
  420. memmove(start,
  421. start + extra_zeros_cnt,
  422. significant_digit_cnt + 1);
  423. }
  424. else {
  425. /* If there are fewer than 2 digits, add zeros
  426. until there are 2, if there's enough room */
  427. int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt;
  428. if (start + zeros + exponent_digit_cnt + 1
  429. < buffer + buf_size) {
  430. memmove(start + zeros, start,
  431. exponent_digit_cnt + 1);
  432. memset(start, '0', zeros);
  433. }
  434. }
  435. }
  436. }
  437. /* Remove trailing zeros after the decimal point from a numeric string; also
  438. remove the decimal point if all digits following it are zero. The numeric
  439. string must end in '\0', and should not have any leading or trailing
  440. whitespace. Assumes that the decimal point is '.'. */
  441. Py_LOCAL_INLINE(void)
  442. remove_trailing_zeros(char *buffer)
  443. {
  444. char *old_fraction_end, *new_fraction_end, *end, *p;
  445. p = buffer;
  446. if (*p == '-' || *p == '+')
  447. /* Skip leading sign, if present */
  448. ++p;
  449. while (Py_ISDIGIT(*p))
  450. ++p;
  451. /* if there's no decimal point there's nothing to do */
  452. if (*p++ != '.')
  453. return;
  454. /* scan any digits after the point */
  455. while (Py_ISDIGIT(*p))
  456. ++p;
  457. old_fraction_end = p;
  458. /* scan up to ending '\0' */
  459. while (*p != '\0')
  460. p++;
  461. /* +1 to make sure that we move the null byte as well */
  462. end = p+1;
  463. /* scan back from fraction_end, looking for removable zeros */
  464. p = old_fraction_end;
  465. while (*(p-1) == '0')
  466. --p;
  467. /* and remove point if we've got that far */
  468. if (*(p-1) == '.')
  469. --p;
  470. new_fraction_end = p;
  471. memmove(new_fraction_end, old_fraction_end, end-old_fraction_end);
  472. }
  473. /* Ensure that buffer has a decimal point in it. The decimal point will not
  474. be in the current locale, it will always be '.'. Don't add a decimal point
  475. if an exponent is present. Also, convert to exponential notation where
  476. adding a '.0' would produce too many significant digits (see issue 5864).
  477. Returns a pointer to the fixed buffer, or NULL on failure.
  478. */
  479. Py_LOCAL_INLINE(char *)
  480. ensure_decimal_point(char* buffer, size_t buf_size, int precision)
  481. {
  482. int digit_count, insert_count = 0, convert_to_exp = 0;
  483. const char *chars_to_insert;
  484. char *digits_start;
  485. /* search for the first non-digit character */
  486. char *p = buffer;
  487. if (*p == '-' || *p == '+')
  488. /* Skip leading sign, if present. I think this could only
  489. ever be '-', but it can't hurt to check for both. */
  490. ++p;
  491. digits_start = p;
  492. while (*p && Py_ISDIGIT(*p))
  493. ++p;
  494. digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int);
  495. if (*p == '.') {
  496. if (Py_ISDIGIT(*(p+1))) {
  497. /* Nothing to do, we already have a decimal
  498. point and a digit after it */
  499. }
  500. else {
  501. /* We have a decimal point, but no following
  502. digit. Insert a zero after the decimal. */
  503. /* can't ever get here via PyOS_double_to_string */
  504. assert(precision == -1);
  505. ++p;
  506. chars_to_insert = "0";
  507. insert_count = 1;
  508. }
  509. }
  510. else if (!(*p == 'e' || *p == 'E')) {
  511. /* Don't add ".0" if we have an exponent. */
  512. if (digit_count == precision) {
  513. /* issue 5864: don't add a trailing .0 in the case
  514. where the '%g'-formatted result already has as many
  515. significant digits as were requested. Switch to
  516. exponential notation instead. */
  517. convert_to_exp = 1;
  518. /* no exponent, no point, and we shouldn't land here
  519. for infs and nans, so we must be at the end of the
  520. string. */
  521. assert(*p == '\0');
  522. }
  523. else {
  524. assert(precision == -1 || digit_count < precision);
  525. chars_to_insert = ".0";
  526. insert_count = 2;
  527. }
  528. }
  529. if (insert_count) {
  530. size_t buf_len = strlen(buffer);
  531. if (buf_len + insert_count + 1 >= buf_size) {
  532. /* If there is not enough room in the buffer
  533. for the additional text, just skip it. It's
  534. not worth generating an error over. */
  535. }
  536. else {
  537. memmove(p + insert_count, p,
  538. buffer + strlen(buffer) - p + 1);
  539. memcpy(p, chars_to_insert, insert_count);
  540. }
  541. }
  542. if (convert_to_exp) {
  543. int written;
  544. size_t buf_avail;
  545. p = digits_start;
  546. /* insert decimal point */
  547. assert(digit_count >= 1);
  548. memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */
  549. p[1] = '.';
  550. p += digit_count+1;
  551. assert(p <= buf_size+buffer);
  552. buf_avail = buf_size+buffer-p;
  553. if (buf_avail == 0)
  554. return NULL;
  555. /* Add exponent. It's okay to use lower case 'e': we only
  556. arrive here as a result of using the empty format code or
  557. repr/str builtins and those never want an upper case 'E' */
  558. written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1);
  559. if (!(0 <= written &&
  560. written < Py_SAFE_DOWNCAST(buf_avail, size_t, int)))
  561. /* output truncated, or something else bad happened */
  562. return NULL;
  563. remove_trailing_zeros(buffer);
  564. }
  565. return buffer;
  566. }
  567. /* see FORMATBUFLEN in unicodeobject.c */
  568. #define FLOAT_FORMATBUFLEN 120
  569. /**
  570. * _PyOS_ascii_formatd:
  571. * @buffer: A buffer to place the resulting string in
  572. * @buf_size: The length of the buffer.
  573. * @format: The printf()-style format to use for the
  574. * code to use for converting.
  575. * @d: The #gdouble to convert
  576. * @precision: The precision to use when formatting.
  577. *
  578. * Converts a #gdouble to a string, using the '.' as
  579. * decimal point. To format the number you pass in
  580. * a printf()-style format string. Allowed conversion
  581. * specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'Z'.
  582. *
  583. * 'Z' is the same as 'g', except it always has a decimal and
  584. * at least one digit after the decimal.
  585. *
  586. * Return value: The pointer to the buffer with the converted string.
  587. * On failure returns NULL but does not set any Python exception.
  588. **/
  589. static char *
  590. _PyOS_ascii_formatd(char *buffer,
  591. size_t buf_size,
  592. const char *format,
  593. double d,
  594. int precision)
  595. {
  596. char format_char;
  597. size_t format_len = strlen(format);
  598. /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but
  599. also with at least one character past the decimal. */
  600. char tmp_format[FLOAT_FORMATBUFLEN];
  601. /* The last character in the format string must be the format char */
  602. format_char = format[format_len - 1];
  603. if (format[0] != '%')
  604. return NULL;
  605. /* I'm not sure why this test is here. It's ensuring that the format
  606. string after the first character doesn't have a single quote, a
  607. lowercase l, or a percent. This is the reverse of the commented-out
  608. test about 10 lines ago. */
  609. if (strpbrk(format + 1, "'l%"))
  610. return NULL;
  611. /* Also curious about this function is that it accepts format strings
  612. like "%xg", which are invalid for floats. In general, the
  613. interface to this function is not very good, but changing it is
  614. difficult because it's a public API. */
  615. if (!(format_char == 'e' || format_char == 'E' ||
  616. format_char == 'f' || format_char == 'F' ||
  617. format_char == 'g' || format_char == 'G' ||
  618. format_char == 'Z'))
  619. return NULL;
  620. /* Map 'Z' format_char to 'g', by copying the format string and
  621. replacing the final char with a 'g' */
  622. if (format_char == 'Z') {
  623. if (format_len + 1 >= sizeof(tmp_format)) {
  624. /* The format won't fit in our copy. Error out. In
  625. practice, this will never happen and will be
  626. detected by returning NULL */
  627. return NULL;
  628. }
  629. strcpy(tmp_format, format);
  630. tmp_format[format_len - 1] = 'g';
  631. format = tmp_format;
  632. }
  633. /* Have PyOS_snprintf do the hard work */
  634. PyOS_snprintf(buffer, buf_size, format, d);
  635. /* Do various fixups on the return string */
  636. /* Get the current locale, and find the decimal point string.
  637. Convert that string back to a dot. */
  638. change_decimal_from_locale_to_dot(buffer);
  639. /* If an exponent exists, ensure that the exponent is at least
  640. MIN_EXPONENT_DIGITS digits, providing the buffer is large enough
  641. for the extra zeros. Also, if there are more than
  642. MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get
  643. back to MIN_EXPONENT_DIGITS */
  644. ensure_minimum_exponent_length(buffer, buf_size);
  645. /* If format_char is 'Z', make sure we have at least one character
  646. after the decimal point (and make sure we have a decimal point);
  647. also switch to exponential notation in some edge cases where the
  648. extra character would produce more significant digits that we
  649. really want. */
  650. if (format_char == 'Z')
  651. buffer = ensure_decimal_point(buffer, buf_size, precision);
  652. return buffer;
  653. }
  654. /* The fallback code to use if _Py_dg_dtoa is not available. */
  655. char * PyOS_double_to_string(double val,
  656. char format_code,
  657. int precision,
  658. int flags,
  659. int *type)
  660. {
  661. char format[32];
  662. Py_ssize_t bufsize;
  663. char *buf;
  664. int t, exp;
  665. int upper = 0;
  666. /* Validate format_code, and map upper and lower case */
  667. switch (format_code) {
  668. case 'e': /* exponent */
  669. case 'f': /* fixed */
  670. case 'g': /* general */
  671. break;
  672. case 'E':
  673. upper = 1;
  674. format_code = 'e';
  675. break;
  676. case 'F':
  677. upper = 1;
  678. format_code = 'f';
  679. break;
  680. case 'G':
  681. upper = 1;
  682. format_code = 'g';
  683. break;
  684. case 'r': /* repr format */
  685. /* Supplied precision is unused, must be 0. */
  686. if (precision != 0) {
  687. PyErr_BadInternalCall();
  688. return NULL;
  689. }
  690. /* The repr() precision (17 significant decimal digits) is the
  691. minimal number that is guaranteed to have enough precision
  692. so that if the number is read back in the exact same binary
  693. value is recreated. This is true for IEEE floating point
  694. by design, and also happens to work for all other modern
  695. hardware. */
  696. precision = 17;
  697. format_code = 'g';
  698. break;
  699. default:
  700. PyErr_BadInternalCall();
  701. return NULL;
  702. }
  703. /* Here's a quick-and-dirty calculation to figure out how big a buffer
  704. we need. In general, for a finite float we need:
  705. 1 byte for each digit of the decimal significand, and
  706. 1 for a possible sign
  707. 1 for a possible decimal point
  708. 2 for a possible [eE][+-]
  709. 1 for each digit of the exponent; if we allow 19 digits
  710. total then we're safe up to exponents of 2**63.
  711. 1 for the trailing nul byte
  712. This gives a total of 24 + the number of digits in the significand,
  713. and the number of digits in the significand is:
  714. for 'g' format: at most precision, except possibly
  715. when precision == 0, when it's 1.
  716. for 'e' format: precision+1
  717. for 'f' format: precision digits after the point, at least 1
  718. before. To figure out how many digits appear before the point
  719. we have to examine the size of the number. If fabs(val) < 1.0
  720. then there will be only one digit before the point. If
  721. fabs(val) >= 1.0, then there are at most
  722. 1+floor(log10(ceiling(fabs(val))))
  723. digits before the point (where the 'ceiling' allows for the
  724. possibility that the rounding rounds the integer part of val
  725. up). A safe upper bound for the above quantity is
  726. 1+floor(exp/3), where exp is the unique integer such that 0.5
  727. <= fabs(val)/2**exp < 1.0. This exp can be obtained from
  728. frexp.
  729. So we allow room for precision+1 digits for all formats, plus an
  730. extra floor(exp/3) digits for 'f' format.
  731. */
  732. if (Py_IS_NAN(val) || Py_IS_INFINITY(val))
  733. /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */
  734. bufsize = 5;
  735. else {
  736. bufsize = 25 + precision;
  737. if (format_code == 'f' && fabs(val) >= 1.0) {
  738. frexp(val, &exp);
  739. bufsize += exp/3;
  740. }
  741. }
  742. buf = PyMem_Malloc(bufsize);
  743. if (buf == NULL) {
  744. PyErr_NoMemory();
  745. return NULL;
  746. }
  747. /* Handle nan and inf. */
  748. if (Py_IS_NAN(val)) {
  749. strcpy(buf, "nan");
  750. t = Py_DTST_NAN;
  751. } else if (Py_IS_INFINITY(val)) {
  752. if (copysign(1., val) == 1.)
  753. strcpy(buf, "inf");
  754. else
  755. strcpy(buf, "-inf");
  756. t = Py_DTST_INFINITE;
  757. } else {
  758. t = Py_DTST_FINITE;
  759. if (flags & Py_DTSF_ADD_DOT_0)
  760. format_code = 'Z';
  761. PyOS_snprintf(format, sizeof(format), "%%%s.%i%c",
  762. (flags & Py_DTSF_ALT ? "#" : ""), precision,
  763. format_code);
  764. _PyOS_ascii_formatd(buf, bufsize, format, val, precision);
  765. if (flags & Py_DTSF_NO_NEG_0 && buf[0] == '-') {
  766. char *buf2 = buf + 1;
  767. while (*buf2 == '0' || *buf2 == '.') {
  768. ++buf2;
  769. }
  770. if (*buf2 == 0 || *buf2 == 'e') {
  771. size_t len = buf2 - buf + strlen(buf2);
  772. assert(buf[len] == 0);
  773. memmove(buf, buf+1, len);
  774. }
  775. }
  776. }
  777. /* Add sign when requested. It's convenient (esp. when formatting
  778. complex numbers) to include a sign even for inf and nan. */
  779. if (flags & Py_DTSF_SIGN && buf[0] != '-') {
  780. size_t len = strlen(buf);
  781. /* the bufsize calculations above should ensure that we've got
  782. space to add a sign */
  783. assert((size_t)bufsize >= len+2);
  784. memmove(buf+1, buf, len+1);
  785. buf[0] = '+';
  786. }
  787. if (upper) {
  788. /* Convert to upper case. */
  789. char *p1;
  790. for (p1 = buf; *p1; p1++)
  791. *p1 = Py_TOUPPER(*p1);
  792. }
  793. if (type)
  794. *type = t;
  795. return buf;
  796. }
  797. #else // _PY_SHORT_FLOAT_REPR == 1
  798. /* _Py_dg_dtoa is available. */
  799. /* I'm using a lookup table here so that I don't have to invent a non-locale
  800. specific way to convert to uppercase */
  801. #define OFS_INF 0
  802. #define OFS_NAN 1
  803. #define OFS_E 2
  804. /* The lengths of these are known to the code below, so don't change them */
  805. static const char * const lc_float_strings[] = {
  806. "inf",
  807. "nan",
  808. "e",
  809. };
  810. static const char * const uc_float_strings[] = {
  811. "INF",
  812. "NAN",
  813. "E",
  814. };
  815. /* Convert a double d to a string, and return a PyMem_Malloc'd block of
  816. memory contain the resulting string.
  817. Arguments:
  818. d is the double to be converted
  819. format_code is one of 'e', 'f', 'g', 'r'. 'e', 'f' and 'g'
  820. correspond to '%e', '%f' and '%g'; 'r' corresponds to repr.
  821. mode is one of '0', '2' or '3', and is completely determined by
  822. format_code: 'e' and 'g' use mode 2; 'f' mode 3, 'r' mode 0.
  823. precision is the desired precision
  824. always_add_sign is nonzero if a '+' sign should be included for positive
  825. numbers
  826. add_dot_0_if_integer is nonzero if integers in non-exponential form
  827. should have ".0" added. Only applies to format codes 'r' and 'g'.
  828. use_alt_formatting is nonzero if alternative formatting should be
  829. used. Only applies to format codes 'e', 'f' and 'g'. For code 'g',
  830. at most one of use_alt_formatting and add_dot_0_if_integer should
  831. be nonzero.
  832. type, if non-NULL, will be set to one of these constants to identify
  833. the type of the 'd' argument:
  834. Py_DTST_FINITE
  835. Py_DTST_INFINITE
  836. Py_DTST_NAN
  837. Returns a PyMem_Malloc'd block of memory containing the resulting string,
  838. or NULL on error. If NULL is returned, the Python error has been set.
  839. */
  840. static char *
  841. format_float_short(double d, char format_code,
  842. int mode, int precision,
  843. int always_add_sign, int add_dot_0_if_integer,
  844. int use_alt_formatting, int no_negative_zero,
  845. const char * const *float_strings, int *type)
  846. {
  847. char *buf = NULL;
  848. char *p = NULL;
  849. Py_ssize_t bufsize = 0;
  850. char *digits, *digits_end;
  851. int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0;
  852. Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end;
  853. _Py_SET_53BIT_PRECISION_HEADER;
  854. /* _Py_dg_dtoa returns a digit string (no decimal point or exponent).
  855. Must be matched by a call to _Py_dg_freedtoa. */
  856. _Py_SET_53BIT_PRECISION_START;
  857. digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign,
  858. &digits_end);
  859. _Py_SET_53BIT_PRECISION_END;
  860. decpt = (Py_ssize_t)decpt_as_int;
  861. if (digits == NULL) {
  862. /* The only failure mode is no memory. */
  863. PyErr_NoMemory();
  864. goto exit;
  865. }
  866. assert(digits_end != NULL && digits_end >= digits);
  867. digits_len = digits_end - digits;
  868. if (no_negative_zero && sign == 1 &&
  869. (digits_len == 0 || (digits_len == 1 && digits[0] == '0'))) {
  870. sign = 0;
  871. }
  872. if (digits_len && !Py_ISDIGIT(digits[0])) {
  873. /* Infinities and nans here; adapt Gay's output,
  874. so convert Infinity to inf and NaN to nan, and
  875. ignore sign of nan. Then return. */
  876. /* ignore the actual sign of a nan */
  877. if (digits[0] == 'n' || digits[0] == 'N')
  878. sign = 0;
  879. /* We only need 5 bytes to hold the result "+inf\0" . */
  880. bufsize = 5; /* Used later in an assert. */
  881. buf = (char *)PyMem_Malloc(bufsize);
  882. if (buf == NULL) {
  883. PyErr_NoMemory();
  884. goto exit;
  885. }
  886. p = buf;
  887. if (sign == 1) {
  888. *p++ = '-';
  889. }
  890. else if (always_add_sign) {
  891. *p++ = '+';
  892. }
  893. if (digits[0] == 'i' || digits[0] == 'I') {
  894. strncpy(p, float_strings[OFS_INF], 3);
  895. p += 3;
  896. if (type)
  897. *type = Py_DTST_INFINITE;
  898. }
  899. else if (digits[0] == 'n' || digits[0] == 'N') {
  900. strncpy(p, float_strings[OFS_NAN], 3);
  901. p += 3;
  902. if (type)
  903. *type = Py_DTST_NAN;
  904. }
  905. else {
  906. /* shouldn't get here: Gay's code should always return
  907. something starting with a digit, an 'I', or 'N' */
  908. Py_UNREACHABLE();
  909. }
  910. goto exit;
  911. }
  912. /* The result must be finite (not inf or nan). */
  913. if (type)
  914. *type = Py_DTST_FINITE;
  915. /* We got digits back, format them. We may need to pad 'digits'
  916. either on the left or right (or both) with extra zeros, so in
  917. general the resulting string has the form
  918. [<sign>]<zeros><digits><zeros>[<exponent>]
  919. where either of the <zeros> pieces could be empty, and there's a
  920. decimal point that could appear either in <digits> or in the
  921. leading or trailing <zeros>.
  922. Imagine an infinite 'virtual' string vdigits, consisting of the
  923. string 'digits' (starting at index 0) padded on both the left and
  924. right with infinite strings of zeros. We want to output a slice
  925. vdigits[vdigits_start : vdigits_end]
  926. of this virtual string. Thus if vdigits_start < 0 then we'll end
  927. up producing some leading zeros; if vdigits_end > digits_len there
  928. will be trailing zeros in the output. The next section of code
  929. determines whether to use an exponent or not, figures out the
  930. position 'decpt' of the decimal point, and computes 'vdigits_start'
  931. and 'vdigits_end'. */
  932. vdigits_end = digits_len;
  933. switch (format_code) {
  934. case 'e':
  935. use_exp = 1;
  936. vdigits_end = precision;
  937. break;
  938. case 'f':
  939. vdigits_end = decpt + precision;
  940. break;
  941. case 'g':
  942. if (decpt <= -4 || decpt >
  943. (add_dot_0_if_integer ? precision-1 : precision))
  944. use_exp = 1;
  945. if (use_alt_formatting)
  946. vdigits_end = precision;
  947. break;
  948. case 'r':
  949. /* convert to exponential format at 1e16. We used to convert
  950. at 1e17, but that gives odd-looking results for some values
  951. when a 16-digit 'shortest' repr is padded with bogus zeros.
  952. For example, repr(2e16+8) would give 20000000000000010.0;
  953. the true value is 20000000000000008.0. */
  954. if (decpt <= -4 || decpt > 16)
  955. use_exp = 1;
  956. break;
  957. default:
  958. PyErr_BadInternalCall();
  959. goto exit;
  960. }
  961. /* if using an exponent, reset decimal point position to 1 and adjust
  962. exponent accordingly.*/
  963. if (use_exp) {
  964. exp = (int)decpt - 1;
  965. decpt = 1;
  966. }
  967. /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start <
  968. decpt < vdigits_end if add_dot_0_if_integer and no exponent */
  969. vdigits_start = decpt <= 0 ? decpt-1 : 0;
  970. if (!use_exp && add_dot_0_if_integer)
  971. vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1;
  972. else
  973. vdigits_end = vdigits_end > decpt ? vdigits_end : decpt;
  974. /* double check inequalities */
  975. assert(vdigits_start <= 0 &&
  976. 0 <= digits_len &&
  977. digits_len <= vdigits_end);
  978. /* decimal point should be in (vdigits_start, vdigits_end] */
  979. assert(vdigits_start < decpt && decpt <= vdigits_end);
  980. /* Compute an upper bound how much memory we need. This might be a few
  981. chars too long, but no big deal. */
  982. bufsize =
  983. /* sign, decimal point and trailing 0 byte */
  984. 3 +
  985. /* total digit count (including zero padding on both sides) */
  986. (vdigits_end - vdigits_start) +
  987. /* exponent "e+100", max 3 numerical digits */
  988. (use_exp ? 5 : 0);
  989. /* Now allocate the memory and initialize p to point to the start of
  990. it. */
  991. buf = (char *)PyMem_Malloc(bufsize);
  992. if (buf == NULL) {
  993. PyErr_NoMemory();
  994. goto exit;
  995. }
  996. p = buf;
  997. /* Add a negative sign if negative, and a plus sign if non-negative
  998. and always_add_sign is true. */
  999. if (sign == 1)
  1000. *p++ = '-';
  1001. else if (always_add_sign)
  1002. *p++ = '+';
  1003. /* note that exactly one of the three 'if' conditions is true,
  1004. so we include exactly one decimal point */
  1005. /* Zero padding on left of digit string */
  1006. if (decpt <= 0) {
  1007. memset(p, '0', decpt-vdigits_start);
  1008. p += decpt - vdigits_start;
  1009. *p++ = '.';
  1010. memset(p, '0', 0-decpt);
  1011. p += 0-decpt;
  1012. }
  1013. else {
  1014. memset(p, '0', 0-vdigits_start);
  1015. p += 0 - vdigits_start;
  1016. }
  1017. /* Digits, with included decimal point */
  1018. if (0 < decpt && decpt <= digits_len) {
  1019. strncpy(p, digits, decpt-0);
  1020. p += decpt-0;
  1021. *p++ = '.';
  1022. strncpy(p, digits+decpt, digits_len-decpt);
  1023. p += digits_len-decpt;
  1024. }
  1025. else {
  1026. strncpy(p, digits, digits_len);
  1027. p += digits_len;
  1028. }
  1029. /* And zeros on the right */
  1030. if (digits_len < decpt) {
  1031. memset(p, '0', decpt-digits_len);
  1032. p += decpt-digits_len;
  1033. *p++ = '.';
  1034. memset(p, '0', vdigits_end-decpt);
  1035. p += vdigits_end-decpt;
  1036. }
  1037. else {
  1038. memset(p, '0', vdigits_end-digits_len);
  1039. p += vdigits_end-digits_len;
  1040. }
  1041. /* Delete a trailing decimal pt unless using alternative formatting. */
  1042. if (p[-1] == '.' && !use_alt_formatting)
  1043. p--;
  1044. /* Now that we've done zero padding, add an exponent if needed. */
  1045. if (use_exp) {
  1046. *p++ = float_strings[OFS_E][0];
  1047. exp_len = sprintf(p, "%+.02d", exp);
  1048. p += exp_len;
  1049. }
  1050. exit:
  1051. if (buf) {
  1052. *p = '\0';
  1053. /* It's too late if this fails, as we've already stepped on
  1054. memory that isn't ours. But it's an okay debugging test. */
  1055. assert(p-buf < bufsize);
  1056. }
  1057. if (digits)
  1058. _Py_dg_freedtoa(digits);
  1059. return buf;
  1060. }
  1061. char * PyOS_double_to_string(double val,
  1062. char format_code,
  1063. int precision,
  1064. int flags,
  1065. int *type)
  1066. {
  1067. const char * const *float_strings = lc_float_strings;
  1068. int mode;
  1069. /* Validate format_code, and map upper and lower case. Compute the
  1070. mode and make any adjustments as needed. */
  1071. switch (format_code) {
  1072. /* exponent */
  1073. case 'E':
  1074. float_strings = uc_float_strings;
  1075. format_code = 'e';
  1076. /* Fall through. */
  1077. case 'e':
  1078. mode = 2;
  1079. precision++;
  1080. break;
  1081. /* fixed */
  1082. case 'F':
  1083. float_strings = uc_float_strings;
  1084. format_code = 'f';
  1085. /* Fall through. */
  1086. case 'f':
  1087. mode = 3;
  1088. break;
  1089. /* general */
  1090. case 'G':
  1091. float_strings = uc_float_strings;
  1092. format_code = 'g';
  1093. /* Fall through. */
  1094. case 'g':
  1095. mode = 2;
  1096. /* precision 0 makes no sense for 'g' format; interpret as 1 */
  1097. if (precision == 0)
  1098. precision = 1;
  1099. break;
  1100. /* repr format */
  1101. case 'r':
  1102. mode = 0;
  1103. /* Supplied precision is unused, must be 0. */
  1104. if (precision != 0) {
  1105. PyErr_BadInternalCall();
  1106. return NULL;
  1107. }
  1108. break;
  1109. default:
  1110. PyErr_BadInternalCall();
  1111. return NULL;
  1112. }
  1113. return format_float_short(val, format_code, mode, precision,
  1114. flags & Py_DTSF_SIGN,
  1115. flags & Py_DTSF_ADD_DOT_0,
  1116. flags & Py_DTSF_ALT,
  1117. flags & Py_DTSF_NO_NEG_0,
  1118. float_strings, type);
  1119. }
  1120. #endif // _PY_SHORT_FLOAT_REPR == 1