You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1249 lines
39 KiB

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