/Objects/stringlib/formatter.h

http://unladen-swallow.googlecode.com/ · C Header · 1056 lines · 684 code · 126 blank · 246 comment · 166 complexity · 1ab4d0a8c6705e4ee54c06a283efb8ec MD5 · raw file

  1. /* implements the string, long, and float formatters. that is,
  2. string.__format__, etc. */
  3. /* Before including this, you must include either:
  4. stringlib/unicodedefs.h
  5. stringlib/stringdefs.h
  6. Also, you should define the names:
  7. FORMAT_STRING
  8. FORMAT_LONG
  9. FORMAT_FLOAT
  10. to be whatever you want the public names of these functions to
  11. be. These are the only non-static functions defined here.
  12. */
  13. #define ALLOW_PARENS_FOR_SIGN 0
  14. /* Raises an exception about an unknown presentation type for this
  15. * type. */
  16. static void
  17. unknown_presentation_type(STRINGLIB_CHAR presentation_type,
  18. const char* type_name)
  19. {
  20. #if STRINGLIB_IS_UNICODE
  21. /* If STRINGLIB_CHAR is Py_UNICODE, %c might be out-of-range,
  22. hence the two cases. If it is char, gcc complains that the
  23. condition below is always true, hence the ifdef. */
  24. if (presentation_type > 32 && presentation_type < 128)
  25. #endif
  26. PyErr_Format(PyExc_ValueError,
  27. "Unknown format code '%c' "
  28. "for object of type '%.200s'",
  29. (char)presentation_type,
  30. type_name);
  31. #if STRINGLIB_IS_UNICODE
  32. else
  33. PyErr_Format(PyExc_ValueError,
  34. "Unknown format code '\\x%x' "
  35. "for object of type '%.200s'",
  36. (unsigned int)presentation_type,
  37. type_name);
  38. #endif
  39. }
  40. /*
  41. get_integer consumes 0 or more decimal digit characters from an
  42. input string, updates *result with the corresponding positive
  43. integer, and returns the number of digits consumed.
  44. returns -1 on error.
  45. */
  46. static int
  47. get_integer(STRINGLIB_CHAR **ptr, STRINGLIB_CHAR *end,
  48. Py_ssize_t *result)
  49. {
  50. Py_ssize_t accumulator, digitval, oldaccumulator;
  51. int numdigits;
  52. accumulator = numdigits = 0;
  53. for (;;(*ptr)++, numdigits++) {
  54. if (*ptr >= end)
  55. break;
  56. digitval = STRINGLIB_TODECIMAL(**ptr);
  57. if (digitval < 0)
  58. break;
  59. /*
  60. This trick was copied from old Unicode format code. It's cute,
  61. but would really suck on an old machine with a slow divide
  62. implementation. Fortunately, in the normal case we do not
  63. expect too many digits.
  64. */
  65. oldaccumulator = accumulator;
  66. accumulator *= 10;
  67. if ((accumulator+10)/10 != oldaccumulator+1) {
  68. PyErr_Format(PyExc_ValueError,
  69. "Too many decimal digits in format string");
  70. return -1;
  71. }
  72. accumulator += digitval;
  73. }
  74. *result = accumulator;
  75. return numdigits;
  76. }
  77. /************************************************************************/
  78. /*********** standard format specifier parsing **************************/
  79. /************************************************************************/
  80. /* returns true if this character is a specifier alignment token */
  81. Py_LOCAL_INLINE(int)
  82. is_alignment_token(STRINGLIB_CHAR c)
  83. {
  84. switch (c) {
  85. case '<': case '>': case '=': case '^':
  86. return 1;
  87. default:
  88. return 0;
  89. }
  90. }
  91. /* returns true if this character is a sign element */
  92. Py_LOCAL_INLINE(int)
  93. is_sign_element(STRINGLIB_CHAR c)
  94. {
  95. switch (c) {
  96. case ' ': case '+': case '-':
  97. #if ALLOW_PARENS_FOR_SIGN
  98. case '(':
  99. #endif
  100. return 1;
  101. default:
  102. return 0;
  103. }
  104. }
  105. typedef struct {
  106. STRINGLIB_CHAR fill_char;
  107. STRINGLIB_CHAR align;
  108. int alternate;
  109. STRINGLIB_CHAR sign;
  110. Py_ssize_t width;
  111. Py_ssize_t precision;
  112. STRINGLIB_CHAR type;
  113. } InternalFormatSpec;
  114. /*
  115. ptr points to the start of the format_spec, end points just past its end.
  116. fills in format with the parsed information.
  117. returns 1 on success, 0 on failure.
  118. if failure, sets the exception
  119. */
  120. static int
  121. parse_internal_render_format_spec(STRINGLIB_CHAR *format_spec,
  122. Py_ssize_t format_spec_len,
  123. InternalFormatSpec *format,
  124. char default_type)
  125. {
  126. STRINGLIB_CHAR *ptr = format_spec;
  127. STRINGLIB_CHAR *end = format_spec + format_spec_len;
  128. /* end-ptr is used throughout this code to specify the length of
  129. the input string */
  130. Py_ssize_t specified_width;
  131. format->fill_char = '\0';
  132. format->align = '\0';
  133. format->alternate = 0;
  134. format->sign = '\0';
  135. format->width = -1;
  136. format->precision = -1;
  137. format->type = default_type;
  138. /* If the second char is an alignment token,
  139. then parse the fill char */
  140. if (end-ptr >= 2 && is_alignment_token(ptr[1])) {
  141. format->align = ptr[1];
  142. format->fill_char = ptr[0];
  143. ptr += 2;
  144. }
  145. else if (end-ptr >= 1 && is_alignment_token(ptr[0])) {
  146. format->align = ptr[0];
  147. ++ptr;
  148. }
  149. /* Parse the various sign options */
  150. if (end-ptr >= 1 && is_sign_element(ptr[0])) {
  151. format->sign = ptr[0];
  152. ++ptr;
  153. #if ALLOW_PARENS_FOR_SIGN
  154. if (end-ptr >= 1 && ptr[0] == ')') {
  155. ++ptr;
  156. }
  157. #endif
  158. }
  159. /* If the next character is #, we're in alternate mode. This only
  160. applies to integers. */
  161. if (end-ptr >= 1 && ptr[0] == '#') {
  162. format->alternate = 1;
  163. ++ptr;
  164. }
  165. /* The special case for 0-padding (backwards compat) */
  166. if (format->fill_char == '\0' && end-ptr >= 1 && ptr[0] == '0') {
  167. format->fill_char = '0';
  168. if (format->align == '\0') {
  169. format->align = '=';
  170. }
  171. ++ptr;
  172. }
  173. /* XXX add error checking */
  174. specified_width = get_integer(&ptr, end, &format->width);
  175. /* if specified_width is 0, we didn't consume any characters for
  176. the width. in that case, reset the width to -1, because
  177. get_integer() will have set it to zero */
  178. if (specified_width == 0) {
  179. format->width = -1;
  180. }
  181. /* Parse field precision */
  182. if (end-ptr && ptr[0] == '.') {
  183. ++ptr;
  184. /* XXX add error checking */
  185. specified_width = get_integer(&ptr, end, &format->precision);
  186. /* not having a precision after a dot is an error */
  187. if (specified_width == 0) {
  188. PyErr_Format(PyExc_ValueError,
  189. "Format specifier missing precision");
  190. return 0;
  191. }
  192. }
  193. /* Finally, parse the type field */
  194. if (end-ptr > 1) {
  195. /* invalid conversion spec */
  196. PyErr_Format(PyExc_ValueError, "Invalid conversion specification");
  197. return 0;
  198. }
  199. if (end-ptr == 1) {
  200. format->type = ptr[0];
  201. ++ptr;
  202. }
  203. return 1;
  204. }
  205. #if defined FORMAT_FLOAT || defined FORMAT_LONG
  206. /************************************************************************/
  207. /*********** common routines for numeric formatting *********************/
  208. /************************************************************************/
  209. /* describes the layout for an integer, see the comment in
  210. calc_number_widths() for details */
  211. typedef struct {
  212. Py_ssize_t n_lpadding;
  213. Py_ssize_t n_prefix;
  214. Py_ssize_t n_spadding;
  215. Py_ssize_t n_rpadding;
  216. char lsign;
  217. Py_ssize_t n_lsign;
  218. char rsign;
  219. Py_ssize_t n_rsign;
  220. Py_ssize_t n_total; /* just a convenience, it's derivable from the
  221. other fields */
  222. } NumberFieldWidths;
  223. /* not all fields of format are used. for example, precision is
  224. unused. should this take discrete params in order to be more clear
  225. about what it does? or is passing a single format parameter easier
  226. and more efficient enough to justify a little obfuscation? */
  227. static void
  228. calc_number_widths(NumberFieldWidths *spec, STRINGLIB_CHAR actual_sign,
  229. Py_ssize_t n_prefix, Py_ssize_t n_digits,
  230. const InternalFormatSpec *format)
  231. {
  232. spec->n_lpadding = 0;
  233. spec->n_prefix = 0;
  234. spec->n_spadding = 0;
  235. spec->n_rpadding = 0;
  236. spec->lsign = '\0';
  237. spec->n_lsign = 0;
  238. spec->rsign = '\0';
  239. spec->n_rsign = 0;
  240. /* the output will look like:
  241. | |
  242. | <lpadding> <lsign> <prefix> <spadding> <digits> <rsign> <rpadding> |
  243. | |
  244. lsign and rsign are computed from format->sign and the actual
  245. sign of the number
  246. prefix is given (it's for the '0x' prefix)
  247. digits is already known
  248. the total width is either given, or computed from the
  249. actual digits
  250. only one of lpadding, spadding, and rpadding can be non-zero,
  251. and it's calculated from the width and other fields
  252. */
  253. /* compute the various parts we're going to write */
  254. if (format->sign == '+') {
  255. /* always put a + or - */
  256. spec->n_lsign = 1;
  257. spec->lsign = (actual_sign == '-' ? '-' : '+');
  258. }
  259. #if ALLOW_PARENS_FOR_SIGN
  260. else if (format->sign == '(') {
  261. if (actual_sign == '-') {
  262. spec->n_lsign = 1;
  263. spec->lsign = '(';
  264. spec->n_rsign = 1;
  265. spec->rsign = ')';
  266. }
  267. }
  268. #endif
  269. else if (format->sign == ' ') {
  270. spec->n_lsign = 1;
  271. spec->lsign = (actual_sign == '-' ? '-' : ' ');
  272. }
  273. else {
  274. /* non specified, or the default (-) */
  275. if (actual_sign == '-') {
  276. spec->n_lsign = 1;
  277. spec->lsign = '-';
  278. }
  279. }
  280. spec->n_prefix = n_prefix;
  281. /* now the number of padding characters */
  282. if (format->width == -1) {
  283. /* no padding at all, nothing to do */
  284. }
  285. else {
  286. /* see if any padding is needed */
  287. if (spec->n_lsign + n_digits + spec->n_rsign +
  288. spec->n_prefix >= format->width) {
  289. /* no padding needed, we're already bigger than the
  290. requested width */
  291. }
  292. else {
  293. /* determine which of left, space, or right padding is
  294. needed */
  295. Py_ssize_t padding = format->width -
  296. (spec->n_lsign + spec->n_prefix +
  297. n_digits + spec->n_rsign);
  298. if (format->align == '<')
  299. spec->n_rpadding = padding;
  300. else if (format->align == '>')
  301. spec->n_lpadding = padding;
  302. else if (format->align == '^') {
  303. spec->n_lpadding = padding / 2;
  304. spec->n_rpadding = padding - spec->n_lpadding;
  305. }
  306. else if (format->align == '=')
  307. spec->n_spadding = padding;
  308. else
  309. spec->n_lpadding = padding;
  310. }
  311. }
  312. spec->n_total = spec->n_lpadding + spec->n_lsign + spec->n_prefix +
  313. spec->n_spadding + n_digits + spec->n_rsign + spec->n_rpadding;
  314. }
  315. /* fill in the non-digit parts of a numbers's string representation,
  316. as determined in calc_number_widths(). returns the pointer to
  317. where the digits go. */
  318. static STRINGLIB_CHAR *
  319. fill_non_digits(STRINGLIB_CHAR *p_buf, const NumberFieldWidths *spec,
  320. STRINGLIB_CHAR *prefix, Py_ssize_t n_digits,
  321. STRINGLIB_CHAR fill_char)
  322. {
  323. STRINGLIB_CHAR *p_digits;
  324. if (spec->n_lpadding) {
  325. STRINGLIB_FILL(p_buf, fill_char, spec->n_lpadding);
  326. p_buf += spec->n_lpadding;
  327. }
  328. if (spec->n_lsign == 1) {
  329. *p_buf++ = spec->lsign;
  330. }
  331. if (spec->n_prefix) {
  332. memmove(p_buf,
  333. prefix,
  334. spec->n_prefix * sizeof(STRINGLIB_CHAR));
  335. p_buf += spec->n_prefix;
  336. }
  337. if (spec->n_spadding) {
  338. STRINGLIB_FILL(p_buf, fill_char, spec->n_spadding);
  339. p_buf += spec->n_spadding;
  340. }
  341. p_digits = p_buf;
  342. p_buf += n_digits;
  343. if (spec->n_rsign == 1) {
  344. *p_buf++ = spec->rsign;
  345. }
  346. if (spec->n_rpadding) {
  347. STRINGLIB_FILL(p_buf, fill_char, spec->n_rpadding);
  348. p_buf += spec->n_rpadding;
  349. }
  350. return p_digits;
  351. }
  352. #endif /* FORMAT_FLOAT || FORMAT_LONG */
  353. /************************************************************************/
  354. /*********** string formatting ******************************************/
  355. /************************************************************************/
  356. static PyObject *
  357. format_string_internal(PyObject *value, const InternalFormatSpec *format)
  358. {
  359. Py_ssize_t width; /* total field width */
  360. Py_ssize_t lpad;
  361. STRINGLIB_CHAR *dst;
  362. STRINGLIB_CHAR *src = STRINGLIB_STR(value);
  363. Py_ssize_t len = STRINGLIB_LEN(value);
  364. PyObject *result = NULL;
  365. /* sign is not allowed on strings */
  366. if (format->sign != '\0') {
  367. PyErr_SetString(PyExc_ValueError,
  368. "Sign not allowed in string format specifier");
  369. goto done;
  370. }
  371. /* alternate is not allowed on strings */
  372. if (format->alternate) {
  373. PyErr_SetString(PyExc_ValueError,
  374. "Alternate form (#) not allowed in string format "
  375. "specifier");
  376. goto done;
  377. }
  378. /* '=' alignment not allowed on strings */
  379. if (format->align == '=') {
  380. PyErr_SetString(PyExc_ValueError,
  381. "'=' alignment not allowed "
  382. "in string format specifier");
  383. goto done;
  384. }
  385. /* if precision is specified, output no more that format.precision
  386. characters */
  387. if (format->precision >= 0 && len >= format->precision) {
  388. len = format->precision;
  389. }
  390. if (format->width >= 0) {
  391. width = format->width;
  392. /* but use at least len characters */
  393. if (len > width) {
  394. width = len;
  395. }
  396. }
  397. else {
  398. /* not specified, use all of the chars and no more */
  399. width = len;
  400. }
  401. /* allocate the resulting string */
  402. result = STRINGLIB_NEW(NULL, width);
  403. if (result == NULL)
  404. goto done;
  405. /* now write into that space */
  406. dst = STRINGLIB_STR(result);
  407. /* figure out how much leading space we need, based on the
  408. aligning */
  409. if (format->align == '>')
  410. lpad = width - len;
  411. else if (format->align == '^')
  412. lpad = (width - len) / 2;
  413. else
  414. lpad = 0;
  415. /* if right aligning, increment the destination allow space on the
  416. left */
  417. memcpy(dst + lpad, src, len * sizeof(STRINGLIB_CHAR));
  418. /* do any padding */
  419. if (width > len) {
  420. STRINGLIB_CHAR fill_char = format->fill_char;
  421. if (fill_char == '\0') {
  422. /* use the default, if not specified */
  423. fill_char = ' ';
  424. }
  425. /* pad on left */
  426. if (lpad)
  427. STRINGLIB_FILL(dst, fill_char, lpad);
  428. /* pad on right */
  429. if (width - len - lpad)
  430. STRINGLIB_FILL(dst + len + lpad, fill_char, width - len - lpad);
  431. }
  432. done:
  433. return result;
  434. }
  435. /************************************************************************/
  436. /*********** long formatting ********************************************/
  437. /************************************************************************/
  438. #if defined FORMAT_LONG || defined FORMAT_INT
  439. typedef PyObject*
  440. (*IntOrLongToString)(PyObject *value, int base);
  441. static PyObject *
  442. format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format,
  443. IntOrLongToString tostring)
  444. {
  445. PyObject *result = NULL;
  446. PyObject *tmp = NULL;
  447. STRINGLIB_CHAR *pnumeric_chars;
  448. STRINGLIB_CHAR numeric_char;
  449. STRINGLIB_CHAR sign = '\0';
  450. STRINGLIB_CHAR *p;
  451. Py_ssize_t n_digits; /* count of digits need from the computed
  452. string */
  453. Py_ssize_t n_leading_chars;
  454. Py_ssize_t n_grouping_chars = 0; /* Count of additional chars to
  455. allocate, used for 'n'
  456. formatting. */
  457. Py_ssize_t n_prefix = 0; /* Count of prefix chars, (e.g., '0x') */
  458. STRINGLIB_CHAR *prefix = NULL;
  459. NumberFieldWidths spec;
  460. long x;
  461. /* no precision allowed on integers */
  462. if (format->precision != -1) {
  463. PyErr_SetString(PyExc_ValueError,
  464. "Precision not allowed in integer format specifier");
  465. goto done;
  466. }
  467. /* special case for character formatting */
  468. if (format->type == 'c') {
  469. /* error to specify a sign */
  470. if (format->sign != '\0') {
  471. PyErr_SetString(PyExc_ValueError,
  472. "Sign not allowed with integer"
  473. " format specifier 'c'");
  474. goto done;
  475. }
  476. /* taken from unicodeobject.c formatchar() */
  477. /* Integer input truncated to a character */
  478. /* XXX: won't work for int */
  479. x = PyLong_AsLong(value);
  480. if (x == -1 && PyErr_Occurred())
  481. goto done;
  482. #ifdef Py_UNICODE_WIDE
  483. if (x < 0 || x > 0x10ffff) {
  484. PyErr_SetString(PyExc_OverflowError,
  485. "%c arg not in range(0x110000) "
  486. "(wide Python build)");
  487. goto done;
  488. }
  489. #else
  490. if (x < 0 || x > 0xffff) {
  491. PyErr_SetString(PyExc_OverflowError,
  492. "%c arg not in range(0x10000) "
  493. "(narrow Python build)");
  494. goto done;
  495. }
  496. #endif
  497. numeric_char = (STRINGLIB_CHAR)x;
  498. pnumeric_chars = &numeric_char;
  499. n_digits = 1;
  500. }
  501. else {
  502. int base;
  503. int leading_chars_to_skip = 0; /* Number of characters added by
  504. PyNumber_ToBase that we want to
  505. skip over. */
  506. /* Compute the base and how many characters will be added by
  507. PyNumber_ToBase */
  508. switch (format->type) {
  509. case 'b':
  510. base = 2;
  511. leading_chars_to_skip = 2; /* 0b */
  512. break;
  513. case 'o':
  514. base = 8;
  515. leading_chars_to_skip = 2; /* 0o */
  516. break;
  517. case 'x':
  518. case 'X':
  519. base = 16;
  520. leading_chars_to_skip = 2; /* 0x */
  521. break;
  522. default: /* shouldn't be needed, but stops a compiler warning */
  523. case 'd':
  524. case 'n':
  525. base = 10;
  526. break;
  527. }
  528. /* The number of prefix chars is the same as the leading
  529. chars to skip */
  530. if (format->alternate)
  531. n_prefix = leading_chars_to_skip;
  532. /* Do the hard part, converting to a string in a given base */
  533. tmp = tostring(value, base);
  534. if (tmp == NULL)
  535. goto done;
  536. pnumeric_chars = STRINGLIB_STR(tmp);
  537. n_digits = STRINGLIB_LEN(tmp);
  538. prefix = pnumeric_chars;
  539. /* Remember not to modify what pnumeric_chars points to. it
  540. might be interned. Only modify it after we copy it into a
  541. newly allocated output buffer. */
  542. /* Is a sign character present in the output? If so, remember it
  543. and skip it */
  544. sign = pnumeric_chars[0];
  545. if (sign == '-') {
  546. ++prefix;
  547. ++leading_chars_to_skip;
  548. }
  549. /* Skip over the leading chars (0x, 0b, etc.) */
  550. n_digits -= leading_chars_to_skip;
  551. pnumeric_chars += leading_chars_to_skip;
  552. }
  553. if (format->type == 'n')
  554. /* Compute how many additional chars we need to allocate
  555. to hold the thousands grouping. */
  556. STRINGLIB_GROUPING(NULL, n_digits, n_digits,
  557. 0, &n_grouping_chars, 0);
  558. /* Calculate the widths of the various leading and trailing parts */
  559. calc_number_widths(&spec, sign, n_prefix, n_digits + n_grouping_chars,
  560. format);
  561. /* Allocate a new string to hold the result */
  562. result = STRINGLIB_NEW(NULL, spec.n_total);
  563. if (!result)
  564. goto done;
  565. p = STRINGLIB_STR(result);
  566. /* XXX There is too much magic here regarding the internals of
  567. spec and the location of the prefix and digits. It would be
  568. better if calc_number_widths returned a number of logical
  569. offsets into the buffer, and those were used. Maybe in a
  570. future code cleanup. */
  571. /* Fill in the digit parts */
  572. n_leading_chars = spec.n_lpadding + spec.n_lsign +
  573. spec.n_prefix + spec.n_spadding;
  574. memmove(p + n_leading_chars,
  575. pnumeric_chars,
  576. n_digits * sizeof(STRINGLIB_CHAR));
  577. /* If type is 'X', convert the filled in digits to uppercase */
  578. if (format->type == 'X') {
  579. Py_ssize_t t;
  580. for (t = 0; t < n_digits; ++t)
  581. p[t + n_leading_chars] = STRINGLIB_TOUPPER(p[t + n_leading_chars]);
  582. }
  583. /* Insert the grouping, if any, after the uppercasing of the digits, so
  584. we can ensure that grouping chars won't be affected. */
  585. if (n_grouping_chars) {
  586. /* We know this can't fail, since we've already
  587. reserved enough space. */
  588. STRINGLIB_CHAR *pstart = p + n_leading_chars;
  589. #ifndef NDEBUG
  590. int r =
  591. #endif
  592. STRINGLIB_GROUPING(pstart, n_digits, n_digits,
  593. spec.n_total+n_grouping_chars-n_leading_chars,
  594. NULL, 0);
  595. assert(r);
  596. }
  597. /* Fill in the non-digit parts (padding, sign, etc.) */
  598. fill_non_digits(p, &spec, prefix, n_digits + n_grouping_chars,
  599. format->fill_char == '\0' ? ' ' : format->fill_char);
  600. /* If type is 'X', uppercase the prefix. This has to be done after the
  601. prefix is filled in by fill_non_digits */
  602. if (format->type == 'X') {
  603. Py_ssize_t t;
  604. for (t = 0; t < n_prefix; ++t)
  605. p[t + spec.n_lpadding + spec.n_lsign] =
  606. STRINGLIB_TOUPPER(p[t + spec.n_lpadding + spec.n_lsign]);
  607. }
  608. done:
  609. Py_XDECREF(tmp);
  610. return result;
  611. }
  612. #endif /* defined FORMAT_LONG || defined FORMAT_INT */
  613. /************************************************************************/
  614. /*********** float formatting *******************************************/
  615. /************************************************************************/
  616. #ifdef FORMAT_FLOAT
  617. #if STRINGLIB_IS_UNICODE
  618. /* taken from unicodeobject.c */
  619. static Py_ssize_t
  620. strtounicode(Py_UNICODE *buffer, const char *charbuffer)
  621. {
  622. register Py_ssize_t i;
  623. Py_ssize_t len = strlen(charbuffer);
  624. for (i = len - 1; i >= 0; --i)
  625. buffer[i] = (Py_UNICODE) charbuffer[i];
  626. return len;
  627. }
  628. #endif
  629. /* see FORMATBUFLEN in unicodeobject.c */
  630. #define FLOAT_FORMATBUFLEN 120
  631. /* much of this is taken from unicodeobject.c */
  632. static PyObject *
  633. format_float_internal(PyObject *value,
  634. const InternalFormatSpec *format)
  635. {
  636. /* fmt = '%.' + `prec` + `type` + '%%'
  637. worst case length = 2 + 10 (len of INT_MAX) + 1 + 2 = 15 (use 20)*/
  638. char fmt[20];
  639. /* taken from unicodeobject.c */
  640. /* Worst case length calc to ensure no buffer overrun:
  641. 'g' formats:
  642. fmt = %#.<prec>g
  643. buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
  644. for any double rep.)
  645. len = 1 + prec + 1 + 2 + 5 = 9 + prec
  646. 'f' formats:
  647. buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
  648. len = 1 + 50 + 1 + prec = 52 + prec
  649. If prec=0 the effective precision is 1 (the leading digit is
  650. always given), therefore increase the length by one.
  651. */
  652. char charbuf[FLOAT_FORMATBUFLEN];
  653. Py_ssize_t n_digits;
  654. double x;
  655. Py_ssize_t precision = format->precision;
  656. PyObject *result = NULL;
  657. STRINGLIB_CHAR sign;
  658. char* trailing = "";
  659. STRINGLIB_CHAR *p;
  660. NumberFieldWidths spec;
  661. STRINGLIB_CHAR type = format->type;
  662. #if STRINGLIB_IS_UNICODE
  663. Py_UNICODE unicodebuf[FLOAT_FORMATBUFLEN];
  664. #endif
  665. /* alternate is not allowed on floats. */
  666. if (format->alternate) {
  667. PyErr_SetString(PyExc_ValueError,
  668. "Alternate form (#) not allowed in float format "
  669. "specifier");
  670. goto done;
  671. }
  672. /* first, do the conversion as 8-bit chars, using the platform's
  673. snprintf. then, if needed, convert to unicode. */
  674. /* 'F' is the same as 'f', per the PEP */
  675. if (type == 'F')
  676. type = 'f';
  677. x = PyFloat_AsDouble(value);
  678. if (x == -1.0 && PyErr_Occurred())
  679. goto done;
  680. if (type == '%') {
  681. type = 'f';
  682. x *= 100;
  683. trailing = "%";
  684. }
  685. if (precision < 0)
  686. precision = 6;
  687. if (type == 'f' && fabs(x) >= 1e50)
  688. type = 'g';
  689. /* cast "type", because if we're in unicode we need to pass a
  690. 8-bit char. this is safe, because we've restricted what "type"
  691. can be */
  692. PyOS_snprintf(fmt, sizeof(fmt), "%%.%" PY_FORMAT_SIZE_T "d%c", precision,
  693. (char)type);
  694. /* do the actual formatting */
  695. PyOS_ascii_formatd(charbuf, sizeof(charbuf), fmt, x);
  696. /* adding trailing to fmt with PyOS_snprintf doesn't work, not
  697. sure why. we'll just concatentate it here, no harm done. we
  698. know we can't have a buffer overflow from the fmt size
  699. analysis */
  700. strcat(charbuf, trailing);
  701. /* rather than duplicate the code for snprintf for both unicode
  702. and 8 bit strings, we just use the 8 bit version and then
  703. convert to unicode in a separate code path. that's probably
  704. the lesser of 2 evils. */
  705. #if STRINGLIB_IS_UNICODE
  706. n_digits = strtounicode(unicodebuf, charbuf);
  707. p = unicodebuf;
  708. #else
  709. /* compute the length. I believe this is done because the return
  710. value from snprintf above is unreliable */
  711. n_digits = strlen(charbuf);
  712. p = charbuf;
  713. #endif
  714. /* is a sign character present in the output? if so, remember it
  715. and skip it */
  716. sign = p[0];
  717. if (sign == '-') {
  718. ++p;
  719. --n_digits;
  720. }
  721. calc_number_widths(&spec, sign, 0, n_digits, format);
  722. /* allocate a string with enough space */
  723. result = STRINGLIB_NEW(NULL, spec.n_total);
  724. if (result == NULL)
  725. goto done;
  726. /* Fill in the non-digit parts (padding, sign, etc.) */
  727. fill_non_digits(STRINGLIB_STR(result), &spec, NULL, n_digits,
  728. format->fill_char == '\0' ? ' ' : format->fill_char);
  729. /* fill in the digit parts */
  730. memmove(STRINGLIB_STR(result) +
  731. (spec.n_lpadding + spec.n_lsign + spec.n_spadding),
  732. p,
  733. n_digits * sizeof(STRINGLIB_CHAR));
  734. done:
  735. return result;
  736. }
  737. #endif /* FORMAT_FLOAT */
  738. /************************************************************************/
  739. /*********** built in formatters ****************************************/
  740. /************************************************************************/
  741. PyObject *
  742. FORMAT_STRING(PyObject *obj,
  743. STRINGLIB_CHAR *format_spec,
  744. Py_ssize_t format_spec_len)
  745. {
  746. InternalFormatSpec format;
  747. PyObject *result = NULL;
  748. /* check for the special case of zero length format spec, make
  749. it equivalent to str(obj) */
  750. if (format_spec_len == 0) {
  751. result = STRINGLIB_TOSTR(obj);
  752. goto done;
  753. }
  754. /* parse the format_spec */
  755. if (!parse_internal_render_format_spec(format_spec, format_spec_len,
  756. &format, 's'))
  757. goto done;
  758. /* type conversion? */
  759. switch (format.type) {
  760. case 's':
  761. /* no type conversion needed, already a string. do the formatting */
  762. result = format_string_internal(obj, &format);
  763. break;
  764. default:
  765. /* unknown */
  766. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  767. goto done;
  768. }
  769. done:
  770. return result;
  771. }
  772. #if defined FORMAT_LONG || defined FORMAT_INT
  773. static PyObject*
  774. format_int_or_long(PyObject* obj,
  775. STRINGLIB_CHAR *format_spec,
  776. Py_ssize_t format_spec_len,
  777. IntOrLongToString tostring)
  778. {
  779. PyObject *result = NULL;
  780. PyObject *tmp = NULL;
  781. InternalFormatSpec format;
  782. /* check for the special case of zero length format spec, make
  783. it equivalent to str(obj) */
  784. if (format_spec_len == 0) {
  785. result = STRINGLIB_TOSTR(obj);
  786. goto done;
  787. }
  788. /* parse the format_spec */
  789. if (!parse_internal_render_format_spec(format_spec,
  790. format_spec_len,
  791. &format, 'd'))
  792. goto done;
  793. /* type conversion? */
  794. switch (format.type) {
  795. case 'b':
  796. case 'c':
  797. case 'd':
  798. case 'o':
  799. case 'x':
  800. case 'X':
  801. case 'n':
  802. /* no type conversion needed, already an int (or long). do
  803. the formatting */
  804. result = format_int_or_long_internal(obj, &format, tostring);
  805. break;
  806. case 'e':
  807. case 'E':
  808. case 'f':
  809. case 'F':
  810. case 'g':
  811. case 'G':
  812. case '%':
  813. /* convert to float */
  814. tmp = PyNumber_Float(obj);
  815. if (tmp == NULL)
  816. goto done;
  817. result = format_float_internal(tmp, &format);
  818. break;
  819. default:
  820. /* unknown */
  821. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  822. goto done;
  823. }
  824. done:
  825. Py_XDECREF(tmp);
  826. return result;
  827. }
  828. #endif /* FORMAT_LONG || defined FORMAT_INT */
  829. #ifdef FORMAT_LONG
  830. /* Need to define long_format as a function that will convert a long
  831. to a string. In 3.0, _PyLong_Format has the correct signature. In
  832. 2.x, we need to fudge a few parameters */
  833. #if PY_VERSION_HEX >= 0x03000000
  834. #define long_format _PyLong_Format
  835. #else
  836. static PyObject*
  837. long_format(PyObject* value, int base)
  838. {
  839. /* Convert to base, don't add trailing 'L', and use the new octal
  840. format. We already know this is a long object */
  841. assert(PyLong_Check(value));
  842. /* convert to base, don't add 'L', and use the new octal format */
  843. return _PyLong_Format(value, base, 0, 1);
  844. }
  845. #endif
  846. PyObject *
  847. FORMAT_LONG(PyObject *obj,
  848. STRINGLIB_CHAR *format_spec,
  849. Py_ssize_t format_spec_len)
  850. {
  851. return format_int_or_long(obj, format_spec, format_spec_len,
  852. long_format);
  853. }
  854. #endif /* FORMAT_LONG */
  855. #ifdef FORMAT_INT
  856. /* this is only used for 2.x, not 3.0 */
  857. static PyObject*
  858. int_format(PyObject* value, int base)
  859. {
  860. /* Convert to base, and use the new octal format. We already
  861. know this is an int object */
  862. assert(PyInt_Check(value));
  863. return _PyInt_Format((PyIntObject*)value, base, 1);
  864. }
  865. PyObject *
  866. FORMAT_INT(PyObject *obj,
  867. STRINGLIB_CHAR *format_spec,
  868. Py_ssize_t format_spec_len)
  869. {
  870. return format_int_or_long(obj, format_spec, format_spec_len,
  871. int_format);
  872. }
  873. #endif /* FORMAT_INT */
  874. #ifdef FORMAT_FLOAT
  875. PyObject *
  876. FORMAT_FLOAT(PyObject *obj,
  877. STRINGLIB_CHAR *format_spec,
  878. Py_ssize_t format_spec_len)
  879. {
  880. PyObject *result = NULL;
  881. InternalFormatSpec format;
  882. /* check for the special case of zero length format spec, make
  883. it equivalent to str(obj) */
  884. if (format_spec_len == 0) {
  885. result = STRINGLIB_TOSTR(obj);
  886. goto done;
  887. }
  888. /* parse the format_spec */
  889. if (!parse_internal_render_format_spec(format_spec,
  890. format_spec_len,
  891. &format, '\0'))
  892. goto done;
  893. /* type conversion? */
  894. switch (format.type) {
  895. case '\0':
  896. /* 'Z' means like 'g', but with at least one decimal. See
  897. PyOS_ascii_formatd */
  898. format.type = 'Z';
  899. /* Deliberate fall through to the next case statement */
  900. case 'e':
  901. case 'E':
  902. case 'f':
  903. case 'F':
  904. case 'g':
  905. case 'G':
  906. case 'n':
  907. case '%':
  908. /* no conversion, already a float. do the formatting */
  909. result = format_float_internal(obj, &format);
  910. break;
  911. default:
  912. /* unknown */
  913. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  914. goto done;
  915. }
  916. done:
  917. return result;
  918. }
  919. #endif /* FORMAT_FLOAT */