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