formatter.h 46.3 KB
Newer Older
1 2 3
/* implements the string, long, and float formatters.  that is,
   string.__format__, etc. */

4 5
#include <locale.h>

6 7 8 9 10 11 12 13
/* Before including this, you must include either:
   stringlib/unicodedefs.h
   stringlib/stringdefs.h

   Also, you should define the names:
   FORMAT_STRING
   FORMAT_LONG
   FORMAT_FLOAT
14
   FORMAT_COMPLEX
15 16 17 18
   to be whatever you want the public names of these functions to
   be.  These are the only non-static functions defined here.
*/

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/* Raises an exception about an unknown presentation type for this
 * type. */

static void
unknown_presentation_type(STRINGLIB_CHAR presentation_type,
                          const char* type_name)
{
#if STRINGLIB_IS_UNICODE
    /* If STRINGLIB_CHAR is Py_UNICODE, %c might be out-of-range,
       hence the two cases. If it is char, gcc complains that the
       condition below is always true, hence the ifdef. */
    if (presentation_type > 32 && presentation_type < 128)
#endif
        PyErr_Format(PyExc_ValueError,
                     "Unknown format code '%c' "
                     "for object of type '%.200s'",
35
                     (char)presentation_type,
36 37 38 39 40 41 42 43 44 45 46
                     type_name);
#if STRINGLIB_IS_UNICODE
    else
        PyErr_Format(PyExc_ValueError,
                     "Unknown format code '\\x%x' "
                     "for object of type '%.200s'",
                     (unsigned int)presentation_type,
                     type_name);
#endif
}

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
static void
invalid_comma_type(STRINGLIB_CHAR presentation_type)
{
#if STRINGLIB_IS_UNICODE
    /* See comment in unknown_presentation_type */
    if (presentation_type > 32 && presentation_type < 128)
#endif
        PyErr_Format(PyExc_ValueError,
                     "Cannot specify ',' with '%c'.",
                     (char)presentation_type);
#if STRINGLIB_IS_UNICODE
    else
        PyErr_Format(PyExc_ValueError,
                     "Cannot specify ',' with '\\x%x'.",
                     (unsigned int)presentation_type);
#endif
}

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
/*
    get_integer consumes 0 or more decimal digit characters from an
    input string, updates *result with the corresponding positive
    integer, and returns the number of digits consumed.

    returns -1 on error.
*/
static int
get_integer(STRINGLIB_CHAR **ptr, STRINGLIB_CHAR *end,
                  Py_ssize_t *result)
{
    Py_ssize_t accumulator, digitval, oldaccumulator;
    int numdigits;
    accumulator = numdigits = 0;
    for (;;(*ptr)++, numdigits++) {
        if (*ptr >= end)
            break;
        digitval = STRINGLIB_TODECIMAL(**ptr);
        if (digitval < 0)
            break;
        /*
           This trick was copied from old Unicode format code.  It's cute,
           but would really suck on an old machine with a slow divide
           implementation.  Fortunately, in the normal case we do not
           expect too many digits.
        */
        oldaccumulator = accumulator;
        accumulator *= 10;
        if ((accumulator+10)/10 != oldaccumulator+1) {
            PyErr_Format(PyExc_ValueError,
                         "Too many decimal digits in format string");
            return -1;
        }
        accumulator += digitval;
    }
    *result = accumulator;
    return numdigits;
}

/************************************************************************/
/*********** standard format specifier parsing **************************/
/************************************************************************/

/* returns true if this character is a specifier alignment token */
Py_LOCAL_INLINE(int)
is_alignment_token(STRINGLIB_CHAR c)
{
    switch (c) {
    case '<': case '>': case '=': case '^':
        return 1;
    default:
        return 0;
    }
}

/* returns true if this character is a sign element */
Py_LOCAL_INLINE(int)
is_sign_element(STRINGLIB_CHAR c)
{
    switch (c) {
125
    case ' ': case '+': case '-':
126 127 128 129 130 131 132 133 134 135
        return 1;
    default:
        return 0;
    }
}


typedef struct {
    STRINGLIB_CHAR fill_char;
    STRINGLIB_CHAR align;
Eric Smith's avatar
Eric Smith committed
136
    int alternate;
137 138
    STRINGLIB_CHAR sign;
    Py_ssize_t width;
139
    int thousands_separators;
140 141 142 143
    Py_ssize_t precision;
    STRINGLIB_CHAR type;
} InternalFormatSpec;

144 145 146 147 148 149 150 151 152 153

#if 0
/* Occassionally useful for debugging. Should normally be commented out. */
static void
DEBUG_PRINT_FORMAT_SPEC(InternalFormatSpec *format)
{
    printf("internal format spec: fill_char %d\n", format->fill_char);
    printf("internal format spec: align %d\n", format->align);
    printf("internal format spec: alternate %d\n", format->alternate);
    printf("internal format spec: sign %d\n", format->sign);
154
    printf("internal format spec: width %zd\n", format->width);
155 156
    printf("internal format spec: thousands_separators %d\n",
           format->thousands_separators);
157
    printf("internal format spec: precision %zd\n", format->precision);
158 159 160 161 162 163
    printf("internal format spec: type %c\n", format->type);
    printf("\n");
}
#endif


164 165 166 167 168 169 170
/*
  ptr points to the start of the format_spec, end points just past its end.
  fills in format with the parsed information.
  returns 1 on success, 0 on failure.
  if failure, sets the exception
*/
static int
171
parse_internal_render_format_spec(STRINGLIB_CHAR *format_spec,
172
                                  Py_ssize_t format_spec_len,
173
                                  InternalFormatSpec *format,
174 175
                                  char default_type,
                                  char default_align)
