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.

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