-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunicodeobject.c
9023 lines (8049 loc) · 271 KB
/
unicodeobject.c
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
/*
Unicode implementation based on original code by Fredrik Lundh,
modified by Marc-Andre Lemburg <[email protected]> according to the
Unicode Integration Proposal (see file Misc/unicode.txt).
Major speed upgrades to the method implementations at the Reykjavik
NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
Copyright (c) Corporation for National Research Initiatives.
--------------------------------------------------------------------
The original string type implementation is:
Copyright (c) 1999 by Secret Labs AB
Copyright (c) 1999 by Fredrik Lundh
By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:
Permission to use, copy, modify, and distribute this software and its
associated documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appears in all
copies, and that both that copyright notice and this permission notice
appear in supporting documentation, and that the name of Secret Labs
AB or the author not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------
*/
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "unicodeobject.h"
#include "ucnhash.h"
#ifdef MS_WINDOWS
#include <windows.h>
#endif
/* Limit for the Unicode object free list */
#define PyUnicode_MAXFREELIST 1024
/* Limit for the Unicode object free list stay alive optimization.
The implementation will keep allocated Unicode memory intact for
all objects on the free list having a size less than this
limit. This reduces malloc() overhead for small Unicode objects.
At worst this will result in PyUnicode_MAXFREELIST *
(sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
malloc()-overhead) bytes of unused garbage.
Setting the limit to 0 effectively turns the feature off.
Note: This is an experimental feature ! If you get core dumps when
using Unicode objects, turn this feature off.
*/
#define KEEPALIVE_SIZE_LIMIT 9
/* Endianness switches; defaults to little endian */
#ifdef WORDS_BIGENDIAN
# define BYTEORDER_IS_BIG_ENDIAN
#else
# define BYTEORDER_IS_LITTLE_ENDIAN
#endif
/* --- Globals ------------------------------------------------------------
NOTE: In the interpreter's initialization phase, some globals are currently
initialized dynamically as needed. In the process Unicode objects may
be created before the Unicode type is ready.
*/
#ifdef __cplusplus
extern "C" {
#endif
/* Free list for Unicode objects */
static PyUnicodeObject *free_list = NULL;
static int numfree = 0;
/* The empty Unicode object is shared to improve performance. */
static PyUnicodeObject *unicode_empty = NULL;
#define _Py_RETURN_UNICODE_EMPTY() \
do { \
if (unicode_empty != NULL) \
Py_INCREF(unicode_empty); \
else { \
unicode_empty = _PyUnicode_New(0); \
if (unicode_empty != NULL) \
Py_INCREF(unicode_empty); \
} \
return (PyObject *)unicode_empty; \
} while (0)
/* Single character Unicode strings in the Latin-1 range are being
shared as well. */
static PyUnicodeObject *unicode_latin1[256] = {NULL};
/* Default encoding to use and assume when NULL is passed as encoding
parameter; it is initialized by _PyUnicode_Init().
Always use the PyUnicode_SetDefaultEncoding() and
PyUnicode_GetDefaultEncoding() APIs to access this global.
*/
static char unicode_default_encoding[100 + 1] = "ascii";
/* Fast detection of the most frequent whitespace characters */
const unsigned char _Py_ascii_whitespace[] = {
0, 0, 0, 0, 0, 0, 0, 0,
/* case 0x0009: * CHARACTER TABULATION */
/* case 0x000A: * LINE FEED */
/* case 0x000B: * LINE TABULATION */
/* case 0x000C: * FORM FEED */
/* case 0x000D: * CARRIAGE RETURN */
0, 1, 1, 1, 1, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
/* case 0x001C: * FILE SEPARATOR */
/* case 0x001D: * GROUP SEPARATOR */
/* case 0x001E: * RECORD SEPARATOR */
/* case 0x001F: * UNIT SEPARATOR */
0, 0, 0, 0, 1, 1, 1, 1,
/* case 0x0020: * SPACE */
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
/* Same for linebreaks */
static unsigned char ascii_linebreak[] = {
0, 0, 0, 0, 0, 0, 0, 0,
/* 0x000A, * LINE FEED */
/* 0x000B, * LINE TABULATION */
/* 0x000C, * FORM FEED */
/* 0x000D, * CARRIAGE RETURN */
0, 0, 1, 1, 1, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
/* 0x001C, * FILE SEPARATOR */
/* 0x001D, * GROUP SEPARATOR */
/* 0x001E, * RECORD SEPARATOR */
0, 0, 0, 0, 1, 1, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
Py_UNICODE
PyUnicode_GetMax(void)
{
#ifdef Py_UNICODE_WIDE
return 0x10FFFF;
#else
/* This is actually an illegal character, so it should
not be passed to unichr. */
return 0xFFFF;
#endif
}
/* --- Bloom Filters ----------------------------------------------------- */
/* stuff to implement simple "bloom filters" for Unicode characters.
to keep things simple, we use a single bitmask, using the least 5
bits from each unicode characters as the bit index. */
/* the linebreak mask is set up by Unicode_Init below */
#if LONG_BIT >= 128
#define BLOOM_WIDTH 128
#elif LONG_BIT >= 64
#define BLOOM_WIDTH 64
#elif LONG_BIT >= 32
#define BLOOM_WIDTH 32
#else
#error "LONG_BIT is smaller than 32"
#endif
#define BLOOM_MASK unsigned long
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
#define BLOOM_LINEBREAK(ch) \
((ch) < 128U ? ascii_linebreak[(ch)] : \
(BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
{
/* calculate simple bloom-style bitmask for a given unicode string */
BLOOM_MASK mask;
Py_ssize_t i;
mask = 0;
for (i = 0; i < len; i++)
BLOOM_ADD(mask, ptr[i]);
return mask;
}
Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
{
Py_ssize_t i;
for (i = 0; i < setlen; i++)
if (set[i] == chr)
return 1;
return 0;
}
#define BLOOM_MEMBER(mask, chr, set, setlen) \
BLOOM(mask, chr) && unicode_member(chr, set, setlen)
/* --- Unicode Object ----------------------------------------------------- */
static
int unicode_resize(register PyUnicodeObject *unicode,
Py_ssize_t length)
{
void *oldstr;
/* Shortcut if there's nothing much to do. */
if (unicode->length == length)
goto reset;
/* Resizing shared object (unicode_empty or single character
objects) in-place is not allowed. Use PyUnicode_Resize()
instead ! */
if (unicode == unicode_empty ||
(unicode->length == 1 &&
unicode->str[0] < 256U &&
unicode_latin1[unicode->str[0]] == unicode)) {
PyErr_SetString(PyExc_SystemError,
"can't resize shared unicode objects");
return -1;
}
/* We allocate one more byte to make sure the string is Ux0000 terminated.
The overallocation is also used by fastsearch, which assumes that it's
safe to look at str[length] (without making any assumptions about what
it contains). */
oldstr = unicode->str;
unicode->str = PyObject_REALLOC(unicode->str,
sizeof(Py_UNICODE) * (length + 1));
if (!unicode->str) {
unicode->str = (Py_UNICODE *)oldstr;
PyErr_NoMemory();
return -1;
}
unicode->str[length] = 0;
unicode->length = length;
reset:
/* Reset the object caches */
if (unicode->defenc) {
Py_CLEAR(unicode->defenc);
}
unicode->hash = -1;
return 0;
}
/* We allocate one more byte to make sure the string is
Ux0000 terminated; some code relies on that.
XXX This allocator could further be enhanced by assuring that the
free list never reduces its size below 1.
*/
static
PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
{
register PyUnicodeObject *unicode;
/* Optimization for empty strings */
if (length == 0 && unicode_empty != NULL) {
Py_INCREF(unicode_empty);
return unicode_empty;
}
/* Ensure we won't overflow the size. */
if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
return (PyUnicodeObject *)PyErr_NoMemory();
}
/* Unicode freelist & memory allocation */
if (free_list) {
unicode = free_list;
free_list = *(PyUnicodeObject **)unicode;
numfree--;
if (unicode->str) {
/* Keep-Alive optimization: we only upsize the buffer,
never downsize it. */
if ((unicode->length < length) &&
unicode_resize(unicode, length) < 0) {
PyObject_DEL(unicode->str);
unicode->str = NULL;
}
}
else {
size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
}
(void)PyObject_INIT(unicode, &PyUnicode_Type);
}
else {
size_t new_size;
unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
if (unicode == NULL)
return NULL;
new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
}
if (!unicode->str) {
PyErr_NoMemory();
goto onError;
}
/* Initialize the first element to guard against cases where
* the caller fails before initializing str -- unicode_resize()
* reads str[0], and the Keep-Alive optimization can keep memory
* allocated for str alive across a call to unicode_dealloc(unicode).
* We don't want unicode_resize to read uninitialized memory in
* that case.
*/
unicode->str[0] = 0;
unicode->str[length] = 0;
unicode->length = length;
unicode->hash = -1;
unicode->defenc = NULL;
return unicode;
onError:
/* XXX UNREF/NEWREF interface should be more symmetrical */
_Py_DEC_REFTOTAL;
_Py_ForgetReference((PyObject *)unicode);
PyObject_Del(unicode);
return NULL;
}
static
void unicode_dealloc(register PyUnicodeObject *unicode)
{
if (PyUnicode_CheckExact(unicode) &&
numfree < PyUnicode_MAXFREELIST) {
/* Keep-Alive optimization */
if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
PyObject_DEL(unicode->str);
unicode->str = NULL;
unicode->length = 0;
}
if (unicode->defenc) {
Py_CLEAR(unicode->defenc);
}
/* Add to free list */
*(PyUnicodeObject **)unicode = free_list;
free_list = unicode;
numfree++;
}
else {
PyObject_DEL(unicode->str);
Py_XDECREF(unicode->defenc);
Py_TYPE(unicode)->tp_free((PyObject *)unicode);
}
}
static
int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
{
register PyUnicodeObject *v;
/* Argument checks */
if (unicode == NULL) {
PyErr_BadInternalCall();
return -1;
}
v = *unicode;
if (v == NULL || !PyUnicode_Check(v) || length < 0) {
PyErr_BadInternalCall();
return -1;
}
if (v->length == 0) {
if (length == 0) {
return 0;
}
*unicode = _PyUnicode_New(length);
Py_DECREF(v);
return (*unicode == NULL) ? -1 : 0;
}
if (Py_REFCNT(v) != 1) {
PyErr_BadInternalCall();
return -1;
}
if (length == 0) {
*unicode = _PyUnicode_New(0);
Py_DECREF(v);
return (*unicode == NULL) ? -1 : 0;
}
/* Resizing unicode_empty and single character objects is not
possible since these are being shared. We simply return a fresh
copy with the same Unicode content. */
if (v->length != length &&
(v == unicode_empty || v->length == 1)) {
PyUnicodeObject *w = _PyUnicode_New(length);
if (w == NULL)
return -1;
Py_UNICODE_COPY(w->str, v->str,
length < v->length ? length : v->length);
Py_SETREF(*unicode, w);
return 0;
}
/* Note that we don't have to modify *unicode for unshared Unicode
objects, since we can modify them in-place. */
return unicode_resize(v, length);
}
int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
{
return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
}
PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
Py_ssize_t size)
{
PyUnicodeObject *unicode;
/* If the Unicode data is known at construction time, we can apply
some optimizations which share commonly used objects. */
if (u != NULL) {
/* Optimization for empty strings */
if (size == 0)
_Py_RETURN_UNICODE_EMPTY();
/* Single character Unicode objects in the Latin-1 range are
shared when using this constructor */
if (size == 1 && *u < 256) {
unicode = unicode_latin1[*u];
if (!unicode) {
unicode = _PyUnicode_New(1);
if (!unicode)
return NULL;
unicode->str[0] = *u;
unicode_latin1[*u] = unicode;
}
Py_INCREF(unicode);
return (PyObject *)unicode;
}
}
unicode = _PyUnicode_New(size);
if (!unicode)
return NULL;
/* Copy the Unicode data into the new object */
if (u != NULL)
Py_UNICODE_COPY(unicode->str, u, size);
return (PyObject *)unicode;
}
PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
{
PyUnicodeObject *unicode;
if (size < 0) {
PyErr_SetString(PyExc_SystemError,
"Negative size passed to PyUnicode_FromStringAndSize");
return NULL;
}
/* If the Unicode data is known at construction time, we can apply
some optimizations which share commonly used objects.
Also, this means the input must be UTF-8, so fall back to the
UTF-8 decoder at the end. */
if (u != NULL) {
/* Optimization for empty strings */
if (size == 0)
_Py_RETURN_UNICODE_EMPTY();
/* Single characters are shared when using this constructor.
Restrict to ASCII, since the input must be UTF-8. */
if (size == 1 && Py_CHARMASK(*u) < 128) {
unicode = unicode_latin1[Py_CHARMASK(*u)];
if (!unicode) {
unicode = _PyUnicode_New(1);
if (!unicode)
return NULL;
unicode->str[0] = Py_CHARMASK(*u);
unicode_latin1[Py_CHARMASK(*u)] = unicode;
}
Py_INCREF(unicode);
return (PyObject *)unicode;
}
return PyUnicode_DecodeUTF8(u, size, NULL);
}
unicode = _PyUnicode_New(size);
if (!unicode)
return NULL;
return (PyObject *)unicode;
}
PyObject *PyUnicode_FromString(const char *u)
{
size_t size = strlen(u);
if (size > PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError, "input too long");
return NULL;
}
return PyUnicode_FromStringAndSize(u, size);
}
/* _Py_UNICODE_NEXT is a private macro used to retrieve the character pointed
* by 'ptr', possibly combining surrogate pairs on narrow builds.
* 'ptr' and 'end' must be Py_UNICODE*, with 'ptr' pointing at the character
* that should be returned and 'end' pointing to the end of the buffer.
* ('end' is used on narrow builds to detect a lone surrogate at the
* end of the buffer that should be returned unchanged.)
* The ptr and end arguments should be side-effect free and ptr must an lvalue.
* The type of the returned char is always Py_UCS4.
*
* Note: the macro advances ptr to next char, so it might have side-effects
* (especially if used with other macros).
*/
/* helper macros used by _Py_UNICODE_NEXT */
#define _Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= ch && ch <= 0xDBFF)
#define _Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= ch && ch <= 0xDFFF)
/* Join two surrogate characters and return a single Py_UCS4 value. */
#define _Py_UNICODE_JOIN_SURROGATES(high, low) \
(((((Py_UCS4)(high) & 0x03FF) << 10) | \
((Py_UCS4)(low) & 0x03FF)) + 0x10000)
#ifdef Py_UNICODE_WIDE
#define _Py_UNICODE_NEXT(ptr, end) *(ptr)++
#else
#define _Py_UNICODE_NEXT(ptr, end) \
(((_Py_UNICODE_IS_HIGH_SURROGATE(*(ptr)) && (ptr) < (end)) && \
_Py_UNICODE_IS_LOW_SURROGATE((ptr)[1])) ? \
((ptr) += 2,_Py_UNICODE_JOIN_SURROGATES((ptr)[-2], (ptr)[-1])) : \
(Py_UCS4)*(ptr)++)
#endif
#ifdef HAVE_WCHAR_H
#if (Py_UNICODE_SIZE == 2) && defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
# define CONVERT_WCHAR_TO_SURROGATES
#endif
#ifdef CONVERT_WCHAR_TO_SURROGATES
/* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
to convert from UTF32 to UTF16. */
PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Py_ssize_t size)
{
PyUnicodeObject *unicode;
register Py_ssize_t i;
Py_ssize_t alloc;
const wchar_t *orig_w;
if (w == NULL) {
PyErr_BadInternalCall();
return NULL;
}
alloc = size;
orig_w = w;
for (i = size; i > 0; i--) {
if (*w > 0xFFFF)
alloc++;
w++;
}
w = orig_w;
unicode = _PyUnicode_New(alloc);
if (!unicode)
return NULL;
/* Copy the wchar_t data into the new object */
{
register Py_UNICODE *u;
u = PyUnicode_AS_UNICODE(unicode);
for (i = size; i > 0; i--) {
if (*w > 0xFFFF) {
wchar_t ordinal = *w++;
ordinal -= 0x10000;
*u++ = 0xD800 | (ordinal >> 10);
*u++ = 0xDC00 | (ordinal & 0x3FF);
}
else
*u++ = *w++;
}
}
return (PyObject *)unicode;
}
#else
PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Py_ssize_t size)
{
PyUnicodeObject *unicode;
if (w == NULL) {
PyErr_BadInternalCall();
return NULL;
}
unicode = _PyUnicode_New(size);
if (!unicode)
return NULL;
/* Copy the wchar_t data into the new object */
#ifdef HAVE_USABLE_WCHAR_T
memcpy(unicode->str, w, size * sizeof(wchar_t));
#else
{
register Py_UNICODE *u;
register Py_ssize_t i;
u = PyUnicode_AS_UNICODE(unicode);
for (i = size; i > 0; i--)
*u++ = *w++;
}
#endif
return (PyObject *)unicode;
}
#endif /* CONVERT_WCHAR_TO_SURROGATES */
#undef CONVERT_WCHAR_TO_SURROGATES
static void
makefmt(char *fmt, int longflag, int size_tflag, int zeropad, int width, int precision, char c)
{
*fmt++ = '%';
if (width) {
if (zeropad)
*fmt++ = '0';
fmt += sprintf(fmt, "%d", width);
}
if (precision)
fmt += sprintf(fmt, ".%d", precision);
if (longflag)
*fmt++ = 'l';
else if (size_tflag) {
char *f = PY_FORMAT_SIZE_T;
while (*f)
*fmt++ = *f++;
}
*fmt++ = c;
*fmt = '\0';
}
#define appendstring(string) \
do { \
for (copy = string;*copy; copy++) { \
*s++ = (unsigned char)*copy; \
} \
} while (0)
PyObject *
PyUnicode_FromFormatV(const char *format, va_list vargs)
{
va_list count;
Py_ssize_t callcount = 0;
PyObject **callresults = NULL;
PyObject **callresult = NULL;
Py_ssize_t n = 0;
int width = 0;
int precision = 0;
int zeropad;
const char* f;
Py_UNICODE *s;
PyObject *string;
/* used by sprintf */
char buffer[21];
/* use abuffer instead of buffer, if we need more space
* (which can happen if there's a format specifier with width). */
char *abuffer = NULL;
char *realbuffer;
Py_ssize_t abuffersize = 0;
char fmt[60]; /* should be enough for %0width.precisionld */
const char *copy;
#ifdef VA_LIST_IS_ARRAY
Py_MEMCPY(count, vargs, sizeof(va_list));
#else
#ifdef __va_copy
__va_copy(count, vargs);
#else
count = vargs;
#endif
#endif
/* step 1: count the number of %S/%R/%s format specifications
* (we call PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() for these
* objects once during step 3 and put the result in an array) */
for (f = format; *f; f++) {
if (*f == '%') {
f++;
while (*f && *f != '%' && !isalpha((unsigned)*f))
f++;
if (!*f)
break;
if (*f == 's' || *f=='S' || *f=='R')
++callcount;
}
}
/* step 2: allocate memory for the results of
* PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
if (callcount) {
callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
if (!callresults) {
PyErr_NoMemory();
return NULL;
}
callresult = callresults;
}
/* step 3: figure out how large a buffer we need */
for (f = format; *f; f++) {
if (*f == '%') {
const char* p = f++;
width = 0;
while (isdigit((unsigned)*f))
width = (width*10) + *f++ - '0';
precision = 0;
if (*f == '.') {
f++;
while (isdigit((unsigned)*f))
precision = (precision*10) + *f++ - '0';
}
/* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
* they don't affect the amount of space we reserve.
*/
if ((*f == 'l' || *f == 'z') &&
(f[1] == 'd' || f[1] == 'u'))
++f;
switch (*f) {
case 'c':
{
int ordinal = va_arg(count, int);
#ifdef Py_UNICODE_WIDE
if (ordinal < 0 || ordinal > 0x10ffff) {
PyErr_SetString(PyExc_OverflowError,
"%c arg not in range(0x110000) "
"(wide Python build)");
goto fail;
}
#else
if (ordinal < 0 || ordinal > 0xffff) {
PyErr_SetString(PyExc_OverflowError,
"%c arg not in range(0x10000) "
"(narrow Python build)");
goto fail;
}
#endif
/* fall through... */
}
case '%':
n++;
break;
case 'd': case 'u': case 'i': case 'x':
(void) va_arg(count, int);
if (width < precision)
width = precision;
/* 20 bytes is enough to hold a 64-bit
integer. Decimal takes the most space.
This isn't enough for octal.
If a width is specified we need more
(which we allocate later). */
if (width < 20)
width = 20;
n += width;
if (abuffersize < width)
abuffersize = width;
break;
case 's':
{
/* UTF-8 */
const char *s = va_arg(count, const char*);
PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
if (!str)
goto fail;
n += PyUnicode_GET_SIZE(str);
/* Remember the str and switch to the next slot */
*callresult++ = str;
break;
}
case 'U':
{
PyObject *obj = va_arg(count, PyObject *);
assert(obj && PyUnicode_Check(obj));
n += PyUnicode_GET_SIZE(obj);
break;
}
case 'V':
{
PyObject *obj = va_arg(count, PyObject *);
const char *str = va_arg(count, const char *);
assert(obj || str);
assert(!obj || PyUnicode_Check(obj));
if (obj)
n += PyUnicode_GET_SIZE(obj);
else
n += strlen(str);
break;
}
case 'S':
{
PyObject *obj = va_arg(count, PyObject *);
PyObject *str;
assert(obj);
str = PyObject_Str(obj);
if (!str)
goto fail;
n += PyString_GET_SIZE(str);
/* Remember the str and switch to the next slot */
*callresult++ = str;
break;
}
case 'R':
{
PyObject *obj = va_arg(count, PyObject *);
PyObject *repr;
assert(obj);
repr = PyObject_Repr(obj);
if (!repr)
goto fail;
n += PyUnicode_GET_SIZE(repr);
/* Remember the repr and switch to the next slot */
*callresult++ = repr;
break;
}
case 'p':
(void) va_arg(count, int);
/* maximum 64-bit pointer representation:
* 0xffffffffffffffff
* so 19 characters is enough.
* XXX I count 18 -- what's the extra for?
*/
n += 19;
break;
default:
/* if we stumble upon an unknown
formatting code, copy the rest of
the format string to the output
string. (we cannot just skip the
code, since there's no way to know
what's in the argument list) */
n += strlen(p);
goto expand;
}
} else
n++;
}
expand:
if (abuffersize > 20) {
/* add 1 for sprintf's trailing null byte */
abuffer = PyObject_Malloc(abuffersize + 1);
if (!abuffer) {
PyErr_NoMemory();
goto fail;
}
realbuffer = abuffer;
}
else
realbuffer = buffer;
/* step 4: fill the buffer */
/* Since we've analyzed how much space we need for the worst case,
we don't have to resize the string.
There can be no errors beyond this point. */
string = PyUnicode_FromUnicode(NULL, n);
if (!string)
goto fail;
s = PyUnicode_AS_UNICODE(string);
callresult = callresults;
for (f = format; *f; f++) {
if (*f == '%') {
const char* p = f++;
int longflag = 0;
int size_tflag = 0;
zeropad = (*f == '0');
/* parse the width.precision part */
width = 0;
while (isdigit((unsigned)*f))
width = (width*10) + *f++ - '0';
precision = 0;
if (*f == '.') {
f++;
while (isdigit((unsigned)*f))
precision = (precision*10) + *f++ - '0';
}
/* handle the long flag, but only for %ld and %lu.
others can be added when necessary. */
if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
longflag = 1;
++f;
}
/* handle the size_t flag. */
if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
size_tflag = 1;
++f;
}
switch (*f) {
case 'c':
*s++ = va_arg(vargs, int);
break;
case 'd':
makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd');
if (longflag)
sprintf(realbuffer, fmt, va_arg(vargs, long));
else if (size_tflag)
sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
else
sprintf(realbuffer, fmt, va_arg(vargs, int));
appendstring(realbuffer);
break;
case 'u':
makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u');
if (longflag)
sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
else if (size_tflag)
sprintf(realbuffer, fmt, va_arg(vargs, size_t));
else
sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
appendstring(realbuffer);
break;
case 'i':
makefmt(fmt, 0, 0, zeropad, width, precision, 'i');
sprintf(realbuffer, fmt, va_arg(vargs, int));
appendstring(realbuffer);
break;
case 'x':
makefmt(fmt, 0, 0, zeropad, width, precision, 'x');
sprintf(realbuffer, fmt, va_arg(vargs, int));
appendstring(realbuffer);
break;
case 's':
{
/* unused, since we already have the result */
(void) va_arg(vargs, char *);