176
{
177 178
    STRINGLIB_CHAR *ptr = format_spec;
    STRINGLIB_CHAR *end = format_spec + format_spec_len;
179 180 181 182

    /* end-ptr is used throughout this code to specify the length of
       the input string */

183
    Py_ssize_t consumed;
184
    int align_specified = 0;
185 186

    format->fill_char = '\0';
187
    format->align = default_align;
Eric Smith's avatar
Eric Smith committed
188
    format->alternate = 0;
189 190
    format->sign = '\0';
    format->width = -1;
191
    format->thousands_separators = 0;
192 193 194 195 196 197 198 199
    format->precision = -1;
    format->type = default_type;

    /* If the second char is an alignment token,
       then parse the fill char */
    if (end-ptr >= 2 && is_alignment_token(ptr[1])) {
        format->align = ptr[1];
        format->fill_char = ptr[0];
200
        align_specified = 1;
201
        ptr += 2;
202 203
    }
    else if (end-ptr >= 1 && is_alignment_token(ptr[0])) {
204
        format->align = ptr[0];
205
        align_specified = 1;
Christian Heimes's avatar
Christian Heimes committed
206
        ++ptr;
207 208 209 210 211
    }

    /* Parse the various sign options */
    if (end-ptr >= 1 && is_sign_element(ptr[0])) {
        format->sign = ptr[0];
Christian Heimes's avatar
Christian Heimes committed
212
        ++ptr;
213 214
    }

215 216 217
    /* If the next character is #, we're in alternate mode.  This only
       applies to integers. */
    if (end-ptr >= 1 && ptr[0] == '#') {
218 219
        format->alternate = 1;
        ++ptr;
220 221
    }

222
    /* The special case for 0-padding (backwards compat) */
Eric Smith's avatar
Eric Smith committed
223
    if (format->fill_char == '\0' && end-ptr >= 1 && ptr[0] == '0') {
224
        format->fill_char = '0';
225
        if (!align_specified) {
226 227
            format->align = '=';
        }
Christian Heimes's avatar
Christian Heimes committed
228
        ++ptr;
229 230
    }

231 232 233 234
    consumed = get_integer(&ptr, end, &format->width);
    if (consumed == -1)
        /* Overflow error. Exception already set. */
        return 0;
235

236 237 238 239 240
    /* If consumed is 0, we didn't consume any characters for the
       width. In that case, reset the width to -1, because
       get_integer() will have set it to zero. -1 is how we record
       that the width wasn't specified. */
    if (consumed == 0)
241 242
        format->width = -1;

243 244 245 246 247 248
    /* Comma signifies add thousands separators */
    if (end-ptr && ptr[0] == ',') {
        format->thousands_separators = 1;
        ++ptr;
    }

249 250
    /* Parse field precision */
    if (end-ptr && ptr[0] == '.') {
Christian Heimes's avatar
Christian Heimes committed
251
        ++ptr;
252

253 254 255 256
        consumed = get_integer(&ptr, end, &format->precision);
        if (consumed == -1)
            /* Overflow error. Exception already set. */
            return 0;
257

258 259
        /* Not having a precision after a dot is an error. */
        if (consumed == 0) {
260 261 262 263 264 265 266
            PyErr_Format(PyExc_ValueError,
                         "Format specifier missing precision");
            return 0;
        }

    }

267
    /* Finally, parse the type field. */
268 269

    if (end-ptr > 1) {
270
        /* More than one char remain, invalid conversion spec. */
271 272 273 274 275 276
        PyErr_Format(PyExc_ValueError, "Invalid conversion specification");
        return 0;
    }

    if (end-ptr == 1) {
        format->type = ptr[0];
Christian Heimes's avatar
Christian Heimes committed
277
        ++ptr;
278 279
    }

280 281 282 283 284 285 286 287 288 289 290 291 292 293
    /* Do as much validating as we can, just by looking at the format
       specifier.  Do not take into account what type of formatting
       we're doing (int, float, string). */

    if (format->thousands_separators) {
        switch (format->type) {
        case 'd':
        case 'e':
        case 'f':
        case 'g':
        case 'E':
        case 'G':
        case '%':
        case 'F':
294
        case '\0':
295 296 297
            /* These are allowed. See PEP 378.*/
            break;
        default:
298
            invalid_comma_type(format->type);
299 300
            return 0;
        }
301 302
    }

303 304 305
    return 1;
}

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
/* Calculate the padding needed. */
static void
calc_padding(Py_ssize_t nchars, Py_ssize_t width, STRINGLIB_CHAR align,
             Py_ssize_t *n_lpadding, Py_ssize_t *n_rpadding,
             Py_ssize_t *n_total)
{
    if (width >= 0) {
        if (nchars > width)
            *n_total = nchars;
        else
            *n_total = width;
    }
    else {
        /* not specified, use all of the chars and no more */
        *n_total = nchars;
    }

323
    /* Figure out how much leading space we need, based on the
324 325 326 327 328
       aligning */
    if (align == '>')
        *n_lpadding = *n_total - nchars;
    else if (align == '^')
        *n_lpadding = (*n_total - nchars) / 2;
329 330 331 332
    else if (align == '<' || align == '=')
        *n_lpadding = 0;
    else {
        /* We should never have an unspecified alignment. */
333
        *n_lpadding = 0;
334 335
        assert(0);
    }
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

    *n_rpadding = *n_total - nchars - *n_lpadding;
}

/* Do the padding, and return a pointer to where the caller-supplied
   content goes. */
static STRINGLIB_CHAR *
fill_padding(STRINGLIB_CHAR *p, Py_ssize_t nchars, STRINGLIB_CHAR fill_char,
             Py_ssize_t n_lpadding, Py_ssize_t n_rpadding)
{
    /* Pad on left. */
    if (n_lpadding)
        STRINGLIB_FILL(p, fill_char, n_lpadding);

    /* Pad on right. */
    if (n_rpadding)
        STRINGLIB_FILL(p + nchars + n_lpadding, fill_char, n_rpadding);

    /* Pointer to the user content. */
    return p + n_lpadding;
}

#if defined FORMAT_FLOAT || defined FORMAT_LONG || defined FORMAT_COMPLEX
359 360 361 362
/************************************************************************/
/*********** common routines for numeric formatting *********************/
/************************************************************************/

363 364 365 366 367 368 369 370 371 372 373 374 375 376
/* Locale type codes. */
#define LT_CURRENT_LOCALE 0
#define LT_DEFAULT_LOCALE 1
#define LT_NO_LOCALE 2

/* Locale info needed for formatting integers and the part of floats
   before and including the decimal. Note that locales only support
   8-bit chars, not unicode. */
typedef struct {
    char *decimal_point;
    char *thousands_sep;
    char *grouping;
} LocaleInfo;

377
/* describes the layout for an integer, see the comment in
378
   calc_number_widths() for details */
379 380
typedef struct {
    Py_ssize_t n_lpadding;
381
    Py_ssize_t n_prefix;
382 383
    Py_ssize_t n_spadding;
    Py_ssize_t n_rpadding;
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    char sign;
    Py_ssize_t n_sign;      /* number of digits needed for sign (0/1) */
    Py_ssize_t n_grouped_digits; /* Space taken up by the digits, including
                                    any grouping chars. */
    Py_ssize_t n_decimal;   /* 0 if only an integer */
    Py_ssize_t n_remainder; /* Digits in decimal and/or exponent part,
                               excluding the decimal itself, if
                               present. */

    /* These 2 are not the widths of fields, but are needed by
       STRINGLIB_GROUPING. */
    Py_ssize_t n_digits;    /* The number of digits before a decimal
                               or exponent. */
    Py_ssize_t n_min_width; /* The min_width we used when we computed
                               the n_grouped_digits width. */
399 400
} NumberFieldWidths;

