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.

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