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.

1546 lines
49 KiB

  1. /* implements the unicode (as opposed to string) version of the
  2. built-in formatters for string, int, float. that is, the versions
  3. of int.__float__, etc., that take and return unicode objects */
  4. #include "Python.h"
  5. #include <locale.h>
  6. /* Raises an exception about an unknown presentation type for this
  7. * type. */
  8. static void
  9. unknown_presentation_type(Py_UCS4 presentation_type,
  10. const char* type_name)
  11. {
  12. /* %c might be out-of-range, hence the two cases. */
  13. if (presentation_type > 32 && presentation_type < 128)
  14. PyErr_Format(PyExc_ValueError,
  15. "Unknown format code '%c' "
  16. "for object of type '%.200s'",
  17. (char)presentation_type,
  18. type_name);
  19. else
  20. PyErr_Format(PyExc_ValueError,
  21. "Unknown format code '\\x%x' "
  22. "for object of type '%.200s'",
  23. (unsigned int)presentation_type,
  24. type_name);
  25. }
  26. static void
  27. invalid_comma_type(Py_UCS4 presentation_type)
  28. {
  29. if (presentation_type > 32 && presentation_type < 128)
  30. PyErr_Format(PyExc_ValueError,
  31. "Cannot specify ',' with '%c'.",
  32. (char)presentation_type);
  33. else
  34. PyErr_Format(PyExc_ValueError,
  35. "Cannot specify ',' with '\\x%x'.",
  36. (unsigned int)presentation_type);
  37. }
  38. /*
  39. get_integer consumes 0 or more decimal digit characters from an
  40. input string, updates *result with the corresponding positive
  41. integer, and returns the number of digits consumed.
  42. returns -1 on error.
  43. */
  44. static int
  45. get_integer(PyObject *str, Py_ssize_t *pos, Py_ssize_t end,
  46. Py_ssize_t *result)
  47. {
  48. Py_ssize_t accumulator, digitval;
  49. int numdigits;
  50. accumulator = numdigits = 0;
  51. for (;;(*pos)++, numdigits++) {
  52. if (*pos >= end)
  53. break;
  54. digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ_CHAR(str, *pos));
  55. if (digitval < 0)
  56. break;
  57. /*
  58. Detect possible overflow before it happens:
  59. accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if
  60. accumulator > (PY_SSIZE_T_MAX - digitval) / 10.
  61. */
  62. if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) {
  63. PyErr_Format(PyExc_ValueError,
  64. "Too many decimal digits in format string");
  65. return -1;
  66. }
  67. accumulator = accumulator * 10 + digitval;
  68. }
  69. *result = accumulator;
  70. return numdigits;
  71. }
  72. /************************************************************************/
  73. /*********** standard format specifier parsing **************************/
  74. /************************************************************************/
  75. /* returns true if this character is a specifier alignment token */
  76. Py_LOCAL_INLINE(int)
  77. is_alignment_token(Py_UCS4 c)
  78. {
  79. switch (c) {
  80. case '<': case '>': case '=': case '^':
  81. return 1;
  82. default:
  83. return 0;
  84. }
  85. }
  86. /* returns true if this character is a sign element */
  87. Py_LOCAL_INLINE(int)
  88. is_sign_element(Py_UCS4 c)
  89. {
  90. switch (c) {
  91. case ' ': case '+': case '-':
  92. return 1;
  93. default:
  94. return 0;
  95. }
  96. }
  97. typedef struct {
  98. Py_UCS4 fill_char;
  99. Py_UCS4 align;
  100. int alternate;
  101. Py_UCS4 sign;
  102. Py_ssize_t width;
  103. int thousands_separators;
  104. Py_ssize_t precision;
  105. Py_UCS4 type;
  106. } InternalFormatSpec;
  107. #if 0
  108. /* Occasionally useful for debugging. Should normally be commented out. */
  109. static void
  110. DEBUG_PRINT_FORMAT_SPEC(InternalFormatSpec *format)
  111. {
  112. printf("internal format spec: fill_char %d\n", format->fill_char);
  113. printf("internal format spec: align %d\n", format->align);
  114. printf("internal format spec: alternate %d\n", format->alternate);
  115. printf("internal format spec: sign %d\n", format->sign);
  116. printf("internal format spec: width %zd\n", format->width);
  117. printf("internal format spec: thousands_separators %d\n",
  118. format->thousands_separators);
  119. printf("internal format spec: precision %zd\n", format->precision);
  120. printf("internal format spec: type %c\n", format->type);
  121. printf("\n");
  122. }
  123. #endif
  124. /*
  125. ptr points to the start of the format_spec, end points just past its end.
  126. fills in format with the parsed information.
  127. returns 1 on success, 0 on failure.
  128. if failure, sets the exception
  129. */
  130. static int
  131. parse_internal_render_format_spec(PyObject *format_spec,
  132. Py_ssize_t start, Py_ssize_t end,
  133. InternalFormatSpec *format,
  134. char default_type,
  135. char default_align)
  136. {
  137. Py_ssize_t pos = start;
  138. /* end-pos is used throughout this code to specify the length of
  139. the input string */
  140. #define READ_spec(index) PyUnicode_READ_CHAR(format_spec, index)
  141. Py_ssize_t consumed;
  142. int align_specified = 0;
  143. int fill_char_specified = 0;
  144. format->fill_char = ' ';
  145. format->align = default_align;
  146. format->alternate = 0;
  147. format->sign = '\0';
  148. format->width = -1;
  149. format->thousands_separators = 0;
  150. format->precision = -1;
  151. format->type = default_type;
  152. /* If the second char is an alignment token,
  153. then parse the fill char */
  154. if (end-pos >= 2 && is_alignment_token(READ_spec(pos+1))) {
  155. format->align = READ_spec(pos+1);
  156. format->fill_char = READ_spec(pos);
  157. fill_char_specified = 1;
  158. align_specified = 1;
  159. pos += 2;
  160. }
  161. else if (end-pos >= 1 && is_alignment_token(READ_spec(pos))) {
  162. format->align = READ_spec(pos);
  163. align_specified = 1;
  164. ++pos;
  165. }
  166. /* Parse the various sign options */
  167. if (end-pos >= 1 && is_sign_element(READ_spec(pos))) {
  168. format->sign = READ_spec(pos);
  169. ++pos;
  170. }
  171. /* If the next character is #, we're in alternate mode. This only
  172. applies to integers. */
  173. if (end-pos >= 1 && READ_spec(pos) == '#') {
  174. format->alternate = 1;
  175. ++pos;
  176. }
  177. /* The special case for 0-padding (backwards compat) */
  178. if (!fill_char_specified && end-pos >= 1 && READ_spec(pos) == '0') {
  179. format->fill_char = '0';
  180. if (!align_specified) {
  181. format->align = '=';
  182. }
  183. ++pos;
  184. }
  185. consumed = get_integer(format_spec, &pos, end, &format->width);
  186. if (consumed == -1)
  187. /* Overflow error. Exception already set. */
  188. return 0;
  189. /* If consumed is 0, we didn't consume any characters for the
  190. width. In that case, reset the width to -1, because
  191. get_integer() will have set it to zero. -1 is how we record
  192. that the width wasn't specified. */
  193. if (consumed == 0)
  194. format->width = -1;
  195. /* Comma signifies add thousands separators */
  196. if (end-pos && READ_spec(pos) == ',') {
  197. format->thousands_separators = 1;
  198. ++pos;
  199. }
  200. /* Parse field precision */
  201. if (end-pos && READ_spec(pos) == '.') {
  202. ++pos;
  203. consumed = get_integer(format_spec, &pos, end, &format->precision);
  204. if (consumed == -1)
  205. /* Overflow error. Exception already set. */
  206. return 0;
  207. /* Not having a precision after a dot is an error. */
  208. if (consumed == 0) {
  209. PyErr_Format(PyExc_ValueError,
  210. "Format specifier missing precision");
  211. return 0;
  212. }
  213. }
  214. /* Finally, parse the type field. */
  215. if (end-pos > 1) {
  216. /* More than one char remain, invalid format specifier. */
  217. PyErr_Format(PyExc_ValueError, "Invalid format specifier");
  218. return 0;
  219. }
  220. if (end-pos == 1) {
  221. format->type = READ_spec(pos);
  222. ++pos;
  223. }
  224. /* Do as much validating as we can, just by looking at the format
  225. specifier. Do not take into account what type of formatting
  226. we're doing (int, float, string). */
  227. if (format->thousands_separators) {
  228. switch (format->type) {
  229. case 'd':
  230. case 'e':
  231. case 'f':
  232. case 'g':
  233. case 'E':
  234. case 'G':
  235. case '%':
  236. case 'F':
  237. case '\0':
  238. /* These are allowed. See PEP 378.*/
  239. break;
  240. default:
  241. invalid_comma_type(format->type);
  242. return 0;
  243. }
  244. }
  245. assert (format->align <= 127);
  246. assert (format->sign <= 127);
  247. return 1;
  248. }
  249. /* Calculate the padding needed. */
  250. static void
  251. calc_padding(Py_ssize_t nchars, Py_ssize_t width, Py_UCS4 align,
  252. Py_ssize_t *n_lpadding, Py_ssize_t *n_rpadding,
  253. Py_ssize_t *n_total)
  254. {
  255. if (width >= 0) {
  256. if (nchars > width)
  257. *n_total = nchars;
  258. else
  259. *n_total = width;
  260. }
  261. else {
  262. /* not specified, use all of the chars and no more */
  263. *n_total = nchars;
  264. }
  265. /* Figure out how much leading space we need, based on the
  266. aligning */
  267. if (align == '>')
  268. *n_lpadding = *n_total - nchars;
  269. else if (align == '^')
  270. *n_lpadding = (*n_total - nchars) / 2;
  271. else if (align == '<' || align == '=')
  272. *n_lpadding = 0;
  273. else {
  274. /* We should never have an unspecified alignment. */
  275. *n_lpadding = 0;
  276. assert(0);
  277. }
  278. *n_rpadding = *n_total - nchars - *n_lpadding;
  279. }
  280. /* Do the padding, and return a pointer to where the caller-supplied
  281. content goes. */
  282. static int
  283. fill_padding(_PyUnicodeWriter *writer,
  284. Py_ssize_t nchars,
  285. Py_UCS4 fill_char, Py_ssize_t n_lpadding,
  286. Py_ssize_t n_rpadding)
  287. {
  288. Py_ssize_t pos;
  289. /* Pad on left. */
  290. if (n_lpadding) {
  291. pos = writer->pos;
  292. _PyUnicode_FastFill(writer->buffer, pos, n_lpadding, fill_char);
  293. }
  294. /* Pad on right. */
  295. if (n_rpadding) {
  296. pos = writer->pos + nchars + n_lpadding;
  297. _PyUnicode_FastFill(writer->buffer, pos, n_rpadding, fill_char);
  298. }
  299. /* Pointer to the user content. */
  300. writer->pos += n_lpadding;
  301. return 0;
  302. }
  303. /************************************************************************/
  304. /*********** common routines for numeric formatting *********************/
  305. /************************************************************************/
  306. /* Locale type codes. */
  307. enum LocaleType {
  308. LT_CURRENT_LOCALE,
  309. LT_DEFAULT_LOCALE,
  310. LT_NO_LOCALE
  311. };
  312. /* Locale info needed for formatting integers and the part of floats
  313. before and including the decimal. Note that locales only support
  314. 8-bit chars, not unicode. */
  315. typedef struct {
  316. PyObject *decimal_point;
  317. PyObject *thousands_sep;
  318. const char *grouping;
  319. } LocaleInfo;
  320. #define STATIC_LOCALE_INFO_INIT {0, 0, 0}
  321. /* describes the layout for an integer, see the comment in
  322. calc_number_widths() for details */
  323. typedef struct {
  324. Py_ssize_t n_lpadding;
  325. Py_ssize_t n_prefix;
  326. Py_ssize_t n_spadding;
  327. Py_ssize_t n_rpadding;
  328. char sign;
  329. Py_ssize_t n_sign; /* number of digits needed for sign (0/1) */
  330. Py_ssize_t n_grouped_digits; /* Space taken up by the digits, including
  331. any grouping chars. */
  332. Py_ssize_t n_decimal; /* 0 if only an integer */
  333. Py_ssize_t n_remainder; /* Digits in decimal and/or exponent part,
  334. excluding the decimal itself, if
  335. present. */
  336. /* These 2 are not the widths of fields, but are needed by
  337. STRINGLIB_GROUPING. */
  338. Py_ssize_t n_digits; /* The number of digits before a decimal
  339. or exponent. */
  340. Py_ssize_t n_min_width; /* The min_width we used when we computed
  341. the n_grouped_digits width. */
  342. } NumberFieldWidths;
  343. /* Given a number of the form:
  344. digits[remainder]
  345. where ptr points to the start and end points to the end, find where
  346. the integer part ends. This could be a decimal, an exponent, both,
  347. or neither.
  348. If a decimal point is present, set *has_decimal and increment
  349. remainder beyond it.
  350. Results are undefined (but shouldn't crash) for improperly
  351. formatted strings.
  352. */
  353. static void
  354. parse_number(PyObject *s, Py_ssize_t pos, Py_ssize_t end,
  355. Py_ssize_t *n_remainder, int *has_decimal)
  356. {
  357. Py_ssize_t remainder;
  358. while (pos<end && Py_ISDIGIT(PyUnicode_READ_CHAR(s, pos)))
  359. ++pos;
  360. remainder = pos;
  361. /* Does remainder start with a decimal point? */
  362. *has_decimal = pos<end && PyUnicode_READ_CHAR(s, remainder) == '.';
  363. /* Skip the decimal point. */
  364. if (*has_decimal)
  365. remainder++;
  366. *n_remainder = end - remainder;
  367. }
  368. /* not all fields of format are used. for example, precision is
  369. unused. should this take discrete params in order to be more clear
  370. about what it does? or is passing a single format parameter easier
  371. and more efficient enough to justify a little obfuscation? */
  372. static Py_ssize_t
  373. calc_number_widths(NumberFieldWidths *spec, Py_ssize_t n_prefix,
  374. Py_UCS4 sign_char, PyObject *number, Py_ssize_t n_start,
  375. Py_ssize_t n_end, Py_ssize_t n_remainder,
  376. int has_decimal, const LocaleInfo *locale,
  377. const InternalFormatSpec *format, Py_UCS4 *maxchar)
  378. {
  379. Py_ssize_t n_non_digit_non_padding;
  380. Py_ssize_t n_padding;
  381. spec->n_digits = n_end - n_start - n_remainder - (has_decimal?1:0);
  382. spec->n_lpadding = 0;
  383. spec->n_prefix = n_prefix;
  384. spec->n_decimal = has_decimal ? PyUnicode_GET_LENGTH(locale->decimal_point) : 0;
  385. spec->n_remainder = n_remainder;
  386. spec->n_spadding = 0;
  387. spec->n_rpadding = 0;
  388. spec->sign = '\0';
  389. spec->n_sign = 0;
  390. /* the output will look like:
  391. | |
  392. | <lpadding> <sign> <prefix> <spadding> <grouped_digits> <decimal> <remainder> <rpadding> |
  393. | |
  394. sign is computed from format->sign and the actual
  395. sign of the number
  396. prefix is given (it's for the '0x' prefix)
  397. digits is already known
  398. the total width is either given, or computed from the
  399. actual digits
  400. only one of lpadding, spadding, and rpadding can be non-zero,
  401. and it's calculated from the width and other fields
  402. */
  403. /* compute the various parts we're going to write */
  404. switch (format->sign) {
  405. case '+':
  406. /* always put a + or - */
  407. spec->n_sign = 1;
  408. spec->sign = (sign_char == '-' ? '-' : '+');
  409. break;
  410. case ' ':
  411. spec->n_sign = 1;
  412. spec->sign = (sign_char == '-' ? '-' : ' ');
  413. break;
  414. default:
  415. /* Not specified, or the default (-) */
  416. if (sign_char == '-') {
  417. spec->n_sign = 1;
  418. spec->sign = '-';
  419. }
  420. }
  421. /* The number of chars used for non-digits and non-padding. */
  422. n_non_digit_non_padding = spec->n_sign + spec->n_prefix + spec->n_decimal +
  423. spec->n_remainder;
  424. /* min_width can go negative, that's okay. format->width == -1 means
  425. we don't care. */
  426. if (format->fill_char == '0' && format->align == '=')
  427. spec->n_min_width = format->width - n_non_digit_non_padding;
  428. else
  429. spec->n_min_width = 0;
  430. if (spec->n_digits == 0)
  431. /* This case only occurs when using 'c' formatting, we need
  432. to special case it because the grouping code always wants
  433. to have at least one character. */
  434. spec->n_grouped_digits = 0;
  435. else {
  436. Py_UCS4 grouping_maxchar;
  437. spec->n_grouped_digits = _PyUnicode_InsertThousandsGrouping(
  438. NULL, 0,
  439. 0, NULL,
  440. spec->n_digits, spec->n_min_width,
  441. locale->grouping, locale->thousands_sep, &grouping_maxchar);
  442. *maxchar = Py_MAX(*maxchar, grouping_maxchar);
  443. }
  444. /* Given the desired width and the total of digit and non-digit
  445. space we consume, see if we need any padding. format->width can
  446. be negative (meaning no padding), but this code still works in
  447. that case. */
  448. n_padding = format->width -
  449. (n_non_digit_non_padding + spec->n_grouped_digits);
  450. if (n_padding > 0) {
  451. /* Some padding is needed. Determine if it's left, space, or right. */
  452. switch (format->align) {
  453. case '<':
  454. spec->n_rpadding = n_padding;
  455. break;
  456. case '^':
  457. spec->n_lpadding = n_padding / 2;
  458. spec->n_rpadding = n_padding - spec->n_lpadding;
  459. break;
  460. case '=':
  461. spec->n_spadding = n_padding;
  462. break;
  463. case '>':
  464. spec->n_lpadding = n_padding;
  465. break;
  466. default:
  467. /* Shouldn't get here, but treat it as '>' */
  468. spec->n_lpadding = n_padding;
  469. assert(0);
  470. break;
  471. }
  472. }
  473. if (spec->n_lpadding || spec->n_spadding || spec->n_rpadding)
  474. *maxchar = Py_MAX(*maxchar, format->fill_char);
  475. if (spec->n_decimal)
  476. *maxchar = Py_MAX(*maxchar, PyUnicode_MAX_CHAR_VALUE(locale->decimal_point));
  477. return spec->n_lpadding + spec->n_sign + spec->n_prefix +
  478. spec->n_spadding + spec->n_grouped_digits + spec->n_decimal +
  479. spec->n_remainder + spec->n_rpadding;
  480. }
  481. /* Fill in the digit parts of a numbers's string representation,
  482. as determined in calc_number_widths().
  483. Return -1 on error, or 0 on success. */
  484. static int
  485. fill_number(_PyUnicodeWriter *writer, const NumberFieldWidths *spec,
  486. PyObject *digits, Py_ssize_t d_start, Py_ssize_t d_end,
  487. PyObject *prefix, Py_ssize_t p_start,
  488. Py_UCS4 fill_char,
  489. LocaleInfo *locale, int toupper)
  490. {
  491. /* Used to keep track of digits, decimal, and remainder. */
  492. Py_ssize_t d_pos = d_start;
  493. const unsigned int kind = writer->kind;
  494. const void *data = writer->data;
  495. Py_ssize_t r;
  496. if (spec->n_lpadding) {
  497. _PyUnicode_FastFill(writer->buffer,
  498. writer->pos, spec->n_lpadding, fill_char);
  499. writer->pos += spec->n_lpadding;
  500. }
  501. if (spec->n_sign == 1) {
  502. PyUnicode_WRITE(kind, data, writer->pos, spec->sign);
  503. writer->pos++;
  504. }
  505. if (spec->n_prefix) {
  506. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  507. prefix, p_start,
  508. spec->n_prefix);
  509. if (toupper) {
  510. Py_ssize_t t;
  511. for (t = 0; t < spec->n_prefix; t++) {
  512. Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t);
  513. c = Py_TOUPPER(c);
  514. assert (c <= 127);
  515. PyUnicode_WRITE(kind, data, writer->pos + t, c);
  516. }
  517. }
  518. writer->pos += spec->n_prefix;
  519. }
  520. if (spec->n_spadding) {
  521. _PyUnicode_FastFill(writer->buffer,
  522. writer->pos, spec->n_spadding, fill_char);
  523. writer->pos += spec->n_spadding;
  524. }
  525. /* Only for type 'c' special case, it has no digits. */
  526. if (spec->n_digits != 0) {
  527. /* Fill the digits with InsertThousandsGrouping. */
  528. char *pdigits;
  529. if (PyUnicode_READY(digits))
  530. return -1;
  531. pdigits = PyUnicode_DATA(digits);
  532. if (PyUnicode_KIND(digits) < kind) {
  533. pdigits = _PyUnicode_AsKind(digits, kind);
  534. if (pdigits == NULL)
  535. return -1;
  536. }
  537. r = _PyUnicode_InsertThousandsGrouping(
  538. writer->buffer, writer->pos,
  539. spec->n_grouped_digits,
  540. pdigits + kind * d_pos,
  541. spec->n_digits, spec->n_min_width,
  542. locale->grouping, locale->thousands_sep, NULL);
  543. if (r == -1)
  544. return -1;
  545. assert(r == spec->n_grouped_digits);
  546. if (PyUnicode_KIND(digits) < kind)
  547. PyMem_Free(pdigits);
  548. d_pos += spec->n_digits;
  549. }
  550. if (toupper) {
  551. Py_ssize_t t;
  552. for (t = 0; t < spec->n_grouped_digits; t++) {
  553. Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t);
  554. c = Py_TOUPPER(c);
  555. if (c > 127) {
  556. PyErr_SetString(PyExc_SystemError, "non-ascii grouped digit");
  557. return -1;
  558. }
  559. PyUnicode_WRITE(kind, data, writer->pos + t, c);
  560. }
  561. }
  562. writer->pos += spec->n_grouped_digits;
  563. if (spec->n_decimal) {
  564. _PyUnicode_FastCopyCharacters(
  565. writer->buffer, writer->pos,
  566. locale->decimal_point, 0, spec->n_decimal);
  567. writer->pos += spec->n_decimal;
  568. d_pos += 1;
  569. }
  570. if (spec->n_remainder) {
  571. _PyUnicode_FastCopyCharacters(
  572. writer->buffer, writer->pos,
  573. digits, d_pos, spec->n_remainder);
  574. writer->pos += spec->n_remainder;
  575. /* d_pos += spec->n_remainder; */
  576. }
  577. if (spec->n_rpadding) {
  578. _PyUnicode_FastFill(writer->buffer,
  579. writer->pos, spec->n_rpadding,
  580. fill_char);
  581. writer->pos += spec->n_rpadding;
  582. }
  583. return 0;
  584. }
  585. static char no_grouping[1] = {CHAR_MAX};
  586. /* Find the decimal point character(s?), thousands_separator(s?), and
  587. grouping description, either for the current locale if type is
  588. LT_CURRENT_LOCALE, a hard-coded locale if LT_DEFAULT_LOCALE, or
  589. none if LT_NO_LOCALE. */
  590. static int
  591. get_locale_info(enum LocaleType type, LocaleInfo *locale_info)
  592. {
  593. switch (type) {
  594. case LT_CURRENT_LOCALE: {
  595. struct lconv *locale_data = localeconv();
  596. locale_info->decimal_point = PyUnicode_DecodeLocale(
  597. locale_data->decimal_point,
  598. NULL);
  599. if (locale_info->decimal_point == NULL)
  600. return -1;
  601. locale_info->thousands_sep = PyUnicode_DecodeLocale(
  602. locale_data->thousands_sep,
  603. NULL);
  604. if (locale_info->thousands_sep == NULL)
  605. return -1;
  606. locale_info->grouping = locale_data->grouping;
  607. break;
  608. }
  609. case LT_DEFAULT_LOCALE:
  610. locale_info->decimal_point = PyUnicode_FromOrdinal('.');
  611. locale_info->thousands_sep = PyUnicode_FromOrdinal(',');
  612. if (!locale_info->decimal_point || !locale_info->thousands_sep)
  613. return -1;
  614. locale_info->grouping = "\3"; /* Group every 3 characters. The
  615. (implicit) trailing 0 means repeat
  616. infinitely. */
  617. break;
  618. case LT_NO_LOCALE:
  619. locale_info->decimal_point = PyUnicode_FromOrdinal('.');
  620. locale_info->thousands_sep = PyUnicode_New(0, 0);
  621. if (!locale_info->decimal_point || !locale_info->thousands_sep)
  622. return -1;
  623. locale_info->grouping = no_grouping;
  624. break;
  625. }
  626. return 0;
  627. }
  628. static void
  629. free_locale_info(LocaleInfo *locale_info)
  630. {
  631. Py_XDECREF(locale_info->decimal_point);
  632. Py_XDECREF(locale_info->thousands_sep);
  633. }
  634. /************************************************************************/
  635. /*********** string formatting ******************************************/
  636. /************************************************************************/
  637. static int
  638. format_string_internal(PyObject *value, const InternalFormatSpec *format,
  639. _PyUnicodeWriter *writer)
  640. {
  641. Py_ssize_t lpad;
  642. Py_ssize_t rpad;
  643. Py_ssize_t total;
  644. Py_ssize_t len;
  645. int result = -1;
  646. Py_UCS4 maxchar;
  647. assert(PyUnicode_IS_READY(value));
  648. len = PyUnicode_GET_LENGTH(value);
  649. /* sign is not allowed on strings */
  650. if (format->sign != '\0') {
  651. PyErr_SetString(PyExc_ValueError,
  652. "Sign not allowed in string format specifier");
  653. goto done;
  654. }
  655. /* alternate is not allowed on strings */
  656. if (format->alternate) {
  657. PyErr_SetString(PyExc_ValueError,
  658. "Alternate form (#) not allowed in string format "
  659. "specifier");
  660. goto done;
  661. }
  662. /* '=' alignment not allowed on strings */
  663. if (format->align == '=') {
  664. PyErr_SetString(PyExc_ValueError,
  665. "'=' alignment not allowed "
  666. "in string format specifier");
  667. goto done;
  668. }
  669. if ((format->width == -1 || format->width <= len)
  670. && (format->precision == -1 || format->precision >= len)) {
  671. /* Fast path */
  672. return _PyUnicodeWriter_WriteStr(writer, value);
  673. }
  674. /* if precision is specified, output no more that format.precision
  675. characters */
  676. if (format->precision >= 0 && len >= format->precision) {
  677. len = format->precision;
  678. }
  679. calc_padding(len, format->width, format->align, &lpad, &rpad, &total);
  680. maxchar = writer->maxchar;
  681. if (lpad != 0 || rpad != 0)
  682. maxchar = Py_MAX(maxchar, format->fill_char);
  683. if (PyUnicode_MAX_CHAR_VALUE(value) > maxchar) {
  684. Py_UCS4 valmaxchar = _PyUnicode_FindMaxChar(value, 0, len);
  685. maxchar = Py_MAX(maxchar, valmaxchar);
  686. }
  687. /* allocate the resulting string */
  688. if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1)
  689. goto done;
  690. /* Write into that space. First the padding. */
  691. result = fill_padding(writer, len, format->fill_char, lpad, rpad);
  692. if (result == -1)
  693. goto done;
  694. /* Then the source string. */
  695. if (len) {
  696. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  697. value, 0, len);
  698. }
  699. writer->pos += (len + rpad);
  700. result = 0;
  701. done:
  702. return result;
  703. }
  704. /************************************************************************/
  705. /*********** long formatting ********************************************/
  706. /************************************************************************/
  707. static int
  708. format_long_internal(PyObject *value, const InternalFormatSpec *format,
  709. _PyUnicodeWriter *writer)
  710. {
  711. int result = -1;
  712. Py_UCS4 maxchar = 127;
  713. PyObject *tmp = NULL;
  714. Py_ssize_t inumeric_chars;
  715. Py_UCS4 sign_char = '\0';
  716. Py_ssize_t n_digits; /* count of digits need from the computed
  717. string */
  718. Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which
  719. produces non-digits */
  720. Py_ssize_t n_prefix = 0; /* Count of prefix chars, (e.g., '0x') */
  721. Py_ssize_t n_total;
  722. Py_ssize_t prefix = 0;
  723. NumberFieldWidths spec;
  724. long x;
  725. /* Locale settings, either from the actual locale or
  726. from a hard-code pseudo-locale */
  727. LocaleInfo locale = STATIC_LOCALE_INFO_INIT;
  728. /* no precision allowed on integers */
  729. if (format->precision != -1) {
  730. PyErr_SetString(PyExc_ValueError,
  731. "Precision not allowed in integer format specifier");
  732. goto done;
  733. }
  734. /* special case for character formatting */
  735. if (format->type == 'c') {
  736. /* error to specify a sign */
  737. if (format->sign != '\0') {
  738. PyErr_SetString(PyExc_ValueError,
  739. "Sign not allowed with integer"
  740. " format specifier 'c'");
  741. goto done;
  742. }
  743. /* error to request alternate format */
  744. if (format->alternate) {
  745. PyErr_SetString(PyExc_ValueError,
  746. "Alternate form (#) not allowed with integer"
  747. " format specifier 'c'");
  748. goto done;
  749. }
  750. /* taken from unicodeobject.c formatchar() */
  751. /* Integer input truncated to a character */
  752. x = PyLong_AsLong(value);
  753. if (x == -1 && PyErr_Occurred())
  754. goto done;
  755. if (x < 0 || x > 0x10ffff) {
  756. PyErr_SetString(PyExc_OverflowError,
  757. "%c arg not in range(0x110000)");
  758. goto done;
  759. }
  760. tmp = PyUnicode_FromOrdinal(x);
  761. inumeric_chars = 0;
  762. n_digits = 1;
  763. maxchar = Py_MAX(maxchar, (Py_UCS4)x);
  764. /* As a sort-of hack, we tell calc_number_widths that we only
  765. have "remainder" characters. calc_number_widths thinks
  766. these are characters that don't get formatted, only copied
  767. into the output string. We do this for 'c' formatting,
  768. because the characters are likely to be non-digits. */
  769. n_remainder = 1;
  770. }
  771. else {
  772. int base;
  773. int leading_chars_to_skip = 0; /* Number of characters added by
  774. PyNumber_ToBase that we want to
  775. skip over. */
  776. /* Compute the base and how many characters will be added by
  777. PyNumber_ToBase */
  778. switch (format->type) {
  779. case 'b':
  780. base = 2;
  781. leading_chars_to_skip = 2; /* 0b */
  782. break;
  783. case 'o':
  784. base = 8;
  785. leading_chars_to_skip = 2; /* 0o */
  786. break;
  787. case 'x':
  788. case 'X':
  789. base = 16;
  790. leading_chars_to_skip = 2; /* 0x */
  791. break;
  792. default: /* shouldn't be needed, but stops a compiler warning */
  793. case 'd':
  794. case 'n':
  795. base = 10;
  796. break;
  797. }
  798. if (format->sign != '+' && format->sign != ' '
  799. && format->width == -1
  800. && format->type != 'X' && format->type != 'n'
  801. && !format->thousands_separators
  802. && PyLong_CheckExact(value))
  803. {
  804. /* Fast path */
  805. return _PyLong_FormatWriter(writer, value, base, format->alternate);
  806. }
  807. /* The number of prefix chars is the same as the leading
  808. chars to skip */
  809. if (format->alternate)
  810. n_prefix = leading_chars_to_skip;
  811. /* Do the hard part, converting to a string in a given base */
  812. tmp = _PyLong_Format(value, base);
  813. if (tmp == NULL || PyUnicode_READY(tmp) == -1)
  814. goto done;
  815. inumeric_chars = 0;
  816. n_digits = PyUnicode_GET_LENGTH(tmp);
  817. prefix = inumeric_chars;
  818. /* Is a sign character present in the output? If so, remember it
  819. and skip it */
  820. if (PyUnicode_READ_CHAR(tmp, inumeric_chars) == '-') {
  821. sign_char = '-';
  822. ++prefix;
  823. ++leading_chars_to_skip;
  824. }
  825. /* Skip over the leading chars (0x, 0b, etc.) */
  826. n_digits -= leading_chars_to_skip;
  827. inumeric_chars += leading_chars_to_skip;
  828. }
  829. /* Determine the grouping, separator, and decimal point, if any. */
  830. if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
  831. (format->thousands_separators ?
  832. LT_DEFAULT_LOCALE :
  833. LT_NO_LOCALE),
  834. &locale) == -1)
  835. goto done;
  836. /* Calculate how much memory we'll need. */
  837. n_total = calc_number_widths(&spec, n_prefix, sign_char, tmp, inumeric_chars,
  838. inumeric_chars + n_digits, n_remainder, 0,
  839. &locale, format, &maxchar);
  840. /* Allocate the memory. */
  841. if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1)
  842. goto done;
  843. /* Populate the memory. */
  844. result = fill_number(writer, &spec,
  845. tmp, inumeric_chars, inumeric_chars + n_digits,
  846. tmp, prefix, format->fill_char,
  847. &locale, format->type == 'X');
  848. done:
  849. Py_XDECREF(tmp);
  850. free_locale_info(&locale);
  851. return result;
  852. }
  853. /************************************************************************/
  854. /*********** float formatting *******************************************/
  855. /************************************************************************/
  856. /* much of this is taken from unicodeobject.c */
  857. static int
  858. format_float_internal(PyObject *value,
  859. const InternalFormatSpec *format,
  860. _PyUnicodeWriter *writer)
  861. {
  862. char *buf = NULL; /* buffer returned from PyOS_double_to_string */
  863. Py_ssize_t n_digits;
  864. Py_ssize_t n_remainder;
  865. Py_ssize_t n_total;
  866. int has_decimal;
  867. double val;
  868. int precision, default_precision = 6;
  869. Py_UCS4 type = format->type;
  870. int add_pct = 0;
  871. Py_ssize_t index;
  872. NumberFieldWidths spec;
  873. int flags = 0;
  874. int result = -1;
  875. Py_UCS4 maxchar = 127;
  876. Py_UCS4 sign_char = '\0';
  877. int float_type; /* Used to see if we have a nan, inf, or regular float. */
  878. PyObject *unicode_tmp = NULL;
  879. /* Locale settings, either from the actual locale or
  880. from a hard-code pseudo-locale */
  881. LocaleInfo locale = STATIC_LOCALE_INFO_INIT;
  882. if (format->precision > INT_MAX) {
  883. PyErr_SetString(PyExc_ValueError, "precision too big");
  884. goto done;
  885. }
  886. precision = (int)format->precision;
  887. if (format->alternate)
  888. flags |= Py_DTSF_ALT;
  889. if (type == '\0') {
  890. /* Omitted type specifier. Behaves in the same way as repr(x)
  891. and str(x) if no precision is given, else like 'g', but with
  892. at least one digit after the decimal point. */
  893. flags |= Py_DTSF_ADD_DOT_0;
  894. type = 'r';
  895. default_precision = 0;
  896. }
  897. if (type == 'n')
  898. /* 'n' is the same as 'g', except for the locale used to
  899. format the result. We take care of that later. */
  900. type = 'g';
  901. val = PyFloat_AsDouble(value);
  902. if (val == -1.0 && PyErr_Occurred())
  903. goto done;
  904. if (type == '%') {
  905. type = 'f';
  906. val *= 100;
  907. add_pct = 1;
  908. }
  909. if (precision < 0)
  910. precision = default_precision;
  911. else if (type == 'r')
  912. type = 'g';
  913. /* Cast "type", because if we're in unicode we need to pass an
  914. 8-bit char. This is safe, because we've restricted what "type"
  915. can be. */
  916. buf = PyOS_double_to_string(val, (char)type, precision, flags,
  917. &float_type);
  918. if (buf == NULL)
  919. goto done;
  920. n_digits = strlen(buf);
  921. if (add_pct) {
  922. /* We know that buf has a trailing zero (since we just called
  923. strlen() on it), and we don't use that fact any more. So we
  924. can just write over the trailing zero. */
  925. buf[n_digits] = '%';
  926. n_digits += 1;
  927. }
  928. if (format->sign != '+' && format->sign != ' '
  929. && format->width == -1
  930. && format->type != 'n'
  931. && !format->thousands_separators)
  932. {
  933. /* Fast path */
  934. result = _PyUnicodeWriter_WriteASCIIString(writer, buf, n_digits);
  935. PyMem_Free(buf);
  936. return result;
  937. }
  938. /* Since there is no unicode version of PyOS_double_to_string,
  939. just use the 8 bit version and then convert to unicode. */
  940. unicode_tmp = _PyUnicode_FromASCII(buf, n_digits);
  941. PyMem_Free(buf);
  942. if (unicode_tmp == NULL)
  943. goto done;
  944. /* Is a sign character present in the output? If so, remember it
  945. and skip it */
  946. index = 0;
  947. if (PyUnicode_READ_CHAR(unicode_tmp, index) == '-') {
  948. sign_char = '-';
  949. ++index;
  950. --n_digits;
  951. }
  952. /* Determine if we have any "remainder" (after the digits, might include
  953. decimal or exponent or both (or neither)) */
  954. parse_number(unicode_tmp, index, index + n_digits, &n_remainder, &has_decimal);
  955. /* Determine the grouping, separator, and decimal point, if any. */
  956. if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
  957. (format->thousands_separators ?
  958. LT_DEFAULT_LOCALE :
  959. LT_NO_LOCALE),
  960. &locale) == -1)
  961. goto done;
  962. /* Calculate how much memory we'll need. */
  963. n_total = calc_number_widths(&spec, 0, sign_char, unicode_tmp, index,
  964. index + n_digits, n_remainder, has_decimal,
  965. &locale, format, &maxchar);
  966. /* Allocate the memory. */
  967. if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1)
  968. goto done;
  969. /* Populate the memory. */
  970. result = fill_number(writer, &spec,
  971. unicode_tmp, index, index + n_digits,
  972. NULL, 0, format->fill_char,
  973. &locale, 0);
  974. done:
  975. Py_XDECREF(unicode_tmp);
  976. free_locale_info(&locale);
  977. return result;
  978. }
  979. /************************************************************************/
  980. /*********** complex formatting *****************************************/
  981. /************************************************************************/
  982. static int
  983. format_complex_internal(PyObject *value,
  984. const InternalFormatSpec *format,
  985. _PyUnicodeWriter *writer)
  986. {
  987. double re;
  988. double im;
  989. char *re_buf = NULL; /* buffer returned from PyOS_double_to_string */
  990. char *im_buf = NULL; /* buffer returned from PyOS_double_to_string */
  991. InternalFormatSpec tmp_format = *format;
  992. Py_ssize_t n_re_digits;
  993. Py_ssize_t n_im_digits;
  994. Py_ssize_t n_re_remainder;
  995. Py_ssize_t n_im_remainder;
  996. Py_ssize_t n_re_total;
  997. Py_ssize_t n_im_total;
  998. int re_has_decimal;
  999. int im_has_decimal;
  1000. int precision, default_precision = 6;
  1001. Py_UCS4 type = format->type;
  1002. Py_ssize_t i_re;
  1003. Py_ssize_t i_im;
  1004. NumberFieldWidths re_spec;
  1005. NumberFieldWidths im_spec;
  1006. int flags = 0;
  1007. int result = -1;
  1008. Py_UCS4 maxchar = 127;
  1009. enum PyUnicode_Kind rkind;
  1010. void *rdata;
  1011. Py_UCS4 re_sign_char = '\0';
  1012. Py_UCS4 im_sign_char = '\0';
  1013. int re_float_type; /* Used to see if we have a nan, inf, or regular float. */
  1014. int im_float_type;
  1015. int add_parens = 0;
  1016. int skip_re = 0;
  1017. Py_ssize_t lpad;
  1018. Py_ssize_t rpad;
  1019. Py_ssize_t total;
  1020. PyObject *re_unicode_tmp = NULL;
  1021. PyObject *im_unicode_tmp = NULL;
  1022. /* Locale settings, either from the actual locale or
  1023. from a hard-code pseudo-locale */
  1024. LocaleInfo locale = STATIC_LOCALE_INFO_INIT;
  1025. if (format->precision > INT_MAX) {
  1026. PyErr_SetString(PyExc_ValueError, "precision too big");
  1027. goto done;
  1028. }
  1029. precision = (int)format->precision;
  1030. /* Zero padding is not allowed. */
  1031. if (format->fill_char == '0') {
  1032. PyErr_SetString(PyExc_ValueError,
  1033. "Zero padding is not allowed in complex format "
  1034. "specifier");
  1035. goto done;
  1036. }
  1037. /* Neither is '=' alignment . */
  1038. if (format->align == '=') {
  1039. PyErr_SetString(PyExc_ValueError,
  1040. "'=' alignment flag is not allowed in complex format "
  1041. "specifier");
  1042. goto done;
  1043. }
  1044. re = PyComplex_RealAsDouble(value);
  1045. if (re == -1.0 && PyErr_Occurred())
  1046. goto done;
  1047. im = PyComplex_ImagAsDouble(value);
  1048. if (im == -1.0 && PyErr_Occurred())
  1049. goto done;
  1050. if (format->alternate)
  1051. flags |= Py_DTSF_ALT;
  1052. if (type == '\0') {
  1053. /* Omitted type specifier. Should be like str(self). */
  1054. type = 'r';
  1055. default_precision = 0;
  1056. if (re == 0.0 && copysign(1.0, re) == 1.0)
  1057. skip_re = 1;
  1058. else
  1059. add_parens = 1;
  1060. }
  1061. if (type == 'n')
  1062. /* 'n' is the same as 'g', except for the locale used to
  1063. format the result. We take care of that later. */
  1064. type = 'g';
  1065. if (precision < 0)
  1066. precision = default_precision;
  1067. else if (type == 'r')
  1068. type = 'g';
  1069. /* Cast "type", because if we're in unicode we need to pass an
  1070. 8-bit char. This is safe, because we've restricted what "type"
  1071. can be. */
  1072. re_buf = PyOS_double_to_string(re, (char)type, precision, flags,
  1073. &re_float_type);
  1074. if (re_buf == NULL)
  1075. goto done;
  1076. im_buf = PyOS_double_to_string(im, (char)type, precision, flags,
  1077. &im_float_type);
  1078. if (im_buf == NULL)
  1079. goto done;
  1080. n_re_digits = strlen(re_buf);
  1081. n_im_digits = strlen(im_buf);
  1082. /* Since there is no unicode version of PyOS_double_to_string,
  1083. just use the 8 bit version and then convert to unicode. */
  1084. re_unicode_tmp = _PyUnicode_FromASCII(re_buf, n_re_digits);
  1085. if (re_unicode_tmp == NULL)
  1086. goto done;
  1087. i_re = 0;
  1088. im_unicode_tmp = _PyUnicode_FromASCII(im_buf, n_im_digits);
  1089. if (im_unicode_tmp == NULL)
  1090. goto done;
  1091. i_im = 0;
  1092. /* Is a sign character present in the output? If so, remember it
  1093. and skip it */
  1094. if (PyUnicode_READ_CHAR(re_unicode_tmp, i_re) == '-') {
  1095. re_sign_char = '-';
  1096. ++i_re;
  1097. --n_re_digits;
  1098. }
  1099. if (PyUnicode_READ_CHAR(im_unicode_tmp, i_im) == '-') {
  1100. im_sign_char = '-';
  1101. ++i_im;
  1102. --n_im_digits;
  1103. }
  1104. /* Determine if we have any "remainder" (after the digits, might include
  1105. decimal or exponent or both (or neither)) */
  1106. parse_number(re_unicode_tmp, i_re, i_re + n_re_digits,
  1107. &n_re_remainder, &re_has_decimal);
  1108. parse_number(im_unicode_tmp, i_im, i_im + n_im_digits,
  1109. &n_im_remainder, &im_has_decimal);
  1110. /* Determine the grouping, separator, and decimal point, if any. */
  1111. if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
  1112. (format->thousands_separators ?
  1113. LT_DEFAULT_LOCALE :
  1114. LT_NO_LOCALE),
  1115. &locale) == -1)
  1116. goto done;
  1117. /* Turn off any padding. We'll do it later after we've composed
  1118. the numbers without padding. */
  1119. tmp_format.fill_char = '\0';
  1120. tmp_format.align = '<';
  1121. tmp_format.width = -1;
  1122. /* Calculate how much memory we'll need. */
  1123. n_re_total = calc_number_widths(&re_spec, 0, re_sign_char, re_unicode_tmp,
  1124. i_re, i_re + n_re_digits, n_re_remainder,
  1125. re_has_decimal, &locale, &tmp_format,
  1126. &maxchar);
  1127. /* Same formatting, but always include a sign, unless the real part is
  1128. * going to be omitted, in which case we use whatever sign convention was
  1129. * requested by the original format. */
  1130. if (!skip_re)
  1131. tmp_format.sign = '+';
  1132. n_im_total = calc_number_widths(&im_spec, 0, im_sign_char, im_unicode_tmp,
  1133. i_im, i_im + n_im_digits, n_im_remainder,
  1134. im_has_decimal, &locale, &tmp_format,
  1135. &maxchar);
  1136. if (skip_re)
  1137. n_re_total = 0;
  1138. /* Add 1 for the 'j', and optionally 2 for parens. */
  1139. calc_padding(n_re_total + n_im_total + 1 + add_parens * 2,
  1140. format->width, format->align, &lpad, &rpad, &total);
  1141. if (lpad || rpad)
  1142. maxchar = Py_MAX(maxchar, format->fill_char);
  1143. if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1)
  1144. goto done;
  1145. rkind = writer->kind;
  1146. rdata = writer->data;
  1147. /* Populate the memory. First, the padding. */
  1148. result = fill_padding(writer,
  1149. n_re_total + n_im_total + 1 + add_parens * 2,
  1150. format->fill_char, lpad, rpad);
  1151. if (result == -1)
  1152. goto done;
  1153. if (add_parens) {
  1154. PyUnicode_WRITE(rkind, rdata, writer->pos, '(');
  1155. writer->pos++;
  1156. }
  1157. if (!skip_re) {
  1158. result = fill_number(writer, &re_spec,
  1159. re_unicode_tmp, i_re, i_re + n_re_digits,
  1160. NULL, 0,
  1161. 0,
  1162. &locale, 0);
  1163. if (result == -1)
  1164. goto done;
  1165. }
  1166. result = fill_number(writer, &im_spec,
  1167. im_unicode_tmp, i_im, i_im + n_im_digits,
  1168. NULL, 0,
  1169. 0,
  1170. &locale, 0);
  1171. if (result == -1)
  1172. goto done;
  1173. PyUnicode_WRITE(rkind, rdata, writer->pos, 'j');
  1174. writer->pos++;
  1175. if (add_parens) {
  1176. PyUnicode_WRITE(rkind, rdata, writer->pos, ')');
  1177. writer->pos++;
  1178. }
  1179. writer->pos += rpad;
  1180. done:
  1181. PyMem_Free(re_buf);
  1182. PyMem_Free(im_buf);
  1183. Py_XDECREF(re_unicode_tmp);
  1184. Py_XDECREF(im_unicode_tmp);
  1185. free_locale_info(&locale);
  1186. return result;
  1187. }
  1188. /************************************************************************/
  1189. /*********** built in formatters ****************************************/
  1190. /************************************************************************/
  1191. static int
  1192. format_obj(PyObject *obj, _PyUnicodeWriter *writer)
  1193. {
  1194. PyObject *str;
  1195. int err;
  1196. str = PyObject_Str(obj);
  1197. if (str == NULL)
  1198. return -1;
  1199. err = _PyUnicodeWriter_WriteStr(writer, str);
  1200. Py_DECREF(str);
  1201. return err;
  1202. }
  1203. int
  1204. _PyUnicode_FormatAdvancedWriter(_PyUnicodeWriter *writer,
  1205. PyObject *obj,
  1206. PyObject *format_spec,
  1207. Py_ssize_t start, Py_ssize_t end)
  1208. {
  1209. InternalFormatSpec format;
  1210. assert(PyUnicode_Check(obj));
  1211. /* check for the special case of zero length format spec, make
  1212. it equivalent to str(obj) */
  1213. if (start == end) {
  1214. if (PyUnicode_CheckExact(obj))
  1215. return _PyUnicodeWriter_WriteStr(writer, obj);
  1216. else
  1217. return format_obj(obj, writer);
  1218. }
  1219. /* parse the format_spec */
  1220. if (!parse_internal_render_format_spec(format_spec, start, end,
  1221. &format, 's', '<'))
  1222. return -1;
  1223. /* type conversion? */
  1224. switch (format.type) {
  1225. case 's':
  1226. /* no type conversion needed, already a string. do the formatting */
  1227. return format_string_internal(obj, &format, writer);
  1228. default:
  1229. /* unknown */
  1230. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1231. return -1;
  1232. }
  1233. }
  1234. int
  1235. _PyLong_FormatAdvancedWriter(_PyUnicodeWriter *writer,
  1236. PyObject *obj,
  1237. PyObject *format_spec,
  1238. Py_ssize_t start, Py_ssize_t end)
  1239. {
  1240. PyObject *tmp = NULL, *str = NULL;
  1241. InternalFormatSpec format;
  1242. int result = -1;
  1243. /* check for the special case of zero length format spec, make
  1244. it equivalent to str(obj) */
  1245. if (start == end) {
  1246. if (PyLong_CheckExact(obj))
  1247. return _PyLong_FormatWriter(writer, obj, 10, 0);
  1248. else
  1249. return format_obj(obj, writer);
  1250. }
  1251. /* parse the format_spec */
  1252. if (!parse_internal_render_format_spec(format_spec, start, end,
  1253. &format, 'd', '>'))
  1254. goto done;
  1255. /* type conversion? */
  1256. switch (format.type) {
  1257. case 'b':
  1258. case 'c':
  1259. case 'd':
  1260. case 'o':
  1261. case 'x':
  1262. case 'X':
  1263. case 'n':
  1264. /* no type conversion needed, already an int. do the formatting */
  1265. result = format_long_internal(obj, &format, writer);
  1266. break;
  1267. case 'e':
  1268. case 'E':
  1269. case 'f':
  1270. case 'F':
  1271. case 'g':
  1272. case 'G':
  1273. case '%':
  1274. /* convert to float */
  1275. tmp = PyNumber_Float(obj);
  1276. if (tmp == NULL)
  1277. goto done;
  1278. result = format_float_internal(tmp, &format, writer);
  1279. break;
  1280. default:
  1281. /* unknown */
  1282. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1283. goto done;
  1284. }
  1285. done:
  1286. Py_XDECREF(tmp);
  1287. Py_XDECREF(str);
  1288. return result;
  1289. }
  1290. int
  1291. _PyFloat_FormatAdvancedWriter(_PyUnicodeWriter *writer,
  1292. PyObject *obj,
  1293. PyObject *format_spec,
  1294. Py_ssize_t start, Py_ssize_t end)
  1295. {
  1296. InternalFormatSpec format;
  1297. /* check for the special case of zero length format spec, make
  1298. it equivalent to str(obj) */
  1299. if (start == end)
  1300. return format_obj(obj, writer);
  1301. /* parse the format_spec */
  1302. if (!parse_internal_render_format_spec(format_spec, start, end,
  1303. &format, '\0', '>'))
  1304. return -1;
  1305. /* type conversion? */
  1306. switch (format.type) {
  1307. case '\0': /* No format code: like 'g', but with at least one decimal. */
  1308. case 'e':
  1309. case 'E':
  1310. case 'f':
  1311. case 'F':
  1312. case 'g':
  1313. case 'G':
  1314. case 'n':
  1315. case '%':
  1316. /* no conversion, already a float. do the formatting */
  1317. return format_float_internal(obj, &format, writer);
  1318. default:
  1319. /* unknown */
  1320. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1321. return -1;
  1322. }
  1323. }
  1324. int
  1325. _PyComplex_FormatAdvancedWriter(_PyUnicodeWriter *writer,
  1326. PyObject *obj,
  1327. PyObject *format_spec,
  1328. Py_ssize_t start, Py_ssize_t end)
  1329. {
  1330. InternalFormatSpec format;
  1331. /* check for the special case of zero length format spec, make
  1332. it equivalent to str(obj) */
  1333. if (start == end)
  1334. return format_obj(obj, writer);
  1335. /* parse the format_spec */
  1336. if (!parse_internal_render_format_spec(format_spec, start, end,
  1337. &format, '\0', '>'))
  1338. return -1;
  1339. /* type conversion? */
  1340. switch (format.type) {
  1341. case '\0': /* No format code: like 'g', but with at least one decimal. */
  1342. case 'e':
  1343. case 'E':
  1344. case 'f':
  1345. case 'F':
  1346. case 'g':
  1347. case 'G':
  1348. case 'n':
  1349. /* no conversion, already a complex. do the formatting */
  1350. return format_complex_internal(obj, &format, writer);
  1351. default:
  1352. /* unknown */
  1353. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1354. return -1;
  1355. }
  1356. }