401

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
/* Given a number of the form:
   digits[remainder]
   where ptr points to the start and end points to the end, find where
    the integer part ends. This could be a decimal, an exponent, both,
    or neither.
   If a decimal point is present, set *has_decimal and increment
    remainder beyond it.
   Results are undefined (but shouldn't crash) for improperly
    formatted strings.
*/
static void
parse_number(STRINGLIB_CHAR *ptr, Py_ssize_t len,
             Py_ssize_t *n_remainder, int *has_decimal)
{
    STRINGLIB_CHAR *end = ptr + len;
    STRINGLIB_CHAR *remainder;

    while (ptr<end && isdigit(*ptr))
        ++ptr;
    remainder = ptr;

    /* Does remainder start with a decimal point? */
    *has_decimal = ptr<end && *remainder == '.';

    /* Skip the decimal point. */
    if (*has_decimal)
        remainder++;

    *n_remainder = end - remainder;
}

433 434 435 436
/* not all fields of format are used.  for example, precision is
   unused.  should this take discrete params in order to be more clear
   about what it does?  or is passing a single format parameter easier
   and more efficient enough to justify a little obfuscation? */
437 438 439 440 441
static Py_ssize_t
calc_number_widths(NumberFieldWidths *spec, Py_ssize_t n_prefix,
                   STRINGLIB_CHAR sign_char, STRINGLIB_CHAR *number,
                   Py_ssize_t n_number, Py_ssize_t n_remainder,
                   int has_decimal, const LocaleInfo *locale,
442
                   const InternalFormatSpec *format)
443
{
444 445 446 447
    Py_ssize_t n_non_digit_non_padding;
    Py_ssize_t n_padding;

    spec->n_digits = n_number - n_remainder - (has_decimal?1:0);
448
    spec->n_lpadding = 0;
449 450 451
    spec->n_prefix = n_prefix;
    spec->n_decimal = has_decimal ? strlen(locale->decimal_point) : 0;
    spec->n_remainder = n_remainder;
452 453
    spec->n_spadding = 0;
    spec->n_rpadding = 0;
454 455
    spec->sign = '\0';
    spec->n_sign = 0;
456 457

    /* the output will look like:
458 459 460
       |                                                                                         |
       | <lpadding> <sign> <prefix> <spadding> <grouped_digits> <decimal> <remainder> <rpadding> |
       |                                                                                         |
461

462
       sign is computed from format->sign and the actual
463 464
       sign of the number

Eric Smith's avatar
Eric Smith committed
465 466
       prefix is given (it's for the '0x' prefix)

467 468 469 470 471 472 473 474 475 476
       digits is already known

       the total width is either given, or computed from the
       actual digits

       only one of lpadding, spadding, and rpadding can be non-zero,
       and it's calculated from the width and other fields
    */

    /* compute the various parts we're going to write */
477 478
    switch (format->sign) {
    case '+':
479
        /* always put a + or - */
480 481 482 483 484 485 486 487 488 489 490 491
        spec->n_sign = 1;
        spec->sign = (sign_char == '-' ? '-' : '+');
        break;
    case ' ':
        spec->n_sign = 1;
        spec->sign = (sign_char == '-' ? '-' : ' ');
        break;
    default:
        /* Not specified, or the default (-) */
        if (sign_char == '-') {
            spec->n_sign = 1;
            spec->sign = '-';
492 493 494
        }
    }

495 496 497
    /* The number of chars used for non-digits and non-padding. */
    n_non_digit_non_padding = spec->n_sign + spec->n_prefix + spec->n_decimal +
        spec->n_remainder;
498

499 500
    /* min_width can go negative, that's okay. format->width == -1 means
       we don't care. */
501
    if (format->fill_char == '0' && format->align == '=')
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
        spec->n_min_width = format->width - n_non_digit_non_padding;
    else
        spec->n_min_width = 0;

    if (spec->n_digits == 0)
        /* This case only occurs when using 'c' formatting, we need
           to special case it because the grouping code always wants
           to have at least one character. */
        spec->n_grouped_digits = 0;
    else
        spec->n_grouped_digits = STRINGLIB_GROUPING(NULL, 0, NULL,
                                                    spec->n_digits,
                                                    spec->n_min_width,
                                                    locale->grouping,
                                                    locale->thousands_sep);

    /* Given the desired width and the total of digit and non-digit
       space we consume, see if we need any padding. format->width can
       be negative (meaning no padding), but this code still works in
       that case. */
    n_padding = format->width -
                        (n_non_digit_non_padding + spec->n_grouped_digits);
    if (n_padding > 0) {
        /* Some padding is needed. Determine if it's left, space, or right. */
        switch (format->align) {
        case '<':
            spec->n_rpadding = n_padding;
            break;
        case '^':
            spec->n_lpadding = n_padding / 2;
            spec->n_rpadding = n_padding - spec->n_lpadding;
            break;
        case '=':
            spec->n_spadding = n_padding;
            break;
537 538 539
        case '>':
            spec->n_lpadding = n_padding;
            break;
540
        default:
541
            /* Shouldn't get here, but treat it as '>' */
542
            spec->n_lpadding = n_padding;
543
            assert(0);
544
            break;
545 546
        }
    }
547 548 549
    return spec->n_lpadding + spec->n_sign + spec->n_prefix +
        spec->n_spadding + spec->n_grouped_digits + spec->n_decimal +
        spec->n_remainder + spec->n_rpadding;
550 551
}

552 553 554 555 556 557 558 559
/* Fill in the digit parts of a numbers's string representation,
   as determined in calc_number_widths().
   No error checking, since we know the buffer is the correct size. */
static void
fill_number(STRINGLIB_CHAR *buf, const NumberFieldWidths *spec,
            STRINGLIB_CHAR *digits, Py_ssize_t n_digits,
            STRINGLIB_CHAR *prefix, STRINGLIB_CHAR fill_char,
            LocaleInfo *locale, int toupper)
