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.

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