source: python/trunk/Objects/stringlib/formatter.h

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

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