560
{
561 562 563 564 565 566
    /* Used to keep track of digits, decimal, and remainder. */
    STRINGLIB_CHAR *p = digits;

#ifndef NDEBUG
    Py_ssize_t r;
#endif
567 568

    if (spec->n_lpadding) {
569 570
        STRINGLIB_FILL(buf, fill_char, spec->n_lpadding);
        buf += spec->n_lpadding;
571
    }
572 573
    if (spec->n_sign == 1) {
        *buf++ = spec->sign;
574
    }
575
    if (spec->n_prefix) {
576
        memmove(buf,
577 578
                prefix,
                spec->n_prefix * sizeof(STRINGLIB_CHAR));
579 580 581 582 583 584
        if (toupper) {
            Py_ssize_t t;
            for (t = 0; t < spec->n_prefix; ++t)
                buf[t] = STRINGLIB_TOUPPER(buf[t]);
        }
        buf += spec->n_prefix;
585
    }
586
    if (spec->n_spadding) {
587 588
        STRINGLIB_FILL(buf, fill_char, spec->n_spadding);
        buf += spec->n_spadding;
589
    }
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623

    /* Only for type 'c' special case, it has no digits. */
    if (spec->n_digits != 0) {
        /* Fill the digits with InsertThousandsGrouping. */
#ifndef NDEBUG
        r =
#endif
            STRINGLIB_GROUPING(buf, spec->n_grouped_digits, digits,
                               spec->n_digits, spec->n_min_width,
                               locale->grouping, locale->thousands_sep);
#ifndef NDEBUG
        assert(r == spec->n_grouped_digits);
#endif
        p += spec->n_digits;
    }
    if (toupper) {
        Py_ssize_t t;
        for (t = 0; t < spec->n_grouped_digits; ++t)
            buf[t] = STRINGLIB_TOUPPER(buf[t]);
    }
    buf += spec->n_grouped_digits;

    if (spec->n_decimal) {
        Py_ssize_t t;
        for (t = 0; t < spec->n_decimal; ++t)
            buf[t] = locale->decimal_point[t];
        buf += spec->n_decimal;
        p += 1;
    }

    if (spec->n_remainder) {
        memcpy(buf, p, spec->n_remainder * sizeof(STRINGLIB_CHAR));
        buf += spec->n_remainder;
        p += spec->n_remainder;
624
    }
625

626
    if (spec->n_rpadding) {
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
        STRINGLIB_FILL(buf, fill_char, spec->n_rpadding);
        buf += spec->n_rpadding;
    }
}

static char no_grouping[1] = {CHAR_MAX};

/* Find the decimal point character(s?), thousands_separator(s?), and
   grouping description, either for the current locale if type is
   LT_CURRENT_LOCALE, a hard-coded locale if LT_DEFAULT_LOCALE, or
   none if LT_NO_LOCALE. */
static void
get_locale_info(int type, LocaleInfo *locale_info)
{
    switch (type) {
    case LT_CURRENT_LOCALE: {
        struct lconv *locale_data = localeconv();
        locale_info->decimal_point = locale_data->decimal_point;
        locale_info->thousands_sep = locale_data->thousands_sep;
        locale_info->grouping = locale_data->grouping;
        break;
    }
    case LT_DEFAULT_LOCALE:
        locale_info->decimal_point = ".";
        locale_info->thousands_sep = ",";
652 653
        locale_info->grouping = "\3"; /* Group every 3 characters.  The
                                         (implicit) trailing 0 means repeat
654 655 656 657 658 659 660 661 662
                                         infinitely. */
        break;
    case LT_NO_LOCALE:
        locale_info->decimal_point = ".";
        locale_info->thousands_sep = "";
        locale_info->grouping = no_grouping;
        break;
    default:
        assert(0);
663 664
    }
}
665

666
#endif /* FORMAT_FLOAT || FORMAT_LONG || FORMAT_COMPLEX */
667 668 669 670 671 672 673 674 675

/************************************************************************/
/*********** string formatting ******************************************/
/************************************************************************/

static PyObject *
format_string_internal(PyObject *value, const InternalFormatSpec *format)
{
    Py_ssize_t lpad;
676 677 678
    Py_ssize_t rpad;
    Py_ssize_t total;
    STRINGLIB_CHAR *p;
679 680 681 682 683 684 685 686 687 688
    Py_ssize_t len = STRINGLIB_LEN(value);
    PyObject *result = NULL;

    /* sign is not allowed on strings */
    if (format->sign != '\0') {
        PyErr_SetString(PyExc_ValueError,
                        "Sign not allowed in string format specifier");
        goto done;
    }

Eric Smith's avatar
Eric Smith committed
689 690 691 692
    /* alternate is not allowed on strings */
    if (format->alternate) {
        PyErr_SetString(PyExc_ValueError,
                        "Alternate form (#) not allowed in string format "
693
                        "specifier");
Eric Smith's avatar
Eric Smith committed
694 695 696
        goto done;
    }

697 698 699 700 701 702 703 704 705 706 707 708 709 710
    /* '=' alignment not allowed on strings */
    if (format->align == '=') {
        PyErr_SetString(PyExc_ValueError,
                        "'=' alignment not allowed "
                        "in string format specifier");
        goto done;
    }

    /* if precision is specified, output no more that format.precision
       characters */
    if (format->precision >= 0 && len >= format->precision) {
        len = format->precision;
    }

711
    calc_padding(len, format->width, format->align, &lpad, &rpad, &total);
712 713

    /* allocate the resulting string */
714
    result = STRINGLIB_NEW(NULL, total);
715 716 717
    if (result == NULL)
        goto done;

718 719 720 721
    /* Write into that space. First the padding. */
    p = fill_padding(STRINGLIB_STR(result), len,
                     format->fill_char=='\0'?' ':format->fill_char,
                     lpad, rpad);
722

723 724
    /* Then the source string. */
    memcpy(p, STRINGLIB_STR(value), len * sizeof(STRINGLIB_CHAR));
725 726 727 728 729 730 731 732 733 734

done:
    return result;
}


/************************************************************************/
/*********** long formatting ********************************************/
/************************************************************************/

735 736 737 738
#if defined FORMAT_LONG || defined FORMAT_INT
typedef PyObject*
(*IntOrLongToString)(PyObject *value, int base);

739
static PyObject *
740
format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format,
741
                            IntOrLongToString tostring)
