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