- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathformatter.h
1547 lines (1353 loc) · 46.8 KB
/
formatter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
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
624
625
626
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* implements the string, long, and float formatters. that is,
string.__format__, etc. */
#include<locale.h>
/* 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
FORMAT_COMPLEX
to be whatever you want the public names of these functions to
be. These are the only non-static functions defined here.
*/
/* Raises an exception about an unknown presentation type for this
* type. */
staticvoid
unknown_presentation_type(STRINGLIB_CHARpresentation_type,
constchar*type_name)
{
#ifSTRINGLIB_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'",
(char)presentation_type,
type_name);
#ifSTRINGLIB_IS_UNICODE
else
PyErr_Format(PyExc_ValueError,
"Unknown format code '\\x%x' "
"for object of type '%.200s'",
(unsigned int)presentation_type,
type_name);
#endif
}
staticvoid
invalid_comma_type(STRINGLIB_CHARpresentation_type)
{
#ifSTRINGLIB_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);
#ifSTRINGLIB_IS_UNICODE
else
PyErr_Format(PyExc_ValueError,
"Cannot specify ',' with '\\x%x'.",
(unsigned int)presentation_type);
#endif
}
/*
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.
*/
staticint
get_integer(STRINGLIB_CHAR**ptr, STRINGLIB_CHAR*end,
Py_ssize_t*result)
{
Py_ssize_taccumulator, digitval;
intnumdigits;
accumulator=numdigits=0;
for (;;(*ptr)++, numdigits++) {
if (*ptr >= end)
break;
digitval=STRINGLIB_TODECIMAL(**ptr);
if (digitval<0)
break;
/*
Detect possible overflow before it happens:
accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if
accumulator > (PY_SSIZE_T_MAX - digitval) / 10.
*/
if (accumulator> (PY_SSIZE_T_MAX-digitval) / 10) {
PyErr_Format(PyExc_ValueError,
"Too many decimal digits in format string");
return-1;
}
accumulator=accumulator*10+digitval;
}
*result=accumulator;
returnnumdigits;
}
/************************************************************************/
/*********** standard format specifier parsing **************************/
/************************************************************************/
/* returns true if this character is a specifier alignment token */
Py_LOCAL_INLINE(int)
is_alignment_token(STRINGLIB_CHARc)
{
switch (c) {
case'<': case'>': case'=': case'^':
return1;
default:
return0;
}
}
/* returns true if this character is a sign element */
Py_LOCAL_INLINE(int)
is_sign_element(STRINGLIB_CHARc)
{
switch (c) {
case' ': case'+': case'-':
return1;
default:
return0;
}
}
typedefstruct {
STRINGLIB_CHARfill_char;
STRINGLIB_CHARalign;
intalternate;
STRINGLIB_CHARsign;
Py_ssize_twidth;
intthousands_separators;
Py_ssize_tprecision;
STRINGLIB_CHARtype;
} InternalFormatSpec;
#if0
/* Occasionally useful for debugging. Should normally be commented out. */
staticvoid
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);
printf("internal format spec: width %zd\n", format->width);
printf("internal format spec: thousands_separators %d\n",
format->thousands_separators);
printf("internal format spec: precision %zd\n", format->precision);
printf("internal format spec: type %c\n", format->type);
printf("\n");
}
#endif
/*
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
*/
staticint
parse_internal_render_format_spec(STRINGLIB_CHAR*format_spec,
Py_ssize_tformat_spec_len,
InternalFormatSpec*format,
chardefault_type,
chardefault_align)
{
STRINGLIB_CHAR*ptr=format_spec;
STRINGLIB_CHAR*end=format_spec+format_spec_len;
/* end-ptr is used throughout this code to specify the length of
the input string */
Py_ssize_tconsumed;
intalign_specified=0;
intfill_char_specified=0;
format->fill_char=' ';
format->align=default_align;
format->alternate=0;
format->sign='\0';
format->width=-1;
format->thousands_separators=0;
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];
fill_char_specified=1;
align_specified=1;
ptr+=2;
}
elseif (end-ptr >= 1&&is_alignment_token(ptr[0])) {
format->align=ptr[0];
align_specified=1;
++ptr;
}
/* Parse the various sign options */
if (end-ptr >= 1&&is_sign_element(ptr[0])) {
format->sign=ptr[0];
++ptr;
}
/* If the next character is #, we're in alternate mode. This only
applies to integers. */
if (end-ptr >= 1&&ptr[0] =='#') {
format->alternate=1;
++ptr;
}
/* The special case for 0-padding (backwards compat) */
if (!fill_char_specified&&end-ptr >= 1&&ptr[0] =='0') {
format->fill_char='0';
if (!align_specified) {
format->align='=';
}
++ptr;
}
consumed=get_integer(&ptr, end, &format->width);
if (consumed==-1)
/* Overflow error. Exception already set. */
return0;
/* 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)
format->width=-1;
/* Comma signifies add thousands separators */
if (end-ptr&&ptr[0] ==',') {
format->thousands_separators=1;
++ptr;
}
/* Parse field precision */
if (end-ptr&&ptr[0] =='.') {
++ptr;
consumed=get_integer(&ptr, end, &format->precision);
if (consumed==-1)
/* Overflow error. Exception already set. */
return0;
/* Not having a precision after a dot is an error. */
if (consumed==0) {
PyErr_Format(PyExc_ValueError,
"Format specifier missing precision");
return0;
}
}
/* Finally, parse the type field. */
if (end-ptr>1) {
/* More than one char remain, invalid conversion spec. */
PyErr_Format(PyExc_ValueError, "Invalid conversion specification");
return0;
}
if (end-ptr==1) {
format->type=ptr[0];
++ptr;
}
/* 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':
case'\0':
/* These are allowed. See PEP 378.*/
break;
default:
invalid_comma_type(format->type);
return0;
}
}
return1;
}
/* Calculate the padding needed. */
staticvoid
calc_padding(Py_ssize_tnchars, Py_ssize_twidth, STRINGLIB_CHARalign,
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;
}
/* Figure out how much leading space we need, based on the
aligning */
if (align=='>')
*n_lpadding=*n_total-nchars;
elseif (align=='^')
*n_lpadding= (*n_total-nchars) / 2;
elseif (align=='<'||align=='=')
*n_lpadding=0;
else {
/* We should never have an unspecified alignment. */
*n_lpadding=0;
assert(0);
}
*n_rpadding=*n_total-nchars-*n_lpadding;
}
/* Do the padding, and return a pointer to where the caller-supplied
content goes. */
staticSTRINGLIB_CHAR*
fill_padding(STRINGLIB_CHAR*p, Py_ssize_tnchars, STRINGLIB_CHARfill_char,
Py_ssize_tn_lpadding, Py_ssize_tn_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. */
returnp+n_lpadding;
}
#if defined FORMAT_FLOAT|| defined FORMAT_LONG|| defined FORMAT_COMPLEX
/************************************************************************/
/*********** common routines for numeric formatting *********************/
/************************************************************************/
/* Locale type codes. */
#defineLT_CURRENT_LOCALE 0
#defineLT_DEFAULT_LOCALE 1
#defineLT_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. */
typedefstruct {
char*decimal_point;
char*thousands_sep;
char*grouping;
} LocaleInfo;
/* describes the layout for an integer, see the comment in
calc_number_widths() for details */
typedefstruct {
Py_ssize_tn_lpadding;
Py_ssize_tn_prefix;
Py_ssize_tn_spadding;
Py_ssize_tn_rpadding;
charsign;
Py_ssize_tn_sign; /* number of digits needed for sign (0/1) */
Py_ssize_tn_grouped_digits; /* Space taken up by the digits, including
any grouping chars. */
Py_ssize_tn_decimal; /* 0 if only an integer */
Py_ssize_tn_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_tn_digits; /* The number of digits before a decimal
or exponent. */
Py_ssize_tn_min_width; /* The min_width we used when we computed
the n_grouped_digits width. */
} NumberFieldWidths;
/* 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.
*/
staticvoid
parse_number(STRINGLIB_CHAR*ptr, Py_ssize_tlen,
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;
}
/* 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? */
staticPy_ssize_t
calc_number_widths(NumberFieldWidths*spec, Py_ssize_tn_prefix,
STRINGLIB_CHARsign_char, STRINGLIB_CHAR*number,
Py_ssize_tn_number, Py_ssize_tn_remainder,
inthas_decimal, constLocaleInfo*locale,
constInternalFormatSpec*format)
{
Py_ssize_tn_non_digit_non_padding;
Py_ssize_tn_padding;
spec->n_digits=n_number-n_remainder- (has_decimal?1:0);
spec->n_lpadding=0;
spec->n_prefix=n_prefix;
spec->n_decimal=has_decimal ? strlen(locale->decimal_point) : 0;
spec->n_remainder=n_remainder;
spec->n_spadding=0;
spec->n_rpadding=0;
spec->sign='\0';
spec->n_sign=0;
/* the output will look like:
| |
| <lpadding> <sign> <prefix> <spadding> <grouped_digits> <decimal> <remainder> <rpadding> |
| |
sign is computed from format->sign and the actual
sign of the number
prefix is given (it's for the '0x' prefix)
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 */
switch (format->sign) {
case'+':
/* always put a + or - */
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='-';
}
}
/* 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;
/* min_width can go negative, that's okay. format->width == -1 means
we don't care. */
if (format->fill_char=='0'&&format->align=='=')
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;
case'>':
spec->n_lpadding=n_padding;
break;
default:
/* Shouldn't get here, but treat it as '>' */
spec->n_lpadding=n_padding;
assert(0);
break;
}
}
returnspec->n_lpadding+spec->n_sign+spec->n_prefix+
spec->n_spadding+spec->n_grouped_digits+spec->n_decimal+
spec->n_remainder+spec->n_rpadding;
}
/* 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. */
staticvoid
fill_number(STRINGLIB_CHAR*buf, constNumberFieldWidths*spec,
STRINGLIB_CHAR*digits, Py_ssize_tn_digits,
STRINGLIB_CHAR*prefix, STRINGLIB_CHARfill_char,
LocaleInfo*locale, inttoupper)
{
/* Used to keep track of digits, decimal, and remainder. */
STRINGLIB_CHAR*p=digits;
#ifndefNDEBUG
Py_ssize_tr;
#endif
if (spec->n_lpadding) {
STRINGLIB_FILL(buf, fill_char, spec->n_lpadding);
buf+=spec->n_lpadding;
}
if (spec->n_sign==1) {
*buf++=spec->sign;
}
if (spec->n_prefix) {
memmove(buf,
prefix,
spec->n_prefix*sizeof(STRINGLIB_CHAR));
if (toupper) {
Py_ssize_tt;
for (t=0; t<spec->n_prefix; ++t)
buf[t] =STRINGLIB_TOUPPER(buf[t]);
}
buf+=spec->n_prefix;
}
if (spec->n_spadding) {
STRINGLIB_FILL(buf, fill_char, spec->n_spadding);
buf+=spec->n_spadding;
}
/* Only for type 'c' special case, it has no digits. */
if (spec->n_digits!=0) {
/* Fill the digits with InsertThousandsGrouping. */
#ifndefNDEBUG
r=
#endif
STRINGLIB_GROUPING(buf, spec->n_grouped_digits, digits,
spec->n_digits, spec->n_min_width,
locale->grouping, locale->thousands_sep);
#ifndefNDEBUG
assert(r==spec->n_grouped_digits);
#endif
p+=spec->n_digits;
}
if (toupper) {
Py_ssize_tt;
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_tt;
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;
}
if (spec->n_rpadding) {
STRINGLIB_FILL(buf, fill_char, spec->n_rpadding);
buf+=spec->n_rpadding;
}
}
staticcharno_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. */
staticvoid
get_locale_info(inttype, LocaleInfo*locale_info)
{
switch (type) {
caseLT_CURRENT_LOCALE: {
structlconv*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;
}
caseLT_DEFAULT_LOCALE:
locale_info->decimal_point=".";
locale_info->thousands_sep=",";
locale_info->grouping="\3"; /* Group every 3 characters. The
(implicit) trailing 0 means repeat
infinitely. */
break;
caseLT_NO_LOCALE:
locale_info->decimal_point=".";
locale_info->thousands_sep="";
locale_info->grouping=no_grouping;
break;
default:
assert(0);
}
}
#endif/* FORMAT_FLOAT || FORMAT_LONG || FORMAT_COMPLEX */
/************************************************************************/
/*********** string formatting ******************************************/
/************************************************************************/
staticPyObject*
format_string_internal(PyObject*value, constInternalFormatSpec*format)
{
Py_ssize_tlpad;
Py_ssize_trpad;
Py_ssize_ttotal;
STRINGLIB_CHAR*p;
Py_ssize_tlen=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;
}
/* alternate is not allowed on strings */
if (format->alternate) {
PyErr_SetString(PyExc_ValueError,
"Alternate form (#) not allowed in string format "
"specifier");
goto done;
}
/* '=' 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;
}
calc_padding(len, format->width, format->align, &lpad, &rpad, &total);
/* allocate the resulting string */
result=STRINGLIB_NEW(NULL, total);
if (result==NULL)
goto done;
/* Write into that space. First the padding. */
p=fill_padding(STRINGLIB_STR(result), len,
format->fill_char, lpad, rpad);
/* Then the source string. */
memcpy(p, STRINGLIB_STR(value), len*sizeof(STRINGLIB_CHAR));
done:
returnresult;
}
/************************************************************************/
/*********** long formatting ********************************************/
/************************************************************************/
#if defined FORMAT_LONG|| defined FORMAT_INT
typedefPyObject*
(*IntOrLongToString)(PyObject*value, intbase);
staticPyObject*
format_int_or_long_internal(PyObject*value, constInternalFormatSpec*format,
IntOrLongToStringtostring)
{
PyObject*result=NULL;
PyObject*tmp=NULL;
STRINGLIB_CHAR*pnumeric_chars;
STRINGLIB_CHARnumeric_char;
STRINGLIB_CHARsign_char='\0';
Py_ssize_tn_digits; /* count of digits need from the computed
string */
Py_ssize_tn_remainder=0; /* Used only for 'c' formatting, which
produces non-digits */
Py_ssize_tn_prefix=0; /* Count of prefix chars, (e.g., '0x') */
Py_ssize_tn_total;
STRINGLIB_CHAR*prefix=NULL;
NumberFieldWidthsspec;
longx;
/* Locale settings, either from the actual locale or
from a hard-code pseudo-locale */
LocaleInfolocale;
/* 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;
}
/* Error to specify a comma. */
if (format->thousands_separators) {
PyErr_SetString(PyExc_ValueError,
"Thousands separators not allowed with integer"
" format specifier 'c'");
goto done;
}
/* taken from unicodeobject.c formatchar() */
/* Integer input truncated to a character */
/* XXX: won't work for int */
x=PyLong_AsLong(value);
if (x==-1&&PyErr_Occurred())
goto done;
#ifSTRINGLIB_IS_UNICODE
#ifdefPy_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
#else
if (x<0||x>0xff) {
PyErr_SetString(PyExc_OverflowError,
"%c arg not in range(0x100)");
goto done;
}
#endif
numeric_char= (STRINGLIB_CHAR)x;
pnumeric_chars=&numeric_char;
n_digits=1;
/* 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;
}
else {
intbase;
intleading_chars_to_skip=0; /* Number of characters added by
PyNumber_ToBase that we want to
skip over. */
/* Compute the base and how many characters will be added by
PyNumber_ToBase */
switch (format->type) {
case'b':
base=2;
leading_chars_to_skip=2; /* 0b */
break;
case'o':
base=8;
leading_chars_to_skip=2; /* 0o */
break;
case'x':
case'X':
base=16;
leading_chars_to_skip=2; /* 0x */
break;
default: /* shouldn't be needed, but stops a compiler warning */
case'd':
case'n':
base=10;
break;
}
/* The number of prefix chars is the same as the leading
chars to skip */
if (format->alternate)
n_prefix=leading_chars_to_skip;
/* Do the hard part, converting to a string in a given base */
tmp=tostring(value, base);
if (tmp==NULL)
goto done;
pnumeric_chars=STRINGLIB_STR(tmp);
n_digits=STRINGLIB_LEN(tmp);
prefix=pnumeric_chars;
/* 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. */
/* Is a sign character present in the output? If so, remember it
and skip it */
if (pnumeric_chars[0] =='-') {
sign_char=pnumeric_chars[0];
++prefix;
++leading_chars_to_skip;
}
/* Skip over the leading chars (0x, 0b, etc.) */
n_digits-=leading_chars_to_skip;
pnumeric_chars+=leading_chars_to_skip;
}
/* 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);
/* 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);
/* Allocate the memory. */
result=STRINGLIB_NEW(NULL, n_total);
if (!result)
goto done;
/* Populate the memory. */
fill_number(STRINGLIB_STR(result), &spec, pnumeric_chars, n_digits,
prefix, format->fill_char, &locale, format->type=='X');
done:
Py_XDECREF(tmp);
returnresult;
}
#endif/* defined FORMAT_LONG || defined FORMAT_INT */
/************************************************************************/
/*********** float formatting *******************************************/
/************************************************************************/
#ifdefFORMAT_FLOAT
#ifSTRINGLIB_IS_UNICODE
staticvoid
strtounicode(Py_UNICODE*buffer, constchar*charbuffer, Py_ssize_tlen)
{
Py_ssize_ti;
for (i=0; i<len; ++i)
buffer[i] = (Py_UNICODE)charbuffer[i];
}
#endif
/* much of this is taken from unicodeobject.c */
staticPyObject*
format_float_internal(PyObject*value,
constInternalFormatSpec*format)
{
char*buf=NULL; /* buffer returned from PyOS_double_to_string */
Py_ssize_tn_digits;
Py_ssize_tn_remainder;
Py_ssize_tn_total;
inthas_decimal;
doubleval;
Py_ssize_tprecision;
Py_ssize_tdefault_precision=6;
STRINGLIB_CHARtype=format->type;
intadd_pct=0;
STRINGLIB_CHAR*p;
NumberFieldWidthsspec;
intflags=0;
PyObject*result=NULL;
STRINGLIB_CHARsign_char='\0';
intfloat_type; /* Used to see if we have a nan, inf, or regular float. */
#ifSTRINGLIB_IS_UNICODE
Py_UNICODE*unicode_tmp=NULL;
#endif
/* Locale settings, either from the actual locale or
from a hard-code pseudo-locale */
LocaleInfolocale;
if (format->precision>INT_MAX) {
PyErr_SetString(PyExc_ValueError, "precision too big");
goto done;
}
precision= (int)format->precision;
/* Alternate is not allowed on floats. */
if (format->alternate) {
PyErr_SetString(PyExc_ValueError,
"Alternate form (#) not allowed in float format "
"specifier");
goto done;
}
if (type=='\0') {
/* Omitted type specifier. This is like 'g' but with at least one
digit after the decimal point, and different default precision.*/
type='g';
default_precision=PyFloat_STR_PRECISION;
flags |= Py_DTSF_ADD_DOT_0;
}
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';
val=PyFloat_AsDouble(value);
if (val==-1.0&&PyErr_Occurred())
goto done;
if (type=='%') {
type='f';
val *= 100;
add_pct=1;
}
if (precision<0)
precision=default_precision;
/* Cast "type", because if we're in unicode we need to pass an
8-bit char. This is safe, because we've restricted what "type"
can be. */