742 743
{
    PyObject *result = NULL;
744 745 746
    PyObject *tmp = NULL;
    STRINGLIB_CHAR *pnumeric_chars;
    STRINGLIB_CHAR numeric_char;
747
    STRINGLIB_CHAR sign_char = '\0';
748 749
    Py_ssize_t n_digits;       /* count of digits need from the computed
                                  string */
750 751
    Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which
                                   produces non-digits */
752
    Py_ssize_t n_prefix = 0;   /* Count of prefix chars, (e.g., '0x') */
753
    Py_ssize_t n_total;
754
    STRINGLIB_CHAR *prefix = NULL;
755 756 757
    NumberFieldWidths spec;
    long x;

758 759 760 761
    /* Locale settings, either from the actual locale or
       from a hard-code pseudo-locale */
    LocaleInfo locale;

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    /* no precision allowed on integers */
    if (format->precision != -1) {
        PyErr_SetString(PyExc_ValueError,
                        "Precision not allowed in integer format specifier");
        goto done;
    }

    /* special case for character formatting */
    if (format->type == 'c') {
        /* error to specify a sign */
        if (format->sign != '\0') {
            PyErr_SetString(PyExc_ValueError,
                            "Sign not allowed with integer"
                            " format specifier 'c'");
            goto done;
        }

        /* taken from unicodeobject.c formatchar() */
        /* Integer input truncated to a character */
781
/* XXX: won't work for int */
782
        x = PyLong_AsLong(value);
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        if (x == -1 && PyErr_Occurred())
            goto done;
#ifdef Py_UNICODE_WIDE
        if (x < 0 || x > 0x10ffff) {
            PyErr_SetString(PyExc_OverflowError,
                            "%c arg not in range(0x110000) "
                            "(wide Python build)");
            goto done;
        }
#else
        if (x < 0 || x > 0xffff) {
            PyErr_SetString(PyExc_OverflowError,
                            "%c arg not in range(0x10000) "
                            "(narrow Python build)");
            goto done;
        }
#endif
800 801
        numeric_char = (STRINGLIB_CHAR)x;
        pnumeric_chars = &numeric_char;
802
        n_digits = 1;
803 804 805 806 807 808 809

        /* As a sort-of hack, we tell calc_number_widths that we only
           have "remainder" characters. calc_number_widths thinks
           these are characters that don't get formatted, only copied
           into the output string. We do this for 'c' formatting,
           because the characters are likely to be non-digits. */
        n_remainder = 1;
810 811
    }
    else {
812
        int base;
813 814 815
        int leading_chars_to_skip = 0;  /* Number of characters added by
                                           PyNumber_ToBase that we want to
                                           skip over. */
816 817

        /* Compute the base and how many characters will be added by
818 819 820 821
           PyNumber_ToBase */
        switch (format->type) {
        case 'b':
            base = 2;
822
            leading_chars_to_skip = 2; /* 0b */
823 824 825
            break;
        case 'o':
            base = 8;
826
            leading_chars_to_skip = 2; /* 0o */
827 828 829 830
            break;
        case 'x':
        case 'X':
            base = 16;
831
            leading_chars_to_skip = 2; /* 0x */
832 833 834
            break;
        default:  /* shouldn't be needed, but stops a compiler warning */
        case 'd':
835
        case 'n':
836 837 838 839
            base = 10;
            break;
        }

840 841 842 843
        /* The number of prefix chars is the same as the leading
           chars to skip */
        if (format->alternate)
            n_prefix = leading_chars_to_skip;
844

845
        /* Do the hard part, converting to a string in a given base */
846
        tmp = tostring(value, base);
847
        if (tmp == NULL)
848 849
            goto done;

850
        pnumeric_chars = STRINGLIB_STR(tmp);
851
        n_digits = STRINGLIB_LEN(tmp);
852

853
        prefix = pnumeric_chars;
854

855 856 857
        /* Remember not to modify what pnumeric_chars points to.  it
           might be interned.  Only modify it after we copy it into a
           newly allocated output buffer. */
858

859
        /* Is a sign character present in the output?  If so, remember it
860
           and skip it */
861 862
        if (pnumeric_chars[0] == '-') {
            sign_char = pnumeric_chars[0];
863 864
            ++prefix;
            ++leading_chars_to_skip;
865 866
        }

867 868 869
        /* Skip over the leading chars (0x, 0b, etc.) */
        n_digits -= leading_chars_to_skip;
        pnumeric_chars += leading_chars_to_skip;
870 871
    }

872 873 874 875 876 877
    /* Determine the grouping, separator, and decimal point, if any. */
    get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
                    (format->thousands_separators ?
                     LT_DEFAULT_LOCALE :
                     LT_NO_LOCALE),
                    &locale);
878

879 880 881
    /* Calculate how much memory we'll need. */
    n_total = calc_number_widths(&spec, n_prefix, sign_char, pnumeric_chars,
                       n_digits, n_remainder, 0, &locale, format);
882

883 884 885 886
    /* Allocate the memory. */
    result = STRINGLIB_NEW(NULL, n_total);
    if (!result)
        goto done;
887

888 889 890 891
    /* Populate the memory. */
    fill_number(STRINGLIB_STR(result), &spec, pnumeric_chars, n_digits,
                prefix, format->fill_char == '\0' ? ' ' : format->fill_char,
                &locale, format->type == 'X');
892

893
done:
894
    Py_XDECREF(tmp);
895 896
    return result;
}
897
#endif /* defined FORMAT_LONG || defined FORMAT_INT */
898 899 900 901 902

/************************************************************************/
/*********** float formatting *******************************************/
/************************************************************************/

903 904
#ifdef FORMAT_FLOAT
#if STRINGLIB_IS_UNICODE
905 906
static void
strtounicode(Py_UNICODE *buffer, const char *charbuffer, Py_ssize_t len)
907
{
908 909 910
    Py_ssize_t i;
    for (i = 0; i < len; ++i)
        buffer[i] = (Py_UNICODE)charbuffer[i];
911
}
912
#endif
913 914 915

/* much of this is taken from unicodeobject.c */
static PyObject *
Christian Heimes's avatar
Christian Heimes committed
916
format_float_internal(PyObject *value,
917
                      const InternalFormatSpec *format)
918
{
919
    char *buf = NULL;       /* buffer returned from PyOS_double_to_string */
920
    Py_ssize_t n_digits;
921 922 923 924
    Py_ssize_t n_remainder;
    Py_ssize_t n_total;
    int has_decimal;
    double val;
925
    Py_ssize_t precision = format->precision;
926
    Py_ssize_t default_precision = 6;
927 928
    STRINGLIB_CHAR type = format->type;
    int add_pct = 0;
929 930
    STRINGLIB_CHAR *p;
    NumberFieldWidths spec;
931 932 933 934
    int flags = 0;
    PyObject *result = NULL;
    STRINGLIB_CHAR sign_char = '\0';
    int float_type; /* Used to see if we have a nan, inf, or regular float. */
935 936

#if STRINGLIB_IS_UNICODE
937
    Py_UNICODE *unicode_tmp = NULL;
938 939
#endif

940 941 942 943 944
    /* Locale settings, either from the actual locale or
       from a hard-code pseudo-locale */
    LocaleInfo locale;

    /* Alternate is not allowed on floats. */
Eric Smith's avatar
Eric Smith committed
945 946 947
    if (format->alternate) {
        PyErr_SetString(PyExc_ValueError,
                        "Alternate form (#) not allowed in float format "
948
                        "specifier");
Eric Smith's avatar
Eric Smith committed
949 950 951
        goto done;
    }

952
    if (type == '\0') {
953 954 955
        /* Omitted type specifier.  Behaves in the same way as repr(x)
           and str(x) if no precision is given, else like 'g', but with
           at least one digit after the decimal point. */
956
        flags |= Py_DTSF_ADD_DOT_0;
957 958
        type = 'r';
        default_precision = 0;
959 960 961 962 963 964
    }

    if (type == 'n')
        /* 'n' is the same as 'g', except for the locale used to
           format the result. We take care of that later. */
        type = 'g';
965

966 967
    val = PyFloat_AsDouble(value);
    if (val == -1.0 && PyErr_Occurred())
Eric Smith's avatar
Eric Smith committed
968
        goto done;
969 970 971

    if (type == '%') {
        type = 'f';
972 973
        val *= 100;
        add_pct = 1;
974 975 976
    }

    if (precision < 0)
977
        precision = default_precision;
978 979
    else if (type == 'r')
        type = 'g';
980

981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
    /* Cast "type", because if we're in unicode we need to pass a
       8-bit char. This is safe, because we've restricted what "type"
       can be. */
    buf = PyOS_double_to_string(val, (char)type, precision, flags,
                                &float_type);
    if (buf == NULL)
        goto done;
    n_digits = strlen(buf);

    if (add_pct) {
        /* We know that buf has a trailing zero (since we just called
           strlen() on it), and we don't use that fact any more. So we
           can just write over the trailing zero. */
        buf[n_digits] = '%';
        n_digits += 1;
    }

    /* Since there is no unicode version of PyOS_double_to_string,
       just use the 8 bit version and then convert to unicode. */
1000
#if STRINGLIB_IS_UNICODE
1001 1002 1003 1004 1005 1006 1007
    unicode_tmp = (Py_UNICODE*)PyMem_Malloc((n_digits)*sizeof(Py_UNICODE));
    if (unicode_tmp == NULL) {
        PyErr_NoMemory();
        goto done;
    }
    strtounicode(unicode_tmp, buf, n_digits);
    p = unicode_tmp;
1008
#else
1009
    p = buf;
1010 1011
#endif

1012
    /* Is a sign character present in the output?  If so, remember it
1013
       and skip it */
1014 1015
    if (*p == '-') {
        sign_char = *p;
Christian Heimes's avatar
Christian Heimes committed
1016 1017
        ++p;
        --n_digits;
1018 1019
    }

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    /* Determine if we have any "remainder" (after the digits, might include
       decimal or exponent or both (or neither)) */
    parse_number(p, n_digits, &n_remainder, &has_decimal);

    /* Determine the grouping, separator, and decimal point, if any. */
    get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
                    (format->thousands_separators ?
                     LT_DEFAULT_LOCALE :
                     LT_NO_LOCALE),
                    &locale);
1030

1031 1032 1033 1034 1035 1036
    /* Calculate how much memory we'll need. */
    n_total = calc_number_widths(&spec, 0, sign_char, p, n_digits,
                                 n_remainder, has_decimal, &locale, format);

    /* Allocate the memory. */
    result = STRINGLIB_NEW(NULL, n_total);
1037 1038 1039
    if (result == NULL)
        goto done;

1040 1041 1042 1043
    /* Populate the memory. */
    fill_number(STRINGLIB_STR(result), &spec, p, n_digits, NULL,
                format->fill_char == '\0' ? ' ' : format->fill_char, &locale,
                0);
1044 1045

done:
1046 1047 1048 1049
    PyMem_Free(buf);
#if STRINGLIB_IS_UNICODE
    PyMem_Free(unicode_tmp);
#endif
1050 1051
    return result;
}
1052
#endif /* FORMAT_FLOAT */
1053

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
/************************************************************************/
/*********** complex formatting *****************************************/
/************************************************************************/

#ifdef FORMAT_COMPLEX

static PyObject *
format_complex_internal(PyObject *value,
                        const InternalFormatSpec *format)
{
    double re;
    double im;
    char *re_buf = NULL;       /* buffer returned from PyOS_double_to_string */
    char *im_buf = NULL;       /* buffer returned from PyOS_double_to_string */

    InternalFormatSpec tmp_format = *format;
    Py_ssize_t n_re_digits;
    Py_ssize_t n_im_digits;
    Py_ssize_t n_re_remainder;
    Py_ssize_t n_im_remainder;
    Py_ssize_t n_re_total;
    Py_ssize_t n_im_total;
    int re_has_decimal;
    int im_has_decimal;
    Py_ssize_t precision = format->precision;
1079
    Py_ssize_t default_precision = 6;
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    STRINGLIB_CHAR type = format->type;
    STRINGLIB_CHAR *p_re;
    STRINGLIB_CHAR *p_im;
    NumberFieldWidths re_spec;
    NumberFieldWidths im_spec;
    int flags = 0;
    PyObject *result = NULL;
    STRINGLIB_CHAR *p;
    STRINGLIB_CHAR re_sign_char = '\0';
    STRINGLIB_CHAR im_sign_char = '\0';
    int re_float_type; /* Used to see if we have a nan, inf, or regular float. */
    int im_float_type;
    int add_parens = 0;
    int skip_re = 0;
    Py_ssize_t lpad;
    Py_ssize_t rpad;
    Py_ssize_t total;

#if STRINGLIB_IS_UNICODE
    Py_UNICODE *re_unicode_tmp = NULL;
    Py_UNICODE *im_unicode_tmp = NULL;
#endif

    /* Locale settings, either from the actual locale or
       from a hard-code pseudo-locale */
    LocaleInfo locale;

    /* Alternate is not allowed on complex. */
    if (format->alternate) {
        PyErr_SetString(PyExc_ValueError,
                        "Alternate form (#) not allowed in complex format "
                        "specifier");
        goto done;
    }

    /* Neither is zero pading. */
    if (format->fill_char == '0') {
        PyErr_SetString(PyExc_ValueError,
                        "Zero padding is not allowed in complex format "
                        "specifier");
        goto done;
    }

    /* Neither is '=' alignment . */
    if (format->align == '=') {
        PyErr_SetString(PyExc_ValueError,
                        "'=' alignment flag is not allowed in complex format "
                        "specifier");
        goto done;
    }

    re = PyComplex_RealAsDouble(value);
    if (re == -1.0 && PyErr_Occurred())
        goto done;
    im = PyComplex_ImagAsDouble(value);
    if (im == -1.0 && PyErr_Occurred())
        goto done;

    if (type == '\0') {
        /* Omitted type specifier. Should be like str(self). */
1140 1141
        type = 'r';
        default_precision = 0;
1142
        if (re == 0.0 && copysign(1.0, re) == 1.0)
1143
            skip_re = 1;
1144 1145
        else
            add_parens = 1;
1146 1147 1148 1149 1150 1151 1152 1153
    }

    if (type == 'n')
        /* 'n' is the same as 'g', except for the locale used to
           format the result. We take care of that later. */
        type = 'g';

    if (precision < 0)
1154
        precision = default_precision;
1155 1156
    else if (type == 'r')
        type = 'g';
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223

    /* Cast "type", because if we're in unicode we need to pass a
       8-bit char. This is safe, because we've restricted what "type"
       can be. */
    re_buf = PyOS_double_to_string(re, (char)type, precision, flags,
                                   &re_float_type);
    if (re_buf == NULL)
        goto done;
    im_buf = PyOS_double_to_string(im, (char)type, precision, flags,
                                   &im_float_type);
    if (im_buf == NULL)
        goto done;

    n_re_digits = strlen(re_buf);
    n_im_digits = strlen(im_buf);

    /* Since there is no unicode version of PyOS_double_to_string,
       just use the 8 bit version and then convert to unicode. */
#if STRINGLIB_IS_UNICODE
    re_unicode_tmp = (Py_UNICODE*)PyMem_Malloc((n_re_digits)*sizeof(Py_UNICODE));
    if (re_unicode_tmp == NULL) {
        PyErr_NoMemory();
        goto done;
    }
    strtounicode(re_unicode_tmp, re_buf, n_re_digits);
    p_re = re_unicode_tmp;

    im_unicode_tmp = (Py_UNICODE*)PyMem_Malloc((n_im_digits)*sizeof(Py_UNICODE));
    if (im_unicode_tmp == NULL) {
        PyErr_NoMemory();
        goto done;
    }
    strtounicode(im_unicode_tmp, im_buf, n_im_digits);
    p_im = im_unicode_tmp;
#else
    p_re = re_buf;
    p_im = im_buf;
#endif

    /* Is a sign character present in the output?  If so, remember it
       and skip it */
    if (*p_re == '-') {
        re_sign_char = *p_re;
        ++p_re;
        --n_re_digits;
    }
    if (*p_im == '-') {
        im_sign_char = *p_im;
        ++p_im;
        --n_im_digits;
    }

    /* Determine if we have any "remainder" (after the digits, might include
       decimal or exponent or both (or neither)) */
    parse_number(p_re, n_re_digits, &n_re_remainder, &re_has_decimal);
    parse_number(p_im, n_im_digits, &n_im_remainder, &im_has_decimal);

    /* Determine the grouping, separator, and decimal point, if any. */
    get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
                    (format->thousands_separators ?
                     LT_DEFAULT_LOCALE :
                     LT_NO_LOCALE),
                    &locale);

    /* Turn off any padding. We'll do it later after we've composed
       the numbers without padding. */
    tmp_format.fill_char = '\0';
1224
    tmp_format.align = '<';
1225 1226 1227 1228 1229 1230 1231
    tmp_format.width = -1;

    /* Calculate how much memory we'll need. */
    n_re_total = calc_number_widths(&re_spec, 0, re_sign_char, p_re,
                                    n_re_digits, n_re_remainder,
                                    re_has_decimal, &locale, &tmp_format);

1232 1233 1234 1235 1236
    /* Same formatting, but always include a sign, unless the real part is
     * going to be omitted, in which case we use whatever sign convention was
     * requested by the original format. */
    if (!skip_re)
        tmp_format.sign = '+';
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    n_im_total = calc_number_widths(&im_spec, 0, im_sign_char, p_im,
                                    n_im_digits, n_im_remainder,
                                    im_has_decimal, &locale, &tmp_format);

    if (skip_re)
        n_re_total = 0;

    /* Add 1 for the 'j', and optionally 2 for parens. */
    calc_padding(n_re_total + n_im_total + 1 + add_parens * 2,
                 format->width, format->align, &lpad, &rpad, &total);

    result = STRINGLIB_NEW(NULL, total);
    if (result == NULL)
        goto done;

    /* Populate the memory. First, the padding. */
    p = fill_padding(STRINGLIB_STR(result),
                     n_re_total + n_im_total + 1 + add_parens * 2,
                     format->fill_char=='\0' ? ' ' : format->fill_char,
                     lpad, rpad);

    if (add_parens)
        *p++ = '(';

    if (!skip_re) {
        fill_number(p, &re_spec, p_re, n_re_digits, NULL, 0, &locale, 0);
        p += n_re_total;
    }
    fill_number(p, &im_spec, p_im, n_im_digits, NULL, 0, &locale, 0);
    p += n_im_total;
    *p++ = 'j';

    if (add_parens)
        *p++ = ')';

done:
    PyMem_Free(re_buf);
    PyMem_Free(im_buf);
#if STRINGLIB_IS_UNICODE
    PyMem_Free(re_unicode_tmp);
    PyMem_Free(im_unicode_tmp);
#endif
    return result;
}
#endif /* FORMAT_COMPLEX */

1283 1284 1285 1286
/************************************************************************/
/*********** built in formatters ****************************************/
/************************************************************************/
PyObject *
1287
FORMAT_STRING(PyObject *obj,
1288 1289
              STRINGLIB_CHAR *format_spec,
              Py_ssize_t format_spec_len)
1290 1291
{
    InternalFormatSpec format;
1292
    PyObject *result = NULL;
1293 1294

    /* check for the special case of zero length format spec, make
1295 1296 1297
       it equivalent to str(obj) */
    if (format_spec_len == 0) {
        result = STRINGLIB_TOSTR(obj);
1298 1299 1300 1301
        goto done;
    }

    /* parse the format_spec */
1302
    if (!parse_internal_render_format_spec(format_spec, format_spec_len,
1303
                                           &format, 's', '<'))
1304 1305 1306 1307 1308 1309
        goto done;

    /* type conversion? */
    switch (format.type) {
    case 's':
        /* no type conversion needed, already a string.  do the formatting */
1310
        result = format_string_internal(obj, &format);
1311 1312 1313
        break;
    default:
        /* unknown */
1314
        unknown_presentation_type(format.type, obj->ob_type->tp_name);
1315 1316 1317 1318 1319 1320 1321
        goto done;
    }

done:
    return result;
}

1322 1323
#if defined FORMAT_LONG || defined FORMAT_INT
static PyObject*
1324
format_int_or_long(PyObject* obj,
1325 1326 1327
                   STRINGLIB_CHAR *format_spec,
                   Py_ssize_t format_spec_len,
                   IntOrLongToString tostring)
1328 1329 1330 1331 1332 1333
{
    PyObject *result = NULL;
    PyObject *tmp = NULL;
    InternalFormatSpec format;

    /* check for the special case of zero length format spec, make
1334 1335 1336
       it equivalent to str(obj) */
    if (format_spec_len == 0) {
        result = STRINGLIB_TOSTR(obj);
1337 1338 1339 1340
        goto done;
    }

    /* parse the format_spec */
1341
    if (!parse_internal_render_format_spec(format_spec,
1342
                                           format_spec_len,
1343
                                           &format, 'd', '>'))
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
        goto done;

    /* type conversion? */
    switch (format.type) {
    case 'b':
    case 'c':
    case 'd':
    case 'o':
    case 'x':
    case 'X':
1354
    case 'n':
1355
        /* no type conversion needed, already an int (or long).  do
1356 1357
           the formatting */
            result = format_int_or_long_internal(obj, &format, tostring);
1358 1359
        break;

1360 1361 1362 1363 1364 1365 1366 1367
    case 'e':
    case 'E':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case '%':
        /* convert to float */
1368
        tmp = PyNumber_Float(obj);
1369 1370
        if (tmp == NULL)
            goto done;
1371
        result = format_float_internal(tmp, &format);
1372 1373
        break;

1374 1375
    default:
        /* unknown */
1376
        unknown_presentation_type(format.type, obj->ob_type->tp_name);
1377 1378 1379 1380 1381 1382 1383
        goto done;
    }

done:
    Py_XDECREF(tmp);
    return result;
}
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
#endif /* FORMAT_LONG || defined FORMAT_INT */

#ifdef FORMAT_LONG
/* Need to define long_format as a function that will convert a long
   to a string.  In 3.0, _PyLong_Format has the correct signature.  In
   2.x, we need to fudge a few parameters */
#if PY_VERSION_HEX >= 0x03000000
#define long_format _PyLong_Format
#else
static PyObject*
long_format(PyObject* value, int base)
{
    /* Convert to base, don't add trailing 'L', and use the new octal
       format. We already know this is a long object */
    assert(PyLong_Check(value));
    /* convert to base, don't add 'L', and use the new octal format */
    return _PyLong_Format(value, base, 0, 1);
}
#endif

PyObject *
1405
FORMAT_LONG(PyObject *obj,
1406 1407
            STRINGLIB_CHAR *format_spec,
            Py_ssize_t format_spec_len)
1408
{
1409
    return format_int_or_long(obj, format_spec, format_spec_len,
1410
                              long_format);
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
}
#endif /* FORMAT_LONG */

#ifdef FORMAT_INT
/* this is only used for 2.x, not 3.0 */
static PyObject*
int_format(PyObject* value, int base)
{
    /* Convert to base, and use the new octal format. We already
       know this is an int object */
    assert(PyInt_Check(value));
    return _PyInt_Format((PyIntObject*)value, base, 1);
}

PyObject *
1426
FORMAT_INT(PyObject *obj,
1427 1428
           STRINGLIB_CHAR *format_spec,
           Py_ssize_t format_spec_len)
1429
{
1430
    return format_int_or_long(obj, format_spec, format_spec_len,
1431
                              int_format);
1432 1433
}
#endif /* FORMAT_INT */
1434

1435
#ifdef FORMAT_FLOAT
1436
PyObject *
1437
FORMAT_FLOAT(PyObject *obj,
1438 1439
             STRINGLIB_CHAR *format_spec,
             Py_ssize_t format_spec_len)
1440 1441 1442 1443 1444
{
    PyObject *result = NULL;
    InternalFormatSpec format;

    /* check for the special case of zero length format spec, make
1445 1446 1447
       it equivalent to str(obj) */
    if (format_spec_len == 0) {
        result = STRINGLIB_TOSTR(obj);
1448 1449 1450 1451
        goto done;
    }

    /* parse the format_spec */
1452
    if (!parse_internal_render_format_spec(format_spec,
1453
                                           format_spec_len,
1454
                                           &format, '\0', '>'))
1455 1456 1457 1458
        goto done;

    /* type conversion? */
    switch (format.type) {
1459
    case '\0': /* No format code: like 'g', but with at least one decimal. */
1460 1461 1462 1463 1464 1465 1466 1467 1468
    case 'e':
    case 'E':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'n':
    case '%':
        /* no conversion, already a float.  do the formatting */
1469
        result = format_float_internal(obj, &format);
1470 1471 1472 1473
        break;

    default:
        /* unknown */
1474
        unknown_presentation_type(format.type, obj->ob_type->tp_name);
1475 1476 1477 1478 1479 1480
        goto done;
    }

done:
    return result;
}
1481
#endif /* FORMAT_FLOAT */
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501

#ifdef FORMAT_COMPLEX
PyObject *
FORMAT_COMPLEX(PyObject *obj,
               STRINGLIB_CHAR *format_spec,
               Py_ssize_t format_spec_len)
{
    PyObject *result = NULL;
    InternalFormatSpec format;

    /* check for the special case of zero length format spec, make
       it equivalent to str(obj) */
    if (format_spec_len == 0) {
        result = STRINGLIB_TOSTR(obj);
        goto done;
    }

    /* parse the format_spec */
    if (!parse_internal_render_format_spec(format_spec,
                                           format_spec_len,
1502
                                           &format, '\0', '>'))
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        goto done;

    /* type conversion? */
    switch (format.type) {
    case '\0': /* No format code: like 'g', but with at least one decimal. */
    case 'e':
    case 'E':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'n':
        /* no conversion, already a complex.  do the formatting */
        result = format_complex_internal(obj, &format);
        break;

    default:
        /* unknown */
        unknown_presentation_type(format.type, obj->ob_type->tp_name);
        goto done;
    }

done:
    return result;
}
#endif /* FORMAT_COMPLEX */