Coverage Report

Created: 2026-10-17 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/unicodeobject.c
Line
Count
Source
1
/*
2
3
Unicode implementation based on original code by Fredrik Lundh,
4
modified by Marc-Andre Lemburg <mal@lemburg.com>.
5
6
Major speed upgrades to the method implementations at the Reykjavik
7
NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
9
Copyright (c) Corporation for National Research Initiatives.
10
11
--------------------------------------------------------------------
12
The original string type implementation is:
13
14
  Copyright (c) 1999 by Secret Labs AB
15
  Copyright (c) 1999 by Fredrik Lundh
16
17
By obtaining, using, and/or copying this software and/or its
18
associated documentation, you agree that you have read, understood,
19
and will comply with the following terms and conditions:
20
21
Permission to use, copy, modify, and distribute this software and its
22
associated documentation for any purpose and without fee is hereby
23
granted, provided that the above copyright notice appears in all
24
copies, and that both that copyright notice and this permission notice
25
appear in supporting documentation, and that the name of Secret Labs
26
AB or the author not be used in advertising or publicity pertaining to
27
distribution of the software without specific, written prior
28
permission.
29
30
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32
FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37
--------------------------------------------------------------------
38
39
*/
40
41
#include "Python.h"
42
#include "pycore_abstract.h"      // _PyIndex_Check()
43
#include "pycore_bytes_methods.h" // _Py_bytes_lower()
44
#include "pycore_bytesobject.h"   // _PyBytes_RepeatBuffer()
45
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
46
#include "pycore_codecs.h"        // _PyCodec_Lookup()
47
#include "pycore_critical_section.h" // Py_*_CRITICAL_SECTION_SEQUENCE_FAST
48
#include "pycore_format.h"        // F_LJUST
49
#include "pycore_initconfig.h"    // _PyStatus_OK()
50
#include "pycore_interp.h"        // PyInterpreterState.fs_codec
51
#include "pycore_long.h"          // _PyLong_FormatWriter()
52
#include "pycore_object.h"        // _PyObject_GC_TRACK(), _Py_FatalRefcountError()
53
#include "pycore_pathconfig.h"    // _Py_DumpPathConfig()
54
#include "pycore_pyerrors.h"      // _PyUnicodeTranslateError_Create()
55
#include "pycore_pyhash.h"        // _Py_HashSecret_t
56
#include "pycore_pylifecycle.h"   // _Py_SetFileSystemEncoding()
57
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
58
#include "pycore_ucnhash.h"       // _PyUnicode_Name_CAPI
59
#include "pycore_unicodectype.h"  // _PyUnicode_IsXidStart
60
#include "pycore_unicodeobject.h" // struct _Py_unicode_state
61
#include "pycore_unicodeobject_generated.h"  // _PyUnicode_InitStaticStrings()
62
63
#include "stringlib/eq.h"         // unicode_eq()
64
#include <stddef.h>               // ptrdiff_t
65
66
#ifdef MS_WINDOWS
67
#include <windows.h>
68
#endif
69
70
#ifdef _Py_HAVE_ICONV
71
#include <iconv.h>                 // iconv_open()
72
#endif
73
74
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
75
#  include "pycore_fileutils.h"   // _Py_LocaleUsesNonUnicodeWchar()
76
#endif
77
78
/* Uncomment to display statistics on interned strings at exit
79
   in _PyUnicode_ClearInterned(). */
80
/* #define INTERNED_STATS 1 */
81
82
83
/*[clinic input]
84
class str "PyObject *" "&PyUnicode_Type"
85
[clinic start generated code]*/
86
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
87
88
/*[python input]
89
class Py_UCS4_converter(CConverter):
90
    type = 'Py_UCS4'
91
    converter = 'convert_uc'
92
93
    def c_default_init(self):
94
        import libclinic
95
        self.c_default = libclinic.c_unichar_repr(self.default)
96
97
[python start generated code]*/
98
/*[python end generated code: output=da39a3ee5e6b4b0d input=22f057b68fd9a65a]*/
99
100
/* --- Globals ------------------------------------------------------------
101
102
NOTE: In the interpreter's initialization phase, some globals are currently
103
      initialized dynamically as needed. In the process Unicode objects may
104
      be created before the Unicode type is ready.
105
106
*/
107
108
25.7M
#define MAX_UNICODE _Py_MAX_UNICODE
109
257M
#define ensure_unicode _PyUnicode_EnsureUnicode
110
111
#ifdef Py_DEBUG
112
#  define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
113
#else
114
#  define _PyUnicode_CHECK(op) PyUnicode_Check(op)
115
#endif
116
117
static inline char* _PyUnicode_UTF8(PyObject *op)
118
253M
{
119
253M
    return FT_ATOMIC_LOAD_PTR_ACQUIRE(_PyCompactUnicodeObject_CAST(op)->utf8);
120
253M
}
121
122
static inline char* PyUnicode_UTF8(PyObject *op)
123
158M
{
124
158M
    assert(_PyUnicode_CHECK(op));
125
158M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
126
143M
        return ((char*)(_PyASCIIObject_CAST(op) + 1));
127
143M
    }
128
14.9M
    else {
129
14.9M
         return _PyUnicode_UTF8(op);
130
14.9M
    }
131
158M
}
132
133
static inline void PyUnicode_SET_UTF8(PyObject *op, char *utf8)
134
31.8M
{
135
31.8M
    FT_ATOMIC_STORE_PTR_RELEASE(_PyCompactUnicodeObject_CAST(op)->utf8, utf8);
136
31.8M
}
137
138
static inline Py_ssize_t PyUnicode_UTF8_LENGTH(PyObject *op)
139
74.8M
{
140
74.8M
    assert(_PyUnicode_CHECK(op));
141
74.8M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
142
71.7M
         return _PyASCIIObject_CAST(op)->length;
143
71.7M
    }
144
3.06M
    else {
145
3.06M
         return _PyCompactUnicodeObject_CAST(op)->utf8_length;
146
3.06M
    }
147
74.8M
}
148
149
static inline void PyUnicode_SET_UTF8_LENGTH(PyObject *op, Py_ssize_t length)
150
31.8M
{
151
31.8M
    _PyCompactUnicodeObject_CAST(op)->utf8_length = length;
152
31.8M
}
153
154
#define _PyUnicode_LENGTH(op)                           \
155
610M
    (_PyASCIIObject_CAST(op)->length)
156
#define _PyUnicode_STATE(op)                            \
157
3.91G
    (_PyASCIIObject_CAST(op)->state)
158
#define _PyUnicode_HASH(op)                             \
159
574M
    (_PyASCIIObject_CAST(op)->hash)
160
161
554M
#define PyUnicode_HASH PyUnstable_Unicode_GET_CACHED_HASH
162
163
static inline void PyUnicode_SET_HASH(PyObject *op, Py_hash_t hash)
164
52.5M
{
165
52.5M
    FT_ATOMIC_STORE_SSIZE_RELAXED(_PyASCIIObject_CAST(op)->hash, hash);
166
52.5M
}
167
168
#define _PyUnicode_DATA_ANY(op)                         \
169
68.9M
    (_PyUnicodeObject_CAST(op)->data.any)
170
171
static inline int _PyUnicode_SHARE_UTF8(PyObject *op)
172
0
{
173
0
    assert(_PyUnicode_CHECK(op));
174
0
    assert(!PyUnicode_IS_COMPACT_ASCII(op));
175
0
    return (_PyUnicode_UTF8(op) == PyUnicode_DATA(op));
176
0
}
177
178
/* true if the Unicode object has an allocated UTF-8 memory block
179
   (not shared with other data) */
180
static inline int _PyUnicode_HAS_UTF8_MEMORY(PyObject *op)
181
609M
{
182
609M
    return (!PyUnicode_IS_COMPACT_ASCII(op)
183
223M
            && _PyUnicode_UTF8(op) != NULL
184
14.6M
            && _PyUnicode_UTF8(op) != PyUnicode_DATA(op));
185
609M
}
186
187
188
303M
#define LATIN1 _Py_LATIN1_CHR
189
190
/* Forward declaration */
191
static PyObject *
192
unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
193
                    const char *errors);
194
static PyObject *
195
unicode_decode_utf8(const char *s, Py_ssize_t size,
196
                    _Py_error_handler error_handler, const char *errors,
197
                    Py_ssize_t *consumed);
198
#ifdef Py_DEBUG
199
static inline int unicode_is_finalizing(void);
200
static int unicode_is_singleton(PyObject *unicode);
201
#endif
202
203
204
// Return a reference to the immortal empty string singleton.
205
PyObject*
206
_PyUnicode_GetEmpty(void)
207
139M
{
208
139M
    _Py_DECLARE_STR(empty, "");
209
139M
    return &_Py_STR(empty);
210
139M
}
211
212
/* This dictionary holds per-interpreter interned strings.
213
 * See InternalDocs/string_interning.md for details.
214
 */
215
static inline PyObject *get_interned_dict(PyInterpreterState *interp)
216
6.64M
{
217
6.64M
    return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
218
6.64M
}
219
220
/* This hashtable holds statically allocated interned strings.
221
 * See InternalDocs/string_interning.md for details.
222
 */
223
6.87M
#define INTERNED_STRINGS _PyRuntime.cached_objects.interned_strings
224
225
/* Get number of all interned strings for the current interpreter. */
226
Py_ssize_t
227
_PyUnicode_InternedSize(void)
228
0
{
229
0
    PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
230
0
    return _Py_hashtable_len(INTERNED_STRINGS) + PyDict_GET_SIZE(dict);
231
0
}
232
233
/* Get number of immortal interned strings for the current interpreter. */
234
Py_ssize_t
235
_PyUnicode_InternedSize_Immortal(void)
236
0
{
237
0
    PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
238
0
    PyObject *key, *value;
239
0
    Py_ssize_t pos = 0;
240
0
    Py_ssize_t count = 0;
241
242
    // It's tempting to keep a count and avoid a loop here. But, this function
243
    // is intended for refleak tests. It spends extra work to report the true
244
    // value, to help detect bugs in optimizations.
245
246
0
    while (PyDict_Next(dict, &pos, &key, &value)) {
247
0
        assert(PyUnicode_CHECK_INTERNED(key) != SSTATE_INTERNED_IMMORTAL_STATIC);
248
0
        if (PyUnicode_CHECK_INTERNED(key) == SSTATE_INTERNED_IMMORTAL) {
249
0
           count++;
250
0
       }
251
0
    }
252
0
    return _Py_hashtable_len(INTERNED_STRINGS) + count;
253
0
}
254
255
static Py_hash_t unicode_hash(PyObject *);
256
257
static Py_uhash_t
258
hashtable_unicode_hash(const void *key)
259
6.87M
{
260
6.87M
    return unicode_hash((PyObject *)key);
261
6.87M
}
262
263
static int
264
hashtable_unicode_compare(const void *key1, const void *key2)
265
359k
{
266
359k
    PyObject *obj1 = (PyObject *)key1;
267
359k
    PyObject *obj2 = (PyObject *)key2;
268
359k
    if (obj1 != NULL && obj2 != NULL) {
269
359k
        return unicode_eq(obj1, obj2);
270
359k
    }
271
0
    else {
272
0
        return obj1 == obj2;
273
0
    }
274
359k
}
275
276
/* Return true if this interpreter should share the main interpreter's
277
   intern_dict.  That's important for interpreters which load basic
278
   single-phase init extension modules (m_size == -1).  There could be interned
279
   immortal strings that are shared between interpreters, due to the
280
   PyDict_Update(mdict, m_copy) call in import_find_extension().
281
282
   It's not safe to deallocate those strings until all interpreters that
283
   potentially use them are freed.  By storing them in the main interpreter, we
284
   ensure they get freed after all other interpreters are freed.
285
*/
286
static bool
287
has_shared_intern_dict(PyInterpreterState *interp)
288
37
{
289
37
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
290
37
    return interp != main_interp  && interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC;
291
37
}
292
293
static int
294
init_interned_dict(PyInterpreterState *interp)
295
37
{
296
37
    assert(get_interned_dict(interp) == NULL);
297
37
    PyObject *interned;
298
37
    if (has_shared_intern_dict(interp)) {
299
0
        interned = get_interned_dict(_PyInterpreterState_Main());
300
0
        Py_INCREF(interned);
301
0
    }
302
37
    else {
303
37
        interned = PyDict_New();
304
37
        if (interned == NULL) {
305
0
            return -1;
306
0
        }
307
37
    }
308
37
    _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
309
37
    return 0;
310
37
}
311
312
static void
313
clear_interned_dict(PyInterpreterState *interp)
314
0
{
315
0
    PyObject *interned = get_interned_dict(interp);
316
0
    if (interned != NULL) {
317
0
        if (!has_shared_intern_dict(interp)) {
318
            // only clear if the dict belongs to this interpreter
319
0
            PyDict_Clear(interned);
320
0
        }
321
0
        Py_DECREF(interned);
322
0
        _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = NULL;
323
0
    }
324
0
}
325
326
static PyStatus
327
init_global_interned_strings(PyInterpreterState *interp)
328
37
{
329
37
    assert(INTERNED_STRINGS == NULL);
330
37
    _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
331
332
37
    INTERNED_STRINGS = _Py_hashtable_new_full(
333
37
        hashtable_unicode_hash,
334
37
        hashtable_unicode_compare,
335
        // Objects stored here are immortal and statically allocated,
336
        // so we don't need key_destroy_func & value_destroy_func:
337
37
        NULL,
338
37
        NULL,
339
37
        &hashtable_alloc
340
37
    );
341
37
    if (INTERNED_STRINGS == NULL) {
342
0
        PyErr_Clear();
343
0
        return _PyStatus_ERR("failed to create global interned dict");
344
0
    }
345
346
    /* Intern statically allocated string identifiers, deepfreeze strings,
347
        * and one-byte latin-1 strings.
348
        * This must be done before any module initialization so that statically
349
        * allocated string identifiers are used instead of heap allocated strings.
350
        * Deepfreeze uses the interned identifiers if present to save space
351
        * else generates them and they are interned to speed up dict lookups.
352
    */
353
37
    _PyUnicode_InitStaticStrings(interp);
354
355
9.50k
    for (int i = 0; i < 256; i++) {
356
9.47k
        PyObject *s = LATIN1(i);
357
9.47k
        _PyUnicode_InternStatic(interp, &s);
358
9.47k
        assert(s == LATIN1(i));
359
9.47k
    }
360
#ifdef Py_DEBUG
361
    assert(_PyUnicode_CheckConsistency(&_Py_STR(empty), 1));
362
363
    for (int i = 0; i < 256; i++) {
364
        assert(_PyUnicode_CheckConsistency(LATIN1(i), 1));
365
    }
366
#endif
367
37
    return _PyStatus_OK();
368
37
}
369
370
static void clear_global_interned_strings(void)
371
0
{
372
0
    if (INTERNED_STRINGS != NULL) {
373
0
        _Py_hashtable_destroy(INTERNED_STRINGS);
374
0
        INTERNED_STRINGS = NULL;
375
0
    }
376
0
}
377
378
#define _Py_RETURN_UNICODE_EMPTY()   \
379
73.6M
    do {                             \
380
73.6M
        return _PyUnicode_GetEmpty();\
381
73.6M
    } while (0)
382
383
384
/* Fast detection of the most frequent whitespace characters */
385
const unsigned char _Py_ascii_whitespace[] = {
386
    0, 0, 0, 0, 0, 0, 0, 0,
387
/*     case 0x0009: * CHARACTER TABULATION */
388
/*     case 0x000A: * LINE FEED */
389
/*     case 0x000B: * LINE TABULATION */
390
/*     case 0x000C: * FORM FEED */
391
/*     case 0x000D: * CARRIAGE RETURN */
392
    0, 1, 1, 1, 1, 1, 0, 0,
393
    0, 0, 0, 0, 0, 0, 0, 0,
394
/*     case 0x001C: * FILE SEPARATOR */
395
/*     case 0x001D: * GROUP SEPARATOR */
396
/*     case 0x001E: * RECORD SEPARATOR */
397
/*     case 0x001F: * UNIT SEPARATOR */
398
    0, 0, 0, 0, 1, 1, 1, 1,
399
/*     case 0x0020: * SPACE */
400
    1, 0, 0, 0, 0, 0, 0, 0,
401
    0, 0, 0, 0, 0, 0, 0, 0,
402
    0, 0, 0, 0, 0, 0, 0, 0,
403
    0, 0, 0, 0, 0, 0, 0, 0,
404
405
    0, 0, 0, 0, 0, 0, 0, 0,
406
    0, 0, 0, 0, 0, 0, 0, 0,
407
    0, 0, 0, 0, 0, 0, 0, 0,
408
    0, 0, 0, 0, 0, 0, 0, 0,
409
    0, 0, 0, 0, 0, 0, 0, 0,
410
    0, 0, 0, 0, 0, 0, 0, 0,
411
    0, 0, 0, 0, 0, 0, 0, 0,
412
    0, 0, 0, 0, 0, 0, 0, 0
413
};
414
415
/* forward */
416
static PyObject* get_latin1_char(unsigned char ch);
417
418
419
static PyObject *
420
_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
421
static PyObject *
422
_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
423
static PyObject *
424
_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
425
426
static PyObject *
427
unicode_encode_call_errorhandler(const char *errors,
428
       PyObject **errorHandler,const char *encoding, const char *reason,
429
       PyObject *unicode, PyObject **exceptionObject,
430
       Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
431
432
static void
433
raise_encode_exception(PyObject **exceptionObject,
434
                       const char *encoding,
435
                       PyObject *unicode,
436
                       Py_ssize_t startpos, Py_ssize_t endpos,
437
                       const char *reason);
438
439
/* Same for linebreaks */
440
static const unsigned char ascii_linebreak[] = {
441
    0, 0, 0, 0, 0, 0, 0, 0,
442
/*         0x000A, * LINE FEED */
443
/*         0x000B, * LINE TABULATION */
444
/*         0x000C, * FORM FEED */
445
/*         0x000D, * CARRIAGE RETURN */
446
    0, 0, 1, 1, 1, 1, 0, 0,
447
    0, 0, 0, 0, 0, 0, 0, 0,
448
/*         0x001C, * FILE SEPARATOR */
449
/*         0x001D, * GROUP SEPARATOR */
450
/*         0x001E, * RECORD SEPARATOR */
451
    0, 0, 0, 0, 1, 1, 1, 0,
452
    0, 0, 0, 0, 0, 0, 0, 0,
453
    0, 0, 0, 0, 0, 0, 0, 0,
454
    0, 0, 0, 0, 0, 0, 0, 0,
455
    0, 0, 0, 0, 0, 0, 0, 0,
456
457
    0, 0, 0, 0, 0, 0, 0, 0,
458
    0, 0, 0, 0, 0, 0, 0, 0,
459
    0, 0, 0, 0, 0, 0, 0, 0,
460
    0, 0, 0, 0, 0, 0, 0, 0,
461
    0, 0, 0, 0, 0, 0, 0, 0,
462
    0, 0, 0, 0, 0, 0, 0, 0,
463
    0, 0, 0, 0, 0, 0, 0, 0,
464
    0, 0, 0, 0, 0, 0, 0, 0
465
};
466
467
static int convert_uc(PyObject *obj, void *addr);
468
469
struct encoding_map;
470
#include "clinic/unicodeobject.c.h"
471
472
_Py_error_handler
473
_Py_GetErrorHandler(const char *errors)
474
6.02M
{
475
6.02M
    if (errors == NULL || strcmp(errors, "strict") == 0) {
476
5.41M
        return _Py_ERROR_STRICT;
477
5.41M
    }
478
608k
    if (strcmp(errors, "surrogateescape") == 0) {
479
409k
        return _Py_ERROR_SURROGATEESCAPE;
480
409k
    }
481
199k
    if (strcmp(errors, "replace") == 0) {
482
199k
        return _Py_ERROR_REPLACE;
483
199k
    }
484
4
    if (strcmp(errors, "ignore") == 0) {
485
0
        return _Py_ERROR_IGNORE;
486
0
    }
487
4
    if (strcmp(errors, "backslashreplace") == 0) {
488
0
        return _Py_ERROR_BACKSLASHREPLACE;
489
0
    }
490
4
    if (strcmp(errors, "surrogatepass") == 0) {
491
4
        return _Py_ERROR_SURROGATEPASS;
492
4
    }
493
0
    if (strcmp(errors, "xmlcharrefreplace") == 0) {
494
0
        return _Py_ERROR_XMLCHARREFREPLACE;
495
0
    }
496
0
    return _Py_ERROR_OTHER;
497
0
}
498
499
500
static _Py_error_handler
501
get_error_handler_wide(const wchar_t *errors)
502
13.5k
{
503
13.5k
    if (errors == NULL || wcscmp(errors, L"strict") == 0) {
504
0
        return _Py_ERROR_STRICT;
505
0
    }
506
13.5k
    if (wcscmp(errors, L"surrogateescape") == 0) {
507
13.5k
        return _Py_ERROR_SURROGATEESCAPE;
508
13.5k
    }
509
0
    if (wcscmp(errors, L"replace") == 0) {
510
0
        return _Py_ERROR_REPLACE;
511
0
    }
512
0
    if (wcscmp(errors, L"ignore") == 0) {
513
0
        return _Py_ERROR_IGNORE;
514
0
    }
515
0
    if (wcscmp(errors, L"backslashreplace") == 0) {
516
0
        return _Py_ERROR_BACKSLASHREPLACE;
517
0
    }
518
0
    if (wcscmp(errors, L"surrogatepass") == 0) {
519
0
        return _Py_ERROR_SURROGATEPASS;
520
0
    }
521
0
    if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
522
0
        return _Py_ERROR_XMLCHARREFREPLACE;
523
0
    }
524
0
    return _Py_ERROR_OTHER;
525
0
}
526
527
528
static inline int
529
unicode_check_encoding_errors(const char *encoding, const char *errors)
530
50.0M
{
531
50.0M
    if (encoding == NULL && errors == NULL) {
532
12.5M
        return 0;
533
12.5M
    }
534
535
37.5M
    PyInterpreterState *interp = _PyInterpreterState_GET();
536
37.5M
#ifndef Py_DEBUG
537
    /* In release mode, only check in development mode (-X dev) */
538
37.5M
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
539
37.5M
        return 0;
540
37.5M
    }
541
#else
542
    /* Always check in debug mode */
543
#endif
544
545
    /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
546
       codec registry is ready: before_PyUnicode_InitEncodings() is called. */
547
0
    if (!interp->unicode.fs_codec.encoding) {
548
0
        return 0;
549
0
    }
550
551
    /* Disable checks during Python finalization. For example, it allows to
552
     * call PyObject_Dump() during finalization for debugging purpose.
553
     */
554
0
    if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
555
0
        return 0;
556
0
    }
557
558
0
    if (encoding != NULL
559
        // Fast path for the most common built-in encodings. Even if the codec
560
        // is cached, _PyCodec_Lookup() decodes the bytes string from UTF-8 to
561
        // create a temporary Unicode string (the key in the cache).
562
0
        && strcmp(encoding, "utf-8") != 0
563
0
        && strcmp(encoding, "utf8") != 0
564
0
        && strcmp(encoding, "ascii") != 0)
565
0
    {
566
0
        PyObject *handler = _PyCodec_Lookup(encoding);
567
0
        if (handler == NULL) {
568
0
            return -1;
569
0
        }
570
0
        Py_DECREF(handler);
571
0
    }
572
573
0
    if (errors != NULL
574
        // Fast path for the most common built-in error handlers.
575
0
        && strcmp(errors, "strict") != 0
576
0
        && strcmp(errors, "ignore") != 0
577
0
        && strcmp(errors, "replace") != 0
578
0
        && strcmp(errors, "surrogateescape") != 0
579
0
        && strcmp(errors, "surrogatepass") != 0)
580
0
    {
581
0
        PyObject *handler = PyCodec_LookupError(errors);
582
0
        if (handler == NULL) {
583
0
            return -1;
584
0
        }
585
0
        Py_DECREF(handler);
586
0
    }
587
0
    return 0;
588
0
}
589
590
591
int
592
_PyUnicode_CheckConsistency(PyObject *op, int check_content)
593
0
{
594
0
#define CHECK(expr) \
595
0
    do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
596
#ifdef Py_GIL_DISABLED
597
# define CHECK_IF_GIL(expr) (void)(expr)
598
# define CHECK_IF_FT(expr) CHECK(expr)
599
#else
600
0
# define CHECK_IF_GIL(expr) CHECK(expr)
601
0
# define CHECK_IF_FT(expr) (void)(expr)
602
0
#endif
603
604
0
    assert(op != NULL);
605
0
    CHECK(PyUnicode_Check(op));
606
607
0
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
608
0
    int kind = ascii->state.kind;
609
610
0
    if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
611
0
        CHECK(kind == PyUnicode_1BYTE_KIND);
612
0
    }
613
0
    else {
614
0
        PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
615
0
        void *data;
616
617
0
        if (ascii->state.compact == 1) {
618
0
            data = compact + 1;
619
0
            CHECK(kind == PyUnicode_1BYTE_KIND
620
0
                                 || kind == PyUnicode_2BYTE_KIND
621
0
                                 || kind == PyUnicode_4BYTE_KIND);
622
0
            CHECK(ascii->state.ascii == 0);
623
0
            CHECK(_PyUnicode_UTF8(op) != data);
624
0
        }
625
0
        else {
626
0
            PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
627
628
0
            data = unicode->data.any;
629
0
            CHECK(kind == PyUnicode_1BYTE_KIND
630
0
                     || kind == PyUnicode_2BYTE_KIND
631
0
                     || kind == PyUnicode_4BYTE_KIND);
632
0
            CHECK(ascii->state.compact == 0);
633
0
            CHECK(data != NULL);
634
0
            if (ascii->state.ascii) {
635
0
                CHECK(_PyUnicode_UTF8(op) == data);
636
0
                CHECK(compact->utf8_length == ascii->length);
637
0
            }
638
0
            else {
639
0
                CHECK(_PyUnicode_UTF8(op) != data);
640
0
            }
641
0
        }
642
0
#ifndef Py_GIL_DISABLED
643
0
        if (_PyUnicode_UTF8(op) == NULL)
644
0
            CHECK(compact->utf8_length == 0);
645
0
#endif
646
0
    }
647
648
    /* check that the best kind is used: O(n) operation */
649
0
    const void *data = PyUnicode_DATA(ascii);
650
0
    if (check_content) {
651
0
        Py_ssize_t i;
652
0
        Py_UCS4 maxchar = 0;
653
0
        Py_UCS4 ch;
654
655
0
        for (i=0; i < ascii->length; i++)
656
0
        {
657
0
            ch = PyUnicode_READ(kind, data, i);
658
0
            if (ch > maxchar)
659
0
                maxchar = ch;
660
0
        }
661
0
        if (kind == PyUnicode_1BYTE_KIND) {
662
0
            if (ascii->state.ascii == 0) {
663
0
                CHECK(maxchar >= 128);
664
0
                CHECK(maxchar <= 255);
665
0
            }
666
0
            else
667
0
                CHECK(maxchar < 128);
668
0
        }
669
0
        else if (kind == PyUnicode_2BYTE_KIND) {
670
0
            CHECK(maxchar >= 0x100);
671
0
            CHECK(maxchar <= 0xFFFF);
672
0
        }
673
0
        else {
674
0
            CHECK(maxchar >= 0x10000);
675
0
            CHECK(maxchar <= MAX_UNICODE);
676
0
        }
677
0
    }
678
679
    // Detect buffer overflow: check if the trailing null character
680
    // has been overridden
681
0
    CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
682
683
    /* Check interning state */
684
#ifdef Py_DEBUG
685
    // Note that we do not check `_Py_IsImmortal(op)` in the GIL-enabled build
686
    // since stable ABI extensions can make immortal strings mortal (but with a
687
    // high enough refcount).
688
    switch (PyUnicode_CHECK_INTERNED(op)) {
689
        case SSTATE_NOT_INTERNED:
690
            if (ascii->state.statically_allocated) {
691
                // This state is for two exceptions:
692
                // - strings are currently checked before they're interned
693
                // - the 256 one-latin1-character strings
694
                //   are static but use SSTATE_NOT_INTERNED
695
            }
696
            else {
697
                CHECK_IF_GIL(!_Py_IsImmortal(op));
698
            }
699
            break;
700
        case SSTATE_INTERNED_MORTAL:
701
            CHECK(!ascii->state.statically_allocated);
702
            CHECK_IF_GIL(!_Py_IsImmortal(op));
703
            break;
704
        case SSTATE_INTERNED_IMMORTAL:
705
            CHECK(!ascii->state.statically_allocated);
706
            CHECK_IF_FT(_Py_IsImmortal(op));
707
            break;
708
        case SSTATE_INTERNED_IMMORTAL_STATIC:
709
            CHECK(ascii->state.statically_allocated);
710
            CHECK_IF_FT(_Py_IsImmortal(op));
711
            break;
712
        default:
713
            Py_UNREACHABLE();
714
    }
715
#endif
716
717
0
    return 1;
718
719
0
#undef CHECK
720
0
}
721
722
PyObject*
723
_PyUnicode_Result(PyObject *unicode)
724
2.30M
{
725
2.30M
    assert(_PyUnicode_CHECK(unicode));
726
727
2.30M
    Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
728
2.30M
    if (length == 0) {
729
261
        PyObject *empty = _PyUnicode_GetEmpty();
730
261
        if (unicode != empty) {
731
0
            Py_DECREF(unicode);
732
0
        }
733
261
        return empty;
734
261
    }
735
736
2.30M
    if (length == 1) {
737
548k
        int kind = PyUnicode_KIND(unicode);
738
548k
        if (kind == PyUnicode_1BYTE_KIND) {
739
56.2k
            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
740
56.2k
            Py_UCS1 ch = data[0];
741
56.2k
            PyObject *latin1_char = LATIN1(ch);
742
56.2k
            if (unicode != latin1_char) {
743
0
                Py_DECREF(unicode);
744
0
            }
745
56.2k
            return latin1_char;
746
56.2k
        }
747
548k
    }
748
749
2.30M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
750
2.25M
    return unicode;
751
2.30M
}
752
2.30M
#define unicode_result _PyUnicode_Result
753
754
static PyObject*
755
unicode_result_unchanged(PyObject *unicode)
756
93.8M
{
757
93.8M
    if (PyUnicode_CheckExact(unicode)) {
758
91.1M
        return Py_NewRef(unicode);
759
91.1M
    }
760
2.76M
    else
761
        /* Subtype -- return genuine unicode string with the same value. */
762
2.76M
        return _PyUnicode_Copy(unicode);
763
93.8M
}
764
765
/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
766
   ASCII, Latin1, UTF-8, etc. */
767
static char*
768
backslashreplace(PyBytesWriter *writer, char *str,
769
                 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
770
0
{
771
0
    Py_ssize_t size, i;
772
0
    Py_UCS4 ch;
773
0
    int kind;
774
0
    const void *data;
775
776
0
    kind = PyUnicode_KIND(unicode);
777
0
    data = PyUnicode_DATA(unicode);
778
779
0
    size = 0;
780
    /* determine replacement size */
781
0
    for (i = collstart; i < collend; ++i) {
782
0
        Py_ssize_t incr;
783
784
0
        ch = PyUnicode_READ(kind, data, i);
785
0
        if (ch < 0x100)
786
0
            incr = 2+2;
787
0
        else if (ch < 0x10000)
788
0
            incr = 2+4;
789
0
        else {
790
0
            assert(ch <= MAX_UNICODE);
791
0
            incr = 2+8;
792
0
        }
793
0
        if (size > PY_SSIZE_T_MAX - incr) {
794
0
            PyErr_SetString(PyExc_OverflowError,
795
0
                            "encoded result is too long for a Python string");
796
0
            return NULL;
797
0
        }
798
0
        size += incr;
799
0
    }
800
    /* subtract preallocated bytes */
801
0
    size -= (collend - collstart);
802
803
0
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
804
0
    if (str == NULL) {
805
0
        return NULL;
806
0
    }
807
808
    /* generate replacement */
809
0
    for (i = collstart; i < collend; ++i) {
810
0
        ch = PyUnicode_READ(kind, data, i);
811
0
        *str++ = '\\';
812
0
        if (ch >= 0x00010000) {
813
0
            *str++ = 'U';
814
0
            *str++ = Py_hexdigits[(ch>>28)&0xf];
815
0
            *str++ = Py_hexdigits[(ch>>24)&0xf];
816
0
            *str++ = Py_hexdigits[(ch>>20)&0xf];
817
0
            *str++ = Py_hexdigits[(ch>>16)&0xf];
818
0
            *str++ = Py_hexdigits[(ch>>12)&0xf];
819
0
            *str++ = Py_hexdigits[(ch>>8)&0xf];
820
0
        }
821
0
        else if (ch >= 0x100) {
822
0
            *str++ = 'u';
823
0
            *str++ = Py_hexdigits[(ch>>12)&0xf];
824
0
            *str++ = Py_hexdigits[(ch>>8)&0xf];
825
0
        }
826
0
        else
827
0
            *str++ = 'x';
828
0
        *str++ = Py_hexdigits[(ch>>4)&0xf];
829
0
        *str++ = Py_hexdigits[ch&0xf];
830
0
    }
831
0
    return str;
832
0
}
833
834
/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
835
   ASCII, Latin1, UTF-8, etc. */
836
static char*
837
xmlcharrefreplace(PyBytesWriter *writer, char *str,
838
                  PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
839
0
{
840
0
    Py_ssize_t size, i;
841
0
    Py_UCS4 ch;
842
0
    int kind;
843
0
    const void *data;
844
845
0
    kind = PyUnicode_KIND(unicode);
846
0
    data = PyUnicode_DATA(unicode);
847
848
0
    size = 0;
849
    /* determine replacement size */
850
0
    for (i = collstart; i < collend; ++i) {
851
0
        Py_ssize_t incr;
852
853
0
        ch = PyUnicode_READ(kind, data, i);
854
0
        if (ch < 10)
855
0
            incr = 2+1+1;
856
0
        else if (ch < 100)
857
0
            incr = 2+2+1;
858
0
        else if (ch < 1000)
859
0
            incr = 2+3+1;
860
0
        else if (ch < 10000)
861
0
            incr = 2+4+1;
862
0
        else if (ch < 100000)
863
0
            incr = 2+5+1;
864
0
        else if (ch < 1000000)
865
0
            incr = 2+6+1;
866
0
        else {
867
0
            assert(ch <= MAX_UNICODE);
868
0
            incr = 2+7+1;
869
0
        }
870
0
        if (size > PY_SSIZE_T_MAX - incr) {
871
0
            PyErr_SetString(PyExc_OverflowError,
872
0
                            "encoded result is too long for a Python string");
873
0
            return NULL;
874
0
        }
875
0
        size += incr;
876
0
    }
877
    /* subtract preallocated bytes */
878
0
    size -= (collend - collstart);
879
880
0
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
881
0
    if (str == NULL) {
882
0
        return NULL;
883
0
    }
884
885
    /* generate replacement */
886
0
    for (i = collstart; i < collend; ++i) {
887
        // Use snprintf() with a temporary buffer to not write the trailing
888
        // NUL byte in the writer buffer.
889
0
        Py_BUILD_ASSERT(_Py_MAX_UNICODE <= 0x10ffff);
890
        // len('&#1114111;\0') is 11 bytes.
891
0
        char buffer[11];
892
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
893
0
        size = snprintf(buffer, sizeof(buffer), "&#%d;", ch);
894
0
        assert(4 <= size && (size_t)size <= (sizeof(buffer) - 1));
895
896
0
        memcpy(str, buffer, size);
897
0
        str += size;
898
0
    }
899
0
    return str;
900
0
}
901
902
/* --- Bloom Filters ----------------------------------------------------- */
903
904
/* stuff to implement simple "bloom filters" for Unicode characters.
905
   to keep things simple, we use a single bitmask, using the least 5
906
   bits from each unicode characters as the bit index. */
907
908
/* the linebreak mask is set up by _PyUnicode_Init() below */
909
910
#if LONG_BIT >= 128
911
#define BLOOM_WIDTH 128
912
#elif LONG_BIT >= 64
913
20.3M
#define BLOOM_WIDTH 64
914
#elif LONG_BIT >= 32
915
#define BLOOM_WIDTH 32
916
#else
917
#error "LONG_BIT is smaller than 32"
918
#endif
919
920
5.00M
#define BLOOM_MASK unsigned long
921
922
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
923
924
30.0M
#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
925
926
#define BLOOM_LINEBREAK(ch)                                             \
927
144M
    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
928
144M
     (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
929
930
static inline BLOOM_MASK
931
make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
932
2.50M
{
933
2.50M
#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
934
2.50M
    do {                                               \
935
2.50M
        TYPE *data = (TYPE *)PTR;                      \
936
2.50M
        TYPE *end = data + LEN;                        \
937
2.50M
        Py_UCS4 ch;                                    \
938
6.75M
        for (; data != end; data++) {                  \
939
4.25M
            ch = *data;                                \
940
4.25M
            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
941
4.25M
        }                                              \
942
2.50M
        break;                                         \
943
2.50M
    } while (0)
944
945
    /* calculate simple bloom-style bitmask for a given unicode string */
946
947
2.50M
    BLOOM_MASK mask;
948
949
2.50M
    mask = 0;
950
2.50M
    switch (kind) {
951
2.50M
    case PyUnicode_1BYTE_KIND:
952
2.50M
        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
953
2.50M
        break;
954
37
    case PyUnicode_2BYTE_KIND:
955
37
        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
956
37
        break;
957
0
    case PyUnicode_4BYTE_KIND:
958
0
        BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
959
0
        break;
960
0
    default:
961
0
        Py_UNREACHABLE();
962
2.50M
    }
963
2.50M
    return mask;
964
965
2.50M
#undef BLOOM_UPDATE
966
2.50M
}
967
968
/* Compilation of templated routines */
969
970
715k
#define STRINGLIB_GET_EMPTY() _PyUnicode_GetEmpty()
971
972
#include "stringlib/asciilib.h"
973
#include "stringlib/fastsearch.h"
974
#include "stringlib/partition.h"
975
#include "stringlib/split.h"
976
#include "stringlib/count.h"
977
#include "stringlib/find.h"
978
#include "stringlib/find_max_char.h"
979
#include "stringlib/undef.h"
980
981
#include "stringlib/ucs1lib.h"
982
#include "stringlib/fastsearch.h"
983
#include "stringlib/partition.h"
984
#include "stringlib/split.h"
985
#include "stringlib/count.h"
986
#include "stringlib/find.h"
987
#include "stringlib/replace.h"
988
#include "stringlib/repr.h"
989
#include "stringlib/find_max_char.h"
990
#include "stringlib/undef.h"
991
992
#include "stringlib/ucs2lib.h"
993
#include "stringlib/fastsearch.h"
994
#include "stringlib/partition.h"
995
#include "stringlib/split.h"
996
#include "stringlib/count.h"
997
#include "stringlib/find.h"
998
#include "stringlib/replace.h"
999
#include "stringlib/repr.h"
1000
#include "stringlib/find_max_char.h"
1001
#include "stringlib/undef.h"
1002
1003
#include "stringlib/ucs4lib.h"
1004
#include "stringlib/fastsearch.h"
1005
#include "stringlib/partition.h"
1006
#include "stringlib/split.h"
1007
#include "stringlib/count.h"
1008
#include "stringlib/find.h"
1009
#include "stringlib/replace.h"
1010
#include "stringlib/repr.h"
1011
#include "stringlib/find_max_char.h"
1012
#include "stringlib/undef.h"
1013
1014
#undef STRINGLIB_GET_EMPTY
1015
1016
/* --- Unicode Object ----------------------------------------------------- */
1017
1018
static inline Py_ssize_t
1019
findchar(const void *s, int kind,
1020
         Py_ssize_t size, Py_UCS4 ch,
1021
         int direction)
1022
191M
{
1023
191M
    switch (kind) {
1024
189M
    case PyUnicode_1BYTE_KIND:
1025
189M
        if ((Py_UCS1) ch != ch)
1026
5.98k
            return -1;
1027
189M
        if (direction > 0)
1028
189M
            return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1029
56.7k
        else
1030
56.7k
            return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1031
1.52M
    case PyUnicode_2BYTE_KIND:
1032
1.52M
        if ((Py_UCS2) ch != ch)
1033
0
            return -1;
1034
1.52M
        if (direction > 0)
1035
1.39M
            return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1036
129k
        else
1037
129k
            return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1038
498k
    case PyUnicode_4BYTE_KIND:
1039
498k
        if (direction > 0)
1040
488k
            return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
1041
9.56k
        else
1042
9.56k
            return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
1043
0
    default:
1044
0
        Py_UNREACHABLE();
1045
191M
    }
1046
191M
}
1047
1048
#ifdef Py_DEBUG
1049
/* Fill the data of a Unicode string with invalid characters to detect bugs
1050
   earlier.
1051
1052
   _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
1053
   ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
1054
   invalid character in Unicode 6.0. */
1055
static void
1056
unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
1057
{
1058
    int kind = PyUnicode_KIND(unicode);
1059
    Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
1060
    Py_ssize_t length = _PyUnicode_LENGTH(unicode);
1061
    if (length <= old_length)
1062
        return;
1063
    memset(data + old_length * kind, 0xff, (length - old_length) * kind);
1064
}
1065
#endif
1066
1067
static PyObject*
1068
resize_copy(PyObject *unicode, Py_ssize_t length)
1069
0
{
1070
0
    Py_ssize_t copy_length;
1071
0
    PyObject *copy;
1072
1073
0
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1074
0
    if (copy == NULL)
1075
0
        return NULL;
1076
1077
0
    copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
1078
0
    _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
1079
0
    return copy;
1080
0
}
1081
1082
PyObject*
1083
_PyUnicode_ResizeCompact(PyObject *unicode, Py_ssize_t length)
1084
53.1M
{
1085
53.1M
    Py_ssize_t char_size;
1086
53.1M
    Py_ssize_t struct_size;
1087
53.1M
    Py_ssize_t new_size;
1088
53.1M
    PyObject *new_unicode;
1089
#ifdef Py_DEBUG
1090
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1091
#endif
1092
1093
53.1M
    if (!_PyUnicode_IsModifiable(unicode)) {
1094
0
        PyObject *copy = resize_copy(unicode, length);
1095
0
        if (copy == NULL) {
1096
0
            return NULL;
1097
0
        }
1098
0
        Py_DECREF(unicode);
1099
0
        return copy;
1100
0
    }
1101
53.1M
    assert(PyUnicode_IS_COMPACT(unicode));
1102
1103
53.1M
    char_size = PyUnicode_KIND(unicode);
1104
53.1M
    if (PyUnicode_IS_ASCII(unicode))
1105
37.7M
        struct_size = sizeof(PyASCIIObject);
1106
15.3M
    else
1107
15.3M
        struct_size = sizeof(PyCompactUnicodeObject);
1108
1109
53.1M
    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1110
0
        PyErr_NoMemory();
1111
0
        return NULL;
1112
0
    }
1113
53.1M
    new_size = (struct_size + (length + 1) * char_size);
1114
1115
53.1M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1116
0
        PyMem_Free(_PyUnicode_UTF8(unicode));
1117
0
        PyUnicode_SET_UTF8_LENGTH(unicode, 0);
1118
0
        PyUnicode_SET_UTF8(unicode, NULL);
1119
0
    }
1120
#ifdef Py_TRACE_REFS
1121
    _Py_ForgetReference(unicode);
1122
#endif
1123
53.1M
    _PyReftracerTrack(unicode, PyRefTracer_DESTROY);
1124
1125
53.1M
    new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
1126
53.1M
    if (new_unicode == NULL) {
1127
0
        _Py_NewReferenceNoTotal(unicode);
1128
0
        PyErr_NoMemory();
1129
0
        return NULL;
1130
0
    }
1131
53.1M
    unicode = new_unicode;
1132
53.1M
    _Py_NewReferenceNoTotal(unicode);
1133
1134
53.1M
    _PyUnicode_LENGTH(unicode) = length;
1135
#ifdef Py_DEBUG
1136
    unicode_fill_invalid(unicode, old_length);
1137
#endif
1138
53.1M
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1139
53.1M
                    length, 0);
1140
53.1M
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1141
53.1M
    return unicode;
1142
53.1M
}
1143
1144
static int
1145
resize_inplace(PyObject *unicode, Py_ssize_t length)
1146
0
{
1147
0
    assert(!PyUnicode_IS_COMPACT(unicode));
1148
0
    assert(Py_REFCNT(unicode) == 1);
1149
1150
0
    Py_ssize_t new_size;
1151
0
    Py_ssize_t char_size;
1152
0
    int share_utf8;
1153
0
    void *data;
1154
#ifdef Py_DEBUG
1155
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1156
#endif
1157
1158
0
    data = _PyUnicode_DATA_ANY(unicode);
1159
0
    char_size = PyUnicode_KIND(unicode);
1160
0
    share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
1161
1162
0
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1163
0
        PyErr_NoMemory();
1164
0
        return -1;
1165
0
    }
1166
0
    new_size = (length + 1) * char_size;
1167
1168
0
    if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1169
0
    {
1170
0
        PyMem_Free(_PyUnicode_UTF8(unicode));
1171
0
        PyUnicode_SET_UTF8_LENGTH(unicode, 0);
1172
0
        PyUnicode_SET_UTF8(unicode, NULL);
1173
0
    }
1174
1175
0
    data = (PyObject *)PyObject_Realloc(data, new_size);
1176
0
    if (data == NULL) {
1177
0
        PyErr_NoMemory();
1178
0
        return -1;
1179
0
    }
1180
0
    _PyUnicode_DATA_ANY(unicode) = data;
1181
0
    if (share_utf8) {
1182
0
        PyUnicode_SET_UTF8_LENGTH(unicode, length);
1183
0
        PyUnicode_SET_UTF8(unicode, data);
1184
0
    }
1185
0
    _PyUnicode_LENGTH(unicode) = length;
1186
0
    PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
1187
#ifdef Py_DEBUG
1188
    unicode_fill_invalid(unicode, old_length);
1189
#endif
1190
1191
    /* check for integer overflow */
1192
0
    if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
1193
0
        PyErr_NoMemory();
1194
0
        return -1;
1195
0
    }
1196
0
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1197
0
    return 0;
1198
0
}
1199
1200
static const char*
1201
unicode_kind_name(PyObject *unicode)
1202
0
{
1203
    /* don't check consistency: unicode_kind_name() is called from
1204
       _PyUnicode_Dump() */
1205
0
    if (!PyUnicode_IS_COMPACT(unicode))
1206
0
    {
1207
0
        switch (PyUnicode_KIND(unicode))
1208
0
        {
1209
0
        case PyUnicode_1BYTE_KIND:
1210
0
            if (PyUnicode_IS_ASCII(unicode))
1211
0
                return "legacy ascii";
1212
0
            else
1213
0
                return "legacy latin1";
1214
0
        case PyUnicode_2BYTE_KIND:
1215
0
            return "legacy UCS2";
1216
0
        case PyUnicode_4BYTE_KIND:
1217
0
            return "legacy UCS4";
1218
0
        default:
1219
0
            return "<legacy invalid kind>";
1220
0
        }
1221
0
    }
1222
0
    switch (PyUnicode_KIND(unicode)) {
1223
0
    case PyUnicode_1BYTE_KIND:
1224
0
        if (PyUnicode_IS_ASCII(unicode))
1225
0
            return "ascii";
1226
0
        else
1227
0
            return "latin1";
1228
0
    case PyUnicode_2BYTE_KIND:
1229
0
        return "UCS2";
1230
0
    case PyUnicode_4BYTE_KIND:
1231
0
        return "UCS4";
1232
0
    default:
1233
0
        return "<invalid compact kind>";
1234
0
    }
1235
0
}
1236
1237
#ifdef Py_DEBUG
1238
/* Functions wrapping macros for use in debugger */
1239
const char *_PyUnicode_utf8(void *unicode_raw){
1240
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1241
    return PyUnicode_UTF8(unicode);
1242
}
1243
1244
const void *_PyUnicode_compact_data(void *unicode_raw) {
1245
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1246
    return _PyUnicode_COMPACT_DATA(unicode);
1247
}
1248
const void *_PyUnicode_data(void *unicode_raw) {
1249
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1250
    printf("obj %p\n", (void*)unicode);
1251
    printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1252
    printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1253
    printf("ascii op %p\n", (void*)(_PyASCIIObject_CAST(unicode) + 1));
1254
    printf("compact op %p\n", (void*)(_PyCompactUnicodeObject_CAST(unicode) + 1));
1255
    printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1256
    return PyUnicode_DATA(unicode);
1257
}
1258
1259
void
1260
_PyUnicode_Dump(PyObject *op)
1261
{
1262
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
1263
    PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
1264
    PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
1265
    const void *data;
1266
1267
    if (ascii->state.compact)
1268
    {
1269
        if (ascii->state.ascii)
1270
            data = (ascii + 1);
1271
        else
1272
            data = (compact + 1);
1273
    }
1274
    else
1275
        data = unicode->data.any;
1276
    printf("%s: len=%zu, ", unicode_kind_name(op), ascii->length);
1277
1278
    if (!ascii->state.ascii) {
1279
        printf("utf8=%p (%zu)", (void *)compact->utf8, compact->utf8_length);
1280
    }
1281
    printf(", data=%p\n", data);
1282
}
1283
#endif
1284
1285
1286
PyObject *
1287
PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1288
568M
{
1289
    /* Optimization for empty strings */
1290
568M
    if (size == 0) {
1291
28.8M
        return _PyUnicode_GetEmpty();
1292
28.8M
    }
1293
1294
540M
    PyObject *obj;
1295
540M
    PyCompactUnicodeObject *unicode;
1296
540M
    void *data;
1297
540M
    int kind;
1298
540M
    int is_ascii;
1299
540M
    Py_ssize_t char_size;
1300
540M
    Py_ssize_t struct_size;
1301
1302
540M
    is_ascii = 0;
1303
540M
    struct_size = sizeof(PyCompactUnicodeObject);
1304
540M
    if (maxchar < 128) {
1305
349M
        kind = PyUnicode_1BYTE_KIND;
1306
349M
        char_size = 1;
1307
349M
        is_ascii = 1;
1308
349M
        struct_size = sizeof(PyASCIIObject);
1309
349M
    }
1310
190M
    else if (maxchar < 256) {
1311
14.4M
        kind = PyUnicode_1BYTE_KIND;
1312
14.4M
        char_size = 1;
1313
14.4M
    }
1314
176M
    else if (maxchar < 65536) {
1315
166M
        kind = PyUnicode_2BYTE_KIND;
1316
166M
        char_size = 2;
1317
166M
    }
1318
9.95M
    else {
1319
9.95M
        if (maxchar > MAX_UNICODE) {
1320
0
            PyErr_SetString(PyExc_SystemError,
1321
0
                            "invalid maximum character passed to PyUnicode_New");
1322
0
            return NULL;
1323
0
        }
1324
9.95M
        kind = PyUnicode_4BYTE_KIND;
1325
9.95M
        char_size = 4;
1326
9.95M
    }
1327
1328
    /* Ensure we won't overflow the size. */
1329
540M
    if (size < 0) {
1330
0
        PyErr_SetString(PyExc_SystemError,
1331
0
                        "Negative size passed to PyUnicode_New");
1332
0
        return NULL;
1333
0
    }
1334
540M
    if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1335
0
        return PyErr_NoMemory();
1336
1337
    /* Duplicated allocation code from _PyObject_New() instead of a call to
1338
     * PyObject_New() so we are able to allocate space for the object and
1339
     * it's data buffer.
1340
     */
1341
540M
    obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
1342
540M
    if (obj == NULL) {
1343
0
        return PyErr_NoMemory();
1344
0
    }
1345
540M
    _PyObject_Init(obj, &PyUnicode_Type);
1346
1347
540M
    unicode = (PyCompactUnicodeObject *)obj;
1348
540M
    if (is_ascii)
1349
349M
        data = ((PyASCIIObject*)obj) + 1;
1350
190M
    else
1351
190M
        data = unicode + 1;
1352
540M
    _PyUnicode_LENGTH(unicode) = size;
1353
540M
    _PyUnicode_HASH(unicode) = -1;
1354
540M
    _PyUnicode_STATE(unicode).interned = 0;
1355
540M
    _PyUnicode_STATE(unicode).kind = kind;
1356
540M
    _PyUnicode_STATE(unicode).compact = 1;
1357
540M
    _PyUnicode_STATE(unicode).ascii = is_ascii;
1358
540M
    _PyUnicode_STATE(unicode).statically_allocated = 0;
1359
540M
    if (is_ascii) {
1360
349M
        ((char*)data)[size] = 0;
1361
349M
    }
1362
190M
    else if (kind == PyUnicode_1BYTE_KIND) {
1363
14.4M
        ((char*)data)[size] = 0;
1364
14.4M
        unicode->utf8 = NULL;
1365
14.4M
        unicode->utf8_length = 0;
1366
14.4M
    }
1367
176M
    else {
1368
176M
        unicode->utf8 = NULL;
1369
176M
        unicode->utf8_length = 0;
1370
176M
        if (kind == PyUnicode_2BYTE_KIND)
1371
166M
            ((Py_UCS2*)data)[size] = 0;
1372
9.95M
        else /* kind == PyUnicode_4BYTE_KIND */
1373
9.95M
            ((Py_UCS4*)data)[size] = 0;
1374
176M
    }
1375
#ifdef Py_DEBUG
1376
    unicode_fill_invalid((PyObject*)unicode, 0);
1377
#endif
1378
540M
    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
1379
540M
    return obj;
1380
540M
}
1381
1382
static int
1383
unicode_check_modifiable(PyObject *unicode)
1384
583
{
1385
583
    if (!_PyUnicode_IsModifiable(unicode)) {
1386
0
        PyErr_SetString(PyExc_SystemError,
1387
0
                        "Cannot modify a string currently used");
1388
0
        return -1;
1389
0
    }
1390
583
    return 0;
1391
583
}
1392
1393
static int
1394
_copy_characters(PyObject *to, Py_ssize_t to_start,
1395
                 PyObject *from, Py_ssize_t from_start,
1396
                 Py_ssize_t how_many, int check_maxchar)
1397
272M
{
1398
272M
    int from_kind, to_kind;
1399
272M
    const void *from_data;
1400
272M
    void *to_data;
1401
1402
272M
    assert(0 <= how_many);
1403
272M
    assert(0 <= from_start);
1404
272M
    assert(0 <= to_start);
1405
272M
    assert(PyUnicode_Check(from));
1406
272M
    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
1407
1408
272M
    assert(to == NULL || PyUnicode_Check(to));
1409
1410
272M
    if (how_many == 0) {
1411
3.11M
        return 0;
1412
3.11M
    }
1413
1414
272M
    assert(to != NULL);
1415
269M
    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1416
1417
269M
    from_kind = PyUnicode_KIND(from);
1418
269M
    from_data = PyUnicode_DATA(from);
1419
269M
    to_kind = PyUnicode_KIND(to);
1420
269M
    to_data = PyUnicode_DATA(to);
1421
1422
#ifdef Py_DEBUG
1423
    if (!check_maxchar
1424
        && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1425
    {
1426
        Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1427
        Py_UCS4 ch;
1428
        Py_ssize_t i;
1429
        for (i=0; i < how_many; i++) {
1430
            ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1431
            assert(ch <= to_maxchar);
1432
        }
1433
    }
1434
#endif
1435
1436
269M
    if (from_kind == to_kind) {
1437
170M
        if (check_maxchar
1438
0
            && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1439
0
        {
1440
            /* Writing Latin-1 characters into an ASCII string requires to
1441
               check that all written characters are pure ASCII */
1442
0
            Py_UCS4 max_char;
1443
0
            max_char = ucs1lib_find_max_char(from_data,
1444
0
                                             (const Py_UCS1*)from_data + how_many);
1445
0
            if (max_char >= 128)
1446
0
                return -1;
1447
0
        }
1448
170M
        memcpy((char*)to_data + to_kind * to_start,
1449
170M
                  (const char*)from_data + from_kind * from_start,
1450
170M
                  to_kind * how_many);
1451
170M
    }
1452
99.6M
    else if (from_kind == PyUnicode_1BYTE_KIND
1453
96.0M
             && to_kind == PyUnicode_2BYTE_KIND)
1454
84.0M
    {
1455
84.0M
        _PyUnicode_CONVERT_BYTES(
1456
84.0M
            Py_UCS1, Py_UCS2,
1457
84.0M
            PyUnicode_1BYTE_DATA(from) + from_start,
1458
84.0M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1459
84.0M
            PyUnicode_2BYTE_DATA(to) + to_start
1460
84.0M
            );
1461
84.0M
    }
1462
15.6M
    else if (from_kind == PyUnicode_1BYTE_KIND
1463
12.0M
             && to_kind == PyUnicode_4BYTE_KIND)
1464
12.0M
    {
1465
12.0M
        _PyUnicode_CONVERT_BYTES(
1466
12.0M
            Py_UCS1, Py_UCS4,
1467
12.0M
            PyUnicode_1BYTE_DATA(from) + from_start,
1468
12.0M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1469
12.0M
            PyUnicode_4BYTE_DATA(to) + to_start
1470
12.0M
            );
1471
12.0M
    }
1472
3.56M
    else if (from_kind == PyUnicode_2BYTE_KIND
1473
3.54M
             && to_kind == PyUnicode_4BYTE_KIND)
1474
3.54M
    {
1475
3.54M
        _PyUnicode_CONVERT_BYTES(
1476
3.54M
            Py_UCS2, Py_UCS4,
1477
3.54M
            PyUnicode_2BYTE_DATA(from) + from_start,
1478
3.54M
            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1479
3.54M
            PyUnicode_4BYTE_DATA(to) + to_start
1480
3.54M
            );
1481
3.54M
    }
1482
18.2k
    else {
1483
18.2k
        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1484
1485
18.2k
        if (!check_maxchar) {
1486
18.2k
            if (from_kind == PyUnicode_2BYTE_KIND
1487
2.53k
                && to_kind == PyUnicode_1BYTE_KIND)
1488
2.53k
            {
1489
2.53k
                _PyUnicode_CONVERT_BYTES(
1490
2.53k
                    Py_UCS2, Py_UCS1,
1491
2.53k
                    PyUnicode_2BYTE_DATA(from) + from_start,
1492
2.53k
                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1493
2.53k
                    PyUnicode_1BYTE_DATA(to) + to_start
1494
2.53k
                    );
1495
2.53k
            }
1496
15.6k
            else if (from_kind == PyUnicode_4BYTE_KIND
1497
15.6k
                     && to_kind == PyUnicode_1BYTE_KIND)
1498
6.83k
            {
1499
6.83k
                _PyUnicode_CONVERT_BYTES(
1500
6.83k
                    Py_UCS4, Py_UCS1,
1501
6.83k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1502
6.83k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1503
6.83k
                    PyUnicode_1BYTE_DATA(to) + to_start
1504
6.83k
                    );
1505
6.83k
            }
1506
8.84k
            else if (from_kind == PyUnicode_4BYTE_KIND
1507
8.84k
                     && to_kind == PyUnicode_2BYTE_KIND)
1508
8.84k
            {
1509
8.84k
                _PyUnicode_CONVERT_BYTES(
1510
8.84k
                    Py_UCS4, Py_UCS2,
1511
8.84k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1512
8.84k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1513
8.84k
                    PyUnicode_2BYTE_DATA(to) + to_start
1514
8.84k
                    );
1515
8.84k
            }
1516
0
            else {
1517
0
                Py_UNREACHABLE();
1518
0
            }
1519
18.2k
        }
1520
0
        else {
1521
0
            const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1522
0
            Py_UCS4 ch;
1523
0
            Py_ssize_t i;
1524
1525
0
            for (i=0; i < how_many; i++) {
1526
0
                ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1527
0
                if (ch > to_maxchar)
1528
0
                    return -1;
1529
0
                PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1530
0
            }
1531
0
        }
1532
18.2k
    }
1533
269M
    return 0;
1534
269M
}
1535
1536
void
1537
_PyUnicode_FastCopyCharacters(
1538
    PyObject *to, Py_ssize_t to_start,
1539
    PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
1540
272M
{
1541
272M
    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1542
272M
}
1543
1544
Py_ssize_t
1545
PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1546
                         PyObject *from, Py_ssize_t from_start,
1547
                         Py_ssize_t how_many)
1548
0
{
1549
0
    int err;
1550
1551
0
    if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1552
0
        PyErr_BadInternalCall();
1553
0
        return -1;
1554
0
    }
1555
1556
0
    if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
1557
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
1558
0
        return -1;
1559
0
    }
1560
0
    if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
1561
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
1562
0
        return -1;
1563
0
    }
1564
0
    if (how_many < 0) {
1565
0
        PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1566
0
        return -1;
1567
0
    }
1568
0
    how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
1569
0
    if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1570
0
        PyErr_Format(PyExc_SystemError,
1571
0
                     "Cannot write %zi characters at %zi "
1572
0
                     "in a string of %zi characters",
1573
0
                     how_many, to_start, PyUnicode_GET_LENGTH(to));
1574
0
        return -1;
1575
0
    }
1576
1577
0
    if (how_many == 0)
1578
0
        return 0;
1579
1580
0
    if (unicode_check_modifiable(to))
1581
0
        return -1;
1582
1583
0
    err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1584
0
    if (err) {
1585
0
        PyErr_Format(PyExc_SystemError,
1586
0
                     "Cannot copy %s characters "
1587
0
                     "into a string of %s characters",
1588
0
                     unicode_kind_name(from),
1589
0
                     unicode_kind_name(to));
1590
0
        return -1;
1591
0
    }
1592
0
    return how_many;
1593
0
}
1594
1595
1596
static void
1597
unicode_invalid_character(PyObject *exc, Py_UCS4 ch)
1598
0
{
1599
0
    PyErr_Format(exc,
1600
0
                 "character U+%x is not in range [U+0000; U+%x]",
1601
0
                 ch, MAX_UNICODE);
1602
0
}
1603
1604
1605
/* Find the maximum code point and count the number of surrogate pairs so a
1606
   correct string length can be computed before converting a string to UCS4.
1607
   This function counts single surrogates as a character and not as a pair.
1608
1609
   Return 0 on success, or -1 on error. */
1610
static int
1611
find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1612
                        Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
1613
367k
{
1614
367k
    const wchar_t *iter;
1615
367k
    Py_UCS4 ch;
1616
1617
367k
    assert(num_surrogates != NULL && maxchar != NULL);
1618
367k
    *num_surrogates = 0;
1619
367k
    *maxchar = 0;
1620
1621
10.9M
    for (iter = begin; iter < end; ) {
1622
#if SIZEOF_WCHAR_T == 2
1623
        if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1624
            && (iter+1) < end
1625
            && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1626
        {
1627
            ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1628
            ++(*num_surrogates);
1629
            iter += 2;
1630
        }
1631
        else
1632
#endif
1633
10.5M
        {
1634
10.5M
            ch = *iter;
1635
10.5M
            iter++;
1636
10.5M
        }
1637
10.5M
        if (ch > *maxchar) {
1638
1.50M
            *maxchar = ch;
1639
1.50M
            if (*maxchar > MAX_UNICODE) {
1640
0
                unicode_invalid_character(PyExc_ValueError, ch);
1641
0
                return -1;
1642
0
            }
1643
1.50M
        }
1644
10.5M
    }
1645
367k
    return 0;
1646
367k
}
1647
1648
static void
1649
unicode_dealloc(PyObject *unicode)
1650
556M
{
1651
#ifdef Py_DEBUG
1652
    if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
1653
        _Py_FatalRefcountError("deallocating an Unicode singleton");
1654
    }
1655
#endif
1656
556M
    if (_PyUnicode_STATE(unicode).statically_allocated) {
1657
        /* This should never get called, but we also don't want to SEGV if
1658
        * we accidentally decref an immortal string out of existence. Since
1659
        * the string is an immortal object, just re-set the reference count.
1660
        */
1661
#ifdef Py_DEBUG
1662
        Py_UNREACHABLE();
1663
#endif
1664
0
        _Py_SetImmortal(unicode);
1665
0
        return;
1666
0
    }
1667
556M
    switch (_PyUnicode_STATE(unicode).interned) {
1668
555M
        case SSTATE_NOT_INTERNED:
1669
555M
            break;
1670
213k
        case SSTATE_INTERNED_MORTAL:
1671
            /* Remove the object from the intern dict.
1672
             * Before doing so, we set the refcount to 2: the key and value
1673
             * in the interned_dict.
1674
             */
1675
213k
            assert(Py_REFCNT(unicode) == 0);
1676
213k
            Py_SET_REFCNT(unicode, 2);
1677
#ifdef Py_REF_DEBUG
1678
            /* let's be pedantic with the ref total */
1679
            _Py_IncRefTotal(_PyThreadState_GET());
1680
            _Py_IncRefTotal(_PyThreadState_GET());
1681
#endif
1682
213k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1683
213k
            PyObject *interned = get_interned_dict(interp);
1684
213k
            assert(interned != NULL);
1685
213k
            PyObject *popped;
1686
213k
            int r = PyDict_Pop(interned, unicode, &popped);
1687
213k
            if (r == -1) {
1688
0
                PyErr_FormatUnraisable("Exception ignored while "
1689
0
                                       "removing an interned string %R",
1690
0
                                       unicode);
1691
                // We don't know what happened to the string. It's probably
1692
                // best to leak it:
1693
                // - if it was popped, there are no more references to it
1694
                //   so it can't cause trouble (except wasted memory)
1695
                // - if it wasn't popped, it'll remain interned
1696
0
                _Py_SetImmortal(unicode);
1697
0
                _PyUnicode_STATE(unicode).interned = SSTATE_INTERNED_IMMORTAL;
1698
0
                return;
1699
0
            }
1700
213k
            if (r == 0) {
1701
                // The interned string was not found in the interned_dict.
1702
#ifdef Py_DEBUG
1703
                Py_UNREACHABLE();
1704
#endif
1705
0
                _Py_SetImmortal(unicode);
1706
0
                return;
1707
0
            }
1708
            // Successfully popped.
1709
213k
            assert(popped == unicode);
1710
            // Only our `popped` reference should be left; remove it too.
1711
213k
            assert(Py_REFCNT(unicode) == 1);
1712
213k
            Py_SET_REFCNT(unicode, 0);
1713
#ifdef Py_REF_DEBUG
1714
            /* let's be pedantic with the ref total */
1715
            _Py_DecRefTotal(_PyThreadState_GET());
1716
#endif
1717
213k
            break;
1718
0
        default:
1719
            // As with `statically_allocated` above.
1720
#ifdef Py_REF_DEBUG
1721
            Py_UNREACHABLE();
1722
#endif
1723
0
            _Py_SetImmortal(unicode);
1724
0
            return;
1725
556M
    }
1726
556M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1727
174k
        PyMem_Free(_PyUnicode_UTF8(unicode));
1728
174k
    }
1729
556M
    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
1730
17.2M
        PyMem_Free(_PyUnicode_DATA_ANY(unicode));
1731
17.2M
    }
1732
1733
556M
    Py_TYPE(unicode)->tp_free(unicode);
1734
556M
}
1735
1736
#ifdef Py_DEBUG
1737
static int
1738
unicode_is_singleton(PyObject *unicode)
1739
{
1740
    if (unicode == &_Py_STR(empty)) {
1741
        return 1;
1742
    }
1743
1744
    PyASCIIObject *ascii = _PyASCIIObject_CAST(unicode);
1745
    if (ascii->length == 1) {
1746
        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1747
        if (ch < 256 && LATIN1(ch) == unicode) {
1748
            return 1;
1749
        }
1750
    }
1751
    return 0;
1752
}
1753
#endif
1754
1755
// If this function is updated, update also _PyUnicodeWriter_CanWrite().
1756
int
1757
_PyUnicode_IsModifiable(PyObject *unicode)
1758
64.2M
{
1759
64.2M
    assert(_PyUnicode_CHECK(unicode));
1760
64.2M
    if (!PyUnicode_CheckExact(unicode))
1761
0
        return 0;
1762
    // On Free Threading, this test fails if called from a thread other
1763
    // than the one which created the str object.
1764
64.2M
    if (!_PyObject_IsUniquelyReferenced(unicode))
1765
4.57M
        return 0;
1766
59.6M
    if (PyUnicode_HASH(unicode) != -1)
1767
0
        return 0;
1768
59.6M
    if (PyUnicode_CHECK_INTERNED(unicode))
1769
0
        return 0;
1770
#ifdef Py_DEBUG
1771
    /* singleton refcount is greater than 1 */
1772
    assert(!unicode_is_singleton(unicode));
1773
#endif
1774
59.6M
    return 1;
1775
59.6M
}
1776
1777
static int
1778
unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1779
3.28M
{
1780
3.28M
    PyObject *unicode;
1781
3.28M
    Py_ssize_t old_length;
1782
1783
3.28M
    assert(p_unicode != NULL);
1784
3.28M
    unicode = *p_unicode;
1785
1786
3.28M
    assert(unicode != NULL);
1787
3.28M
    assert(PyUnicode_Check(unicode));
1788
3.28M
    assert(0 <= length);
1789
1790
3.28M
    old_length = PyUnicode_GET_LENGTH(unicode);
1791
3.28M
    if (old_length == length)
1792
0
        return 0;
1793
1794
3.28M
    if (length == 0) {
1795
0
        PyObject *empty = _PyUnicode_GetEmpty();
1796
0
        Py_SETREF(*p_unicode, empty);
1797
0
        return 0;
1798
0
    }
1799
1800
3.28M
    if (!_PyUnicode_IsModifiable(unicode)) {
1801
0
        PyObject *copy = resize_copy(unicode, length);
1802
0
        if (copy == NULL)
1803
0
            return -1;
1804
0
        Py_SETREF(*p_unicode, copy);
1805
0
        return 0;
1806
0
    }
1807
1808
3.28M
    if (PyUnicode_IS_COMPACT(unicode)) {
1809
3.28M
        PyObject *new_unicode = _PyUnicode_ResizeCompact(unicode, length);
1810
3.28M
        if (new_unicode == NULL)
1811
0
            return -1;
1812
3.28M
        *p_unicode = new_unicode;
1813
3.28M
        return 0;
1814
3.28M
    }
1815
0
    return resize_inplace(unicode, length);
1816
3.28M
}
1817
1818
int
1819
PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
1820
0
{
1821
0
    PyObject *unicode;
1822
0
    if (p_unicode == NULL) {
1823
0
        PyErr_BadInternalCall();
1824
0
        return -1;
1825
0
    }
1826
0
    unicode = *p_unicode;
1827
0
    if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
1828
0
    {
1829
0
        PyErr_BadInternalCall();
1830
0
        return -1;
1831
0
    }
1832
0
    return unicode_resize(p_unicode, length);
1833
0
}
1834
1835
static PyObject*
1836
get_latin1_char(Py_UCS1 ch)
1837
303M
{
1838
303M
    PyObject *o = LATIN1(ch);
1839
303M
    return o;
1840
303M
}
1841
1842
static PyObject*
1843
unicode_char(Py_UCS4 ch)
1844
336M
{
1845
336M
    if (ch < 256) {
1846
212M
        return get_latin1_char(ch);
1847
212M
    }
1848
1849
    // Raise SystemError if the character is not in range [U+0000; MAX_UNICODE]
1850
123M
    PyObject *unicode = PyUnicode_New(1, ch);
1851
123M
    if (unicode == NULL) {
1852
0
        return NULL;
1853
0
    }
1854
1855
123M
    assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1856
123M
    if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
1857
117M
        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1858
117M
    } else {
1859
6.07M
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1860
6.07M
        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1861
6.07M
    }
1862
123M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
1863
123M
    return unicode;
1864
123M
}
1865
1866
1867
static inline void
1868
unicode_write_widechar(int kind, void *data,
1869
                       const wchar_t *u, Py_ssize_t size,
1870
                       Py_ssize_t num_surrogates)
1871
367k
{
1872
367k
    switch (kind) {
1873
341k
    case PyUnicode_1BYTE_KIND:
1874
341k
        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, u, u + size, data);
1875
341k
        break;
1876
1877
24.8k
    case PyUnicode_2BYTE_KIND:
1878
#if SIZEOF_WCHAR_T == 2
1879
        memcpy(data, u, size * 2);
1880
#else
1881
24.8k
        _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2, u, u + size, data);
1882
24.8k
#endif
1883
24.8k
        break;
1884
1885
1.41k
    case PyUnicode_4BYTE_KIND:
1886
1.41k
    {
1887
#if SIZEOF_WCHAR_T == 2
1888
        // Convert a 16-bits wchar_t representation to UCS4, this will decode
1889
        // surrogate pairs.
1890
        const wchar_t *end = u + size;
1891
        Py_UCS4 *ucs4_out = (Py_UCS4*)data;
1892
#  ifndef NDEBUG
1893
        Py_UCS4 *ucs4_end = (Py_UCS4*)data + (size - num_surrogates);
1894
#  endif
1895
        for (const wchar_t *iter = u; iter < end; ) {
1896
            assert(ucs4_out < ucs4_end);
1897
            if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1898
                && (iter+1) < end
1899
                && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1900
            {
1901
                *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1902
                iter += 2;
1903
            }
1904
            else {
1905
                *ucs4_out++ = *iter;
1906
                iter++;
1907
            }
1908
        }
1909
        assert(ucs4_out == ucs4_end);
1910
#else
1911
1.41k
        assert(num_surrogates == 0);
1912
1.41k
        memcpy(data, u, size * 4);
1913
1.41k
#endif
1914
1.41k
        break;
1915
0
    }
1916
0
    default:
1917
0
        Py_UNREACHABLE();
1918
367k
    }
1919
367k
}
1920
1921
1922
PyObject *
1923
PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
1924
672k
{
1925
672k
    PyObject *unicode;
1926
672k
    Py_UCS4 maxchar = 0;
1927
672k
    Py_ssize_t num_surrogates;
1928
1929
672k
    if (u == NULL && size != 0) {
1930
0
        PyErr_BadInternalCall();
1931
0
        return NULL;
1932
0
    }
1933
1934
672k
    if (size == -1) {
1935
1.29k
        size = wcslen(u);
1936
1.29k
    }
1937
1938
    /* If the Unicode data is known at construction time, we can apply
1939
       some optimizations which share commonly used objects. */
1940
1941
    /* Optimization for empty strings */
1942
672k
    if (size == 0)
1943
242k
        _Py_RETURN_UNICODE_EMPTY();
1944
1945
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
1946
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
1947
       non-Unicode locales and hence needs conversion to UCS-4 first. */
1948
    if (_Py_LocaleUsesNonUnicodeWchar()) {
1949
        wchar_t* converted = _Py_DecodeNonUnicodeWchar(u, size);
1950
        if (!converted) {
1951
            return NULL;
1952
        }
1953
        PyObject *unicode = _PyUnicode_FromUCS4(converted, size);
1954
        PyMem_Free(converted);
1955
        return unicode;
1956
    }
1957
#endif
1958
1959
    /* Single character Unicode objects in the Latin-1 range are
1960
       shared when using this constructor */
1961
429k
    if (size == 1 && (Py_UCS4)*u < 256)
1962
62.4k
        return get_latin1_char((unsigned char)*u);
1963
1964
    /* If not empty and not single character, copy the Unicode data
1965
       into the new object */
1966
367k
    if (find_maxchar_surrogates(u, u + size,
1967
367k
                                &maxchar, &num_surrogates) == -1)
1968
0
        return NULL;
1969
1970
367k
    unicode = PyUnicode_New(size - num_surrogates, maxchar);
1971
367k
    if (!unicode)
1972
0
        return NULL;
1973
1974
367k
    unicode_write_widechar(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1975
367k
                           u, size, num_surrogates);
1976
1977
367k
    return unicode_result(unicode);
1978
367k
}
1979
1980
1981
int
1982
PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *pub_writer,
1983
                              const wchar_t *str,
1984
                              Py_ssize_t size)
1985
0
{
1986
0
    _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer;
1987
1988
0
    if (size < 0) {
1989
0
        size = wcslen(str);
1990
0
    }
1991
1992
0
    if (size == 0) {
1993
0
        return 0;
1994
0
    }
1995
1996
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
1997
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
1998
       non-Unicode locales and hence needs conversion to UCS-4 first. */
1999
    if (_Py_LocaleUsesNonUnicodeWchar()) {
2000
        wchar_t* converted = _Py_DecodeNonUnicodeWchar(str, size);
2001
        if (!converted) {
2002
            return -1;
2003
        }
2004
2005
        int res = PyUnicodeWriter_WriteUCS4(pub_writer, converted, size);
2006
        PyMem_Free(converted);
2007
        return res;
2008
    }
2009
#endif
2010
2011
0
    Py_UCS4 maxchar = 0;
2012
0
    Py_ssize_t num_surrogates;
2013
0
    if (find_maxchar_surrogates(str, str + size,
2014
0
                                &maxchar, &num_surrogates) == -1) {
2015
0
        return -1;
2016
0
    }
2017
2018
0
    if (_PyUnicodeWriter_Prepare(writer, size - num_surrogates, maxchar) < 0) {
2019
0
        return -1;
2020
0
    }
2021
0
    assert(_PyUnicodeWriter_CanWrite(writer));
2022
2023
0
    int kind = writer->kind;
2024
0
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2025
0
    unicode_write_widechar(kind, data, str, size, num_surrogates);
2026
2027
0
    writer->pos += size - num_surrogates;
2028
0
    return 0;
2029
0
}
2030
2031
2032
PyObject *
2033
PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
2034
12.0M
{
2035
12.0M
    if (size < 0) {
2036
0
        PyErr_SetString(PyExc_SystemError,
2037
0
                        "Negative size passed to PyUnicode_FromStringAndSize");
2038
0
        return NULL;
2039
0
    }
2040
12.0M
    if (u != NULL) {
2041
12.0M
        return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2042
12.0M
    }
2043
0
    if (size > 0) {
2044
0
        PyErr_SetString(PyExc_SystemError,
2045
0
            "NULL string with positive size with NULL passed to PyUnicode_FromStringAndSize");
2046
0
        return NULL;
2047
0
    }
2048
0
    return _PyUnicode_GetEmpty();
2049
0
}
2050
2051
PyObject *
2052
PyUnicode_FromString(const char *u)
2053
37.4M
{
2054
37.4M
    size_t size = strlen(u);
2055
37.4M
    if (size > PY_SSIZE_T_MAX) {
2056
0
        PyErr_SetString(PyExc_OverflowError, "input too long");
2057
0
        return NULL;
2058
0
    }
2059
37.4M
    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
2060
37.4M
}
2061
2062
2063
PyObject *
2064
_PyUnicode_FromId(_Py_Identifier *id)
2065
0
{
2066
0
    PyMutex_Lock((PyMutex *)&id->mutex);
2067
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2068
0
    struct _Py_unicode_ids *ids = &interp->unicode.ids;
2069
2070
0
    Py_ssize_t index = _Py_atomic_load_ssize(&id->index);
2071
0
    if (index < 0) {
2072
0
        struct _Py_unicode_runtime_ids *rt_ids = &interp->runtime->unicode_state.ids;
2073
2074
0
        PyMutex_Lock(&rt_ids->mutex);
2075
        // Check again to detect concurrent access. Another thread can have
2076
        // initialized the index while this thread waited for the lock.
2077
0
        index = _Py_atomic_load_ssize(&id->index);
2078
0
        if (index < 0) {
2079
0
            assert(rt_ids->next_index < PY_SSIZE_T_MAX);
2080
0
            index = rt_ids->next_index;
2081
0
            rt_ids->next_index++;
2082
0
            _Py_atomic_store_ssize(&id->index, index);
2083
0
        }
2084
0
        PyMutex_Unlock(&rt_ids->mutex);
2085
0
    }
2086
0
    assert(index >= 0);
2087
2088
0
    PyObject *obj;
2089
0
    if (index < ids->size) {
2090
0
        obj = ids->array[index];
2091
0
        if (obj) {
2092
            // Return a borrowed reference
2093
0
            goto end;
2094
0
        }
2095
0
    }
2096
2097
0
    obj = PyUnicode_DecodeUTF8Stateful(id->string, strlen(id->string),
2098
0
                                       NULL, NULL);
2099
0
    if (!obj) {
2100
0
        goto end;
2101
0
    }
2102
0
    _PyUnicode_InternImmortal(interp, &obj);
2103
2104
0
    if (index >= ids->size) {
2105
        // Overallocate to reduce the number of realloc
2106
0
        Py_ssize_t new_size = Py_MAX(index * 2, 16);
2107
0
        Py_ssize_t item_size = sizeof(ids->array[0]);
2108
0
        PyObject **new_array = PyMem_Realloc(ids->array, new_size * item_size);
2109
0
        if (new_array == NULL) {
2110
0
            PyErr_NoMemory();
2111
0
            obj = NULL;
2112
0
            goto end;
2113
0
        }
2114
0
        memset(&new_array[ids->size], 0, (new_size - ids->size) * item_size);
2115
0
        ids->array = new_array;
2116
0
        ids->size = new_size;
2117
0
    }
2118
2119
    // The array stores a strong reference
2120
0
    ids->array[index] = obj;
2121
2122
0
end:
2123
0
    PyMutex_Unlock((PyMutex *)&id->mutex);
2124
    // Return a borrowed reference
2125
0
    return obj;
2126
0
}
2127
2128
2129
static void
2130
unicode_clear_identifiers(struct _Py_unicode_state *state)
2131
0
{
2132
0
    struct _Py_unicode_ids *ids = &state->ids;
2133
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
2134
0
        Py_XDECREF(ids->array[i]);
2135
0
    }
2136
0
    ids->size = 0;
2137
0
    PyMem_Free(ids->array);
2138
0
    ids->array = NULL;
2139
    // Don't reset _PyRuntime next_index: _Py_Identifier.id remains valid
2140
    // after Py_Finalize().
2141
0
}
2142
2143
2144
/* Internal function, doesn't check maximum character */
2145
2146
PyObject*
2147
_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
2148
107M
{
2149
107M
    const unsigned char *s = (const unsigned char *)buffer;
2150
107M
    PyObject *unicode;
2151
107M
    if (size == 1) {
2152
#ifdef Py_DEBUG
2153
        assert((unsigned char)s[0] < 128);
2154
#endif
2155
35.9M
        return get_latin1_char(s[0]);
2156
35.9M
    }
2157
71.6M
    unicode = PyUnicode_New(size, 127);
2158
71.6M
    if (!unicode)
2159
0
        return NULL;
2160
71.6M
    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2161
71.6M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
2162
71.6M
    return unicode;
2163
71.6M
}
2164
2165
static Py_UCS4
2166
kind_maxchar_limit(int kind)
2167
0
{
2168
0
    switch (kind) {
2169
0
    case PyUnicode_1BYTE_KIND:
2170
0
        return 0x80;
2171
0
    case PyUnicode_2BYTE_KIND:
2172
0
        return 0x100;
2173
0
    case PyUnicode_4BYTE_KIND:
2174
0
        return 0x10000;
2175
0
    default:
2176
0
        Py_UNREACHABLE();
2177
0
    }
2178
0
}
2179
2180
static PyObject*
2181
_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
2182
53.9M
{
2183
53.9M
    PyObject *res;
2184
53.9M
    unsigned char max_char;
2185
2186
53.9M
    if (size == 0) {
2187
14.9M
        _Py_RETURN_UNICODE_EMPTY();
2188
14.9M
    }
2189
53.9M
    assert(size > 0);
2190
39.0M
    if (size == 1) {
2191
9.77M
        return get_latin1_char(u[0]);
2192
9.77M
    }
2193
2194
29.3M
    max_char = ucs1lib_find_max_char(u, u + size);
2195
29.3M
    res = PyUnicode_New(size, max_char);
2196
29.3M
    if (!res)
2197
0
        return NULL;
2198
29.3M
    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
2199
29.3M
    assert(_PyUnicode_CheckConsistency(res, 1));
2200
29.3M
    return res;
2201
29.3M
}
2202
2203
static PyObject*
2204
_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
2205
79.4M
{
2206
79.4M
    PyObject *res;
2207
79.4M
    Py_UCS2 max_char;
2208
2209
79.4M
    if (size == 0)
2210
16.7M
        _Py_RETURN_UNICODE_EMPTY();
2211
79.4M
    assert(size > 0);
2212
62.7M
    if (size == 1)
2213
43.0M
        return unicode_char(u[0]);
2214
2215
19.7M
    max_char = ucs2lib_find_max_char(u, u + size);
2216
19.7M
    res = PyUnicode_New(size, max_char);
2217
19.7M
    if (!res)
2218
0
        return NULL;
2219
19.7M
    if (max_char >= 256)
2220
14.9M
        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
2221
4.77M
    else {
2222
4.77M
        _PyUnicode_CONVERT_BYTES(
2223
4.77M
            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2224
4.77M
    }
2225
19.7M
    assert(_PyUnicode_CheckConsistency(res, 1));
2226
19.7M
    return res;
2227
19.7M
}
2228
2229
static PyObject*
2230
_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
2231
69.9M
{
2232
69.9M
    PyObject *res;
2233
2234
69.9M
    if (size == 0)
2235
15.8M
        _Py_RETURN_UNICODE_EMPTY();
2236
69.9M
    assert(size > 0);
2237
2238
54.0M
    if (size == 1) {
2239
        // Raise SystemError if the character is invalid
2240
37.8M
        return unicode_char(u[0]);
2241
37.8M
    }
2242
2243
#ifdef Py_DEBUG
2244
    // Check for invalid characters in debug mode
2245
    Py_UCS4 max_char = 127;
2246
    for (Py_ssize_t i = 0; i < size; i++) {
2247
        Py_UCS4 ch = u[i];
2248
        if (ch > max_char) {
2249
            if (ch > MAX_UNICODE) {
2250
                unicode_invalid_character(PyExc_SystemError, ch);
2251
                return NULL;
2252
            }
2253
            max_char = ch;
2254
        }
2255
    }
2256
#else
2257
    // gh-158445: Return MAX_UNICODE even if the string contains invalid
2258
    // characters. Checking for invalid characters would make the function
2259
    // slower whereas it's unlikely in practice.
2260
16.2M
    Py_UCS4 max_char = ucs4lib_find_max_char(u, u + size);
2261
16.2M
#endif
2262
2263
16.2M
    res = PyUnicode_New(size, max_char);
2264
16.2M
    if (!res)
2265
0
        return NULL;
2266
16.2M
    if (max_char < 256)
2267
9.94M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2268
16.2M
                                 PyUnicode_1BYTE_DATA(res));
2269
6.26M
    else if (max_char < 0x10000)
2270
4.74M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2271
6.26M
                                 PyUnicode_2BYTE_DATA(res));
2272
1.51M
    else
2273
1.51M
        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
2274
16.2M
    assert(_PyUnicode_CheckConsistency(res, 1));
2275
16.2M
    return res;
2276
16.2M
}
2277
2278
2279
int
2280
PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *pub_writer,
2281
                          const Py_UCS4 *str,
2282
                          Py_ssize_t size)
2283
21.7k
{
2284
21.7k
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
2285
2286
21.7k
    if (size < 0) {
2287
0
        PyErr_SetString(PyExc_ValueError,
2288
0
                        "size must be positive");
2289
0
        return -1;
2290
0
    }
2291
2292
21.7k
    if (size == 0) {
2293
0
        return 0;
2294
0
    }
2295
2296
#ifdef Py_DEBUG
2297
    // Check for invalid characters in debug mode
2298
    Py_UCS4 maxchar = 127;
2299
    for (Py_ssize_t i = 0; i < size; i++) {
2300
        Py_UCS4 ch = str[i];
2301
        if (ch > maxchar) {
2302
            if (ch > MAX_UNICODE) {
2303
                unicode_invalid_character(PyExc_SystemError, ch);
2304
                return -1;
2305
            }
2306
            maxchar = ch;
2307
        }
2308
    }
2309
#else
2310
    // gh-158445: Return MAX_UNICODE even if the string contains invalid
2311
    // characters. Checking for invalid characters would make the function
2312
    // slower whereas it's unlikely in practice.
2313
21.7k
    Py_UCS4 maxchar = ucs4lib_find_max_char(str, str + size);
2314
21.7k
#endif
2315
2316
21.7k
    if (_PyUnicodeWriter_Prepare(writer, size, maxchar) < 0) {
2317
0
        return -1;
2318
0
    }
2319
21.7k
    assert(_PyUnicodeWriter_CanWrite(writer));
2320
2321
21.7k
    int kind = writer->kind;
2322
21.7k
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2323
21.7k
    if (kind == PyUnicode_1BYTE_KIND) {
2324
5.12k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1,
2325
5.12k
                                 str, str + size,
2326
5.12k
                                 data);
2327
5.12k
    }
2328
16.6k
    else if (kind == PyUnicode_2BYTE_KIND) {
2329
16.6k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2,
2330
16.6k
                                 str, str + size,
2331
16.6k
                                 data);
2332
16.6k
    }
2333
6
    else {
2334
6
        memcpy(data, str, size * sizeof(Py_UCS4));
2335
6
    }
2336
21.7k
    writer->pos += size;
2337
2338
21.7k
    return 0;
2339
21.7k
}
2340
2341
2342
PyObject*
2343
PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2344
137M
{
2345
137M
    if (size < 0) {
2346
0
        PyErr_SetString(PyExc_ValueError, "size must be positive");
2347
0
        return NULL;
2348
0
    }
2349
137M
    switch (kind) {
2350
21.2M
    case PyUnicode_1BYTE_KIND:
2351
21.2M
        return _PyUnicode_FromUCS1(buffer, size);
2352
62.2M
    case PyUnicode_2BYTE_KIND:
2353
62.2M
        return _PyUnicode_FromUCS2(buffer, size);
2354
54.1M
    case PyUnicode_4BYTE_KIND:
2355
54.1M
        return _PyUnicode_FromUCS4(buffer, size);
2356
0
    default:
2357
0
        PyErr_SetString(PyExc_SystemError, "invalid kind");
2358
0
        return NULL;
2359
137M
    }
2360
137M
}
2361
2362
Py_UCS4
2363
_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2364
11.9M
{
2365
11.9M
    int kind;
2366
11.9M
    const void *startptr, *endptr;
2367
2368
11.9M
    assert(0 <= start);
2369
11.9M
    assert(end <= PyUnicode_GET_LENGTH(unicode));
2370
11.9M
    assert(start <= end);
2371
2372
11.9M
    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2373
27.8k
        return PyUnicode_MAX_CHAR_VALUE(unicode);
2374
2375
11.9M
    if (start == end)
2376
0
        return 127;
2377
2378
11.9M
    if (PyUnicode_IS_ASCII(unicode))
2379
11.8M
        return 127;
2380
2381
32.7k
    kind = PyUnicode_KIND(unicode);
2382
32.7k
    startptr = PyUnicode_DATA(unicode);
2383
32.7k
    endptr = (char *)startptr + end * kind;
2384
32.7k
    startptr = (char *)startptr + start * kind;
2385
32.7k
    switch(kind) {
2386
1.67k
    case PyUnicode_1BYTE_KIND:
2387
1.67k
        return ucs1lib_find_max_char(startptr, endptr);
2388
4.91k
    case PyUnicode_2BYTE_KIND:
2389
4.91k
        return ucs2lib_find_max_char(startptr, endptr);
2390
26.1k
    case PyUnicode_4BYTE_KIND:
2391
26.1k
        return ucs4lib_find_max_char(startptr, endptr);
2392
0
    default:
2393
0
        Py_UNREACHABLE();
2394
32.7k
    }
2395
32.7k
}
2396
2397
/* Ensure that a string uses the most efficient storage, if it is not the
2398
   case: create a new string with of the right kind. Write NULL into *p_unicode
2399
   on error. */
2400
static void
2401
unicode_adjust_maxchar(PyObject **p_unicode)
2402
0
{
2403
0
    PyObject *unicode, *copy;
2404
0
    Py_UCS4 max_char;
2405
0
    Py_ssize_t len;
2406
0
    int kind;
2407
2408
0
    assert(p_unicode != NULL);
2409
0
    unicode = *p_unicode;
2410
0
    if (PyUnicode_IS_ASCII(unicode))
2411
0
        return;
2412
2413
0
    len = PyUnicode_GET_LENGTH(unicode);
2414
0
    kind = PyUnicode_KIND(unicode);
2415
0
    if (kind == PyUnicode_1BYTE_KIND) {
2416
0
        const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
2417
0
        max_char = ucs1lib_find_max_char(u, u + len);
2418
0
        if (max_char >= 128)
2419
0
            return;
2420
0
    }
2421
0
    else if (kind == PyUnicode_2BYTE_KIND) {
2422
0
        const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
2423
0
        max_char = ucs2lib_find_max_char(u, u + len);
2424
0
        if (max_char >= 256)
2425
0
            return;
2426
0
    }
2427
0
    else if (kind == PyUnicode_4BYTE_KIND) {
2428
0
        const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
2429
0
        max_char = ucs4lib_find_max_char(u, u + len);
2430
0
        if (max_char >= 0x10000)
2431
0
            return;
2432
0
    }
2433
0
    else
2434
0
        Py_UNREACHABLE();
2435
2436
0
    copy = PyUnicode_New(len, max_char);
2437
0
    if (copy != NULL)
2438
0
        _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
2439
0
    Py_DECREF(unicode);
2440
0
    *p_unicode = copy;
2441
0
}
2442
2443
PyObject*
2444
_PyUnicode_Copy(PyObject *unicode)
2445
2.76M
{
2446
2.76M
    Py_ssize_t length;
2447
2.76M
    PyObject *copy;
2448
2449
2.76M
    if (!PyUnicode_Check(unicode)) {
2450
0
        PyErr_BadInternalCall();
2451
0
        return NULL;
2452
0
    }
2453
2454
2.76M
    length = PyUnicode_GET_LENGTH(unicode);
2455
2.76M
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
2456
2.76M
    if (!copy)
2457
0
        return NULL;
2458
2.76M
    assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2459
2460
2.76M
    memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2461
2.76M
              length * PyUnicode_KIND(unicode));
2462
2.76M
    assert(_PyUnicode_CheckConsistency(copy, 1));
2463
2.76M
    return copy;
2464
2.76M
}
2465
2466
2467
/* Widen Unicode objects to larger buffers. Don't write terminating null
2468
   character. Return NULL on error. */
2469
2470
static void*
2471
unicode_askind(int skind, void const *data, Py_ssize_t len, int kind)
2472
1.35M
{
2473
1.35M
    void *result;
2474
2475
1.35M
    assert(skind < kind);
2476
1.35M
    switch (kind) {
2477
1.17M
    case PyUnicode_2BYTE_KIND:
2478
1.17M
        result = PyMem_New(Py_UCS2, len);
2479
1.17M
        if (!result)
2480
0
            return PyErr_NoMemory();
2481
1.17M
        assert(skind == PyUnicode_1BYTE_KIND);
2482
1.17M
        _PyUnicode_CONVERT_BYTES(
2483
1.17M
            Py_UCS1, Py_UCS2,
2484
1.17M
            (const Py_UCS1 *)data,
2485
1.17M
            ((const Py_UCS1 *)data) + len,
2486
1.17M
            result);
2487
1.17M
        return result;
2488
189k
    case PyUnicode_4BYTE_KIND:
2489
189k
        result = PyMem_New(Py_UCS4, len);
2490
189k
        if (!result)
2491
0
            return PyErr_NoMemory();
2492
189k
        if (skind == PyUnicode_2BYTE_KIND) {
2493
0
            _PyUnicode_CONVERT_BYTES(
2494
0
                Py_UCS2, Py_UCS4,
2495
0
                (const Py_UCS2 *)data,
2496
0
                ((const Py_UCS2 *)data) + len,
2497
0
                result);
2498
0
        }
2499
189k
        else {
2500
189k
            assert(skind == PyUnicode_1BYTE_KIND);
2501
189k
            _PyUnicode_CONVERT_BYTES(
2502
189k
                Py_UCS1, Py_UCS4,
2503
189k
                (const Py_UCS1 *)data,
2504
189k
                ((const Py_UCS1 *)data) + len,
2505
189k
                result);
2506
189k
        }
2507
189k
        return result;
2508
0
    default:
2509
0
        Py_UNREACHABLE();
2510
0
        return NULL;
2511
1.35M
    }
2512
1.35M
}
2513
2514
static Py_UCS4*
2515
as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2516
        int copy_null)
2517
78.4k
{
2518
78.4k
    int kind;
2519
78.4k
    const void *data;
2520
78.4k
    Py_ssize_t len, targetlen;
2521
78.4k
    kind = PyUnicode_KIND(string);
2522
78.4k
    data = PyUnicode_DATA(string);
2523
78.4k
    len = PyUnicode_GET_LENGTH(string);
2524
78.4k
    targetlen = len;
2525
78.4k
    if (copy_null)
2526
0
        targetlen++;
2527
78.4k
    if (!target) {
2528
0
        target = PyMem_New(Py_UCS4, targetlen);
2529
0
        if (!target) {
2530
0
            PyErr_NoMemory();
2531
0
            return NULL;
2532
0
        }
2533
0
    }
2534
78.4k
    else {
2535
78.4k
        if (targetsize < targetlen) {
2536
0
            PyErr_Format(PyExc_SystemError,
2537
0
                         "string is longer than the buffer");
2538
0
            if (copy_null && 0 < targetsize)
2539
0
                target[0] = 0;
2540
0
            return NULL;
2541
0
        }
2542
78.4k
    }
2543
78.4k
    if (kind == PyUnicode_1BYTE_KIND) {
2544
53.9k
        const Py_UCS1 *start = (const Py_UCS1 *) data;
2545
53.9k
        _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
2546
53.9k
    }
2547
24.5k
    else if (kind == PyUnicode_2BYTE_KIND) {
2548
17.8k
        const Py_UCS2 *start = (const Py_UCS2 *) data;
2549
17.8k
        _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2550
17.8k
    }
2551
6.65k
    else if (kind == PyUnicode_4BYTE_KIND) {
2552
6.65k
        memcpy(target, data, len * sizeof(Py_UCS4));
2553
6.65k
    }
2554
0
    else {
2555
0
        Py_UNREACHABLE();
2556
0
    }
2557
78.4k
    if (copy_null)
2558
0
        target[len] = 0;
2559
78.4k
    return target;
2560
78.4k
}
2561
2562
Py_UCS4*
2563
PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2564
                 int copy_null)
2565
78.4k
{
2566
78.4k
    if (target == NULL || targetsize < 0) {
2567
0
        PyErr_BadInternalCall();
2568
0
        return NULL;
2569
0
    }
2570
78.4k
    return as_ucs4(string, target, targetsize, copy_null);
2571
78.4k
}
2572
2573
Py_UCS4*
2574
PyUnicode_AsUCS4Copy(PyObject *string)
2575
0
{
2576
0
    return as_ucs4(string, NULL, 0, 1);
2577
0
}
2578
2579
/* maximum number of characters required for output of %jo or %jd or %p.
2580
   We need at most ceil(log8(256)*sizeof(intmax_t)) digits,
2581
   plus 1 for the sign, plus 2 for the 0x prefix (for %p),
2582
   plus 1 for the terminal NUL. */
2583
#define MAX_INTMAX_CHARS (5 + (sizeof(intmax_t)*8-1) / 3)
2584
2585
static int
2586
unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2587
                             Py_ssize_t width, Py_ssize_t precision, int flags)
2588
5.67M
{
2589
5.67M
    Py_ssize_t length, fill, arglen;
2590
5.67M
    Py_UCS4 maxchar;
2591
2592
5.67M
    length = PyUnicode_GET_LENGTH(str);
2593
5.67M
    if ((precision == -1 || precision >= length) && width <= length) {
2594
5.67M
        return _PyUnicodeWriter_WriteStr(writer, str);
2595
5.67M
    }
2596
2597
39
    if (precision != -1)
2598
39
        length = Py_MIN(precision, length);
2599
2600
39
    arglen = Py_MAX(length, width);
2601
39
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2602
17
        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2603
22
    else
2604
22
        maxchar = writer->maxchar;
2605
2606
39
    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1) {
2607
0
        return -1;
2608
0
    }
2609
39
    assert(_PyUnicodeWriter_CanWrite(writer));
2610
2611
39
    fill = Py_MAX(width - length, 0);
2612
39
    if (fill && !(flags & F_LJUST)) {
2613
0
        if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2614
0
            return -1;
2615
0
        writer->pos += fill;
2616
0
    }
2617
2618
39
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2619
39
                                  str, 0, length);
2620
39
    writer->pos += length;
2621
2622
39
    if (fill && (flags & F_LJUST)) {
2623
0
        if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2624
0
            return -1;
2625
0
        writer->pos += fill;
2626
0
    }
2627
2628
39
    return 0;
2629
39
}
2630
2631
static int
2632
unicode_fromformat_write_utf8(_PyUnicodeWriter *writer, const char *str,
2633
                              Py_ssize_t width, Py_ssize_t precision, int flags)
2634
2.47M
{
2635
    /* UTF-8 */
2636
2.47M
    Py_ssize_t *pconsumed = NULL;
2637
2.47M
    Py_ssize_t length;
2638
2.47M
    if (precision == -1) {
2639
736k
        length = strlen(str);
2640
736k
    }
2641
1.73M
    else {
2642
1.73M
        length = 0;
2643
28.0M
        while (length < precision && str[length]) {
2644
26.3M
            length++;
2645
26.3M
        }
2646
1.73M
        if (length == precision) {
2647
            /* The input string is not NUL-terminated.  If it ends with an
2648
             * incomplete UTF-8 sequence, truncate the string just before it.
2649
             * Incomplete sequences in the middle and sequences which cannot
2650
             * be valid prefixes are still treated as errors and replaced
2651
             * with \xfffd. */
2652
2.21k
            pconsumed = &length;
2653
2.21k
        }
2654
1.73M
    }
2655
2656
2.47M
    if (width < 0) {
2657
2.47M
        return _PyUnicode_DecodeUTF8Writer(writer, str, length,
2658
2.47M
                                           _Py_ERROR_REPLACE, "replace", pconsumed);
2659
2.47M
    }
2660
2661
0
    PyObject *unicode = PyUnicode_DecodeUTF8Stateful(str, length,
2662
0
                                                     "replace", pconsumed);
2663
0
    if (unicode == NULL)
2664
0
        return -1;
2665
2666
0
    int res = unicode_fromformat_write_str(writer, unicode,
2667
0
                                           width, -1, flags);
2668
0
    Py_DECREF(unicode);
2669
0
    return res;
2670
0
}
2671
2672
static int
2673
unicode_fromformat_write_wcstr(_PyUnicodeWriter *writer, const wchar_t *str,
2674
                              Py_ssize_t width, Py_ssize_t precision, int flags)
2675
0
{
2676
0
    Py_ssize_t length;
2677
0
    if (precision == -1) {
2678
0
        length = wcslen(str);
2679
0
    }
2680
0
    else {
2681
0
        length = 0;
2682
0
        while (length < precision && str[length]) {
2683
0
            length++;
2684
0
        }
2685
0
    }
2686
2687
0
    if (width < 0) {
2688
0
        return PyUnicodeWriter_WriteWideChar((PyUnicodeWriter*)writer,
2689
0
                                             str, length);
2690
0
    }
2691
2692
0
    PyObject *unicode = PyUnicode_FromWideChar(str, length);
2693
0
    if (unicode == NULL)
2694
0
        return -1;
2695
2696
0
    int res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
2697
0
    Py_DECREF(unicode);
2698
0
    return res;
2699
0
}
2700
2701
0
#define F_LONG 1
2702
0
#define F_LONGLONG 2
2703
252k
#define F_SIZE 3
2704
0
#define F_PTRDIFF 4
2705
0
#define F_INTMAX 5
2706
2707
static const char*
2708
unicode_fromformat_arg(_PyUnicodeWriter *writer,
2709
                       const char *f, va_list *vargs)
2710
23.7M
{
2711
23.7M
    const char *p;
2712
23.7M
    Py_ssize_t len;
2713
23.7M
    int flags = 0;
2714
23.7M
    Py_ssize_t width;
2715
23.7M
    Py_ssize_t precision;
2716
2717
23.7M
    p = f;
2718
23.7M
    f++;
2719
23.7M
    if (*f == '%') {
2720
804k
        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
2721
0
            return NULL;
2722
804k
        f++;
2723
804k
        return f;
2724
804k
    }
2725
2726
    /* Parse flags. Example: "%-i" => flags=F_LJUST. */
2727
    /* Flags '+', ' ' and '#' are not particularly useful.
2728
     * They are not worth the implementation and maintenance costs.
2729
     * In addition, '#' should add "0" for "o" conversions for compatibility
2730
     * with printf, but it would confuse Python users. */
2731
22.9M
    while (1) {
2732
22.9M
        switch (*f++) {
2733
0
        case '-': flags |= F_LJUST; continue;
2734
1.88k
        case '0': flags |= F_ZERO; continue;
2735
0
        case '#': flags |= F_ALT; continue;
2736
22.9M
        }
2737
22.9M
        f--;
2738
22.9M
        break;
2739
22.9M
    }
2740
2741
    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2742
22.9M
    width = -1;
2743
22.9M
    if (*f == '*') {
2744
0
        width = va_arg(*vargs, int);
2745
0
        if (width < 0) {
2746
0
            flags |= F_LJUST;
2747
0
            width = -width;
2748
0
        }
2749
0
        f++;
2750
0
    }
2751
22.9M
    else if (Py_ISDIGIT((unsigned)*f)) {
2752
1.88k
        width = *f - '0';
2753
1.88k
        f++;
2754
1.88k
        while (Py_ISDIGIT((unsigned)*f)) {
2755
0
            if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2756
0
                PyErr_SetString(PyExc_ValueError,
2757
0
                                "width too big");
2758
0
                return NULL;
2759
0
            }
2760
0
            width = (width * 10) + (*f - '0');
2761
0
            f++;
2762
0
        }
2763
1.88k
    }
2764
22.9M
    precision = -1;
2765
22.9M
    if (*f == '.') {
2766
3.52M
        f++;
2767
3.52M
        if (*f == '*') {
2768
0
            precision = va_arg(*vargs, int);
2769
0
            if (precision < 0) {
2770
0
                precision = -2;
2771
0
            }
2772
0
            f++;
2773
0
        }
2774
3.52M
        else if (Py_ISDIGIT((unsigned)*f)) {
2775
3.52M
            precision = (*f - '0');
2776
3.52M
            f++;
2777
10.5M
            while (Py_ISDIGIT((unsigned)*f)) {
2778
7.04M
                if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2779
0
                    PyErr_SetString(PyExc_ValueError,
2780
0
                                    "precision too big");
2781
0
                    return NULL;
2782
0
                }
2783
7.04M
                precision = (precision * 10) + (*f - '0');
2784
7.04M
                f++;
2785
7.04M
            }
2786
3.52M
        }
2787
3.52M
    }
2788
2789
22.9M
    int sizemod = 0;
2790
22.9M
    if (*f == 'l') {
2791
0
        if (f[1] == 'l') {
2792
0
            sizemod = F_LONGLONG;
2793
0
            f += 2;
2794
0
        }
2795
0
        else {
2796
0
            sizemod = F_LONG;
2797
0
            ++f;
2798
0
        }
2799
0
    }
2800
22.9M
    else if (*f == 'z') {
2801
126k
        sizemod = F_SIZE;
2802
126k
        ++f;
2803
126k
    }
2804
22.7M
    else if (*f == 't') {
2805
0
        sizemod = F_PTRDIFF;
2806
0
        ++f;
2807
0
    }
2808
22.7M
    else if (*f == 'j') {
2809
0
        sizemod = F_INTMAX;
2810
0
        ++f;
2811
0
    }
2812
22.9M
    if (f[0] != '\0' && f[1] == '\0')
2813
3.21M
        writer->overallocate = 0;
2814
2815
22.9M
    switch (*f) {
2816
13.5M
    case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
2817
13.5M
        break;
2818
1.26M
    case 'c': case 'p':
2819
1.26M
        if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
2820
1.26M
        break;
2821
2.47M
    case 's':
2822
2.47M
    case 'V':
2823
2.47M
        if (sizemod && sizemod != F_LONG) goto invalid_format;
2824
2.47M
        break;
2825
5.67M
    default:
2826
5.67M
        if (sizemod) goto invalid_format;
2827
5.67M
        break;
2828
22.9M
    }
2829
2830
22.9M
    switch (*f) {
2831
1.26M
    case 'c':
2832
1.26M
    {
2833
1.26M
        int ordinal = va_arg(*vargs, int);
2834
1.26M
        if (ordinal < 0 || ordinal > MAX_UNICODE) {
2835
0
            PyErr_SetString(PyExc_OverflowError,
2836
0
                            "character argument not in range(0x110000)");
2837
0
            return NULL;
2838
0
        }
2839
1.26M
        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
2840
0
            return NULL;
2841
1.26M
        break;
2842
1.26M
    }
2843
2844
13.4M
    case 'd': case 'i':
2845
13.5M
    case 'o': case 'u': case 'x': case 'X':
2846
13.5M
    {
2847
13.5M
        char buffer[MAX_INTMAX_CHARS];
2848
2849
        // Fill buffer using sprinf, with one of many possible format
2850
        // strings, like "%llX" for `long long` in hexadecimal.
2851
        // The type/size is in `sizemod`; the format is in `*f`.
2852
2853
        // Use macros with nested switches to keep the sprintf format strings
2854
        // as compile-time literals, avoiding warnings and maybe allowing
2855
        // optimizations.
2856
2857
        // `SPRINT` macro does one sprintf
2858
        // Example usage: SPRINT("l", "X", unsigned long) expands to
2859
        // sprintf(buffer, "%" "l" "X", va_arg(*vargs, unsigned long))
2860
13.5M
        #define SPRINT(SIZE_SPEC, FMT_CHAR, TYPE) \
2861
13.5M
            sprintf(buffer, "%" SIZE_SPEC FMT_CHAR, va_arg(*vargs, TYPE))
2862
2863
        // One inner switch to handle all format variants
2864
13.5M
        #define DO_SPRINTS(SIZE_SPEC, SIGNED_TYPE, UNSIGNED_TYPE)             \
2865
13.5M
            switch (*f) {                                                     \
2866
107
                case 'o': len = SPRINT(SIZE_SPEC, "o", UNSIGNED_TYPE); break; \
2867
20.3k
                case 'u': len = SPRINT(SIZE_SPEC, "u", UNSIGNED_TYPE); break; \
2868
1.47k
                case 'x': len = SPRINT(SIZE_SPEC, "x", UNSIGNED_TYPE); break; \
2869
952
                case 'X': len = SPRINT(SIZE_SPEC, "X", UNSIGNED_TYPE); break; \
2870
13.4M
                default:  len = SPRINT(SIZE_SPEC, "d", SIGNED_TYPE); break;   \
2871
13.5M
            }
2872
2873
        // Outer switch to handle all the sizes/types
2874
13.5M
        switch (sizemod) {
2875
0
            case F_LONG:     DO_SPRINTS("l", long, unsigned long); break;
2876
0
            case F_LONGLONG: DO_SPRINTS("ll", long long, unsigned long long); break;
2877
126k
            case F_SIZE:     DO_SPRINTS("z", Py_ssize_t, size_t); break;
2878
0
            case F_PTRDIFF:  DO_SPRINTS("t", ptrdiff_t, ptrdiff_t); break;
2879
0
            case F_INTMAX:   DO_SPRINTS("j", intmax_t, uintmax_t); break;
2880
13.3M
            default:         DO_SPRINTS("", int, unsigned int); break;
2881
13.5M
        }
2882
13.5M
        #undef SPRINT
2883
13.5M
        #undef DO_SPRINTS
2884
2885
13.5M
        assert(len >= 1);
2886
2887
13.5M
        int sign = (buffer[0] == '-');
2888
13.5M
        len -= sign;
2889
2890
13.5M
        precision = Py_MAX(precision, len);
2891
13.5M
        width = Py_MAX(width, precision + sign);
2892
13.5M
        if ((flags & F_ZERO) && !(flags & F_LJUST)) {
2893
1.88k
            precision = width - sign;
2894
1.88k
        }
2895
2896
13.5M
        Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
2897
13.5M
        Py_ssize_t zeropad = Py_MAX(precision - len, 0);
2898
2899
13.5M
        if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1) {
2900
0
            return NULL;
2901
0
        }
2902
13.5M
        assert(_PyUnicodeWriter_CanWrite(writer));
2903
2904
13.5M
        if (spacepad && !(flags & F_LJUST)) {
2905
0
            if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
2906
0
                return NULL;
2907
0
            writer->pos += spacepad;
2908
0
        }
2909
2910
13.5M
        if (sign) {
2911
765
            if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
2912
0
                return NULL;
2913
765
        }
2914
2915
13.5M
        if (zeropad) {
2916
583
            if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
2917
0
                return NULL;
2918
583
            writer->pos += zeropad;
2919
583
        }
2920
2921
13.5M
        if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
2922
0
            return NULL;
2923
2924
13.5M
        if (spacepad && (flags & F_LJUST)) {
2925
0
            if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
2926
0
                return NULL;
2927
0
            writer->pos += spacepad;
2928
0
        }
2929
13.5M
        break;
2930
13.5M
    }
2931
2932
13.5M
    case 'p':
2933
7.21k
    {
2934
7.21k
        char number[MAX_INTMAX_CHARS];
2935
2936
7.21k
        len = sprintf(number, "%p", va_arg(*vargs, void*));
2937
7.21k
        assert(len >= 0);
2938
2939
        /* %p is ill-defined:  ensure leading 0x. */
2940
7.21k
        if (number[1] == 'X')
2941
0
            number[1] = 'x';
2942
7.21k
        else if (number[1] != 'x') {
2943
0
            memmove(number + 2, number,
2944
0
                    strlen(number) + 1);
2945
0
            number[0] = '0';
2946
0
            number[1] = 'x';
2947
0
            len += 2;
2948
0
        }
2949
2950
7.21k
        if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
2951
0
            return NULL;
2952
7.21k
        break;
2953
7.21k
    }
2954
2955
2.47M
    case 's':
2956
2.47M
    {
2957
2.47M
        if (sizemod) {
2958
0
            const wchar_t *s = va_arg(*vargs, const wchar_t*);
2959
0
            if (unicode_fromformat_write_wcstr(writer, s, width, precision, flags) < 0)
2960
0
                return NULL;
2961
0
        }
2962
2.47M
        else {
2963
            /* UTF-8 */
2964
2.47M
            const char *s = va_arg(*vargs, const char*);
2965
2.47M
            if (unicode_fromformat_write_utf8(writer, s, width, precision, flags) < 0)
2966
0
                return NULL;
2967
2.47M
        }
2968
2.47M
        break;
2969
2.47M
    }
2970
2971
2.63M
    case 'U':
2972
2.63M
    {
2973
2.63M
        PyObject *obj = va_arg(*vargs, PyObject *);
2974
2.63M
        assert(obj && _PyUnicode_CHECK(obj));
2975
2976
2.63M
        if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2977
0
            return NULL;
2978
2.63M
        break;
2979
2.63M
    }
2980
2981
2.63M
    case 'V':
2982
541
    {
2983
541
        PyObject *obj = va_arg(*vargs, PyObject *);
2984
541
        const char *str;
2985
541
        const wchar_t *wstr;
2986
541
        if (sizemod) {
2987
0
            wstr = va_arg(*vargs, const wchar_t*);
2988
0
        }
2989
541
        else {
2990
541
            str = va_arg(*vargs, const char *);
2991
541
        }
2992
541
        if (obj) {
2993
0
            assert(_PyUnicode_CHECK(obj));
2994
0
            if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2995
0
                return NULL;
2996
0
        }
2997
541
        else if (sizemod) {
2998
0
            assert(wstr != NULL);
2999
0
            if (unicode_fromformat_write_wcstr(writer, wstr, width, precision, flags) < 0)
3000
0
                return NULL;
3001
0
        }
3002
541
        else {
3003
541
            assert(str != NULL);
3004
541
            if (unicode_fromformat_write_utf8(writer, str, width, precision, flags) < 0)
3005
0
                return NULL;
3006
541
        }
3007
541
        break;
3008
541
    }
3009
3010
1.48k
    case 'S':
3011
1.48k
    {
3012
1.48k
        PyObject *obj = va_arg(*vargs, PyObject *);
3013
1.48k
        PyObject *str;
3014
1.48k
        assert(obj);
3015
1.48k
        str = PyObject_Str(obj);
3016
1.48k
        if (!str)
3017
0
            return NULL;
3018
1.48k
        if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
3019
0
            Py_DECREF(str);
3020
0
            return NULL;
3021
0
        }
3022
1.48k
        Py_DECREF(str);
3023
1.48k
        break;
3024
1.48k
    }
3025
3026
1.79M
    case 'R':
3027
1.79M
    {
3028
1.79M
        PyObject *obj = va_arg(*vargs, PyObject *);
3029
1.79M
        PyObject *repr;
3030
1.79M
        assert(obj);
3031
1.79M
        repr = PyObject_Repr(obj);
3032
1.79M
        if (!repr)
3033
0
            return NULL;
3034
1.79M
        if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
3035
0
            Py_DECREF(repr);
3036
0
            return NULL;
3037
0
        }
3038
1.79M
        Py_DECREF(repr);
3039
1.79M
        break;
3040
1.79M
    }
3041
3042
0
    case 'A':
3043
0
    {
3044
0
        PyObject *obj = va_arg(*vargs, PyObject *);
3045
0
        PyObject *ascii;
3046
0
        assert(obj);
3047
0
        ascii = PyObject_ASCII(obj);
3048
0
        if (!ascii)
3049
0
            return NULL;
3050
0
        if (unicode_fromformat_write_str(writer, ascii, width, precision, flags) == -1) {
3051
0
            Py_DECREF(ascii);
3052
0
            return NULL;
3053
0
        }
3054
0
        Py_DECREF(ascii);
3055
0
        break;
3056
0
    }
3057
3058
1.24M
    case 'T':
3059
1.24M
    {
3060
1.24M
        PyObject *obj = va_arg(*vargs, PyObject *);
3061
1.24M
        PyTypeObject *type = (PyTypeObject *)Py_NewRef(Py_TYPE(obj));
3062
3063
1.24M
        PyObject *type_name;
3064
1.24M
        if (flags & F_ALT) {
3065
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3066
0
        }
3067
1.24M
        else {
3068
1.24M
            type_name = PyType_GetFullyQualifiedName(type);
3069
1.24M
        }
3070
1.24M
        Py_DECREF(type);
3071
1.24M
        if (!type_name) {
3072
0
            return NULL;
3073
0
        }
3074
3075
1.24M
        if (unicode_fromformat_write_str(writer, type_name,
3076
1.24M
                                         width, precision, flags) == -1) {
3077
0
            Py_DECREF(type_name);
3078
0
            return NULL;
3079
0
        }
3080
1.24M
        Py_DECREF(type_name);
3081
1.24M
        break;
3082
1.24M
    }
3083
3084
0
    case 'N':
3085
0
    {
3086
0
        PyObject *type_raw = va_arg(*vargs, PyObject *);
3087
0
        assert(type_raw != NULL);
3088
3089
0
        if (!PyType_Check(type_raw)) {
3090
0
            PyErr_SetString(PyExc_TypeError, "%N argument must be a type");
3091
0
            return NULL;
3092
0
        }
3093
0
        PyTypeObject *type = (PyTypeObject*)type_raw;
3094
3095
0
        PyObject *type_name;
3096
0
        if (flags & F_ALT) {
3097
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3098
0
        }
3099
0
        else {
3100
0
            type_name = PyType_GetFullyQualifiedName(type);
3101
0
        }
3102
0
        if (!type_name) {
3103
0
            return NULL;
3104
0
        }
3105
0
        if (unicode_fromformat_write_str(writer, type_name,
3106
0
                                         width, precision, flags) == -1) {
3107
0
            Py_DECREF(type_name);
3108
0
            return NULL;
3109
0
        }
3110
0
        Py_DECREF(type_name);
3111
0
        break;
3112
0
    }
3113
3114
0
    default:
3115
0
    invalid_format:
3116
0
        PyErr_Format(PyExc_SystemError, "invalid format string: %s", p);
3117
0
        return NULL;
3118
22.9M
    }
3119
3120
22.9M
    f++;
3121
22.9M
    return f;
3122
22.9M
}
3123
3124
static int
3125
unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
3126
11.3M
{
3127
11.3M
    Py_ssize_t len = strlen(format);
3128
11.3M
    writer->min_length += len + 100;
3129
11.3M
    writer->overallocate = 1;
3130
3131
    // Copy varags to be able to pass a reference to a subfunction.
3132
11.3M
    va_list vargs2;
3133
11.3M
    va_copy(vargs2, vargs);
3134
3135
    // _PyUnicodeWriter_WriteASCIIString() below requires the format string
3136
    // to be encoded to ASCII.
3137
11.3M
    int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)format, (Py_UCS1*)format + len) < 128);
3138
11.3M
    if (!is_ascii) {
3139
0
        Py_ssize_t i;
3140
0
        for (i=0; i < len && (unsigned char)format[i] <= 127; i++);
3141
0
        PyErr_Format(PyExc_ValueError,
3142
0
            "PyUnicode_FromFormatV() expects an ASCII-encoded format "
3143
0
            "string, got a non-ASCII byte: 0x%02x",
3144
0
            (unsigned char)format[i]);
3145
0
        goto fail;
3146
0
    }
3147
3148
64.7M
    for (const char *f = format; *f; ) {
3149
53.3M
        if (*f == '%') {
3150
23.7M
            f = unicode_fromformat_arg(writer, f, &vargs2);
3151
23.7M
            if (f == NULL)
3152
0
                goto fail;
3153
23.7M
        }
3154
29.6M
        else {
3155
29.6M
            const char *p = strchr(f, '%');
3156
29.6M
            if (p != NULL) {
3157
21.4M
                len = p - f;
3158
21.4M
            }
3159
8.15M
            else {
3160
8.15M
                len = strlen(f);
3161
8.15M
                writer->overallocate = 0;
3162
8.15M
            }
3163
3164
29.6M
            if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
3165
0
                goto fail;
3166
0
            }
3167
29.6M
            f += len;
3168
29.6M
        }
3169
53.3M
    }
3170
11.3M
    va_end(vargs2);
3171
11.3M
    return 0;
3172
3173
0
  fail:
3174
0
    va_end(vargs2);
3175
0
    return -1;
3176
11.3M
}
3177
3178
PyObject *
3179
PyUnicode_FromFormatV(const char *format, va_list vargs)
3180
11.3M
{
3181
11.3M
    _PyUnicodeWriter writer;
3182
11.3M
    _PyUnicodeWriter_Init(&writer);
3183
3184
11.3M
    if (unicode_from_format(&writer, format, vargs) < 0) {
3185
0
        _PyUnicodeWriter_Dealloc(&writer);
3186
0
        return NULL;
3187
0
    }
3188
11.3M
    return _PyUnicodeWriter_Finish(&writer);
3189
11.3M
}
3190
3191
PyObject *
3192
PyUnicode_FromFormat(const char *format, ...)
3193
505k
{
3194
505k
    PyObject* ret;
3195
505k
    va_list vargs;
3196
3197
505k
    va_start(vargs, format);
3198
505k
    ret = PyUnicode_FromFormatV(format, vargs);
3199
505k
    va_end(vargs);
3200
505k
    return ret;
3201
505k
}
3202
3203
int
3204
PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...)
3205
0
{
3206
0
    va_list vargs;
3207
0
    va_start(vargs, format);
3208
0
    int res = _PyUnicodeWriter_FormatV(writer, format, vargs);
3209
0
    va_end(vargs);
3210
0
    return res;
3211
0
}
3212
3213
int
3214
_PyUnicodeWriter_FormatV(PyUnicodeWriter *pub_writer, const char *format,
3215
                         va_list vargs)
3216
0
{
3217
0
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
3218
0
    Py_ssize_t old_pos = writer->pos;
3219
0
    Py_UCS4 old_maxchar = writer->maxchar;
3220
3221
0
    int res = unicode_from_format(writer, format, vargs);
3222
3223
0
    if (res < 0) {
3224
0
        writer->pos = old_pos;
3225
0
        if (writer->maxchar > old_maxchar) {
3226
            // _PyUnicodeWriter_Finish() will check maxchar
3227
0
            writer->recheck_maxchar = 1;
3228
0
        }
3229
0
    }
3230
0
    return res;
3231
0
}
3232
3233
static Py_ssize_t
3234
unicode_get_widechar_size(PyObject *unicode)
3235
164k
{
3236
164k
    Py_ssize_t res;
3237
3238
164k
    assert(unicode != NULL);
3239
164k
    assert(_PyUnicode_CHECK(unicode));
3240
3241
164k
    res = _PyUnicode_LENGTH(unicode);
3242
#if SIZEOF_WCHAR_T == 2
3243
    if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
3244
        const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3245
        const Py_UCS4 *end = s + res;
3246
        for (; s < end; ++s) {
3247
            if (*s > 0xFFFF) {
3248
                ++res;
3249
            }
3250
        }
3251
    }
3252
#endif
3253
164k
    return res;
3254
164k
}
3255
3256
static void
3257
unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3258
164k
{
3259
164k
    assert(unicode != NULL);
3260
164k
    assert(_PyUnicode_CHECK(unicode));
3261
3262
164k
    if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
3263
1.41k
        memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
3264
1.41k
        return;
3265
1.41k
    }
3266
3267
163k
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3268
138k
        const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3269
3.97M
        for (; size--; ++s, ++w) {
3270
3.84M
            *w = *s;
3271
3.84M
        }
3272
138k
    }
3273
24.8k
    else {
3274
24.8k
#if SIZEOF_WCHAR_T == 4
3275
24.8k
        assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3276
24.8k
        const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3277
1.37M
        for (; size--; ++s, ++w) {
3278
1.34M
            *w = *s;
3279
1.34M
        }
3280
#else
3281
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3282
        const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3283
        for (; size--; ++s, ++w) {
3284
            Py_UCS4 ch = *s;
3285
            if (ch > 0xFFFF) {
3286
                assert(ch <= MAX_UNICODE);
3287
                /* encode surrogate pair in this case */
3288
                *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3289
                if (!size--)
3290
                    break;
3291
                *w = Py_UNICODE_LOW_SURROGATE(ch);
3292
            }
3293
            else {
3294
                *w = ch;
3295
            }
3296
        }
3297
#endif
3298
24.8k
    }
3299
163k
}
3300
3301
#ifdef HAVE_WCHAR_H
3302
3303
/* Convert a Unicode object to a wide character string.
3304
3305
   - If w is NULL: return the number of wide characters (including the null
3306
     character) required to convert the unicode object. Ignore size argument.
3307
3308
   - Otherwise: return the number of wide characters (excluding the null
3309
     character) written into w. Write at most size wide characters (including
3310
     the null character). */
3311
Py_ssize_t
3312
PyUnicode_AsWideChar(PyObject *unicode,
3313
                     wchar_t *w,
3314
                     Py_ssize_t size)
3315
0
{
3316
0
    Py_ssize_t res;
3317
3318
0
    if (unicode == NULL) {
3319
0
        PyErr_BadInternalCall();
3320
0
        return -1;
3321
0
    }
3322
0
    if (!PyUnicode_Check(unicode)) {
3323
0
        PyErr_BadArgument();
3324
0
        return -1;
3325
0
    }
3326
3327
0
    res = unicode_get_widechar_size(unicode);
3328
0
    if (w == NULL) {
3329
0
        return res + 1;
3330
0
    }
3331
3332
0
    if (size > res) {
3333
0
        size = res + 1;
3334
0
    }
3335
0
    else {
3336
0
        res = size;
3337
0
    }
3338
0
    unicode_copy_as_widechar(unicode, w, size);
3339
3340
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
3341
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
3342
       non-Unicode locales and hence needs conversion first. */
3343
    if (_Py_LocaleUsesNonUnicodeWchar()) {
3344
        if (_Py_EncodeNonUnicodeWchar_InPlace(w, size) < 0) {
3345
            return -1;
3346
        }
3347
    }
3348
#endif
3349
3350
0
    return res;
3351
0
}
3352
3353
wchar_t*
3354
PyUnicode_AsWideCharString(PyObject *unicode,
3355
                           Py_ssize_t *size)
3356
164k
{
3357
164k
    wchar_t *buffer;
3358
164k
    Py_ssize_t buflen;
3359
3360
164k
    if (unicode == NULL) {
3361
0
        PyErr_BadInternalCall();
3362
0
        return NULL;
3363
0
    }
3364
164k
    if (!PyUnicode_Check(unicode)) {
3365
0
        PyErr_BadArgument();
3366
0
        return NULL;
3367
0
    }
3368
3369
164k
    buflen = unicode_get_widechar_size(unicode);
3370
164k
    buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
3371
164k
    if (buffer == NULL) {
3372
0
        PyErr_NoMemory();
3373
0
        return NULL;
3374
0
    }
3375
164k
    unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3376
3377
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
3378
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
3379
       non-Unicode locales and hence needs conversion first. */
3380
    if (_Py_LocaleUsesNonUnicodeWchar()) {
3381
        if (_Py_EncodeNonUnicodeWchar_InPlace(buffer, (buflen + 1)) < 0) {
3382
            return NULL;
3383
        }
3384
    }
3385
#endif
3386
3387
164k
    if (size != NULL) {
3388
161k
        *size = buflen;
3389
161k
    }
3390
2.95k
    else if (wcslen(buffer) != (size_t)buflen) {
3391
0
        PyMem_Free(buffer);
3392
0
        PyErr_SetString(PyExc_ValueError,
3393
0
                        "embedded null character");
3394
0
        return NULL;
3395
0
    }
3396
164k
    return buffer;
3397
164k
}
3398
3399
#endif /* HAVE_WCHAR_H */
3400
3401
int
3402
_PyUnicode_WideCharString_Converter(PyObject *obj, void *ptr)
3403
0
{
3404
0
    wchar_t **p = (wchar_t **)ptr;
3405
0
    if (obj == NULL) {
3406
0
        PyMem_Free(*p);
3407
0
        *p = NULL;
3408
0
        return 1;
3409
0
    }
3410
0
    if (PyUnicode_Check(obj)) {
3411
0
        *p = PyUnicode_AsWideCharString(obj, NULL);
3412
0
        if (*p == NULL) {
3413
0
            return 0;
3414
0
        }
3415
0
        return Py_CLEANUP_SUPPORTED;
3416
0
    }
3417
0
    PyErr_Format(PyExc_TypeError,
3418
0
                 "argument must be str, not %.50s",
3419
0
                 Py_TYPE(obj)->tp_name);
3420
0
    return 0;
3421
0
}
3422
3423
int
3424
_PyUnicode_WideCharString_Opt_Converter(PyObject *obj, void *ptr)
3425
0
{
3426
0
    wchar_t **p = (wchar_t **)ptr;
3427
0
    if (obj == NULL) {
3428
0
        PyMem_Free(*p);
3429
0
        *p = NULL;
3430
0
        return 1;
3431
0
    }
3432
0
    if (obj == Py_None) {
3433
0
        *p = NULL;
3434
0
        return 1;
3435
0
    }
3436
0
    if (PyUnicode_Check(obj)) {
3437
0
        *p = PyUnicode_AsWideCharString(obj, NULL);
3438
0
        if (*p == NULL) {
3439
0
            return 0;
3440
0
        }
3441
0
        return Py_CLEANUP_SUPPORTED;
3442
0
    }
3443
0
    PyErr_Format(PyExc_TypeError,
3444
0
                 "argument must be str or None, not %.50s",
3445
0
                 Py_TYPE(obj)->tp_name);
3446
0
    return 0;
3447
0
}
3448
3449
PyObject *
3450
PyUnicode_FromOrdinal(int ordinal)
3451
13.0M
{
3452
13.0M
    if (ordinal < 0 || ordinal > MAX_UNICODE) {
3453
26
        PyErr_SetString(PyExc_ValueError,
3454
26
                        "chr() arg not in range(0x110000)");
3455
26
        return NULL;
3456
26
    }
3457
3458
13.0M
    return unicode_char((Py_UCS4)ordinal);
3459
13.0M
}
3460
3461
PyObject *
3462
PyUnicode_FromObject(PyObject *obj)
3463
3.72M
{
3464
    /* XXX Perhaps we should make this API an alias of
3465
       PyObject_Str() instead ?! */
3466
3.72M
    if (PyUnicode_CheckExact(obj)) {
3467
3.72M
        return Py_NewRef(obj);
3468
3.72M
    }
3469
0
    if (PyUnicode_Check(obj)) {
3470
        /* For a Unicode subtype that's not a Unicode object,
3471
           return a true Unicode object with the same data. */
3472
0
        return _PyUnicode_Copy(obj);
3473
0
    }
3474
0
    PyErr_Format(PyExc_TypeError,
3475
0
                 "Can't convert '%.100s' object to str implicitly",
3476
0
                 Py_TYPE(obj)->tp_name);
3477
0
    return NULL;
3478
0
}
3479
3480
PyObject *
3481
PyUnicode_FromEncodedObject(PyObject *obj,
3482
                            const char *encoding,
3483
                            const char *errors)
3484
27.8M
{
3485
27.8M
    Py_buffer buffer;
3486
27.8M
    PyObject *v;
3487
3488
27.8M
    if (obj == NULL) {
3489
0
        PyErr_BadInternalCall();
3490
0
        return NULL;
3491
0
    }
3492
3493
    /* Decoding bytes objects is the most common case and should be fast */
3494
27.8M
    if (PyBytes_Check(obj)) {
3495
27.8M
        if (PyBytes_GET_SIZE(obj) == 0) {
3496
5.57M
            if (unicode_check_encoding_errors(encoding, errors) < 0) {
3497
0
                return NULL;
3498
0
            }
3499
5.57M
            _Py_RETURN_UNICODE_EMPTY();
3500
5.57M
        }
3501
22.2M
        return PyUnicode_Decode(
3502
22.2M
                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3503
22.2M
                encoding, errors);
3504
27.8M
    }
3505
3506
0
    if (PyUnicode_Check(obj)) {
3507
0
        PyErr_SetString(PyExc_TypeError,
3508
0
                        "decoding str is not supported");
3509
0
        return NULL;
3510
0
    }
3511
3512
    /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3513
0
    if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3514
0
        PyErr_Format(PyExc_TypeError,
3515
0
                     "decoding to str: need a bytes-like object, %.80s found",
3516
0
                     Py_TYPE(obj)->tp_name);
3517
0
        return NULL;
3518
0
    }
3519
3520
0
    if (buffer.len == 0) {
3521
0
        PyBuffer_Release(&buffer);
3522
0
        if (unicode_check_encoding_errors(encoding, errors) < 0) {
3523
0
            return NULL;
3524
0
        }
3525
0
        _Py_RETURN_UNICODE_EMPTY();
3526
0
    }
3527
3528
0
    v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
3529
0
    PyBuffer_Release(&buffer);
3530
0
    return v;
3531
0
}
3532
3533
/* Normalize an encoding name like encodings.normalize_encoding()
3534
   but allow to convert to lowercase if *to_lower* is true.
3535
   Return 1 on success, or 0 on error (encoding is longer than lower_len-1). */
3536
int
3537
_Py_normalize_encoding(const char *encoding,
3538
                       char *lower,
3539
                       size_t lower_len,
3540
                       int to_lower)
3541
32.0M
{
3542
32.0M
    const char *e;
3543
32.0M
    char *l;
3544
32.0M
    char *l_end;
3545
32.0M
    int punct;
3546
3547
32.0M
    assert(encoding != NULL);
3548
3549
32.0M
    e = encoding;
3550
32.0M
    l = lower;
3551
32.0M
    l_end = &lower[lower_len - 1];
3552
32.0M
    punct = 0;
3553
214M
    while (1) {
3554
214M
        char c = *e;
3555
214M
        if (c == 0) {
3556
31.2M
            break;
3557
31.2M
        }
3558
3559
183M
        if (Py_ISALNUM(c) || c == '.') {
3560
166M
            if (punct && l != lower) {
3561
12.4M
                if (l == l_end) {
3562
2.33k
                    return 0;
3563
2.33k
                }
3564
12.4M
                *l++ = '_';
3565
12.4M
            }
3566
166M
            punct = 0;
3567
3568
166M
            if (l == l_end) {
3569
705k
                return 0;
3570
705k
            }
3571
166M
            *l++ = to_lower ? Py_TOLOWER(c) : c;
3572
166M
        }
3573
16.8M
        else {
3574
16.8M
            punct = 1;
3575
16.8M
        }
3576
3577
182M
        e++;
3578
182M
    }
3579
31.2M
    *l = '\0';
3580
31.2M
    return 1;
3581
32.0M
}
3582
3583
PyObject *
3584
PyUnicode_Decode(const char *s,
3585
                 Py_ssize_t size,
3586
                 const char *encoding,
3587
                 const char *errors)
3588
22.7M
{
3589
22.7M
    PyObject *buffer = NULL, *unicode;
3590
22.7M
    Py_buffer info;
3591
22.7M
    char buflower[11];   /* strlen("iso-8859-1\0") == 11, longest shortcut */
3592
3593
22.7M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3594
0
        return NULL;
3595
0
    }
3596
3597
22.7M
    if (size == 0) {
3598
0
        _Py_RETURN_UNICODE_EMPTY();
3599
0
    }
3600
3601
22.7M
    if (encoding == NULL) {
3602
54.3k
        return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3603
54.3k
    }
3604
3605
    /* Shortcuts for common default encodings */
3606
22.6M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3607
22.6M
        char *lower = buflower;
3608
3609
        /* Fast paths */
3610
22.6M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3611
3.79M
            lower += 3;
3612
3.79M
            if (*lower == '_') {
3613
                /* Match "utf8" and "utf_8" */
3614
3.79M
                lower++;
3615
3.79M
            }
3616
3617
3.79M
            if (lower[0] == '8' && lower[1] == 0) {
3618
3.78M
                return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3619
3.78M
            }
3620
14.1k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3621
184
                return PyUnicode_DecodeUTF16(s, size, errors, 0);
3622
184
            }
3623
13.9k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3624
132
                return PyUnicode_DecodeUTF32(s, size, errors, 0);
3625
132
            }
3626
3.79M
        }
3627
18.8M
        else {
3628
18.8M
            if (strcmp(lower, "ascii") == 0
3629
14.1M
                || strcmp(lower, "us_ascii") == 0) {
3630
14.1M
                return PyUnicode_DecodeASCII(s, size, errors);
3631
14.1M
            }
3632
    #ifdef MS_WINDOWS
3633
            else if (strcmp(lower, "mbcs") == 0) {
3634
                return PyUnicode_DecodeMBCS(s, size, errors);
3635
            }
3636
    #endif
3637
4.78M
            else if (strcmp(lower, "latin1") == 0
3638
4.78M
                     || strcmp(lower, "latin_1") == 0
3639
1.96M
                     || strcmp(lower, "iso_8859_1") == 0
3640
2.84M
                     || strcmp(lower, "iso8859_1") == 0) {
3641
2.84M
                return PyUnicode_DecodeLatin1(s, size, errors);
3642
2.84M
            }
3643
18.8M
        }
3644
22.6M
    }
3645
3646
    /* Decode via the codec registry */
3647
1.96M
    buffer = NULL;
3648
1.96M
    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
3649
0
        goto onError;
3650
1.96M
    buffer = PyMemoryView_FromBuffer(&info);
3651
1.96M
    if (buffer == NULL)
3652
0
        goto onError;
3653
1.96M
    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
3654
1.96M
    if (unicode == NULL)
3655
60.6k
        goto onError;
3656
1.90M
    if (!PyUnicode_Check(unicode)) {
3657
0
        PyErr_Format(PyExc_TypeError,
3658
0
                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
3659
0
                     "use codecs.decode() to decode to arbitrary types",
3660
0
                     encoding,
3661
0
                     Py_TYPE(unicode)->tp_name);
3662
0
        Py_DECREF(unicode);
3663
0
        goto onError;
3664
0
    }
3665
1.90M
    Py_DECREF(buffer);
3666
1.90M
    return unicode_result(unicode);
3667
3668
60.6k
  onError:
3669
60.6k
    Py_XDECREF(buffer);
3670
60.6k
    return NULL;
3671
1.90M
}
3672
3673
PyAPI_FUNC(PyObject *)
3674
PyUnicode_AsDecodedObject(PyObject *unicode,
3675
                          const char *encoding,
3676
                          const char *errors)
3677
0
{
3678
0
    if (!PyUnicode_Check(unicode)) {
3679
0
        PyErr_BadArgument();
3680
0
        return NULL;
3681
0
    }
3682
3683
0
    if (encoding == NULL)
3684
0
        encoding = PyUnicode_GetDefaultEncoding();
3685
3686
    /* Decode via the codec registry */
3687
0
    return PyCodec_Decode(unicode, encoding, errors);
3688
0
}
3689
3690
PyAPI_FUNC(PyObject *)
3691
PyUnicode_AsDecodedUnicode(PyObject *unicode,
3692
                           const char *encoding,
3693
                           const char *errors)
3694
0
{
3695
0
    PyObject *v;
3696
3697
0
    if (!PyUnicode_Check(unicode)) {
3698
0
        PyErr_BadArgument();
3699
0
        goto onError;
3700
0
    }
3701
3702
0
    if (encoding == NULL)
3703
0
        encoding = PyUnicode_GetDefaultEncoding();
3704
3705
    /* Decode via the codec registry */
3706
0
    v = PyCodec_Decode(unicode, encoding, errors);
3707
0
    if (v == NULL)
3708
0
        goto onError;
3709
0
    if (!PyUnicode_Check(v)) {
3710
0
        PyErr_Format(PyExc_TypeError,
3711
0
                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
3712
0
                     "use codecs.decode() to decode to arbitrary types",
3713
0
                     encoding,
3714
0
                     Py_TYPE(unicode)->tp_name);
3715
0
        Py_DECREF(v);
3716
0
        goto onError;
3717
0
    }
3718
0
    return unicode_result(v);
3719
3720
0
  onError:
3721
0
    return NULL;
3722
0
}
3723
3724
PyAPI_FUNC(PyObject *)
3725
PyUnicode_AsEncodedObject(PyObject *unicode,
3726
                          const char *encoding,
3727
                          const char *errors)
3728
0
{
3729
0
    PyObject *v;
3730
3731
0
    if (!PyUnicode_Check(unicode)) {
3732
0
        PyErr_BadArgument();
3733
0
        goto onError;
3734
0
    }
3735
3736
0
    if (encoding == NULL)
3737
0
        encoding = PyUnicode_GetDefaultEncoding();
3738
3739
    /* Encode via the codec registry */
3740
0
    v = PyCodec_Encode(unicode, encoding, errors);
3741
0
    if (v == NULL)
3742
0
        goto onError;
3743
0
    return v;
3744
3745
0
  onError:
3746
0
    return NULL;
3747
0
}
3748
3749
3750
static PyObject *
3751
unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
3752
                      int current_locale)
3753
1.44k
{
3754
1.44k
    Py_ssize_t wlen;
3755
1.44k
    wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3756
1.44k
    if (wstr == NULL) {
3757
0
        return NULL;
3758
0
    }
3759
3760
1.44k
    if ((size_t)wlen != wcslen(wstr)) {
3761
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
3762
0
        PyMem_Free(wstr);
3763
0
        return NULL;
3764
0
    }
3765
3766
1.44k
    char *str;
3767
1.44k
    size_t str_len;
3768
1.44k
    size_t error_pos;
3769
1.44k
    int res = _Py_EncodeLocale(wstr, &str, &str_len, &error_pos,
3770
1.44k
                               current_locale, error_handler);
3771
1.44k
    PyMem_Free(wstr);
3772
3773
1.44k
    if (res != 0) {
3774
0
        if (res == _Py_CODEC_ENCODE_ERROR) {
3775
0
            PyObject *exc;
3776
0
            assert(error_pos <= (size_t)(PY_SSIZE_T_MAX - 1));
3777
0
            exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3778
0
                    "locale", unicode,
3779
0
                    (Py_ssize_t)error_pos,
3780
0
                    (Py_ssize_t)(error_pos+1),
3781
0
                    "encode error");
3782
0
            if (exc != NULL) {
3783
0
                PyCodec_StrictErrors(exc);
3784
0
                Py_DECREF(exc);
3785
0
            }
3786
0
        }
3787
0
        else if (res == _Py_CODEC_UNSUPPORTED_ERROR_HANDLER) {
3788
0
            PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3789
0
        }
3790
0
        else {
3791
0
            assert(res == _Py_CODEC_MEMORY_ERROR);
3792
0
            PyErr_NoMemory();
3793
0
        }
3794
0
        return NULL;
3795
0
    }
3796
3797
1.44k
    PyObject *bytes = PyBytes_FromStringAndSize(str, str_len);
3798
1.44k
    PyMem_RawFree(str);
3799
1.44k
    return bytes;
3800
1.44k
}
3801
3802
PyObject *
3803
PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3804
0
{
3805
0
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3806
0
    return unicode_encode_locale(unicode, error_handler, 1);
3807
0
}
3808
3809
PyObject *
3810
PyUnicode_EncodeFSDefault(PyObject *unicode)
3811
701k
{
3812
701k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3813
701k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3814
701k
    if (fs_codec->utf8) {
3815
700k
        return unicode_encode_utf8(unicode,
3816
700k
                                   fs_codec->error_handler,
3817
700k
                                   fs_codec->errors);
3818
700k
    }
3819
1.44k
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3820
1.44k
    else if (fs_codec->encoding) {
3821
0
        return PyUnicode_AsEncodedString(unicode,
3822
0
                                         fs_codec->encoding,
3823
0
                                         fs_codec->errors);
3824
0
    }
3825
1.44k
#endif
3826
1.44k
    else {
3827
        /* Before _PyUnicode_InitEncodings() is called, the Python codec
3828
           machinery is not ready and so cannot be used:
3829
           use wcstombs() in this case. */
3830
1.44k
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3831
1.44k
        const wchar_t *filesystem_errors = config->filesystem_errors;
3832
1.44k
        assert(filesystem_errors != NULL);
3833
1.44k
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3834
1.44k
        assert(errors != _Py_ERROR_UNKNOWN);
3835
#ifdef _Py_FORCE_UTF8_FS_ENCODING
3836
        return unicode_encode_utf8(unicode, errors, NULL);
3837
#else
3838
1.44k
        return unicode_encode_locale(unicode, errors, 0);
3839
1.44k
#endif
3840
1.44k
    }
3841
701k
}
3842
3843
PyObject *
3844
PyUnicode_AsEncodedString(PyObject *unicode,
3845
                          const char *encoding,
3846
                          const char *errors)
3847
21.7M
{
3848
21.7M
    PyObject *v;
3849
21.7M
    char buflower[11];   /* strlen("iso_8859_1\0") == 11, longest shortcut */
3850
3851
21.7M
    if (!PyUnicode_Check(unicode)) {
3852
0
        PyErr_BadArgument();
3853
0
        return NULL;
3854
0
    }
3855
3856
21.7M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3857
0
        return NULL;
3858
0
    }
3859
3860
21.7M
    if (encoding == NULL) {
3861
12.4M
        return _PyUnicode_AsUTF8String(unicode, errors);
3862
12.4M
    }
3863
3864
    /* Shortcuts for common default encodings */
3865
9.30M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3866
8.60M
        char *lower = buflower;
3867
3868
        /* Fast paths */
3869
8.60M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3870
4.86M
            lower += 3;
3871
4.86M
            if (*lower == '_') {
3872
                /* Match "utf8" and "utf_8" */
3873
4.86M
                lower++;
3874
4.86M
            }
3875
3876
4.86M
            if (lower[0] == '8' && lower[1] == 0) {
3877
4.86M
                return _PyUnicode_AsUTF8String(unicode, errors);
3878
4.86M
            }
3879
8.37k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3880
0
                return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3881
0
            }
3882
8.37k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3883
0
                return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3884
0
            }
3885
4.86M
        }
3886
3.73M
        else {
3887
3.73M
            if (strcmp(lower, "ascii") == 0
3888
2.54M
                || strcmp(lower, "us_ascii") == 0) {
3889
2.54M
                return _PyUnicode_AsASCIIString(unicode, errors);
3890
2.54M
            }
3891
#ifdef MS_WINDOWS
3892
            else if (strcmp(lower, "mbcs") == 0) {
3893
                return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3894
            }
3895
#endif
3896
1.18M
            else if (strcmp(lower, "latin1") == 0 ||
3897
1.18M
                     strcmp(lower, "latin_1") == 0 ||
3898
1.18M
                     strcmp(lower, "iso_8859_1") == 0 ||
3899
1.18M
                     strcmp(lower, "iso8859_1") == 0) {
3900
10
                return _PyUnicode_AsLatin1String(unicode, errors);
3901
10
            }
3902
3.73M
        }
3903
8.60M
    }
3904
3905
    /* Encode via the codec registry */
3906
1.90M
    v = _PyCodec_EncodeText(unicode, encoding, errors);
3907
1.90M
    if (v == NULL)
3908
0
        return NULL;
3909
3910
    /* The normal path */
3911
1.90M
    if (PyBytes_Check(v))
3912
1.90M
        return v;
3913
3914
    /* If the codec returns a buffer, raise a warning and convert to bytes */
3915
0
    if (PyByteArray_Check(v)) {
3916
0
        int error;
3917
0
        PyObject *b;
3918
3919
0
        error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3920
0
            "encoder %s returned bytearray instead of bytes; "
3921
0
            "use codecs.encode() to encode to arbitrary types",
3922
0
            encoding);
3923
0
        if (error) {
3924
0
            Py_DECREF(v);
3925
0
            return NULL;
3926
0
        }
3927
3928
0
        b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3929
0
                                      PyByteArray_GET_SIZE(v));
3930
0
        Py_DECREF(v);
3931
0
        return b;
3932
0
    }
3933
3934
0
    PyErr_Format(PyExc_TypeError,
3935
0
                 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3936
0
                 "use codecs.encode() to encode to arbitrary types",
3937
0
                 encoding,
3938
0
                 Py_TYPE(v)->tp_name);
3939
0
    Py_DECREF(v);
3940
0
    return NULL;
3941
0
}
3942
3943
PyAPI_FUNC(PyObject *)
3944
PyUnicode_AsEncodedUnicode(PyObject *unicode,
3945
                           const char *encoding,
3946
                           const char *errors)
3947
0
{
3948
0
    PyObject *v;
3949
3950
0
    if (!PyUnicode_Check(unicode)) {
3951
0
        PyErr_BadArgument();
3952
0
        goto onError;
3953
0
    }
3954
3955
0
    if (encoding == NULL)
3956
0
        encoding = PyUnicode_GetDefaultEncoding();
3957
3958
    /* Encode via the codec registry */
3959
0
    v = PyCodec_Encode(unicode, encoding, errors);
3960
0
    if (v == NULL)
3961
0
        goto onError;
3962
0
    if (!PyUnicode_Check(v)) {
3963
0
        PyErr_Format(PyExc_TypeError,
3964
0
                     "'%.400s' encoder returned '%.400s' instead of 'str'; "
3965
0
                     "use codecs.encode() to encode to arbitrary types",
3966
0
                     encoding,
3967
0
                     Py_TYPE(v)->tp_name);
3968
0
        Py_DECREF(v);
3969
0
        goto onError;
3970
0
    }
3971
0
    return v;
3972
3973
0
  onError:
3974
0
    return NULL;
3975
0
}
3976
3977
static PyObject*
3978
unicode_decode_locale(const char *str, Py_ssize_t len,
3979
                      _Py_error_handler errors, int current_locale)
3980
244k
{
3981
244k
    if (str[len] != '\0' || (size_t)len != strlen(str))  {
3982
0
        PyErr_SetString(PyExc_ValueError, "embedded null byte");
3983
0
        return NULL;
3984
0
    }
3985
3986
244k
    wchar_t *wstr;
3987
244k
    size_t wlen;
3988
244k
    int res = _Py_DecodeLocale(str, &wstr, &wlen, current_locale, errors);
3989
244k
    if (res != 0) {
3990
0
        if (res == _Py_CODEC_DECODE_ERROR) {
3991
0
            PyObject *exc;
3992
0
            assert(wlen <= (size_t)(PY_SSIZE_T_MAX - 1));
3993
0
            exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3994
0
                                        "locale", str, len,
3995
0
                                        (Py_ssize_t)wlen,
3996
0
                                        (Py_ssize_t)(wlen + 1),
3997
0
                                        "decode error");
3998
0
            if (exc != NULL) {
3999
0
                PyCodec_StrictErrors(exc);
4000
0
                Py_DECREF(exc);
4001
0
            }
4002
0
        }
4003
0
        else if (res == _Py_CODEC_UNSUPPORTED_ERROR_HANDLER) {
4004
0
            PyErr_SetString(PyExc_ValueError, "unsupported error handler");
4005
0
        }
4006
0
        else {
4007
0
            assert(res == _Py_CODEC_MEMORY_ERROR);
4008
0
            PyErr_NoMemory();
4009
0
        }
4010
0
        return NULL;
4011
0
    }
4012
4013
244k
    PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
4014
244k
    PyMem_RawFree(wstr);
4015
244k
    return unicode;
4016
244k
}
4017
4018
PyObject*
4019
PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
4020
                              const char *errors)
4021
0
{
4022
0
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
4023
0
    return unicode_decode_locale(str, len, error_handler, 1);
4024
0
}
4025
4026
PyObject*
4027
PyUnicode_DecodeLocale(const char *str, const char *errors)
4028
232k
{
4029
232k
    Py_ssize_t size = (Py_ssize_t)strlen(str);
4030
232k
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
4031
232k
    return unicode_decode_locale(str, size, error_handler, 1);
4032
232k
}
4033
4034
4035
PyObject*
4036
689
PyUnicode_DecodeFSDefault(const char *s) {
4037
689
    Py_ssize_t size = (Py_ssize_t)strlen(s);
4038
689
    return PyUnicode_DecodeFSDefaultAndSize(s, size);
4039
689
}
4040
4041
PyObject*
4042
PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
4043
128k
{
4044
128k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4045
128k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
4046
128k
    if (fs_codec->utf8) {
4047
116k
        return unicode_decode_utf8(s, size,
4048
116k
                                   fs_codec->error_handler,
4049
116k
                                   fs_codec->errors,
4050
116k
                                   NULL);
4051
116k
    }
4052
12.0k
#ifndef _Py_FORCE_UTF8_FS_ENCODING
4053
12.0k
    else if (fs_codec->encoding) {
4054
0
        return PyUnicode_Decode(s, size,
4055
0
                                fs_codec->encoding,
4056
0
                                fs_codec->errors);
4057
0
    }
4058
12.0k
#endif
4059
12.0k
    else {
4060
        /* Before _PyUnicode_InitEncodings() is called, the Python codec
4061
           machinery is not ready and so cannot be used:
4062
           use mbstowcs() in this case. */
4063
12.0k
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
4064
12.0k
        const wchar_t *filesystem_errors = config->filesystem_errors;
4065
12.0k
        assert(filesystem_errors != NULL);
4066
12.0k
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
4067
12.0k
        assert(errors != _Py_ERROR_UNKNOWN);
4068
#ifdef _Py_FORCE_UTF8_FS_ENCODING
4069
        return unicode_decode_utf8(s, size, errors, NULL, NULL);
4070
#else
4071
12.0k
        return unicode_decode_locale(s, size, errors, 0);
4072
12.0k
#endif
4073
12.0k
    }
4074
128k
}
4075
4076
4077
int
4078
PyUnicode_FSConverter(PyObject* arg, void* addr)
4079
164k
{
4080
164k
    PyObject *path = NULL;
4081
164k
    PyObject *output = NULL;
4082
164k
    Py_ssize_t size;
4083
164k
    const char *data;
4084
164k
    if (arg == NULL) {
4085
0
        Py_DECREF(*(PyObject**)addr);
4086
0
        *(PyObject**)addr = NULL;
4087
0
        return 1;
4088
0
    }
4089
164k
    path = PyOS_FSPath(arg);
4090
164k
    if (path == NULL) {
4091
0
        return 0;
4092
0
    }
4093
164k
    if (PyBytes_Check(path)) {
4094
0
        output = path;
4095
0
    }
4096
164k
    else {  // PyOS_FSPath() guarantees its returned value is bytes or str.
4097
164k
        output = PyUnicode_EncodeFSDefault(path);
4098
164k
        Py_DECREF(path);
4099
164k
        if (!output) {
4100
0
            return 0;
4101
0
        }
4102
164k
        assert(PyBytes_Check(output));
4103
164k
    }
4104
4105
164k
    size = PyBytes_GET_SIZE(output);
4106
164k
    data = PyBytes_AS_STRING(output);
4107
164k
    if ((size_t)size != strlen(data)) {
4108
0
        PyErr_SetString(PyExc_ValueError, "embedded null byte");
4109
0
        Py_DECREF(output);
4110
0
        return 0;
4111
0
    }
4112
164k
    *(PyObject**)addr = output;
4113
164k
    return Py_CLEANUP_SUPPORTED;
4114
164k
}
4115
4116
4117
int
4118
PyUnicode_FSDecoder(PyObject* arg, void* addr)
4119
64.4k
{
4120
64.4k
    if (arg == NULL) {
4121
0
        Py_DECREF(*(PyObject**)addr);
4122
0
        *(PyObject**)addr = NULL;
4123
0
        return 1;
4124
0
    }
4125
4126
64.4k
    PyObject *path = PyOS_FSPath(arg);
4127
64.4k
    if (path == NULL) {
4128
0
        return 0;
4129
0
    }
4130
4131
64.4k
    PyObject *output = NULL;
4132
64.4k
    if (PyUnicode_Check(path)) {
4133
64.4k
        output = path;
4134
64.4k
    }
4135
0
    else if (PyBytes_Check(path)) {
4136
0
        output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path),
4137
0
                                                  PyBytes_GET_SIZE(path));
4138
0
        Py_DECREF(path);
4139
0
        if (!output) {
4140
0
            return 0;
4141
0
        }
4142
0
    }
4143
0
    else {
4144
0
        PyErr_Format(PyExc_TypeError,
4145
0
                     "path should be string, bytes, or os.PathLike, not %.200s",
4146
0
                     Py_TYPE(arg)->tp_name);
4147
0
        Py_DECREF(path);
4148
0
        return 0;
4149
0
    }
4150
4151
64.4k
    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
4152
64.4k
                 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
4153
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4154
0
        Py_DECREF(output);
4155
0
        return 0;
4156
0
    }
4157
64.4k
    *(PyObject**)addr = output;
4158
64.4k
    return Py_CLEANUP_SUPPORTED;
4159
64.4k
}
4160
4161
4162
static int unicode_fill_utf8(PyObject *unicode);
4163
4164
4165
static int
4166
unicode_ensure_utf8(PyObject *unicode)
4167
65.6M
{
4168
65.6M
    int err = 0;
4169
65.6M
    if (PyUnicode_UTF8(unicode) == NULL) {
4170
176k
        Py_BEGIN_CRITICAL_SECTION(unicode);
4171
176k
        if (PyUnicode_UTF8(unicode) == NULL) {
4172
176k
            err = unicode_fill_utf8(unicode);
4173
176k
        }
4174
176k
        Py_END_CRITICAL_SECTION();
4175
176k
    }
4176
65.6M
    return err;
4177
65.6M
}
4178
4179
const char *
4180
PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
4181
65.6M
{
4182
65.6M
    if (!PyUnicode_Check(unicode)) {
4183
0
        PyErr_BadArgument();
4184
0
        if (psize) {
4185
0
            *psize = -1;
4186
0
        }
4187
0
        return NULL;
4188
0
    }
4189
4190
65.6M
    if (unicode_ensure_utf8(unicode) == -1) {
4191
262
        if (psize) {
4192
262
            *psize = -1;
4193
262
        }
4194
262
        return NULL;
4195
262
    }
4196
4197
65.6M
    if (psize) {
4198
65.4M
        *psize = PyUnicode_UTF8_LENGTH(unicode);
4199
65.4M
    }
4200
65.6M
    return PyUnicode_UTF8(unicode);
4201
65.6M
}
4202
4203
const char *
4204
PyUnicode_AsUTF8(PyObject *unicode)
4205
162k
{
4206
162k
    return PyUnicode_AsUTF8AndSize(unicode, NULL);
4207
162k
}
4208
4209
const char *
4210
_PyUnicode_AsUTF8NoNUL(PyObject *unicode)
4211
55.7M
{
4212
55.7M
    Py_ssize_t size;
4213
55.7M
    const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
4214
55.7M
    if (s && strlen(s) != (size_t)size) {
4215
2.08k
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4216
2.08k
        return NULL;
4217
2.08k
    }
4218
55.7M
    return s;
4219
55.7M
}
4220
4221
/*
4222
PyUnicode_GetSize() has been deprecated since Python 3.3
4223
because it returned length of Py_UNICODE.
4224
4225
But this function is part of stable abi, because it doesn't
4226
include Py_UNICODE in signature and it was not excluded from
4227
stable ABI in PEP 384.
4228
*/
4229
PyAPI_FUNC(Py_ssize_t)
4230
PyUnicode_GetSize(PyObject *unicode)
4231
0
{
4232
0
    PyErr_SetString(PyExc_RuntimeError,
4233
0
                    "PyUnicode_GetSize has been removed.");
4234
0
    return -1;
4235
0
}
4236
4237
Py_ssize_t
4238
PyUnicode_GetLength(PyObject *unicode)
4239
25.6k
{
4240
25.6k
    if (!PyUnicode_Check(unicode)) {
4241
0
        PyErr_BadArgument();
4242
0
        return -1;
4243
0
    }
4244
25.6k
    return PyUnicode_GET_LENGTH(unicode);
4245
25.6k
}
4246
4247
Py_UCS4
4248
PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4249
1.59k
{
4250
1.59k
    const void *data;
4251
1.59k
    int kind;
4252
4253
1.59k
    if (!PyUnicode_Check(unicode)) {
4254
0
        PyErr_BadArgument();
4255
0
        return (Py_UCS4)-1;
4256
0
    }
4257
1.59k
    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
4258
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
4259
0
        return (Py_UCS4)-1;
4260
0
    }
4261
1.59k
    data = PyUnicode_DATA(unicode);
4262
1.59k
    kind = PyUnicode_KIND(unicode);
4263
1.59k
    return PyUnicode_READ(kind, data, index);
4264
1.59k
}
4265
4266
int
4267
PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4268
0
{
4269
0
    if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
4270
0
        PyErr_BadArgument();
4271
0
        return -1;
4272
0
    }
4273
0
    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
4274
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
4275
0
        return -1;
4276
0
    }
4277
0
    if (unicode_check_modifiable(unicode))
4278
0
        return -1;
4279
0
    if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4280
0
        PyErr_SetString(PyExc_ValueError, "character out of range");
4281
0
        return -1;
4282
0
    }
4283
0
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4284
0
                    index, ch);
4285
0
    return 0;
4286
0
}
4287
4288
const char *
4289
PyUnicode_GetDefaultEncoding(void)
4290
0
{
4291
0
    return "utf-8";
4292
0
}
4293
4294
/* create or adjust a UnicodeDecodeError */
4295
static void
4296
make_decode_exception(PyObject **exceptionObject,
4297
                      const char *encoding,
4298
                      const char *input, Py_ssize_t length,
4299
                      Py_ssize_t startpos, Py_ssize_t endpos,
4300
                      const char *reason)
4301
3.20M
{
4302
3.20M
    if (*exceptionObject == NULL) {
4303
2.96M
        *exceptionObject = PyUnicodeDecodeError_Create(
4304
2.96M
            encoding, input, length, startpos, endpos, reason);
4305
2.96M
    }
4306
244k
    else {
4307
244k
        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4308
0
            goto onError;
4309
244k
        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4310
0
            goto onError;
4311
244k
        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4312
0
            goto onError;
4313
244k
    }
4314
3.20M
    return;
4315
4316
3.20M
onError:
4317
0
    Py_CLEAR(*exceptionObject);
4318
0
}
4319
4320
#ifdef MS_WINDOWS
4321
static int
4322
widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
4323
{
4324
    if (newsize > *size) {
4325
        wchar_t *newbuf = *buf;
4326
        if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
4327
            PyErr_NoMemory();
4328
            return -1;
4329
        }
4330
        *buf = newbuf;
4331
    }
4332
    *size = newsize;
4333
    return 0;
4334
}
4335
4336
/* error handling callback helper:
4337
   build arguments, call the callback and check the arguments,
4338
   if no exception occurred, copy the replacement to the output
4339
   and adjust various state variables.
4340
   return 0 on success, -1 on error
4341
*/
4342
4343
static int
4344
unicode_decode_call_errorhandler_wchar(
4345
    const char *errors, PyObject **errorHandler,
4346
    const char *encoding, const char *reason,
4347
    const char **input, const char **inend, Py_ssize_t *startinpos,
4348
    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4349
    wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
4350
{
4351
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4352
4353
    PyObject *restuple = NULL;
4354
    PyObject *repunicode = NULL;
4355
    Py_ssize_t outsize;
4356
    Py_ssize_t insize;
4357
    Py_ssize_t requiredsize;
4358
    Py_ssize_t newpos;
4359
    PyObject *inputobj = NULL;
4360
    Py_ssize_t repwlen;
4361
4362
    if (*errorHandler == NULL) {
4363
        *errorHandler = PyCodec_LookupError(errors);
4364
        if (*errorHandler == NULL)
4365
            goto onError;
4366
    }
4367
4368
    make_decode_exception(exceptionObject,
4369
        encoding,
4370
        *input, *inend - *input,
4371
        *startinpos, *endinpos,
4372
        reason);
4373
    if (*exceptionObject == NULL)
4374
        goto onError;
4375
4376
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4377
    if (restuple == NULL)
4378
        goto onError;
4379
    if (!PyTuple_Check(restuple)) {
4380
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4381
        goto onError;
4382
    }
4383
    if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
4384
        goto onError;
4385
4386
    /* Copy back the bytes variables, which might have been modified by the
4387
       callback */
4388
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4389
    if (!inputobj)
4390
        goto onError;
4391
    *input = PyBytes_AS_STRING(inputobj);
4392
    insize = PyBytes_GET_SIZE(inputobj);
4393
    *inend = *input + insize;
4394
    /* we can DECREF safely, as the exception has another reference,
4395
       so the object won't go away. */
4396
    Py_DECREF(inputobj);
4397
4398
    if (newpos<0)
4399
        newpos = insize+newpos;
4400
    if (newpos<0 || newpos>insize) {
4401
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4402
        goto onError;
4403
    }
4404
4405
    repwlen = PyUnicode_AsWideChar(repunicode, NULL, 0);
4406
    if (repwlen < 0)
4407
        goto onError;
4408
    repwlen--;
4409
    /* need more space? (at least enough for what we
4410
       have+the replacement+the rest of the string (starting
4411
       at the new input position), so we won't have to check space
4412
       when there are no errors in the rest of the string) */
4413
    requiredsize = *outpos;
4414
    if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4415
        goto overflow;
4416
    requiredsize += repwlen;
4417
    if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4418
        goto overflow;
4419
    requiredsize += insize - newpos;
4420
    outsize = *bufsize;
4421
    if (requiredsize > outsize) {
4422
        if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
4423
            requiredsize = 2*outsize;
4424
        if (widechar_resize(buf, bufsize, requiredsize) < 0) {
4425
            goto onError;
4426
        }
4427
    }
4428
    PyUnicode_AsWideChar(repunicode, *buf + *outpos, repwlen);
4429
    *outpos += repwlen;
4430
    *endinpos = newpos;
4431
    *inptr = *input + newpos;
4432
4433
    /* we made it! */
4434
    Py_DECREF(restuple);
4435
    return 0;
4436
4437
  overflow:
4438
    PyErr_SetString(PyExc_OverflowError,
4439
                    "decoded result is too long for a Python string");
4440
4441
  onError:
4442
    Py_XDECREF(restuple);
4443
    return -1;
4444
}
4445
#endif   /* MS_WINDOWS */
4446
4447
static int
4448
unicode_decode_call_errorhandler_writer(
4449
    const char *errors, PyObject **errorHandler,
4450
    const char *encoding, const char *reason,
4451
    const char **input, const char **inend, Py_ssize_t *startinpos,
4452
    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4453
    _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4454
3.20M
{
4455
3.20M
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4456
4457
3.20M
    PyObject *restuple = NULL;
4458
3.20M
    PyObject *repunicode = NULL;
4459
3.20M
    Py_ssize_t insize;
4460
3.20M
    Py_ssize_t newpos;
4461
3.20M
    Py_ssize_t replen;
4462
3.20M
    Py_ssize_t remain;
4463
3.20M
    PyObject *inputobj = NULL;
4464
3.20M
    int need_to_grow = 0;
4465
3.20M
    const char *new_inptr;
4466
4467
3.20M
    if (*errorHandler == NULL) {
4468
2.96M
        *errorHandler = PyCodec_LookupError(errors);
4469
2.96M
        if (*errorHandler == NULL)
4470
0
            goto onError;
4471
2.96M
    }
4472
4473
3.20M
    make_decode_exception(exceptionObject,
4474
3.20M
        encoding,
4475
3.20M
        *input, *inend - *input,
4476
3.20M
        *startinpos, *endinpos,
4477
3.20M
        reason);
4478
3.20M
    if (*exceptionObject == NULL)
4479
0
        goto onError;
4480
4481
3.20M
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4482
3.20M
    if (restuple == NULL)
4483
2.92M
        goto onError;
4484
284k
    if (!PyTuple_Check(restuple)) {
4485
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4486
0
        goto onError;
4487
0
    }
4488
284k
    if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
4489
0
        goto onError;
4490
4491
    /* Copy back the bytes variables, which might have been modified by the
4492
       callback */
4493
284k
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4494
284k
    if (!inputobj)
4495
0
        goto onError;
4496
284k
    remain = *inend - *input - *endinpos;
4497
284k
    *input = PyBytes_AS_STRING(inputobj);
4498
284k
    insize = PyBytes_GET_SIZE(inputobj);
4499
284k
    *inend = *input + insize;
4500
    /* we can DECREF safely, as the exception has another reference,
4501
       so the object won't go away. */
4502
284k
    Py_DECREF(inputobj);
4503
4504
284k
    if (newpos<0)
4505
0
        newpos = insize+newpos;
4506
284k
    if (newpos<0 || newpos>insize) {
4507
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4508
0
        goto onError;
4509
0
    }
4510
4511
284k
    replen = PyUnicode_GET_LENGTH(repunicode);
4512
284k
    if (replen > 1) {
4513
17.2k
        writer->min_length += replen - 1;
4514
17.2k
        need_to_grow = 1;
4515
17.2k
    }
4516
284k
    new_inptr = *input + newpos;
4517
284k
    if (*inend - new_inptr > remain) {
4518
        /* We don't know the decoding algorithm here so we make the worst
4519
           assumption that one byte decodes to one unicode character.
4520
           If unfortunately one byte could decode to more unicode characters,
4521
           the decoder may write out-of-bound then.  Is it possible for the
4522
           algorithms using this function? */
4523
6.84k
        writer->min_length += *inend - new_inptr - remain;
4524
6.84k
        need_to_grow = 1;
4525
6.84k
    }
4526
284k
    if (need_to_grow) {
4527
17.3k
        writer->overallocate = 1;
4528
17.3k
        if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
4529
17.3k
                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4530
0
            goto onError;
4531
17.3k
    }
4532
284k
    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4533
0
        goto onError;
4534
4535
284k
    *endinpos = newpos;
4536
284k
    *inptr = new_inptr;
4537
4538
    /* we made it! */
4539
284k
    Py_DECREF(restuple);
4540
284k
    return 0;
4541
4542
2.92M
  onError:
4543
2.92M
    Py_XDECREF(restuple);
4544
2.92M
    return -1;
4545
284k
}
4546
4547
/* --- UTF-7 Codec -------------------------------------------------------- */
4548
4549
/* See RFC2152 for details.  We encode conservatively and decode liberally. */
4550
4551
/* Three simple macros defining base-64. */
4552
4553
/* Is c a base-64 character? */
4554
4555
#define IS_BASE64(c) \
4556
383k
    (((c) >= 'A' && (c) <= 'Z') ||     \
4557
383k
     ((c) >= 'a' && (c) <= 'z') ||     \
4558
383k
     ((c) >= '0' && (c) <= '9') ||     \
4559
383k
     (c) == '+' || (c) == '/')
4560
4561
/* given that c is a base-64 character, what is its base-64 value? */
4562
4563
#define FROM_BASE64(c)                                                  \
4564
342k
    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
4565
342k
     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
4566
209k
     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
4567
121k
     (c) == '+' ? 62 : 63)
4568
4569
/* What is the base-64 character of the bottom 6 bits of n? */
4570
4571
#define TO_BASE64(n)  \
4572
0
    ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4573
4574
/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4575
 * decoded as itself.  We are permissive on decoding; the only ASCII
4576
 * byte not decoding to itself is the + which begins a base64
4577
 * string. */
4578
4579
#define DECODE_DIRECT(c)                                \
4580
6.19M
    ((c) <= 127 && (c) != '+')
4581
4582
/* The UTF-7 encoder treats ASCII characters differently according to
4583
 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4584
 * the above).  See RFC2152.  This array identifies these different
4585
 * sets:
4586
 * 0 : "Set D"
4587
 *     alphanumeric and '(),-./:?
4588
 * 1 : "Set O"
4589
 *     !"#$%&*;<=>@[]^_`{|}
4590
 * 2 : "whitespace"
4591
 *     ht nl cr sp
4592
 * 3 : special (must be base64 encoded)
4593
 *     everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4594
 */
4595
4596
static
4597
char utf7_category[128] = {
4598
/* nul soh stx etx eot enq ack bel bs  ht  nl  vt  np  cr  so  si  */
4599
    3,  3,  3,  3,  3,  3,  3,  3,  3,  2,  2,  3,  3,  2,  3,  3,
4600
/* dle dc1 dc2 dc3 dc4 nak syn etb can em  sub esc fs  gs  rs  us  */
4601
    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
4602
/* sp   !   "   #   $   %   &   '   (   )   *   +   ,   -   .   /  */
4603
    2,  1,  1,  1,  1,  1,  1,  0,  0,  0,  1,  3,  0,  0,  0,  0,
4604
/*  0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?  */
4605
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0,
4606
/*  @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O  */
4607
    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
4608
/*  P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _  */
4609
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  3,  1,  1,  1,
4610
/*  `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o  */
4611
    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
4612
/*  p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~  del */
4613
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  3,  3,
4614
};
4615
4616
/* ENCODE_DIRECT: this character should be encoded as itself.  The
4617
 * answer depends on whether we are encoding set O as itself, and also
4618
 * on whether we are encoding whitespace as itself.  RFC 2152 makes it
4619
 * clear that the answers to these questions vary between
4620
 * applications, so this code needs to be flexible.  */
4621
4622
#define ENCODE_DIRECT(c) \
4623
0
    ((c) < 128 && (c) > 0 && ((utf7_category[(c)] != 3)))
4624
4625
PyObject *
4626
PyUnicode_DecodeUTF7(const char *s,
4627
                     Py_ssize_t size,
4628
                     const char *errors)
4629
0
{
4630
0
    return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4631
0
}
4632
4633
/* The decoder.  The only state we preserve is our read position,
4634
 * i.e. how many characters we have consumed.  So if we end in the
4635
 * middle of a shift sequence we have to back off the read position
4636
 * and the output to the beginning of the sequence, otherwise we lose
4637
 * all the shift state (seen bits, number of bits seen, high
4638
 * surrogate). */
4639
4640
PyObject *
4641
PyUnicode_DecodeUTF7Stateful(const char *s,
4642
                             Py_ssize_t size,
4643
                             const char *errors,
4644
                             Py_ssize_t *consumed)
4645
21.8k
{
4646
21.8k
    const char *starts = s;
4647
21.8k
    Py_ssize_t startinpos;
4648
21.8k
    Py_ssize_t endinpos;
4649
21.8k
    const char *e;
4650
21.8k
    _PyUnicodeWriter writer;
4651
21.8k
    const char *errmsg = "";
4652
21.8k
    int inShift = 0;
4653
21.8k
    Py_ssize_t shiftOutStart;
4654
21.8k
    unsigned int base64bits = 0;
4655
21.8k
    unsigned long base64buffer = 0;
4656
21.8k
    Py_UCS4 surrogate = 0;
4657
21.8k
    PyObject *errorHandler = NULL;
4658
21.8k
    PyObject *exc = NULL;
4659
4660
21.8k
    if (size == 0) {
4661
0
        if (consumed)
4662
0
            *consumed = 0;
4663
0
        _Py_RETURN_UNICODE_EMPTY();
4664
0
    }
4665
4666
    /* Start off assuming it's all ASCII. Widen later as necessary. */
4667
21.8k
    _PyUnicodeWriter_Init(&writer);
4668
21.8k
    writer.min_length = size;
4669
4670
21.8k
    shiftOutStart = 0;
4671
21.8k
    e = s + size;
4672
4673
6.59M
    while (s < e) {
4674
6.57M
        Py_UCS4 ch;
4675
6.57M
      restart:
4676
6.57M
        ch = (unsigned char) *s;
4677
4678
6.57M
        if (inShift) { /* in a base-64 section */
4679
359k
            if (IS_BASE64(ch)) { /* consume a base-64 character */
4680
342k
                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4681
342k
                base64bits += 6;
4682
342k
                s++;
4683
342k
                if (base64bits >= 16) {
4684
                    /* we have enough bits for a UTF-16 value */
4685
123k
                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
4686
123k
                    base64bits -= 16;
4687
123k
                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4688
123k
                    assert(outCh <= 0xffff);
4689
123k
                    if (surrogate) {
4690
                        /* expecting a second surrogate */
4691
10.3k
                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4692
4.63k
                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
4693
4.63k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
4694
0
                                goto onError;
4695
4.63k
                            surrogate = 0;
4696
4.63k
                            continue;
4697
4.63k
                        }
4698
5.71k
                        else {
4699
5.71k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4700
0
                                goto onError;
4701
5.71k
                            surrogate = 0;
4702
5.71k
                        }
4703
10.3k
                    }
4704
118k
                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
4705
                        /* first surrogate */
4706
15.0k
                        surrogate = outCh;
4707
15.0k
                    }
4708
103k
                    else {
4709
103k
                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
4710
0
                            goto onError;
4711
103k
                    }
4712
118k
                }
4713
342k
            }
4714
16.9k
            else { /* now leaving a base-64 section */
4715
16.9k
                inShift = 0;
4716
16.9k
                if (base64bits > 0) { /* left-over bits */
4717
12.5k
                    if (base64bits >= 6) {
4718
                        /* We've seen at least one base-64 character */
4719
5.80k
                        s++;
4720
5.80k
                        errmsg = "partial character in shift sequence";
4721
5.80k
                        goto utf7Error;
4722
5.80k
                    }
4723
6.73k
                    else {
4724
                        /* Some bits remain; they should be zero */
4725
6.73k
                        if (base64buffer != 0) {
4726
1.38k
                            s++;
4727
1.38k
                            errmsg = "non-zero padding bits in shift sequence";
4728
1.38k
                            goto utf7Error;
4729
1.38k
                        }
4730
6.73k
                    }
4731
12.5k
                }
4732
9.71k
                if (surrogate && DECODE_DIRECT(ch)) {
4733
4.12k
                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4734
0
                        goto onError;
4735
4.12k
                }
4736
9.71k
                surrogate = 0;
4737
9.71k
                if (ch == '-') {
4738
                    /* '-' is absorbed; other terminating
4739
                       characters are preserved */
4740
1.51k
                    s++;
4741
1.51k
                }
4742
9.71k
            }
4743
359k
        }
4744
6.21M
        else if ( ch == '+' ) {
4745
26.0k
            startinpos = s-starts;
4746
26.0k
            s++; /* consume '+' */
4747
26.0k
            if (s < e && *s == '-') { /* '+-' encodes '+' */
4748
2.29k
                s++;
4749
2.29k
                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
4750
0
                    goto onError;
4751
2.29k
            }
4752
23.7k
            else if (s < e && !IS_BASE64(*s)) {
4753
2.74k
                s++;
4754
2.74k
                errmsg = "ill-formed sequence";
4755
2.74k
                goto utf7Error;
4756
2.74k
            }
4757
20.9k
            else { /* begin base64-encoded section */
4758
20.9k
                inShift = 1;
4759
20.9k
                surrogate = 0;
4760
20.9k
                shiftOutStart = writer.pos;
4761
20.9k
                base64bits = 0;
4762
20.9k
                base64buffer = 0;
4763
20.9k
            }
4764
26.0k
        }
4765
6.19M
        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
4766
6.11M
            s++;
4767
6.11M
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
4768
0
                goto onError;
4769
6.11M
        }
4770
75.7k
        else {
4771
75.7k
            startinpos = s-starts;
4772
75.7k
            s++;
4773
75.7k
            errmsg = "unexpected special character";
4774
75.7k
            goto utf7Error;
4775
75.7k
        }
4776
6.48M
        continue;
4777
6.48M
utf7Error:
4778
85.6k
        endinpos = s-starts;
4779
85.6k
        if (unicode_decode_call_errorhandler_writer(
4780
85.6k
                errors, &errorHandler,
4781
85.6k
                "utf7", errmsg,
4782
85.6k
                &starts, &e, &startinpos, &endinpos, &exc, &s,
4783
85.6k
                &writer))
4784
8.30k
            goto onError;
4785
85.6k
    }
4786
4787
    /* end of string */
4788
4789
13.5k
    if (inShift && !consumed) { /* in shift sequence, no more to follow */
4790
        /* if we're in an inconsistent state, that's an error */
4791
4.07k
        inShift = 0;
4792
4.07k
        if (surrogate ||
4793
3.83k
                (base64bits >= 6) ||
4794
2.86k
                (base64bits > 0 && base64buffer != 0)) {
4795
2.24k
            endinpos = size;
4796
2.24k
            if (unicode_decode_call_errorhandler_writer(
4797
2.24k
                    errors, &errorHandler,
4798
2.24k
                    "utf7", "unterminated shift sequence",
4799
2.24k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
4800
2.24k
                    &writer))
4801
1.85k
                goto onError;
4802
395
            if (s < e)
4803
0
                goto restart;
4804
395
        }
4805
4.07k
    }
4806
4807
    /* return state */
4808
11.7k
    if (consumed) {
4809
0
        if (inShift) {
4810
0
            *consumed = startinpos;
4811
4812
0
            Py_XDECREF(errorHandler);
4813
0
            Py_XDECREF(exc);
4814
0
            return _PyUnicodeWriter_FinishWithSize(&writer, shiftOutStart);
4815
0
        }
4816
0
        else {
4817
0
            *consumed = s-starts;
4818
0
        }
4819
0
    }
4820
4821
11.7k
    Py_XDECREF(errorHandler);
4822
11.7k
    Py_XDECREF(exc);
4823
11.7k
    return _PyUnicodeWriter_Finish(&writer);
4824
4825
10.1k
  onError:
4826
10.1k
    Py_XDECREF(errorHandler);
4827
10.1k
    Py_XDECREF(exc);
4828
10.1k
    _PyUnicodeWriter_Dealloc(&writer);
4829
10.1k
    return NULL;
4830
11.7k
}
4831
4832
4833
PyObject *
4834
_PyUnicode_EncodeUTF7(PyObject *str,
4835
                      const char *errors)
4836
0
{
4837
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
4838
0
    if (len == 0) {
4839
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
4840
0
    }
4841
0
    int kind = PyUnicode_KIND(str);
4842
0
    const void *data = PyUnicode_DATA(str);
4843
4844
    /* It might be possible to tighten this worst case */
4845
0
    if (len > PY_SSIZE_T_MAX / 8) {
4846
0
        return PyErr_NoMemory();
4847
0
    }
4848
0
    PyBytesWriter *writer = PyBytesWriter_Create(len * 8);
4849
0
    if (writer == NULL) {
4850
0
        return NULL;
4851
0
    }
4852
4853
0
    int inShift = 0;
4854
0
    unsigned int base64bits = 0;
4855
0
    unsigned long base64buffer = 0;
4856
0
    char *out = PyBytesWriter_GetData(writer);
4857
0
    for (Py_ssize_t i = 0; i < len; ++i) {
4858
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
4859
4860
0
        if (inShift) {
4861
0
            if (ENCODE_DIRECT(ch)) {
4862
                /* shifting out */
4863
0
                if (base64bits) { /* output remaining bits */
4864
0
                    *out++ = TO_BASE64(base64buffer << (6-base64bits));
4865
0
                    base64buffer = 0;
4866
0
                    base64bits = 0;
4867
0
                }
4868
0
                inShift = 0;
4869
                /* Characters not in the BASE64 set implicitly unshift the sequence
4870
                   so no '-' is required, except if the character is itself a '-' */
4871
0
                if (IS_BASE64(ch) || ch == '-') {
4872
0
                    *out++ = '-';
4873
0
                }
4874
0
                *out++ = (char) ch;
4875
0
            }
4876
0
            else {
4877
0
                goto encode_char;
4878
0
            }
4879
0
        }
4880
0
        else { /* not in a shift sequence */
4881
0
            if (ch == '+') {
4882
0
                *out++ = '+';
4883
0
                *out++ = '-';
4884
0
            }
4885
0
            else if (ENCODE_DIRECT(ch)) {
4886
0
                *out++ = (char) ch;
4887
0
            }
4888
0
            else {
4889
0
                *out++ = '+';
4890
0
                inShift = 1;
4891
0
                goto encode_char;
4892
0
            }
4893
0
        }
4894
0
        continue;
4895
0
encode_char:
4896
0
        if (ch >= 0x10000) {
4897
0
            assert(ch <= MAX_UNICODE);
4898
4899
            /* code first surrogate */
4900
0
            base64bits += 16;
4901
0
            base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
4902
0
            while (base64bits >= 6) {
4903
0
                *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4904
0
                base64bits -= 6;
4905
0
            }
4906
            /* prepare second surrogate */
4907
0
            ch = Py_UNICODE_LOW_SURROGATE(ch);
4908
0
        }
4909
0
        base64bits += 16;
4910
0
        base64buffer = (base64buffer << 16) | ch;
4911
0
        while (base64bits >= 6) {
4912
0
            *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4913
0
            base64bits -= 6;
4914
0
        }
4915
0
    }
4916
0
    if (base64bits)
4917
0
        *out++= TO_BASE64(base64buffer << (6-base64bits) );
4918
0
    if (inShift)
4919
0
        *out++ = '-';
4920
0
    return PyBytesWriter_FinishWithPointer(writer, out);
4921
0
}
4922
4923
#undef IS_BASE64
4924
#undef FROM_BASE64
4925
#undef TO_BASE64
4926
#undef DECODE_DIRECT
4927
#undef ENCODE_DIRECT
4928
4929
/* --- UTF-8 Codec -------------------------------------------------------- */
4930
4931
PyObject *
4932
PyUnicode_DecodeUTF8(const char *s,
4933
                     Py_ssize_t size,
4934
                     const char *errors)
4935
73.1M
{
4936
73.1M
    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4937
73.1M
}
4938
4939
#include "stringlib/asciilib.h"
4940
#include "stringlib/codecs.h"
4941
#include "stringlib/undef.h"
4942
4943
#include "stringlib/ucs1lib.h"
4944
#include "stringlib/codecs.h"
4945
#include "stringlib/undef.h"
4946
4947
#include "stringlib/ucs2lib.h"
4948
#include "stringlib/codecs.h"
4949
#include "stringlib/undef.h"
4950
4951
#include "stringlib/ucs4lib.h"
4952
#include "stringlib/codecs.h"
4953
#include "stringlib/undef.h"
4954
4955
#if (SIZEOF_SIZE_T == 8)
4956
/* Mask to quickly check whether a C 'size_t' contains a
4957
   non-ASCII, UTF8-encoded char. */
4958
197M
# define ASCII_CHAR_MASK 0x8080808080808080ULL
4959
// used to count codepoints in UTF-8 string.
4960
44.9M
# define VECTOR_0101     0x0101010101010101ULL
4961
911k
# define VECTOR_00FF     0x00ff00ff00ff00ffULL
4962
#elif (SIZEOF_SIZE_T == 4)
4963
# define ASCII_CHAR_MASK 0x80808080U
4964
# define VECTOR_0101     0x01010101U
4965
# define VECTOR_00FF     0x00ff00ffU
4966
#else
4967
# error C 'size_t' size should be either 4 or 8!
4968
#endif
4969
4970
#if (defined(__clang__) || defined(__GNUC__))
4971
#define HAVE_CTZ 1
4972
static inline unsigned int
4973
ctz(size_t v)
4974
7.53M
{
4975
7.53M
    return __builtin_ctzll((unsigned long long)v);
4976
7.53M
}
4977
#elif defined(_MSC_VER)
4978
#define HAVE_CTZ 1
4979
static inline unsigned int
4980
ctz(size_t v)
4981
{
4982
    unsigned long pos;
4983
#if SIZEOF_SIZE_T == 4
4984
    _BitScanForward(&pos, v);
4985
#else
4986
    _BitScanForward64(&pos, v);
4987
#endif /* SIZEOF_SIZE_T */
4988
    return pos;
4989
}
4990
#else
4991
#define HAVE_CTZ 0
4992
#endif
4993
4994
#if HAVE_CTZ && PY_LITTLE_ENDIAN
4995
// load p[0]..p[size-1] as a size_t without unaligned access nor read ahead.
4996
static size_t
4997
load_unaligned(const unsigned char *p, size_t size)
4998
76.5M
{
4999
76.5M
    union {
5000
76.5M
        size_t s;
5001
76.5M
        unsigned char b[SIZEOF_SIZE_T];
5002
76.5M
    } u;
5003
76.5M
    u.s = 0;
5004
    // This switch statement assumes little endian because:
5005
    // * union is faster than bitwise or and shift.
5006
    // * big endian machine is rare and hard to maintain.
5007
76.5M
    switch (size) {
5008
0
    default:
5009
0
#if SIZEOF_SIZE_T == 8
5010
0
    case 8:
5011
0
        u.b[7] = p[7];
5012
0
        _Py_FALLTHROUGH;
5013
3.57M
    case 7:
5014
3.57M
        u.b[6] = p[6];
5015
3.57M
        _Py_FALLTHROUGH;
5016
11.4M
    case 6:
5017
11.4M
        u.b[5] = p[5];
5018
11.4M
        _Py_FALLTHROUGH;
5019
22.4M
    case 5:
5020
22.4M
        u.b[4] = p[4];
5021
22.4M
        _Py_FALLTHROUGH;
5022
22.4M
#endif
5023
34.7M
    case 4:
5024
34.7M
        u.b[3] = p[3];
5025
34.7M
        _Py_FALLTHROUGH;
5026
44.2M
    case 3:
5027
44.2M
        u.b[2] = p[2];
5028
44.2M
        _Py_FALLTHROUGH;
5029
71.0M
    case 2:
5030
71.0M
        u.b[1] = p[1];
5031
71.0M
        _Py_FALLTHROUGH;
5032
71.9M
    case 1:
5033
71.9M
        u.b[0] = p[0];
5034
71.9M
        break;
5035
4.55M
    case 0:
5036
4.55M
        break;
5037
76.5M
    }
5038
76.5M
    return u.s;
5039
76.5M
}
5040
#endif
5041
5042
/*
5043
 * Find the first non-ASCII character in a byte sequence.
5044
 *
5045
 * This function scans a range of bytes from `start` to `end` and returns the
5046
 * index of the first byte that is not an ASCII character (i.e., has the most
5047
 * significant bit set). If all characters in the range are ASCII, it returns
5048
 * `end - start`.
5049
 */
5050
static Py_ssize_t
5051
find_first_nonascii(const unsigned char *start, const unsigned char *end)
5052
79.5M
{
5053
    // The search is done in `size_t` chunks.
5054
    // The start and end might not be aligned at `size_t` boundaries,
5055
    // so they're handled specially.
5056
5057
79.5M
    const unsigned char *p = start;
5058
5059
79.5M
    if (end - start >= SIZEOF_SIZE_T) {
5060
        // Avoid unaligned read.
5061
21.4M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5062
21.4M
        size_t u;
5063
21.4M
        memcpy(&u, p, sizeof(size_t));
5064
21.4M
        u &= ASCII_CHAR_MASK;
5065
21.4M
        if (u) {
5066
1.92M
            return (ctz(u) - 7) / 8;
5067
1.92M
        }
5068
19.5M
        p = _Py_ALIGN_DOWN(p + SIZEOF_SIZE_T, SIZEOF_SIZE_T);
5069
#else /* PY_LITTLE_ENDIAN && HAVE_CTZ */
5070
        const unsigned char *p2 = _Py_ALIGN_UP(p, SIZEOF_SIZE_T);
5071
        while (p < p2) {
5072
            if (*p & 0x80) {
5073
                return p - start;
5074
            }
5075
            p++;
5076
        }
5077
#endif
5078
5079
19.5M
        const unsigned char *e = end - SIZEOF_SIZE_T;
5080
106M
        while (p <= e) {
5081
87.9M
            size_t u = (*(const size_t *)p) & ASCII_CHAR_MASK;
5082
87.9M
            if (u) {
5083
1.12M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5084
1.12M
                return p - start + (ctz(u) - 7) / 8;
5085
#else
5086
                // big endian and minor compilers are difficult to test.
5087
                // fallback to per byte check.
5088
                break;
5089
#endif
5090
1.12M
            }
5091
86.8M
            p += SIZEOF_SIZE_T;
5092
86.8M
        }
5093
19.5M
    }
5094
76.5M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5095
79.5M
    assert((end - p) < SIZEOF_SIZE_T);
5096
    // we can not use *(const size_t*)p to avoid buffer overrun.
5097
76.5M
    size_t u = load_unaligned(p, end - p) & ASCII_CHAR_MASK;
5098
76.5M
    if (u) {
5099
4.48M
        return p - start + (ctz(u) - 7) / 8;
5100
4.48M
    }
5101
72.0M
    return end - start;
5102
#else
5103
    while (p < end) {
5104
        if (*p & 0x80) {
5105
            break;
5106
        }
5107
        p++;
5108
    }
5109
    return p - start;
5110
#endif
5111
76.5M
}
5112
5113
static inline int
5114
scalar_utf8_start_char(unsigned int ch)
5115
5.20M
{
5116
    // 0xxxxxxx or 11xxxxxx are first byte.
5117
5.20M
    return (~ch >> 7 | ch >> 6) & 1;
5118
5.20M
}
5119
5120
static inline size_t
5121
vector_utf8_start_chars(size_t v)
5122
44.9M
{
5123
44.9M
    return ((~v >> 7) | (v >> 6)) & VECTOR_0101;
5124
44.9M
}
5125
5126
5127
// Count the number of UTF-8 code points in a given byte sequence.
5128
static Py_ssize_t
5129
utf8_count_codepoints(const unsigned char *s, const unsigned char *end)
5130
1.45M
{
5131
1.45M
    Py_ssize_t len = 0;
5132
5133
1.45M
    if (end - s >= SIZEOF_SIZE_T) {
5134
324k
        while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
5135
34.5k
            len += scalar_utf8_start_char(*s++);
5136
34.5k
        }
5137
5138
745k
        while (s + SIZEOF_SIZE_T <= end) {
5139
455k
            const unsigned char *e = end;
5140
455k
            if (e - s > SIZEOF_SIZE_T * 255) {
5141
167k
                e = s + SIZEOF_SIZE_T * 255;
5142
167k
            }
5143
455k
            Py_ssize_t vstart = 0;
5144
45.3M
            while (s + SIZEOF_SIZE_T <= e) {
5145
44.9M
                size_t v = *(size_t*)s;
5146
44.9M
                size_t vs = vector_utf8_start_chars(v);
5147
44.9M
                vstart += vs;
5148
44.9M
                s += SIZEOF_SIZE_T;
5149
44.9M
            }
5150
455k
            vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF);
5151
455k
            vstart += vstart >> 16;
5152
455k
#if SIZEOF_SIZE_T == 8
5153
455k
            vstart += vstart >> 32;
5154
455k
#endif
5155
455k
            len += vstart & 0x7ff;
5156
455k
        }
5157
289k
    }
5158
6.62M
    while (s < end) {
5159
5.17M
        len += scalar_utf8_start_char(*s++);
5160
5.17M
    }
5161
1.45M
    return len;
5162
1.45M
}
5163
5164
static Py_ssize_t
5165
ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
5166
15.8M
{
5167
15.8M
#if SIZEOF_SIZE_T <= SIZEOF_VOID_P
5168
15.8M
    if (_Py_IS_ALIGNED(start, ALIGNOF_SIZE_T)
5169
15.6M
        && _Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T))
5170
13.3M
    {
5171
        /* Fast path, see in STRINGLIB(utf8_decode) for
5172
           an explanation. */
5173
13.3M
        const char *p = start;
5174
13.3M
        Py_UCS1 *q = dest;
5175
22.3M
        while (p + SIZEOF_SIZE_T <= end) {
5176
11.9M
            size_t value = *(const size_t *) p;
5177
11.9M
            if (value & ASCII_CHAR_MASK)
5178
3.00M
                break;
5179
8.93M
            *((size_t *)q) = value;
5180
8.93M
            p += SIZEOF_SIZE_T;
5181
8.93M
            q += SIZEOF_SIZE_T;
5182
8.93M
        }
5183
60.2M
        while (p < end) {
5184
49.9M
            if ((unsigned char)*p & 0x80)
5185
3.02M
                break;
5186
46.8M
            *q++ = *p++;
5187
46.8M
        }
5188
13.3M
        return p - start;
5189
13.3M
    }
5190
2.44M
#endif
5191
2.44M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)start,
5192
2.44M
                                         (const unsigned char*)end);
5193
2.44M
    memcpy(dest, start, pos);
5194
2.44M
    return pos;
5195
15.8M
}
5196
5197
static int
5198
unicode_decode_utf8_impl(_PyUnicodeWriter *writer,
5199
                         const char *starts, const char *s, const char *end,
5200
                         _Py_error_handler error_handler,
5201
                         const char *errors,
5202
                         Py_ssize_t *consumed)
5203
7.54M
{
5204
7.54M
    Py_ssize_t startinpos, endinpos;
5205
7.54M
    const char *errmsg = "";
5206
7.54M
    PyObject *error_handler_obj = NULL;
5207
7.54M
    PyObject *exc = NULL;
5208
5209
298M
    while (s < end) {
5210
295M
        Py_UCS4 ch;
5211
295M
        int kind = writer->kind;
5212
5213
295M
        if (kind == PyUnicode_1BYTE_KIND) {
5214
6.51M
            if (PyUnicode_IS_ASCII(writer->buffer))
5215
6.08M
                ch = asciilib_utf8_decode(&s, end, writer->data, &writer->pos);
5216
430k
            else
5217
430k
                ch = ucs1lib_utf8_decode(&s, end, writer->data, &writer->pos);
5218
289M
        } else if (kind == PyUnicode_2BYTE_KIND) {
5219
109M
            ch = ucs2lib_utf8_decode(&s, end, writer->data, &writer->pos);
5220
179M
        } else {
5221
179M
            assert(kind == PyUnicode_4BYTE_KIND);
5222
179M
            ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos);
5223
179M
        }
5224
5225
295M
        switch (ch) {
5226
4.96M
        case 0:
5227
4.96M
            if (s == end || consumed)
5228
4.93M
                goto End;
5229
28.4k
            errmsg = "unexpected end of data";
5230
28.4k
            startinpos = s - starts;
5231
28.4k
            endinpos = end - starts;
5232
28.4k
            break;
5233
172M
        case 1:
5234
172M
            errmsg = "invalid start byte";
5235
172M
            startinpos = s - starts;
5236
172M
            endinpos = startinpos + 1;
5237
172M
            break;
5238
110M
        case 2:
5239
110M
            if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5240
0
                && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
5241
0
            {
5242
                /* Truncated surrogate code in range D800-DFFF */
5243
0
                goto End;
5244
0
            }
5245
110M
            _Py_FALLTHROUGH;
5246
111M
        case 3:
5247
111M
        case 4:
5248
111M
            errmsg = "invalid continuation byte";
5249
111M
            startinpos = s - starts;
5250
111M
            endinpos = startinpos + ch - 1;
5251
111M
            break;
5252
6.14M
        default:
5253
            // ch doesn't fit into kind, so change the buffer kind to write
5254
            // the character
5255
6.14M
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
5256
0
                goto onError;
5257
6.14M
            continue;
5258
295M
        }
5259
5260
284M
        if (error_handler == _Py_ERROR_UNKNOWN)
5261
162k
            error_handler = _Py_GetErrorHandler(errors);
5262
5263
284M
        switch (error_handler) {
5264
0
        case _Py_ERROR_IGNORE:
5265
0
            s += (endinpos - startinpos);
5266
0
            break;
5267
5268
281M
        case _Py_ERROR_REPLACE:
5269
281M
            if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0)
5270
0
                goto onError;
5271
281M
            s += (endinpos - startinpos);
5272
281M
            break;
5273
5274
2.76M
        case _Py_ERROR_SURROGATEESCAPE:
5275
2.76M
        {
5276
2.76M
            Py_ssize_t i;
5277
5278
2.76M
            if (_PyUnicodeWriter_PrepareKind(writer, PyUnicode_2BYTE_KIND) < 0)
5279
0
                goto onError;
5280
2.76M
            assert(_PyUnicodeWriter_CanWrite(writer));
5281
5.52M
            for (i=startinpos; i<endinpos; i++) {
5282
2.76M
                ch = (Py_UCS4)(unsigned char)(starts[i]);
5283
2.76M
                PyUnicode_WRITE(writer->kind, writer->data, writer->pos,
5284
2.76M
                                ch + 0xdc00);
5285
2.76M
                writer->pos++;
5286
2.76M
            }
5287
2.76M
            s += (endinpos - startinpos);
5288
2.76M
            break;
5289
2.76M
        }
5290
5291
2.24k
        default:
5292
2.24k
            if (unicode_decode_call_errorhandler_writer(
5293
2.24k
                    errors, &error_handler_obj,
5294
2.24k
                    "utf-8", errmsg,
5295
2.24k
                    &starts, &end, &startinpos, &endinpos, &exc, &s,
5296
2.24k
                    writer)) {
5297
2.23k
                goto onError;
5298
2.23k
            }
5299
5300
8
            if (_PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) {
5301
0
                goto onError;
5302
0
            }
5303
284M
        }
5304
284M
    }
5305
5306
7.53M
End:
5307
7.53M
    if (consumed)
5308
1.05k
        *consumed = s - starts;
5309
5310
7.53M
    Py_XDECREF(error_handler_obj);
5311
7.53M
    Py_XDECREF(exc);
5312
7.53M
    return 0;
5313
5314
2.23k
onError:
5315
2.23k
    Py_XDECREF(error_handler_obj);
5316
2.23k
    Py_XDECREF(exc);
5317
2.23k
    return -1;
5318
7.54M
}
5319
5320
5321
static PyObject *
5322
unicode_decode_utf8(const char *s, Py_ssize_t size,
5323
                    _Py_error_handler error_handler, const char *errors,
5324
                    Py_ssize_t *consumed)
5325
126M
{
5326
126M
    if (size == 0) {
5327
5.28M
        if (consumed) {
5328
0
            *consumed = 0;
5329
0
        }
5330
5.28M
        _Py_RETURN_UNICODE_EMPTY();
5331
5.28M
    }
5332
5333
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5334
121M
    if (size == 1 && (unsigned char)s[0] < 128) {
5335
44.2M
        if (consumed) {
5336
0
            *consumed = 1;
5337
0
        }
5338
44.2M
        return get_latin1_char((unsigned char)s[0]);
5339
44.2M
    }
5340
5341
    // I don't know this check is necessary or not. But there is a test
5342
    // case that requires size=PY_SSIZE_T_MAX cause MemoryError.
5343
77.1M
    if (PY_SSIZE_T_MAX - sizeof(PyCompactUnicodeObject) < (size_t)size) {
5344
0
        PyErr_NoMemory();
5345
0
        return NULL;
5346
0
    }
5347
5348
77.1M
    const char *starts = s;
5349
77.1M
    const char *end = s + size;
5350
5351
77.1M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end);
5352
77.1M
    if (pos == size) {  // fast path: ASCII string.
5353
69.6M
        PyObject *u = PyUnicode_New(size, 127);
5354
69.6M
        if (u == NULL) {
5355
0
            return NULL;
5356
0
        }
5357
69.6M
        memcpy(PyUnicode_1BYTE_DATA(u), s, size);
5358
69.6M
        if (consumed) {
5359
120
            *consumed = size;
5360
120
        }
5361
69.6M
        return u;
5362
69.6M
    }
5363
5364
7.46M
    int maxchr = 127;
5365
7.46M
    Py_ssize_t maxsize = size;
5366
5367
7.46M
    unsigned char ch = (unsigned char)(s[pos]);
5368
    // error handler other than strict may remove/replace the invalid byte.
5369
    // consumed != NULL allows 1~3 bytes remainings.
5370
    // 0x80 <= ch < 0xc2 is invalid start byte that cause UnicodeDecodeError.
5371
    // otherwise: check the input and decide the maxchr and maxsize to reduce
5372
    // reallocation and copy.
5373
7.46M
    if (error_handler == _Py_ERROR_STRICT && !consumed && ch >= 0xc2) {
5374
        // we only calculate the number of codepoints and don't determine the exact maxchr.
5375
        // This is because writing fast and portable SIMD code to find maxchr is difficult.
5376
        // If reallocation occurs for a larger maxchar, knowing the exact number of codepoints
5377
        // means that it is no longer necessary to allocate several times the required amount
5378
        // of memory.
5379
1.45M
        maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end);
5380
1.45M
        if (ch < 0xc4) { // latin1
5381
252k
            maxchr = 0xff;
5382
252k
        }
5383
1.19M
        else if (ch < 0xf0) { // ucs2
5384
138k
            maxchr = 0xffff;
5385
138k
        }
5386
1.05M
        else { // ucs4
5387
1.05M
            maxchr = 0x10ffff;
5388
1.05M
        }
5389
1.45M
    }
5390
7.46M
    PyObject *u = PyUnicode_New(maxsize, maxchr);
5391
7.46M
    if (!u) {
5392
0
        return NULL;
5393
0
    }
5394
5395
    // Use _PyUnicodeWriter after fast path is failed.
5396
7.46M
    _PyUnicodeWriter writer;
5397
7.46M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
5398
7.46M
    if (maxchr <= 255) {
5399
6.27M
        memcpy(PyUnicode_1BYTE_DATA(u), s, pos);
5400
6.27M
        s += pos;
5401
6.27M
        writer.pos = pos;
5402
6.27M
    }
5403
5404
7.46M
    if (unicode_decode_utf8_impl(&writer, starts, s, end,
5405
7.46M
                                 error_handler, errors,
5406
7.46M
                                 consumed) < 0) {
5407
2.23k
        _PyUnicodeWriter_Dealloc(&writer);
5408
2.23k
        return NULL;
5409
2.23k
    }
5410
7.46M
    return _PyUnicodeWriter_Finish(&writer);
5411
7.46M
}
5412
5413
5414
// Used by PyUnicodeWriter_WriteUTF8() and PyUnicodeWriter_DecodeUTF8Stateful()
5415
int
5416
_PyUnicode_DecodeUTF8Writer(_PyUnicodeWriter *writer,
5417
                            const char *s, Py_ssize_t size,
5418
                            _Py_error_handler error_handler, const char *errors,
5419
                            Py_ssize_t *consumed)
5420
2.47M
{
5421
2.47M
    if (size == 0) {
5422
10.3k
        if (consumed) {
5423
0
            *consumed = 0;
5424
0
        }
5425
10.3k
        return 0;
5426
10.3k
    }
5427
5428
2.46M
    Py_ssize_t old_pos = writer->pos;
5429
2.46M
    Py_UCS4 old_maxchar = writer->maxchar;
5430
5431
    // fast path: try ASCII string.
5432
2.46M
    if (_PyUnicodeWriter_Prepare(writer, size, 127) < 0) {
5433
0
        goto error;
5434
0
    }
5435
2.46M
    assert(_PyUnicodeWriter_CanWrite(writer));
5436
5437
2.46M
    const char *starts = s;
5438
2.46M
    const char *end = s + size;
5439
2.46M
    if (writer->kind == PyUnicode_1BYTE_KIND) {
5440
2.46M
        Py_UCS1 *dest = (Py_UCS1*)writer->data + writer->pos * writer->kind;
5441
2.46M
        Py_ssize_t decoded = ascii_decode(s, end, dest);
5442
2.46M
        writer->pos += decoded;
5443
5444
2.46M
        if (decoded == size) {
5445
2.39M
            if (consumed) {
5446
1.16k
                *consumed = size;
5447
1.16k
            }
5448
2.39M
            return 0;
5449
2.39M
        }
5450
69.3k
        s += decoded;
5451
69.3k
    }
5452
5453
71.9k
    int res = unicode_decode_utf8_impl(writer, starts, s, end,
5454
71.9k
                                       error_handler, errors, consumed);
5455
71.9k
    if (res < 0) {
5456
0
        goto error;
5457
0
    }
5458
71.9k
    return 0;
5459
5460
0
error:
5461
    // Restore the writer to its previous state
5462
0
    writer->pos = old_pos;
5463
0
    if (writer->maxchar > old_maxchar) {
5464
        // _PyUnicodeWriter_Finish() will check maxchar
5465
0
        writer->recheck_maxchar = 1;
5466
0
    }
5467
0
    if (consumed) {
5468
0
        *consumed = 0;
5469
0
    }
5470
0
    return -1;
5471
71.9k
}
5472
5473
5474
PyObject *
5475
PyUnicode_DecodeUTF8Stateful(const char *s,
5476
                             Py_ssize_t size,
5477
                             const char *errors,
5478
                             Py_ssize_t *consumed)
5479
126M
{
5480
126M
    return unicode_decode_utf8(s, size,
5481
126M
                               errors ? _Py_ERROR_UNKNOWN : _Py_ERROR_STRICT,
5482
126M
                               errors, consumed);
5483
126M
}
5484
5485
5486
// UTF-8 decoder.
5487
//
5488
// Supported error handlers: "strict", "surrogateescape" and "surrogatepass".
5489
//
5490
// On success, write a pointer to a newly allocated wide character string into
5491
// *wstr (use PyMem_RawFree() to free the memory), write the output length
5492
// (in number of wchar_t units) into *wlen (if wlen is set), and return 0.
5493
//
5494
// On error, return a negative number.
5495
//
5496
// On memory allocation failure, return _Py_CODEC_MEMORY_ERROR.
5497
//
5498
// On decoding error (if errors is "strict"), return _Py_CODEC_DECODE_ERROR.
5499
// If wlen is non-NULL, write the start of the illegal byte sequence into
5500
// *wlen.
5501
//
5502
// Return _Py_CODEC_UNSUPPORTED_ERROR_HANDLER if errors error handler is not
5503
// supported.
5504
int
5505
_Py_DecodeUTF8(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
5506
               _Py_error_handler errors)
5507
12.2k
{
5508
12.2k
    assert(0 <= size);
5509
12.2k
    assert(s != NULL);
5510
12.2k
    assert(wstr != NULL);
5511
5512
12.2k
    int surrogateescape = 0;
5513
12.2k
    int surrogatepass = 0;
5514
12.2k
    switch (errors)
5515
12.2k
    {
5516
0
    case _Py_ERROR_STRICT:
5517
0
        break;
5518
12.2k
    case _Py_ERROR_SURROGATEESCAPE:
5519
12.2k
        surrogateescape = 1;
5520
12.2k
        break;
5521
0
    case _Py_ERROR_SURROGATEPASS:
5522
0
        surrogatepass = 1;
5523
0
        break;
5524
0
    default:
5525
0
        return _Py_CODEC_UNSUPPORTED_ERROR_HANDLER;
5526
12.2k
    }
5527
5528
    /* Note: size will always be longer than the resulting Unicode
5529
       character count */
5530
12.2k
    if ((size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1 < (size_t)size) {
5531
0
        return _Py_CODEC_MEMORY_ERROR;
5532
0
    }
5533
12.2k
    wchar_t *unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
5534
12.2k
    if (!unicode) {
5535
0
        return _Py_CODEC_MEMORY_ERROR;
5536
0
    }
5537
5538
    /* Unpack UTF-8 encoded data */
5539
12.2k
    const char *orig_s = s;
5540
12.2k
    const char *e = s + size;
5541
12.2k
    Py_ssize_t outpos = 0;
5542
12.2k
    while (s < e) {
5543
12.2k
        Py_UCS4 ch;
5544
12.2k
#if SIZEOF_WCHAR_T == 4
5545
12.2k
        ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
5546
#else
5547
        ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
5548
#endif
5549
12.2k
        if (ch > 0xFF) {
5550
0
#if SIZEOF_WCHAR_T == 4
5551
0
            Py_UNREACHABLE();
5552
#else
5553
            assert(ch > 0xFFFF && ch <= MAX_UNICODE);
5554
            /* write a surrogate pair */
5555
            unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5556
            unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5557
#endif
5558
0
        }
5559
12.2k
        else {
5560
12.2k
            if (!ch && s == e) {
5561
12.2k
                break;
5562
12.2k
            }
5563
5564
0
            if (surrogateescape) {
5565
0
                unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5566
0
            }
5567
0
            else {
5568
                /* Is it a valid three-byte code? */
5569
0
                if (surrogatepass
5570
0
                    && (e - s) >= 3
5571
0
                    && (s[0] & 0xf0) == 0xe0
5572
0
                    && (s[1] & 0xc0) == 0x80
5573
0
                    && (s[2] & 0xc0) == 0x80)
5574
0
                {
5575
0
                    ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5576
0
                    s += 3;
5577
0
                    unicode[outpos++] = ch;
5578
0
                }
5579
0
                else {
5580
0
                    PyMem_RawFree(unicode );
5581
0
                    if (wlen != NULL) {
5582
0
                        *wlen = s - orig_s;
5583
0
                    }
5584
0
                    return _Py_CODEC_DECODE_ERROR;
5585
0
                }
5586
0
            }
5587
0
        }
5588
12.2k
    }
5589
12.2k
    unicode[outpos] = L'\0';
5590
12.2k
    if (wlen) {
5591
12.2k
        *wlen = outpos;
5592
12.2k
    }
5593
12.2k
    *wstr = unicode;
5594
12.2k
    return 0;
5595
12.2k
}
5596
5597
5598
// Decode from UTF-8 with the "surrogateescape" error handler.
5599
// On success, set *wlen and return a newly allocated string.
5600
// On error, set *wlen to the error (_Py_CODEC_MEMORY_ERROR or
5601
// _Py_CODEC_DECODE_ERROR) and the return NULL
5602
wchar_t*
5603
_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
5604
                               size_t *wlen)
5605
0
{
5606
0
    wchar_t *wstr;
5607
0
    int res = _Py_DecodeUTF8(arg, arglen, &wstr, wlen,
5608
0
                             _Py_ERROR_SURROGATEESCAPE);
5609
0
    if (res != 0) {
5610
        /* _Py_DecodeUTF8() must support _Py_ERROR_SURROGATEESCAPE */
5611
0
        assert(res != _Py_CODEC_UNSUPPORTED_ERROR_HANDLER);
5612
0
        if (wlen) {
5613
0
            *wlen = (size_t)res;
5614
0
        }
5615
0
        return NULL;
5616
0
    }
5617
0
    return wstr;
5618
0
}
5619
5620
5621
/* UTF-8 encoder.
5622
5623
   On success, return 0 and write the newly allocated character string (use
5624
   PyMem_Free() to free the memory) into *str.
5625
5626
   On encoding failure, return _Py_CODEC_ENCODE_ERROR (-2) and write the
5627
   position of the invalid surrogate character into *error_pos (if error_pos is
5628
   set).
5629
5630
   On memory allocation failure, return _Py_CODEC_MEMORY_ERROR (-1).
5631
5632
   str and output_length must not be NULL
5633
*/
5634
int
5635
_Py_EncodeUTF8(const wchar_t *text, char **str, size_t *output_length,
5636
               size_t *error_pos, int raw_malloc, _Py_error_handler errors)
5637
1.73k
{
5638
1.73k
    assert(str != NULL);
5639
1.73k
    assert(output_length != NULL);
5640
5641
    // U+10ffff encoded to UTF-8 takes 4 bytes
5642
1.73k
    const size_t max_char_size = 4;
5643
1.73k
    size_t len = wcslen(text);
5644
5645
1.73k
    int surrogateescape = 0;
5646
1.73k
    int surrogatepass = 0;
5647
1.73k
    switch (errors)
5648
1.73k
    {
5649
148
    case _Py_ERROR_STRICT:
5650
148
        break;
5651
1.59k
    case _Py_ERROR_SURROGATEESCAPE:
5652
1.59k
        surrogateescape = 1;
5653
1.59k
        break;
5654
0
    case _Py_ERROR_SURROGATEPASS:
5655
0
        surrogatepass = 1;
5656
0
        break;
5657
0
    default:
5658
0
        return _Py_CODEC_UNSUPPORTED_ERROR_HANDLER;
5659
1.73k
    }
5660
5661
1.73k
    if (len > (size_t)PY_SSIZE_T_MAX / max_char_size - 1) {
5662
0
        return _Py_CODEC_MEMORY_ERROR;
5663
0
    }
5664
1.73k
    char *bytes;
5665
1.73k
    if (raw_malloc) {
5666
1.73k
        bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5667
1.73k
    }
5668
0
    else {
5669
0
        bytes = PyMem_Malloc((len + 1) * max_char_size);
5670
0
    }
5671
1.73k
    if (bytes == NULL) {
5672
0
        return _Py_CODEC_MEMORY_ERROR;
5673
0
    }
5674
5675
1.73k
    char *p = bytes;
5676
124k
    for (size_t i = 0; i < len; ) {
5677
122k
        Py_ssize_t ch_pos = i;
5678
122k
        Py_UCS4 ch = text[i];
5679
122k
        i++;
5680
122k
        if (sizeof(wchar_t) == 2
5681
0
            && Py_UNICODE_IS_HIGH_SURROGATE(ch)
5682
0
            && i < len
5683
0
            && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5684
0
        {
5685
0
            ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5686
0
            i++;
5687
0
        }
5688
5689
122k
        if (ch < 0x80) {
5690
            /* Encode ASCII */
5691
122k
            *p++ = (char) ch;
5692
122k
        }
5693
0
        else if (ch < 0x0800) {
5694
            /* Encode Latin-1 */
5695
0
            *p++ = (char)(0xc0 | (ch >> 6));
5696
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5697
0
        }
5698
0
        else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
5699
            /* surrogateescape error handler */
5700
0
            if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
5701
0
                if (error_pos != NULL) {
5702
0
                    *error_pos = (size_t)ch_pos;
5703
0
                }
5704
0
                if (raw_malloc) {
5705
0
                    PyMem_RawFree(bytes);
5706
0
                }
5707
0
                else {
5708
0
                    PyMem_Free(bytes);
5709
0
                }
5710
0
                return _Py_CODEC_ENCODE_ERROR;
5711
0
            }
5712
0
            *p++ = (char)(ch & 0xff);
5713
0
        }
5714
0
        else if (ch < 0x10000) {
5715
0
            *p++ = (char)(0xe0 | (ch >> 12));
5716
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5717
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5718
0
        }
5719
0
        else {  /* ch >= 0x10000 */
5720
0
            assert(ch <= MAX_UNICODE);
5721
            /* Encode UCS4 Unicode ordinals */
5722
0
            *p++ = (char)(0xf0 | (ch >> 18));
5723
0
            *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5724
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5725
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5726
0
        }
5727
122k
    }
5728
5729
1.73k
    *p++ = '\0';  // trailing NUL byte
5730
1.73k
    size_t final_size = (p - bytes);
5731
1.73k
    assert(final_size >= 1);
5732
1.73k
    *output_length = final_size - 1;  // -1 for the trailing NUL byte
5733
5734
1.73k
    char *result;
5735
1.73k
    if (raw_malloc) {
5736
1.73k
        result = PyMem_RawRealloc(bytes, final_size);
5737
1.73k
    }
5738
0
    else {
5739
0
        result = PyMem_Realloc(bytes, final_size);
5740
0
    }
5741
1.73k
    if (result == NULL) {
5742
0
        if (raw_malloc) {
5743
0
            PyMem_RawFree(bytes);
5744
0
        }
5745
0
        else {
5746
0
            PyMem_Free(bytes);
5747
0
        }
5748
0
        return _Py_CODEC_MEMORY_ERROR;
5749
0
    }
5750
1.73k
    *str = result;
5751
1.73k
    return 0;
5752
1.73k
}
5753
5754
5755
/* Primary internal function which creates utf8 encoded bytes objects.
5756
5757
   Allocation strategy:  if the string is short, convert into a stack buffer
5758
   and allocate exactly as much space needed at the end.  Else allocate the
5759
   maximum possible needed (4 result bytes per Unicode character), and return
5760
   the excess memory at the end.
5761
*/
5762
static PyObject *
5763
unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
5764
                    const char *errors)
5765
18.0M
{
5766
18.0M
    if (!PyUnicode_Check(unicode)) {
5767
0
        PyErr_BadArgument();
5768
0
        return NULL;
5769
0
    }
5770
5771
18.0M
    if (PyUnicode_UTF8(unicode))
5772
9.37M
        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5773
9.37M
                                         PyUnicode_UTF8_LENGTH(unicode));
5774
5775
8.65M
    int kind = PyUnicode_KIND(unicode);
5776
8.65M
    const void *data = PyUnicode_DATA(unicode);
5777
8.65M
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5778
5779
8.65M
    PyBytesWriter *writer;
5780
8.65M
    char *end;
5781
5782
8.65M
    switch (kind) {
5783
0
    default:
5784
0
        Py_UNREACHABLE();
5785
5.96M
    case PyUnicode_1BYTE_KIND:
5786
        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5787
5.96M
        assert(!PyUnicode_IS_ASCII(unicode));
5788
5.96M
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5789
5.96M
                                      error_handler, errors, &end);
5790
5.96M
        break;
5791
1.51M
    case PyUnicode_2BYTE_KIND:
5792
1.51M
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5793
1.51M
                                      error_handler, errors, &end);
5794
1.51M
        break;
5795
1.17M
    case PyUnicode_4BYTE_KIND:
5796
1.17M
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5797
1.17M
                                      error_handler, errors, &end);
5798
1.17M
        break;
5799
8.65M
    }
5800
5801
8.65M
    if (writer == NULL) {
5802
129k
        PyBytesWriter_Discard(writer);
5803
129k
        return NULL;
5804
129k
    }
5805
8.53M
    return PyBytesWriter_FinishWithPointer(writer, end);
5806
8.65M
}
5807
5808
static int
5809
unicode_fill_utf8(PyObject *unicode)
5810
176k
{
5811
176k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(unicode);
5812
    /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5813
176k
    assert(!PyUnicode_IS_ASCII(unicode));
5814
5815
176k
    int kind = PyUnicode_KIND(unicode);
5816
176k
    const void *data = PyUnicode_DATA(unicode);
5817
176k
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5818
5819
176k
    PyBytesWriter *writer;
5820
176k
    char *end;
5821
5822
176k
    switch (kind) {
5823
0
    default:
5824
0
        Py_UNREACHABLE();
5825
130k
    case PyUnicode_1BYTE_KIND:
5826
130k
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5827
130k
                                      _Py_ERROR_STRICT, NULL, &end);
5828
130k
        break;
5829
38.2k
    case PyUnicode_2BYTE_KIND:
5830
38.2k
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5831
38.2k
                                      _Py_ERROR_STRICT, NULL, &end);
5832
38.2k
        break;
5833
8.32k
    case PyUnicode_4BYTE_KIND:
5834
8.32k
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5835
8.32k
                                      _Py_ERROR_STRICT, NULL, &end);
5836
8.32k
        break;
5837
176k
    }
5838
176k
    if (writer == NULL) {
5839
262
        return -1;
5840
262
    }
5841
5842
176k
    const char *start = PyBytesWriter_GetData(writer);
5843
176k
    Py_ssize_t len = end - start;
5844
5845
176k
    char *cache = PyMem_Malloc(len + 1);
5846
176k
    if (cache == NULL) {
5847
0
        PyBytesWriter_Discard(writer);
5848
0
        PyErr_NoMemory();
5849
0
        return -1;
5850
0
    }
5851
176k
    memcpy(cache, start, len);
5852
176k
    cache[len] = '\0';
5853
176k
    PyUnicode_SET_UTF8_LENGTH(unicode, len);
5854
176k
    PyUnicode_SET_UTF8(unicode, cache);
5855
176k
    PyBytesWriter_Discard(writer);
5856
176k
    return 0;
5857
176k
}
5858
5859
PyObject *
5860
_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5861
17.3M
{
5862
17.3M
    return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5863
17.3M
}
5864
5865
5866
PyObject *
5867
PyUnicode_AsUTF8String(PyObject *unicode)
5868
397
{
5869
397
    return _PyUnicode_AsUTF8String(unicode, NULL);
5870
397
}
5871
5872
/* --- UTF-32 Codec ------------------------------------------------------- */
5873
5874
PyObject *
5875
PyUnicode_DecodeUTF32(const char *s,
5876
                      Py_ssize_t size,
5877
                      const char *errors,
5878
                      int *byteorder)
5879
132
{
5880
132
    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5881
132
}
5882
5883
PyObject *
5884
PyUnicode_DecodeUTF32Stateful(const char *s,
5885
                              Py_ssize_t size,
5886
                              const char *errors,
5887
                              int *byteorder,
5888
                              Py_ssize_t *consumed)
5889
19.4k
{
5890
19.4k
    const char *starts = s;
5891
19.4k
    Py_ssize_t startinpos;
5892
19.4k
    Py_ssize_t endinpos;
5893
19.4k
    _PyUnicodeWriter writer;
5894
19.4k
    const unsigned char *q, *e;
5895
19.4k
    int le, bo = 0;       /* assume native ordering by default */
5896
19.4k
    const char *encoding;
5897
19.4k
    const char *errmsg = "";
5898
19.4k
    PyObject *errorHandler = NULL;
5899
19.4k
    PyObject *exc = NULL;
5900
5901
19.4k
    q = (const unsigned char *)s;
5902
19.4k
    e = q + size;
5903
5904
19.4k
    if (byteorder)
5905
19.2k
        bo = *byteorder;
5906
5907
    /* Check for BOM marks (U+FEFF) in the input and adjust current
5908
       byte order setting accordingly. In native mode, the leading BOM
5909
       mark is skipped, in all other modes, it is copied to the output
5910
       stream as-is (giving a ZWNBSP character). */
5911
19.4k
    if (bo == 0 && size >= 4) {
5912
16.9k
        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5913
16.9k
        if (bom == 0x0000FEFF) {
5914
216
            bo = -1;
5915
216
            q += 4;
5916
216
        }
5917
16.7k
        else if (bom == 0xFFFE0000) {
5918
282
            bo = 1;
5919
282
            q += 4;
5920
282
        }
5921
16.9k
        if (byteorder)
5922
16.8k
            *byteorder = bo;
5923
16.9k
    }
5924
5925
19.4k
    if (q == e) {
5926
75
        if (consumed)
5927
0
            *consumed = size;
5928
75
        _Py_RETURN_UNICODE_EMPTY();
5929
75
    }
5930
5931
#ifdef WORDS_BIGENDIAN
5932
    le = bo < 0;
5933
#else
5934
19.3k
    le = bo <= 0;
5935
19.3k
#endif
5936
19.3k
    encoding = le ? "utf-32-le" : "utf-32-be";
5937
5938
19.3k
    _PyUnicodeWriter_Init(&writer);
5939
19.3k
    writer.min_length = (e - q + 3) / 4;
5940
19.3k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
5941
0
        goto onError;
5942
5943
94.1k
    while (1) {
5944
94.1k
        Py_UCS4 ch = 0;
5945
94.1k
        Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
5946
5947
94.1k
        if (e - q >= 4) {
5948
80.2k
            int kind = writer.kind;
5949
80.2k
            void *data = writer.data;
5950
80.2k
            const unsigned char *last = e - 4;
5951
80.2k
            Py_ssize_t pos = writer.pos;
5952
80.2k
            if (le) {
5953
2.66M
                do {
5954
2.66M
                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5955
2.66M
                    if (ch > maxch)
5956
67.1k
                        break;
5957
2.59M
                    if (kind != PyUnicode_1BYTE_KIND &&
5958
2.57M
                        Py_UNICODE_IS_SURROGATE(ch))
5959
244
                        break;
5960
2.59M
                    PyUnicode_WRITE(kind, data, pos++, ch);
5961
2.59M
                    q += 4;
5962
2.59M
                } while (q <= last);
5963
68.6k
            }
5964
11.6k
            else {
5965
16.8k
                do {
5966
16.8k
                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5967
16.8k
                    if (ch > maxch)
5968
11.3k
                        break;
5969
5.52k
                    if (kind != PyUnicode_1BYTE_KIND &&
5970
2.67k
                        Py_UNICODE_IS_SURROGATE(ch))
5971
120
                        break;
5972
5.40k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5973
5.40k
                    q += 4;
5974
5.40k
                } while (q <= last);
5975
11.6k
            }
5976
80.2k
            writer.pos = pos;
5977
80.2k
        }
5978
5979
94.1k
        if (Py_UNICODE_IS_SURROGATE(ch)) {
5980
368
            errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
5981
368
            startinpos = ((const char *)q) - starts;
5982
368
            endinpos = startinpos + 4;
5983
368
        }
5984
93.7k
        else if (ch <= maxch) {
5985
15.2k
            if (q == e || consumed)
5986
3.71k
                break;
5987
            /* remaining bytes at the end? (size should be divisible by 4) */
5988
11.5k
            errmsg = "truncated data";
5989
11.5k
            startinpos = ((const char *)q) - starts;
5990
11.5k
            endinpos = ((const char *)e) - starts;
5991
11.5k
        }
5992
78.5k
        else {
5993
78.5k
            if (ch < 0x110000) {
5994
4.02k
                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
5995
0
                    goto onError;
5996
4.02k
                q += 4;
5997
4.02k
                continue;
5998
4.02k
            }
5999
74.4k
            errmsg = "code point not in range(0x110000)";
6000
74.4k
            startinpos = ((const char *)q) - starts;
6001
74.4k
            endinpos = startinpos + 4;
6002
74.4k
        }
6003
6004
        /* The remaining input chars are ignored if the callback
6005
           chooses to skip the input */
6006
86.3k
        if (unicode_decode_call_errorhandler_writer(
6007
86.3k
                errors, &errorHandler,
6008
86.3k
                encoding, errmsg,
6009
86.3k
                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
6010
86.3k
                &writer))
6011
15.6k
            goto onError;
6012
86.3k
    }
6013
6014
3.71k
    if (consumed)
6015
0
        *consumed = (const char *)q-starts;
6016
6017
3.71k
    Py_XDECREF(errorHandler);
6018
3.71k
    Py_XDECREF(exc);
6019
3.71k
    return _PyUnicodeWriter_Finish(&writer);
6020
6021
15.6k
  onError:
6022
15.6k
    _PyUnicodeWriter_Dealloc(&writer);
6023
15.6k
    Py_XDECREF(errorHandler);
6024
15.6k
    Py_XDECREF(exc);
6025
15.6k
    return NULL;
6026
19.3k
}
6027
6028
PyObject *
6029
_PyUnicode_EncodeUTF32(PyObject *str,
6030
                       const char *errors,
6031
                       int byteorder)
6032
0
{
6033
0
    if (!PyUnicode_Check(str)) {
6034
0
        PyErr_BadArgument();
6035
0
        return NULL;
6036
0
    }
6037
0
    int kind = PyUnicode_KIND(str);
6038
0
    const void *data = PyUnicode_DATA(str);
6039
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6040
6041
0
    if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
6042
0
        return PyErr_NoMemory();
6043
0
    Py_ssize_t nsize = len + (byteorder == 0);
6044
6045
0
#if PY_LITTLE_ENDIAN
6046
0
    int native_ordering = byteorder <= 0;
6047
#else
6048
    int native_ordering = byteorder >= 0;
6049
#endif
6050
6051
0
    if (kind == PyUnicode_1BYTE_KIND) {
6052
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6053
        // on short strings
6054
0
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 4);
6055
0
        if (v == NULL) {
6056
0
            return NULL;
6057
0
        }
6058
6059
        /* output buffer is 4-bytes aligned */
6060
0
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
6061
0
        uint32_t *out = (uint32_t *)PyBytes_AS_STRING(v);
6062
0
        if (byteorder == 0) {
6063
0
            *out++ = 0xFEFF;
6064
0
        }
6065
0
        if (len > 0) {
6066
0
            ucs1lib_utf32_encode((const Py_UCS1 *)data, len,
6067
0
                                 &out, native_ordering);
6068
0
        }
6069
0
        return v;
6070
0
    }
6071
6072
0
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 4);
6073
0
    if (writer == NULL) {
6074
0
        return NULL;
6075
0
    }
6076
6077
    /* output buffer is 4-bytes aligned */
6078
0
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 4));
6079
0
    uint32_t *out = (uint32_t *)PyBytesWriter_GetData(writer);
6080
0
    if (byteorder == 0) {
6081
0
        *out++ = 0xFEFF;
6082
0
    }
6083
0
    if (len == 0) {
6084
0
        return PyBytesWriter_Finish(writer);
6085
0
    }
6086
6087
0
    const char *encoding;
6088
0
    if (byteorder == -1)
6089
0
        encoding = "utf-32-le";
6090
0
    else if (byteorder == 1)
6091
0
        encoding = "utf-32-be";
6092
0
    else
6093
0
        encoding = "utf-32";
6094
6095
0
    PyObject *errorHandler = NULL;
6096
0
    PyObject *exc = NULL;
6097
0
    PyObject *rep = NULL;
6098
6099
0
    for (Py_ssize_t pos = 0; pos < len; ) {
6100
0
        if (kind == PyUnicode_2BYTE_KIND) {
6101
0
            pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
6102
0
                                        &out, native_ordering);
6103
0
        }
6104
0
        else {
6105
0
            assert(kind == PyUnicode_4BYTE_KIND);
6106
0
            pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
6107
0
                                        &out, native_ordering);
6108
0
        }
6109
0
        if (pos == len)
6110
0
            break;
6111
6112
0
        Py_ssize_t newpos;
6113
0
        rep = unicode_encode_call_errorhandler(
6114
0
                errors, &errorHandler,
6115
0
                encoding, "surrogates not allowed",
6116
0
                str, &exc, pos, pos + 1, &newpos);
6117
0
        if (!rep)
6118
0
            goto error;
6119
6120
0
        Py_ssize_t repsize, moreunits;
6121
0
        if (PyBytes_Check(rep)) {
6122
0
            repsize = PyBytes_GET_SIZE(rep);
6123
0
            if (repsize & 3) {
6124
0
                raise_encode_exception(&exc, encoding,
6125
0
                                       str, pos, pos + 1,
6126
0
                                       "surrogates not allowed");
6127
0
                goto error;
6128
0
            }
6129
0
            moreunits = repsize / 4;
6130
0
        }
6131
0
        else {
6132
0
            assert(PyUnicode_Check(rep));
6133
0
            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6134
0
            if (!PyUnicode_IS_ASCII(rep)) {
6135
0
                raise_encode_exception(&exc, encoding,
6136
0
                                       str, pos, pos + 1,
6137
0
                                       "surrogates not allowed");
6138
0
                goto error;
6139
0
            }
6140
0
        }
6141
0
        moreunits += pos - newpos;
6142
0
        pos = newpos;
6143
6144
        /* four bytes are reserved for each surrogate */
6145
0
        if (moreunits > 0) {
6146
0
            out = PyBytesWriter_GrowAndUpdatePointer(writer, 4 * moreunits, out);
6147
0
            if (out == NULL) {
6148
0
                goto error;
6149
0
            }
6150
0
        }
6151
6152
0
        if (PyBytes_Check(rep)) {
6153
0
            memcpy(out, PyBytes_AS_STRING(rep), repsize);
6154
0
            out += repsize / 4;
6155
0
        }
6156
0
        else {
6157
            /* rep is unicode */
6158
0
            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6159
0
            ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6160
0
                                 &out, native_ordering);
6161
0
        }
6162
6163
0
        Py_CLEAR(rep);
6164
0
    }
6165
6166
0
    Py_XDECREF(errorHandler);
6167
0
    Py_XDECREF(exc);
6168
6169
    /* Cut back to size actually needed. This is necessary for, for example,
6170
       encoding of a string containing isolated surrogates and the 'ignore'
6171
       handler is used. */
6172
0
    return PyBytesWriter_FinishWithPointer(writer, out);
6173
6174
0
  error:
6175
0
    Py_XDECREF(rep);
6176
0
    Py_XDECREF(errorHandler);
6177
0
    Py_XDECREF(exc);
6178
0
    PyBytesWriter_Discard(writer);
6179
0
    return NULL;
6180
0
}
6181
6182
PyObject *
6183
PyUnicode_AsUTF32String(PyObject *unicode)
6184
0
{
6185
0
    return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
6186
0
}
6187
6188
/* --- UTF-16 Codec ------------------------------------------------------- */
6189
6190
PyObject *
6191
PyUnicode_DecodeUTF16(const char *s,
6192
                      Py_ssize_t size,
6193
                      const char *errors,
6194
                      int *byteorder)
6195
184
{
6196
184
    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
6197
184
}
6198
6199
PyObject *
6200
PyUnicode_DecodeUTF16Stateful(const char *s,
6201
                              Py_ssize_t size,
6202
                              const char *errors,
6203
                              int *byteorder,
6204
                              Py_ssize_t *consumed)
6205
28.4k
{
6206
28.4k
    const char *starts = s;
6207
28.4k
    Py_ssize_t startinpos;
6208
28.4k
    Py_ssize_t endinpos;
6209
28.4k
    _PyUnicodeWriter writer;
6210
28.4k
    const unsigned char *q, *e;
6211
28.4k
    int bo = 0;       /* assume native ordering by default */
6212
28.4k
    int native_ordering;
6213
28.4k
    const char *errmsg = "";
6214
28.4k
    PyObject *errorHandler = NULL;
6215
28.4k
    PyObject *exc = NULL;
6216
28.4k
    const char *encoding;
6217
6218
28.4k
    q = (const unsigned char *)s;
6219
28.4k
    e = q + size;
6220
6221
28.4k
    if (byteorder)
6222
28.2k
        bo = *byteorder;
6223
6224
    /* Check for BOM marks (U+FEFF) in the input and adjust current
6225
       byte order setting accordingly. In native mode, the leading BOM
6226
       mark is skipped, in all other modes, it is copied to the output
6227
       stream as-is (giving a ZWNBSP character). */
6228
28.4k
    if (bo == 0 && size >= 2) {
6229
16.4k
        const Py_UCS4 bom = (q[1] << 8) | q[0];
6230
16.4k
        if (bom == 0xFEFF) {
6231
270
            q += 2;
6232
270
            bo = -1;
6233
270
        }
6234
16.2k
        else if (bom == 0xFFFE) {
6235
2.28k
            q += 2;
6236
2.28k
            bo = 1;
6237
2.28k
        }
6238
16.4k
        if (byteorder)
6239
16.3k
            *byteorder = bo;
6240
16.4k
    }
6241
6242
28.4k
    if (q == e) {
6243
95
        if (consumed)
6244
0
            *consumed = size;
6245
95
        _Py_RETURN_UNICODE_EMPTY();
6246
95
    }
6247
6248
28.3k
#if PY_LITTLE_ENDIAN
6249
28.3k
    native_ordering = bo <= 0;
6250
28.3k
    encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
6251
#else
6252
    native_ordering = bo >= 0;
6253
    encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
6254
#endif
6255
6256
    /* Note: size will always be longer than the resulting Unicode
6257
       character count normally.  Error handler will take care of
6258
       resizing when needed. */
6259
28.3k
    _PyUnicodeWriter_Init(&writer);
6260
28.3k
    writer.min_length = (e - q + 1) / 2;
6261
28.3k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
6262
0
        goto onError;
6263
6264
79.3k
    while (1) {
6265
79.3k
        Py_UCS4 ch = 0;
6266
79.3k
        if (e - q >= 2) {
6267
63.5k
            int kind = writer.kind;
6268
63.5k
            if (kind == PyUnicode_1BYTE_KIND) {
6269
32.6k
                if (PyUnicode_IS_ASCII(writer.buffer))
6270
27.8k
                    ch = asciilib_utf16_decode(&q, e,
6271
27.8k
                            (Py_UCS1*)writer.data, &writer.pos,
6272
27.8k
                            native_ordering);
6273
4.74k
                else
6274
4.74k
                    ch = ucs1lib_utf16_decode(&q, e,
6275
4.74k
                            (Py_UCS1*)writer.data, &writer.pos,
6276
4.74k
                            native_ordering);
6277
32.6k
            } else if (kind == PyUnicode_2BYTE_KIND) {
6278
18.2k
                ch = ucs2lib_utf16_decode(&q, e,
6279
18.2k
                        (Py_UCS2*)writer.data, &writer.pos,
6280
18.2k
                        native_ordering);
6281
18.2k
            } else {
6282
12.7k
                assert(kind == PyUnicode_4BYTE_KIND);
6283
12.7k
                ch = ucs4lib_utf16_decode(&q, e,
6284
12.7k
                        (Py_UCS4*)writer.data, &writer.pos,
6285
12.7k
                        native_ordering);
6286
12.7k
            }
6287
63.5k
        }
6288
6289
79.3k
        switch (ch)
6290
79.3k
        {
6291
28.7k
        case 0:
6292
            /* remaining byte at the end? (size should be even) */
6293
28.7k
            if (q == e || consumed)
6294
21.5k
                goto End;
6295
7.22k
            errmsg = "truncated data";
6296
7.22k
            startinpos = ((const char *)q) - starts;
6297
7.22k
            endinpos = ((const char *)e) - starts;
6298
7.22k
            break;
6299
            /* The remaining input chars are ignored if the callback
6300
               chooses to skip the input */
6301
1.98k
        case 1:
6302
1.98k
            q -= 2;
6303
1.98k
            if (consumed)
6304
0
                goto End;
6305
1.98k
            errmsg = "unexpected end of data";
6306
1.98k
            startinpos = ((const char *)q) - starts;
6307
1.98k
            endinpos = ((const char *)e) - starts;
6308
1.98k
            break;
6309
11.4k
        case 2:
6310
11.4k
            errmsg = "illegal encoding";
6311
11.4k
            startinpos = ((const char *)q) - 2 - starts;
6312
11.4k
            endinpos = startinpos + 2;
6313
11.4k
            break;
6314
8.59k
        case 3:
6315
8.59k
            errmsg = "illegal UTF-16 surrogate";
6316
8.59k
            startinpos = ((const char *)q) - 4 - starts;
6317
8.59k
            endinpos = startinpos + 2;
6318
8.59k
            break;
6319
28.5k
        default:
6320
28.5k
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
6321
0
                goto onError;
6322
28.5k
            continue;
6323
79.3k
        }
6324
6325
29.2k
        if (unicode_decode_call_errorhandler_writer(
6326
29.2k
                errors,
6327
29.2k
                &errorHandler,
6328
29.2k
                encoding, errmsg,
6329
29.2k
                &starts,
6330
29.2k
                (const char **)&e,
6331
29.2k
                &startinpos,
6332
29.2k
                &endinpos,
6333
29.2k
                &exc,
6334
29.2k
                (const char **)&q,
6335
29.2k
                &writer))
6336
6.85k
            goto onError;
6337
29.2k
    }
6338
6339
21.5k
End:
6340
21.5k
    if (consumed)
6341
0
        *consumed = (const char *)q-starts;
6342
6343
21.5k
    Py_XDECREF(errorHandler);
6344
21.5k
    Py_XDECREF(exc);
6345
21.5k
    return _PyUnicodeWriter_Finish(&writer);
6346
6347
6.85k
  onError:
6348
6.85k
    _PyUnicodeWriter_Dealloc(&writer);
6349
6.85k
    Py_XDECREF(errorHandler);
6350
6.85k
    Py_XDECREF(exc);
6351
6.85k
    return NULL;
6352
28.3k
}
6353
6354
PyObject *
6355
_PyUnicode_EncodeUTF16(PyObject *str,
6356
                       const char *errors,
6357
                       int byteorder)
6358
8.37k
{
6359
8.37k
    if (!PyUnicode_Check(str)) {
6360
0
        PyErr_BadArgument();
6361
0
        return NULL;
6362
0
    }
6363
8.37k
    int kind = PyUnicode_KIND(str);
6364
8.37k
    const void *data = PyUnicode_DATA(str);
6365
8.37k
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6366
6367
8.37k
    Py_ssize_t pairs = 0;
6368
8.37k
    if (kind == PyUnicode_4BYTE_KIND) {
6369
0
        const Py_UCS4 *in = (const Py_UCS4 *)data;
6370
0
        const Py_UCS4 *end = in + len;
6371
0
        while (in < end) {
6372
0
            if (*in++ >= 0x10000) {
6373
0
                pairs++;
6374
0
            }
6375
0
        }
6376
0
    }
6377
8.37k
    if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
6378
0
        return PyErr_NoMemory();
6379
0
    }
6380
8.37k
    Py_ssize_t nsize = len + pairs + (byteorder == 0);
6381
6382
#if PY_BIG_ENDIAN
6383
    int native_ordering = byteorder >= 0;
6384
#else
6385
8.37k
    int native_ordering = byteorder <= 0;
6386
8.37k
#endif
6387
6388
8.37k
    if (kind == PyUnicode_1BYTE_KIND) {
6389
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6390
        // on short strings
6391
8.29k
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 2);
6392
8.29k
        if (v == NULL) {
6393
0
            return NULL;
6394
0
        }
6395
6396
        /* output buffer is 2-bytes aligned */
6397
8.29k
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
6398
8.29k
        unsigned short *out = (unsigned short *)PyBytes_AS_STRING(v);
6399
8.29k
        if (byteorder == 0) {
6400
0
            *out++ = 0xFEFF;
6401
0
        }
6402
8.29k
        if (len > 0) {
6403
8.29k
            ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
6404
8.29k
        }
6405
8.29k
        return v;
6406
8.29k
    }
6407
6408
86
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 2);
6409
86
    if (writer == NULL) {
6410
0
        return NULL;
6411
0
    }
6412
6413
    /* output buffer is 2-bytes aligned */
6414
86
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 2));
6415
86
    unsigned short *out = PyBytesWriter_GetData(writer);
6416
86
    if (byteorder == 0) {
6417
0
        *out++ = 0xFEFF;
6418
0
    }
6419
86
    if (len == 0) {
6420
0
        return PyBytesWriter_Finish(writer);
6421
0
    }
6422
6423
86
    const char *encoding;
6424
86
    if (byteorder < 0) {
6425
0
        encoding = "utf-16-le";
6426
0
    }
6427
86
    else if (byteorder > 0) {
6428
86
        encoding = "utf-16-be";
6429
86
    }
6430
0
    else {
6431
0
        encoding = "utf-16";
6432
0
    }
6433
6434
86
    PyObject *errorHandler = NULL;
6435
86
    PyObject *exc = NULL;
6436
86
    PyObject *rep = NULL;
6437
6438
86
    for (Py_ssize_t pos = 0; pos < len; ) {
6439
86
        if (kind == PyUnicode_2BYTE_KIND) {
6440
86
            pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
6441
86
                                        &out, native_ordering);
6442
86
        }
6443
0
        else {
6444
0
            assert(kind == PyUnicode_4BYTE_KIND);
6445
0
            pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
6446
0
                                        &out, native_ordering);
6447
0
        }
6448
86
        if (pos == len)
6449
86
            break;
6450
6451
0
        Py_ssize_t newpos;
6452
0
        rep = unicode_encode_call_errorhandler(
6453
0
                errors, &errorHandler,
6454
0
                encoding, "surrogates not allowed",
6455
0
                str, &exc, pos, pos + 1, &newpos);
6456
0
        if (!rep)
6457
0
            goto error;
6458
6459
0
        Py_ssize_t repsize, moreunits;
6460
0
        if (PyBytes_Check(rep)) {
6461
0
            repsize = PyBytes_GET_SIZE(rep);
6462
0
            if (repsize & 1) {
6463
0
                raise_encode_exception(&exc, encoding,
6464
0
                                       str, pos, pos + 1,
6465
0
                                       "surrogates not allowed");
6466
0
                goto error;
6467
0
            }
6468
0
            moreunits = repsize / 2;
6469
0
        }
6470
0
        else {
6471
0
            assert(PyUnicode_Check(rep));
6472
0
            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6473
0
            if (!PyUnicode_IS_ASCII(rep)) {
6474
0
                raise_encode_exception(&exc, encoding,
6475
0
                                       str, pos, pos + 1,
6476
0
                                       "surrogates not allowed");
6477
0
                goto error;
6478
0
            }
6479
0
        }
6480
0
        moreunits += pos - newpos;
6481
0
        pos = newpos;
6482
6483
        /* two bytes are reserved for each surrogate */
6484
0
        if (moreunits > 0) {
6485
0
            out = PyBytesWriter_GrowAndUpdatePointer(writer, 2 * moreunits, out);
6486
0
            if (out == NULL) {
6487
0
                goto error;
6488
0
            }
6489
0
        }
6490
6491
0
        if (PyBytes_Check(rep)) {
6492
0
            memcpy(out, PyBytes_AS_STRING(rep), repsize);
6493
0
            out += repsize / 2;
6494
0
        } else {
6495
            /* rep is unicode */
6496
0
            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6497
0
            ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6498
0
                                 &out, native_ordering);
6499
0
        }
6500
6501
0
        Py_CLEAR(rep);
6502
0
    }
6503
6504
86
    Py_XDECREF(errorHandler);
6505
86
    Py_XDECREF(exc);
6506
6507
    /* Cut back to size actually needed. This is necessary for, for example,
6508
    encoding of a string containing isolated surrogates and the 'ignore' handler
6509
    is used. */
6510
86
    return PyBytesWriter_FinishWithPointer(writer, out);
6511
6512
0
  error:
6513
0
    Py_XDECREF(rep);
6514
0
    Py_XDECREF(errorHandler);
6515
0
    Py_XDECREF(exc);
6516
0
    PyBytesWriter_Discard(writer);
6517
0
    return NULL;
6518
86
}
6519
6520
PyObject *
6521
PyUnicode_AsUTF16String(PyObject *unicode)
6522
0
{
6523
0
    return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
6524
0
}
6525
6526
_PyUnicode_Name_CAPI *
6527
_PyUnicode_GetNameCAPI(void)
6528
48.7k
{
6529
48.7k
    PyInterpreterState *interp = _PyInterpreterState_GET();
6530
48.7k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6531
6532
48.7k
    ucnhash_capi = _Py_atomic_load_ptr(&interp->unicode.ucnhash_capi);
6533
48.7k
    if (ucnhash_capi == NULL) {
6534
2
        ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6535
2
                PyUnicodeData_CAPSULE_NAME, 1);
6536
6537
        // It's fine if we overwrite the value here. It's always the same value.
6538
2
        _Py_atomic_store_ptr(&interp->unicode.ucnhash_capi, ucnhash_capi);
6539
2
    }
6540
48.7k
    return ucnhash_capi;
6541
48.7k
}
6542
6543
/* --- Unicode Escape Codec ----------------------------------------------- */
6544
6545
PyObject *
6546
_PyUnicode_DecodeUnicodeEscapeInternal2(const char *s,
6547
                               Py_ssize_t size,
6548
                               const char *errors,
6549
                               Py_ssize_t *consumed,
6550
                               int *first_invalid_escape_char,
6551
                               const char **first_invalid_escape_ptr)
6552
31.3k
{
6553
31.3k
    const char *starts = s;
6554
31.3k
    const char *initial_starts = starts;
6555
31.3k
    _PyUnicodeWriter writer;
6556
31.3k
    const char *end;
6557
31.3k
    PyObject *errorHandler = NULL;
6558
31.3k
    PyObject *exc = NULL;
6559
31.3k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6560
6561
    // so we can remember if we've seen an invalid escape char or not
6562
31.3k
    *first_invalid_escape_char = -1;
6563
31.3k
    *first_invalid_escape_ptr = NULL;
6564
6565
31.3k
    if (size == 0) {
6566
3.22k
        if (consumed) {
6567
0
            *consumed = 0;
6568
0
        }
6569
3.22k
        _Py_RETURN_UNICODE_EMPTY();
6570
3.22k
    }
6571
    /* Escaped strings will always be longer than the resulting
6572
       Unicode string, so we start with size here and then reduce the
6573
       length after conversion to the true value.
6574
       (but if the error callback returns a long replacement string
6575
       we'll have to allocate more space) */
6576
28.1k
    _PyUnicodeWriter_Init(&writer);
6577
28.1k
    writer.min_length = size;
6578
28.1k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6579
0
        goto onError;
6580
0
    }
6581
6582
28.1k
    end = s + size;
6583
8.66M
    while (s < end) {
6584
8.63M
        unsigned char c = (unsigned char) *s++;
6585
8.63M
        Py_UCS4 ch;
6586
8.63M
        int count;
6587
8.63M
        const char *message;
6588
6589
8.63M
#define WRITE_ASCII_CHAR(ch)                                                  \
6590
8.63M
            do {                                                              \
6591
119k
                assert(ch <= 127);                                            \
6592
119k
                assert(writer.pos < writer.size);                             \
6593
119k
                PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch);  \
6594
119k
            } while(0)
6595
6596
8.63M
#define WRITE_CHAR(ch)                                                        \
6597
8.63M
            do {                                                              \
6598
8.53M
                if (ch <= writer.maxchar) {                                   \
6599
8.52M
                    assert(writer.pos < writer.size);                         \
6600
8.52M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6601
8.52M
                }                                                             \
6602
8.53M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6603
0
                    goto onError;                                             \
6604
0
                }                                                             \
6605
8.53M
            } while(0)
6606
6607
        /* Non-escape characters are interpreted as Unicode ordinals */
6608
8.63M
        if (c != '\\') {
6609
8.39M
            WRITE_CHAR(c);
6610
8.39M
            continue;
6611
8.39M
        }
6612
6613
242k
        Py_ssize_t startinpos = s - starts - 1;
6614
        /* \ - Escapes */
6615
242k
        if (s >= end) {
6616
27
            message = "\\ at end of string";
6617
27
            goto incomplete;
6618
27
        }
6619
242k
        c = (unsigned char) *s++;
6620
6621
242k
        assert(writer.pos < writer.size);
6622
242k
        switch (c) {
6623
6624
            /* \x escapes */
6625
1.69k
        case '\n': continue;
6626
16.0k
        case '\\': WRITE_ASCII_CHAR('\\'); continue;
6627
2.19k
        case '\'': WRITE_ASCII_CHAR('\''); continue;
6628
1.57k
        case '\"': WRITE_ASCII_CHAR('\"'); continue;
6629
1.41k
        case 'b': WRITE_ASCII_CHAR('\b'); continue;
6630
        /* FF */
6631
1.47k
        case 'f': WRITE_ASCII_CHAR('\014'); continue;
6632
1.35k
        case 't': WRITE_ASCII_CHAR('\t'); continue;
6633
1.58k
        case 'n': WRITE_ASCII_CHAR('\n'); continue;
6634
18.2k
        case 'r': WRITE_ASCII_CHAR('\r'); continue;
6635
        /* VT */
6636
49.0k
        case 'v': WRITE_ASCII_CHAR('\013'); continue;
6637
        /* BEL, not classic C */
6638
2.20k
        case 'a': WRITE_ASCII_CHAR('\007'); continue;
6639
6640
            /* \OOO (octal) escapes */
6641
33.4k
        case '0': case '1': case '2': case '3':
6642
44.1k
        case '4': case '5': case '6': case '7':
6643
44.1k
            ch = c - '0';
6644
44.1k
            if (s < end && '0' <= *s && *s <= '7') {
6645
6.74k
                ch = (ch<<3) + *s++ - '0';
6646
6.74k
                if (s < end && '0' <= *s && *s <= '7') {
6647
3.92k
                    ch = (ch<<3) + *s++ - '0';
6648
3.92k
                }
6649
6.74k
            }
6650
44.1k
            if (ch > 0377) {
6651
3.44k
                if (*first_invalid_escape_char == -1) {
6652
1.05k
                    *first_invalid_escape_char = ch;
6653
1.05k
                    if (starts == initial_starts) {
6654
                        /* Back up 3 chars, since we've already incremented s. */
6655
1.05k
                        *first_invalid_escape_ptr = s - 3;
6656
1.05k
                    }
6657
1.05k
                }
6658
3.44k
            }
6659
44.1k
            WRITE_CHAR(ch);
6660
44.1k
            continue;
6661
6662
            /* hex escapes */
6663
            /* \xXX */
6664
44.1k
        case 'x':
6665
6.58k
            count = 2;
6666
6.58k
            message = "truncated \\xXX escape";
6667
6.58k
            goto hexescape;
6668
6669
            /* \uXXXX */
6670
6.27k
        case 'u':
6671
6.27k
            count = 4;
6672
6.27k
            message = "truncated \\uXXXX escape";
6673
6.27k
            goto hexescape;
6674
6675
            /* \UXXXXXXXX */
6676
15.1k
        case 'U':
6677
15.1k
            count = 8;
6678
15.1k
            message = "truncated \\UXXXXXXXX escape";
6679
28.0k
        hexescape:
6680
187k
            for (ch = 0; count; ++s, --count) {
6681
159k
                if (s >= end) {
6682
34
                    goto incomplete;
6683
34
                }
6684
159k
                c = (unsigned char)*s;
6685
159k
                ch <<= 4;
6686
159k
                if (c >= '0' && c <= '9') {
6687
119k
                    ch += c - '0';
6688
119k
                }
6689
39.4k
                else if (c >= 'a' && c <= 'f') {
6690
38.5k
                    ch += c - ('a' - 10);
6691
38.5k
                }
6692
809
                else if (c >= 'A' && c <= 'F') {
6693
801
                    ch += c - ('A' - 10);
6694
801
                }
6695
8
                else {
6696
8
                    goto error;
6697
8
                }
6698
159k
            }
6699
6700
            /* when we get here, ch is a 32-bit unicode character */
6701
27.9k
            if (ch > MAX_UNICODE) {
6702
2
                message = "illegal Unicode character";
6703
2
                goto error;
6704
2
            }
6705
6706
27.9k
            WRITE_CHAR(ch);
6707
27.9k
            continue;
6708
6709
            /* \N{name} */
6710
48.7k
        case 'N':
6711
48.7k
            ucnhash_capi = _PyUnicode_GetNameCAPI();
6712
48.7k
            if (ucnhash_capi == NULL) {
6713
0
                PyErr_SetString(
6714
0
                        PyExc_UnicodeError,
6715
0
                        "\\N escapes not supported (can't load unicodedata module)"
6716
0
                );
6717
0
                goto onError;
6718
0
            }
6719
6720
48.7k
            message = "malformed \\N character escape";
6721
48.7k
            if (s >= end) {
6722
8
                goto incomplete;
6723
8
            }
6724
48.7k
            if (*s == '{') {
6725
48.6k
                const char *start = ++s;
6726
48.6k
                size_t namelen;
6727
                /* look for the closing brace */
6728
1.21M
                while (s < end && *s != '}')
6729
1.16M
                    s++;
6730
48.6k
                if (s >= end) {
6731
24
                    goto incomplete;
6732
24
                }
6733
48.6k
                namelen = s - start;
6734
48.6k
                if (namelen) {
6735
                    /* found a name.  look it up in the unicode database */
6736
48.6k
                    s++;
6737
48.6k
                    ch = 0xffffffff; /* in case 'getcode' messes up */
6738
48.6k
                    if (namelen <= INT_MAX &&
6739
48.6k
                        ucnhash_capi->getcode(start, (int)namelen,
6740
48.6k
                                              &ch, 0)) {
6741
48.5k
                        assert(ch <= MAX_UNICODE);
6742
48.5k
                        WRITE_CHAR(ch);
6743
48.5k
                        continue;
6744
48.5k
                    }
6745
150
                    message = "unknown Unicode character name";
6746
150
                }
6747
48.6k
            }
6748
164
            goto error;
6749
6750
24.4k
        default:
6751
24.4k
            if (*first_invalid_escape_char == -1) {
6752
5.49k
                *first_invalid_escape_char = c;
6753
5.49k
                if (starts == initial_starts) {
6754
                    /* Back up one char, since we've already incremented s. */
6755
5.49k
                    *first_invalid_escape_ptr = s - 1;
6756
5.49k
                }
6757
5.49k
            }
6758
24.4k
            WRITE_ASCII_CHAR('\\');
6759
24.4k
            WRITE_CHAR(c);
6760
24.4k
            continue;
6761
242k
        }
6762
6763
93
      incomplete:
6764
93
        if (consumed) {
6765
0
            *consumed = startinpos;
6766
0
            break;
6767
0
        }
6768
267
      error:;
6769
267
        Py_ssize_t endinpos = s-starts;
6770
267
        writer.min_length = end - s + writer.pos;
6771
267
        if (unicode_decode_call_errorhandler_writer(
6772
267
                errors, &errorHandler,
6773
267
                "unicodeescape", message,
6774
267
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6775
267
                &writer)) {
6776
267
            goto onError;
6777
267
        }
6778
267
        assert(end - s <= writer.size - writer.pos);
6779
6780
0
#undef WRITE_ASCII_CHAR
6781
0
#undef WRITE_CHAR
6782
0
    }
6783
6784
27.8k
    Py_XDECREF(errorHandler);
6785
27.8k
    Py_XDECREF(exc);
6786
27.8k
    return _PyUnicodeWriter_Finish(&writer);
6787
6788
267
  onError:
6789
267
    _PyUnicodeWriter_Dealloc(&writer);
6790
267
    Py_XDECREF(errorHandler);
6791
267
    Py_XDECREF(exc);
6792
267
    return NULL;
6793
28.1k
}
6794
6795
PyObject *
6796
_PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
6797
                              Py_ssize_t size,
6798
                              const char *errors,
6799
                              Py_ssize_t *consumed)
6800
614
{
6801
614
    int first_invalid_escape_char;
6802
614
    const char *first_invalid_escape_ptr;
6803
614
    PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal2(s, size, errors,
6804
614
                                                      consumed,
6805
614
                                                      &first_invalid_escape_char,
6806
614
                                                      &first_invalid_escape_ptr);
6807
614
    if (result == NULL)
6808
150
        return NULL;
6809
464
    if (first_invalid_escape_char != -1) {
6810
241
        if (first_invalid_escape_char > 0xff) {
6811
107
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6812
107
                                 "\"\\%o\" is an invalid octal escape sequence. "
6813
107
                                 "Such sequences will not work in the future. ",
6814
107
                                 first_invalid_escape_char) < 0)
6815
0
            {
6816
0
                Py_DECREF(result);
6817
0
                return NULL;
6818
0
            }
6819
107
        }
6820
134
        else {
6821
134
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6822
134
                                 "\"\\%c\" is an invalid escape sequence. "
6823
134
                                 "Such sequences will not work in the future. ",
6824
134
                                 first_invalid_escape_char) < 0)
6825
0
            {
6826
0
                Py_DECREF(result);
6827
0
                return NULL;
6828
0
            }
6829
134
        }
6830
241
    }
6831
464
    return result;
6832
464
}
6833
6834
PyObject *
6835
PyUnicode_DecodeUnicodeEscape(const char *s,
6836
                              Py_ssize_t size,
6837
                              const char *errors)
6838
0
{
6839
0
    return _PyUnicode_DecodeUnicodeEscapeStateful(s, size, errors, NULL);
6840
0
}
6841
6842
/* Return a Unicode-Escape string version of the Unicode object. */
6843
6844
PyObject *
6845
PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
6846
448k
{
6847
448k
    if (!PyUnicode_Check(unicode)) {
6848
0
        PyErr_BadArgument();
6849
0
        return NULL;
6850
0
    }
6851
6852
448k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
6853
448k
    if (len == 0) {
6854
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
6855
0
    }
6856
448k
    int kind = PyUnicode_KIND(unicode);
6857
448k
    const void *data = PyUnicode_DATA(unicode);
6858
6859
    /* Initial allocation is based on the longest-possible character
6860
     * escape.
6861
     *
6862
     * For UCS1 strings it's '\xxx', 4 bytes per source character.
6863
     * For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6864
     * For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character. */
6865
448k
    Py_ssize_t expandsize = kind * 2 + 2;
6866
448k
    if (len > PY_SSIZE_T_MAX / expandsize) {
6867
0
        return PyErr_NoMemory();
6868
0
    }
6869
6870
448k
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
6871
448k
    if (writer == NULL) {
6872
0
        return NULL;
6873
0
    }
6874
448k
    char *p = PyBytesWriter_GetData(writer);
6875
6876
896k
    for (Py_ssize_t i = 0; i < len; i++) {
6877
448k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6878
6879
        /* U+0000-U+00ff range */
6880
448k
        if (ch < 0x100) {
6881
440k
            if (ch >= ' ' && ch < 127) {
6882
24.4k
                if (ch != '\\') {
6883
                    /* Copy printable US ASCII as-is */
6884
0
                    *p++ = (char) ch;
6885
0
                }
6886
                /* Escape backslashes */
6887
24.4k
                else {
6888
24.4k
                    *p++ = '\\';
6889
24.4k
                    *p++ = '\\';
6890
24.4k
                }
6891
24.4k
            }
6892
6893
            /* Map special whitespace to '\t', \n', '\r' */
6894
415k
            else if (ch == '\t') {
6895
1.26k
                *p++ = '\\';
6896
1.26k
                *p++ = 't';
6897
1.26k
            }
6898
414k
            else if (ch == '\n') {
6899
1.28k
                *p++ = '\\';
6900
1.28k
                *p++ = 'n';
6901
1.28k
            }
6902
413k
            else if (ch == '\r') {
6903
479
                *p++ = '\\';
6904
479
                *p++ = 'r';
6905
479
            }
6906
6907
            /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6908
412k
            else {
6909
412k
                *p++ = '\\';
6910
412k
                *p++ = 'x';
6911
412k
                *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6912
412k
                *p++ = Py_hexdigits[ch & 0x000F];
6913
412k
            }
6914
440k
        }
6915
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
6916
8.07k
        else if (ch < 0x10000) {
6917
6.15k
            *p++ = '\\';
6918
6.15k
            *p++ = 'u';
6919
6.15k
            *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6920
6.15k
            *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6921
6.15k
            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6922
6.15k
            *p++ = Py_hexdigits[ch & 0x000F];
6923
6.15k
        }
6924
        /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6925
1.91k
        else {
6926
6927
            /* Make sure that the first two digits are zero */
6928
1.91k
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6929
1.91k
            *p++ = '\\';
6930
1.91k
            *p++ = 'U';
6931
1.91k
            *p++ = '0';
6932
1.91k
            *p++ = '0';
6933
1.91k
            *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6934
1.91k
            *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6935
1.91k
            *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6936
1.91k
            *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6937
1.91k
            *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6938
1.91k
            *p++ = Py_hexdigits[ch & 0x0000000F];
6939
1.91k
        }
6940
448k
    }
6941
6942
448k
    return PyBytesWriter_FinishWithPointer(writer, p);
6943
448k
}
6944
6945
/* --- Raw Unicode Escape Codec ------------------------------------------- */
6946
6947
PyObject *
6948
_PyUnicode_DecodeRawUnicodeEscapeStateful(const char *s,
6949
                                          Py_ssize_t size,
6950
                                          const char *errors,
6951
                                          Py_ssize_t *consumed)
6952
115
{
6953
115
    const char *starts = s;
6954
115
    _PyUnicodeWriter writer;
6955
115
    const char *end;
6956
115
    PyObject *errorHandler = NULL;
6957
115
    PyObject *exc = NULL;
6958
6959
115
    if (size == 0) {
6960
0
        if (consumed) {
6961
0
            *consumed = 0;
6962
0
        }
6963
0
        _Py_RETURN_UNICODE_EMPTY();
6964
0
    }
6965
6966
    /* Escaped strings will always be longer than the resulting
6967
       Unicode string, so we start with size here and then reduce the
6968
       length after conversion to the true value. (But decoding error
6969
       handler might have to resize the string) */
6970
115
    _PyUnicodeWriter_Init(&writer);
6971
115
    writer.min_length = size;
6972
115
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6973
0
        goto onError;
6974
0
    }
6975
6976
115
    end = s + size;
6977
276k
    while (s < end) {
6978
275k
        unsigned char c = (unsigned char) *s++;
6979
275k
        Py_UCS4 ch;
6980
275k
        int count;
6981
275k
        const char *message;
6982
6983
275k
#define WRITE_CHAR(ch)                                                        \
6984
275k
            do {                                                              \
6985
275k
                if (ch <= writer.maxchar) {                                   \
6986
275k
                    assert(writer.pos < writer.size);                         \
6987
275k
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6988
275k
                }                                                             \
6989
275k
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6990
0
                    goto onError;                                             \
6991
0
                }                                                             \
6992
275k
            } while(0)
6993
6994
        /* Non-escape characters are interpreted as Unicode ordinals */
6995
275k
        if (c != '\\' || (s >= end && !consumed)) {
6996
274k
            WRITE_CHAR(c);
6997
274k
            continue;
6998
274k
        }
6999
7000
1.67k
        Py_ssize_t startinpos = s - starts - 1;
7001
        /* \ - Escapes */
7002
1.67k
        if (s >= end) {
7003
0
            assert(consumed);
7004
            // Set message to silent compiler warning.
7005
            // Actually it is never used.
7006
0
            message = "\\ at end of string";
7007
0
            goto incomplete;
7008
0
        }
7009
7010
1.67k
        c = (unsigned char) *s++;
7011
1.67k
        if (c == 'u') {
7012
369
            count = 4;
7013
369
            message = "truncated \\uXXXX escape";
7014
369
        }
7015
1.30k
        else if (c == 'U') {
7016
430
            count = 8;
7017
430
            message = "truncated \\UXXXXXXXX escape";
7018
430
        }
7019
875
        else {
7020
875
            assert(writer.pos < writer.size);
7021
875
            PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
7022
875
            WRITE_CHAR(c);
7023
875
            continue;
7024
875
        }
7025
7026
        /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
7027
5.57k
        for (ch = 0; count; ++s, --count) {
7028
4.80k
            if (s >= end) {
7029
20
                goto incomplete;
7030
20
            }
7031
4.78k
            c = (unsigned char)*s;
7032
4.78k
            ch <<= 4;
7033
4.78k
            if (c >= '0' && c <= '9') {
7034
3.50k
                ch += c - '0';
7035
3.50k
            }
7036
1.28k
            else if (c >= 'a' && c <= 'f') {
7037
859
                ch += c - ('a' - 10);
7038
859
            }
7039
428
            else if (c >= 'A' && c <= 'F') {
7040
420
                ch += c - ('A' - 10);
7041
420
            }
7042
8
            else {
7043
8
                goto error;
7044
8
            }
7045
4.78k
        }
7046
771
        if (ch > MAX_UNICODE) {
7047
2
            message = "\\Uxxxxxxxx out of range";
7048
2
            goto error;
7049
2
        }
7050
769
        WRITE_CHAR(ch);
7051
769
        continue;
7052
7053
769
      incomplete:
7054
20
        if (consumed) {
7055
0
            *consumed = startinpos;
7056
0
            break;
7057
0
        }
7058
30
      error:;
7059
30
        Py_ssize_t endinpos = s-starts;
7060
30
        writer.min_length = end - s + writer.pos;
7061
30
        if (unicode_decode_call_errorhandler_writer(
7062
30
                errors, &errorHandler,
7063
30
                "rawunicodeescape", message,
7064
30
                &starts, &end, &startinpos, &endinpos, &exc, &s,
7065
30
                &writer)) {
7066
30
            goto onError;
7067
30
        }
7068
30
        assert(end - s <= writer.size - writer.pos);
7069
7070
0
#undef WRITE_CHAR
7071
0
    }
7072
85
    Py_XDECREF(errorHandler);
7073
85
    Py_XDECREF(exc);
7074
85
    return _PyUnicodeWriter_Finish(&writer);
7075
7076
30
  onError:
7077
30
    _PyUnicodeWriter_Dealloc(&writer);
7078
30
    Py_XDECREF(errorHandler);
7079
30
    Py_XDECREF(exc);
7080
30
    return NULL;
7081
115
}
7082
7083
PyObject *
7084
PyUnicode_DecodeRawUnicodeEscape(const char *s,
7085
                                 Py_ssize_t size,
7086
                                 const char *errors)
7087
0
{
7088
0
    return _PyUnicode_DecodeRawUnicodeEscapeStateful(s, size, errors, NULL);
7089
0
}
7090
7091
7092
PyObject *
7093
PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
7094
253k
{
7095
253k
    if (!PyUnicode_Check(unicode)) {
7096
0
        PyErr_BadArgument();
7097
0
        return NULL;
7098
0
    }
7099
253k
    int kind = PyUnicode_KIND(unicode);
7100
253k
    const void *data = PyUnicode_DATA(unicode);
7101
253k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
7102
253k
    if (len == 0) {
7103
527
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7104
527
    }
7105
253k
    if (kind == PyUnicode_1BYTE_KIND) {
7106
252k
        return PyBytes_FromStringAndSize(data, len);
7107
252k
    }
7108
7109
    /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
7110
       bytes, and 1 byte characters 4. */
7111
324
    Py_ssize_t expandsize = kind * 2 + 2;
7112
324
    if (len > PY_SSIZE_T_MAX / expandsize) {
7113
0
        return PyErr_NoMemory();
7114
0
    }
7115
7116
324
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
7117
324
    if (writer == NULL) {
7118
0
        return NULL;
7119
0
    }
7120
324
    char *p = PyBytesWriter_GetData(writer);
7121
7122
4.56M
    for (Py_ssize_t pos = 0; pos < len; pos++) {
7123
4.56M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7124
7125
        /* U+0000-U+00ff range: Copy 8-bit characters as-is */
7126
4.56M
        if (ch < 0x100) {
7127
4.51M
            *p++ = (char) ch;
7128
4.51M
        }
7129
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
7130
56.1k
        else if (ch < 0x10000) {
7131
55.3k
            *p++ = '\\';
7132
55.3k
            *p++ = 'u';
7133
55.3k
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7134
55.3k
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7135
55.3k
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7136
55.3k
            *p++ = Py_hexdigits[ch & 15];
7137
55.3k
        }
7138
        /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
7139
826
        else {
7140
826
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
7141
826
            *p++ = '\\';
7142
826
            *p++ = 'U';
7143
826
            *p++ = '0';
7144
826
            *p++ = '0';
7145
826
            *p++ = Py_hexdigits[(ch >> 20) & 0xf];
7146
826
            *p++ = Py_hexdigits[(ch >> 16) & 0xf];
7147
826
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7148
826
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7149
826
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7150
826
            *p++ = Py_hexdigits[ch & 15];
7151
826
        }
7152
4.56M
    }
7153
7154
324
    return PyBytesWriter_FinishWithPointer(writer, p);
7155
324
}
7156
7157
/* --- Latin-1 Codec ------------------------------------------------------ */
7158
7159
PyObject *
7160
PyUnicode_DecodeLatin1(const char *s,
7161
                       Py_ssize_t size,
7162
                       const char *errors)
7163
2.84M
{
7164
    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
7165
2.84M
    return _PyUnicode_FromUCS1((const unsigned char*)s, size);
7166
2.84M
}
7167
7168
/* create or adjust a UnicodeEncodeError */
7169
static void
7170
make_encode_exception(PyObject **exceptionObject,
7171
                      const char *encoding,
7172
                      PyObject *unicode,
7173
                      Py_ssize_t startpos, Py_ssize_t endpos,
7174
                      const char *reason)
7175
2.54M
{
7176
2.54M
    if (*exceptionObject == NULL) {
7177
2.54M
        *exceptionObject = PyObject_CallFunction(
7178
2.54M
            PyExc_UnicodeEncodeError, "sOnns",
7179
2.54M
            encoding, unicode, startpos, endpos, reason);
7180
2.54M
    }
7181
0
    else {
7182
0
        if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
7183
0
            goto onError;
7184
0
        if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
7185
0
            goto onError;
7186
0
        if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
7187
0
            goto onError;
7188
0
        return;
7189
0
      onError:
7190
0
        Py_CLEAR(*exceptionObject);
7191
0
    }
7192
2.54M
}
7193
7194
/* raises a UnicodeEncodeError */
7195
static void
7196
raise_encode_exception(PyObject **exceptionObject,
7197
                       const char *encoding,
7198
                       PyObject *unicode,
7199
                       Py_ssize_t startpos, Py_ssize_t endpos,
7200
                       const char *reason)
7201
2.40M
{
7202
2.40M
    make_encode_exception(exceptionObject,
7203
2.40M
                          encoding, unicode, startpos, endpos, reason);
7204
2.40M
    if (*exceptionObject != NULL)
7205
2.40M
        PyCodec_StrictErrors(*exceptionObject);
7206
2.40M
}
7207
7208
/* error handling callback helper:
7209
   build arguments, call the callback and check the arguments,
7210
   put the result into newpos and return the replacement string, which
7211
   has to be freed by the caller */
7212
static PyObject *
7213
unicode_encode_call_errorhandler(const char *errors,
7214
                                 PyObject **errorHandler,
7215
                                 const char *encoding, const char *reason,
7216
                                 PyObject *unicode, PyObject **exceptionObject,
7217
                                 Py_ssize_t startpos, Py_ssize_t endpos,
7218
                                 Py_ssize_t *newpos)
7219
145k
{
7220
145k
    static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
7221
145k
    Py_ssize_t len;
7222
145k
    PyObject *restuple;
7223
145k
    PyObject *resunicode;
7224
7225
145k
    if (*errorHandler == NULL) {
7226
145k
        *errorHandler = PyCodec_LookupError(errors);
7227
145k
        if (*errorHandler == NULL)
7228
0
            return NULL;
7229
145k
    }
7230
7231
145k
    len = PyUnicode_GET_LENGTH(unicode);
7232
7233
145k
    make_encode_exception(exceptionObject,
7234
145k
                          encoding, unicode, startpos, endpos, reason);
7235
145k
    if (*exceptionObject == NULL)
7236
0
        return NULL;
7237
7238
145k
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
7239
145k
    if (restuple == NULL)
7240
145k
        return NULL;
7241
0
    if (!PyTuple_Check(restuple)) {
7242
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
7243
0
        Py_DECREF(restuple);
7244
0
        return NULL;
7245
0
    }
7246
0
    if (!PyArg_ParseTuple(restuple, argparse,
7247
0
                          &resunicode, newpos)) {
7248
0
        Py_DECREF(restuple);
7249
0
        return NULL;
7250
0
    }
7251
0
    if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
7252
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
7253
0
        Py_DECREF(restuple);
7254
0
        return NULL;
7255
0
    }
7256
0
    if (*newpos<0)
7257
0
        *newpos = len + *newpos;
7258
0
    if (*newpos<0 || *newpos>len) {
7259
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7260
0
        Py_DECREF(restuple);
7261
0
        return NULL;
7262
0
    }
7263
0
    Py_INCREF(resunicode);
7264
0
    Py_DECREF(restuple);
7265
0
    return resunicode;
7266
0
}
7267
7268
static PyObject *
7269
unicode_encode_ucs1(PyObject *unicode,
7270
                    const char *errors,
7271
                    const Py_UCS4 limit)
7272
2.42M
{
7273
    /* input state */
7274
2.42M
    Py_ssize_t pos=0, size;
7275
2.42M
    int kind;
7276
2.42M
    const void *data;
7277
2.42M
    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
7278
2.42M
    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
7279
2.42M
    PyObject *error_handler_obj = NULL;
7280
2.42M
    PyObject *exc = NULL;
7281
2.42M
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7282
2.42M
    PyObject *rep = NULL;
7283
7284
2.42M
    size = PyUnicode_GET_LENGTH(unicode);
7285
2.42M
    kind = PyUnicode_KIND(unicode);
7286
2.42M
    data = PyUnicode_DATA(unicode);
7287
    /* allocate enough for a simple encoding without
7288
       replacements, if we need more, we'll resize */
7289
2.42M
    if (size == 0)
7290
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7291
7292
    /* output object */
7293
2.42M
    PyBytesWriter *writer = PyBytesWriter_Create(size);
7294
2.42M
    if (writer == NULL) {
7295
0
        return NULL;
7296
0
    }
7297
    /* pointer into the output */
7298
2.42M
    char *str = PyBytesWriter_GetData(writer);
7299
7300
8.97M
    while (pos < size) {
7301
8.97M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7302
7303
        /* can we encode this? */
7304
8.97M
        if (ch < limit) {
7305
            /* no overflow check, because we know that the space is enough */
7306
6.55M
            *str++ = (char)ch;
7307
6.55M
            ++pos;
7308
6.55M
        }
7309
2.42M
        else {
7310
2.42M
            Py_ssize_t newpos, i;
7311
            /* startpos for collecting unencodable chars */
7312
2.42M
            Py_ssize_t collstart = pos;
7313
2.42M
            Py_ssize_t collend = collstart + 1;
7314
            /* find all unecodable characters */
7315
7316
6.00M
            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
7317
3.58M
                ++collend;
7318
7319
            /* Only overallocate the buffer if it's not the last write */
7320
2.42M
            writer->overallocate = (collend < size);
7321
7322
            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
7323
2.42M
            if (error_handler == _Py_ERROR_UNKNOWN)
7324
2.42M
                error_handler = _Py_GetErrorHandler(errors);
7325
7326
2.42M
            switch (error_handler) {
7327
2.40M
            case _Py_ERROR_STRICT:
7328
2.40M
                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
7329
2.40M
                goto onError;
7330
7331
2.39k
            case _Py_ERROR_REPLACE:
7332
2.39k
                memset(str, '?', collend - collstart);
7333
2.39k
                str += (collend - collstart);
7334
2.39k
                _Py_FALLTHROUGH;
7335
2.39k
            case _Py_ERROR_IGNORE:
7336
2.39k
                pos = collend;
7337
2.39k
                break;
7338
7339
0
            case _Py_ERROR_BACKSLASHREPLACE:
7340
0
                str = backslashreplace(writer, str,
7341
0
                                       unicode, collstart, collend);
7342
0
                if (str == NULL)
7343
0
                    goto onError;
7344
0
                pos = collend;
7345
0
                break;
7346
7347
0
            case _Py_ERROR_XMLCHARREFREPLACE:
7348
0
                str = xmlcharrefreplace(writer, str,
7349
0
                                        unicode, collstart, collend);
7350
0
                if (str == NULL)
7351
0
                    goto onError;
7352
0
                pos = collend;
7353
0
                break;
7354
7355
15.9k
            case _Py_ERROR_SURROGATEESCAPE:
7356
15.9k
                for (i = collstart; i < collend; ++i) {
7357
15.9k
                    ch = PyUnicode_READ(kind, data, i);
7358
15.9k
                    if (ch < 0xdc80 || 0xdcff < ch) {
7359
                        /* Not a UTF-8b surrogate */
7360
15.9k
                        break;
7361
15.9k
                    }
7362
0
                    *str++ = (char)(ch - 0xdc00);
7363
0
                    ++pos;
7364
0
                }
7365
15.9k
                if (i >= collend)
7366
0
                    break;
7367
15.9k
                collstart = pos;
7368
15.9k
                assert(collstart != collend);
7369
15.9k
                _Py_FALLTHROUGH;
7370
7371
15.9k
            default:
7372
15.9k
                rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
7373
15.9k
                                                       encoding, reason, unicode, &exc,
7374
15.9k
                                                       collstart, collend, &newpos);
7375
15.9k
                if (rep == NULL)
7376
15.9k
                    goto onError;
7377
7378
0
                if (newpos < collstart) {
7379
0
                    writer->overallocate = 1;
7380
0
                    str = PyBytesWriter_GrowAndUpdatePointer(writer,
7381
0
                                                             collstart - newpos,
7382
0
                                                             str);
7383
0
                    if (str == NULL) {
7384
0
                        goto onError;
7385
0
                    }
7386
0
                }
7387
0
                else {
7388
                    /* Only overallocate the buffer if it's not the last write */
7389
0
                    writer->overallocate = (newpos < size);
7390
7391
                    /* subtract preallocated bytes */
7392
0
                    if (PyBytesWriter_Grow(writer, -(newpos - collstart)) < 0) {
7393
0
                        goto onError;
7394
0
                    }
7395
0
                }
7396
7397
0
                const char *rep_str;
7398
0
                Py_ssize_t rep_len;
7399
0
                if (PyBytes_Check(rep)) {
7400
                    /* Directly copy bytes result to output. */
7401
0
                    rep_str = PyBytes_AS_STRING(rep);
7402
0
                    rep_len = PyBytes_GET_SIZE(rep);
7403
0
                }
7404
0
                else {
7405
0
                    assert(PyUnicode_Check(rep));
7406
7407
0
                    if (limit == 256 ?
7408
0
                        PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
7409
0
                        !PyUnicode_IS_ASCII(rep))
7410
0
                    {
7411
                        /* Not all characters are smaller than limit */
7412
0
                        raise_encode_exception(&exc, encoding, unicode,
7413
0
                                               collstart, collend, reason);
7414
0
                        goto onError;
7415
0
                    }
7416
0
                    assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
7417
0
                    rep_str = PyUnicode_DATA(rep);
7418
0
                    rep_len = PyUnicode_GET_LENGTH(rep);
7419
0
                }
7420
7421
0
                str = PyBytesWriter_GrowAndUpdatePointer(writer, rep_len, str);
7422
0
                if (str == NULL) {
7423
0
                    goto onError;
7424
0
                }
7425
0
                memcpy(str, rep_str, rep_len);
7426
0
                str += rep_len;
7427
7428
0
                pos = newpos;
7429
0
                Py_CLEAR(rep);
7430
2.42M
            }
7431
7432
            /* If overallocation was disabled, ensure that it was the last
7433
               write. Otherwise, we missed an optimization */
7434
2.42M
            assert(writer->overallocate || pos == size);
7435
2.39k
        }
7436
8.97M
    }
7437
7438
2.30k
    Py_XDECREF(error_handler_obj);
7439
2.30k
    Py_XDECREF(exc);
7440
2.30k
    return PyBytesWriter_FinishWithPointer(writer, str);
7441
7442
2.41M
  onError:
7443
2.41M
    Py_XDECREF(rep);
7444
2.41M
    PyBytesWriter_Discard(writer);
7445
2.41M
    Py_XDECREF(error_handler_obj);
7446
2.41M
    Py_XDECREF(exc);
7447
2.41M
    return NULL;
7448
2.42M
}
7449
7450
PyObject *
7451
_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
7452
10
{
7453
10
    if (!PyUnicode_Check(unicode)) {
7454
0
        PyErr_BadArgument();
7455
0
        return NULL;
7456
0
    }
7457
    /* Fast path: if it is a one-byte string, construct
7458
       bytes object directly. */
7459
10
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7460
10
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7461
10
                                         PyUnicode_GET_LENGTH(unicode));
7462
    /* Non-Latin-1 characters present. Defer to above function to
7463
       raise the exception. */
7464
0
    return unicode_encode_ucs1(unicode, errors, 256);
7465
10
}
7466
7467
PyObject*
7468
PyUnicode_AsLatin1String(PyObject *unicode)
7469
0
{
7470
0
    return _PyUnicode_AsLatin1String(unicode, NULL);
7471
0
}
7472
7473
/* --- 7-bit ASCII Codec -------------------------------------------------- */
7474
7475
PyObject *
7476
PyUnicode_DecodeASCII(const char *s,
7477
                      Py_ssize_t size,
7478
                      const char *errors)
7479
14.1M
{
7480
14.1M
    const char *starts = s;
7481
14.1M
    const char *e = s + size;
7482
14.1M
    PyObject *error_handler_obj = NULL;
7483
14.1M
    PyObject *exc = NULL;
7484
14.1M
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7485
7486
14.1M
    if (size == 0)
7487
0
        _Py_RETURN_UNICODE_EMPTY();
7488
7489
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
7490
14.1M
    if (size == 1 && (unsigned char)s[0] < 128) {
7491
777k
        return get_latin1_char((unsigned char)s[0]);
7492
777k
    }
7493
7494
    // Shortcut for simple case
7495
13.3M
    PyObject *u = PyUnicode_New(size, 127);
7496
13.3M
    if (u == NULL) {
7497
0
        return NULL;
7498
0
    }
7499
13.3M
    Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
7500
13.3M
    if (outpos == size) {
7501
10.3M
        return u;
7502
10.3M
    }
7503
7504
3.02M
    _PyUnicodeWriter writer;
7505
3.02M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
7506
3.02M
    writer.pos = outpos;
7507
7508
3.02M
    s += outpos;
7509
3.02M
    int kind = writer.kind;
7510
3.02M
    void *data = writer.data;
7511
3.02M
    Py_ssize_t startinpos, endinpos;
7512
7513
20.9M
    while (s < e) {
7514
20.8M
        unsigned char c = (unsigned char)*s;
7515
20.8M
        if (c < 128) {
7516
6.33M
            PyUnicode_WRITE(kind, data, writer.pos, c);
7517
6.33M
            writer.pos++;
7518
6.33M
            ++s;
7519
6.33M
            continue;
7520
6.33M
        }
7521
7522
        /* byte outsize range 0x00..0x7f: call the error handler */
7523
7524
14.5M
        if (error_handler == _Py_ERROR_UNKNOWN)
7525
3.02M
            error_handler = _Py_GetErrorHandler(errors);
7526
7527
14.5M
        switch (error_handler)
7528
14.5M
        {
7529
756k
        case _Py_ERROR_REPLACE:
7530
11.6M
        case _Py_ERROR_SURROGATEESCAPE:
7531
            /* Fast-path: the error handler only writes one character,
7532
               but we may switch to UCS2 at the first write */
7533
11.6M
            if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7534
0
                goto onError;
7535
11.6M
            assert(_PyUnicodeWriter_CanWrite(&writer));
7536
11.6M
            kind = writer.kind;
7537
11.6M
            data = writer.data;
7538
7539
11.6M
            if (error_handler == _Py_ERROR_REPLACE)
7540
756k
                PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7541
10.8M
            else
7542
10.8M
                PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7543
11.6M
            writer.pos++;
7544
11.6M
            ++s;
7545
11.6M
            break;
7546
7547
0
        case _Py_ERROR_IGNORE:
7548
0
            ++s;
7549
0
            break;
7550
7551
2.88M
        default:
7552
2.88M
            startinpos = s-starts;
7553
2.88M
            endinpos = startinpos + 1;
7554
2.88M
            if (unicode_decode_call_errorhandler_writer(
7555
2.88M
                    errors, &error_handler_obj,
7556
2.88M
                    "ascii", "ordinal not in range(128)",
7557
2.88M
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
7558
2.88M
                    &writer))
7559
2.88M
                goto onError;
7560
0
            kind = writer.kind;
7561
0
            data = writer.data;
7562
14.5M
        }
7563
14.5M
    }
7564
141k
    Py_XDECREF(error_handler_obj);
7565
141k
    Py_XDECREF(exc);
7566
141k
    return _PyUnicodeWriter_Finish(&writer);
7567
7568
2.88M
  onError:
7569
2.88M
    _PyUnicodeWriter_Dealloc(&writer);
7570
2.88M
    Py_XDECREF(error_handler_obj);
7571
2.88M
    Py_XDECREF(exc);
7572
2.88M
    return NULL;
7573
3.02M
}
7574
7575
PyObject *
7576
_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
7577
2.66M
{
7578
2.66M
    if (!PyUnicode_Check(unicode)) {
7579
0
        PyErr_BadArgument();
7580
0
        return NULL;
7581
0
    }
7582
    /* Fast path: if it is an ASCII-only string, construct bytes object
7583
       directly. Else defer to above function to raise the exception. */
7584
2.66M
    if (PyUnicode_IS_ASCII(unicode))
7585
244k
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7586
244k
                                         PyUnicode_GET_LENGTH(unicode));
7587
2.42M
    return unicode_encode_ucs1(unicode, errors, 128);
7588
2.66M
}
7589
7590
PyObject *
7591
PyUnicode_AsASCIIString(PyObject *unicode)
7592
124k
{
7593
124k
    return _PyUnicode_AsASCIIString(unicode, NULL);
7594
124k
}
7595
7596
#ifdef MS_WINDOWS
7597
7598
/* --- MBCS codecs for Windows -------------------------------------------- */
7599
7600
#if SIZEOF_INT < SIZEOF_SIZE_T
7601
#define NEED_RETRY
7602
#endif
7603
7604
/* INT_MAX is the theoretical largest chunk (or INT_MAX / 2 when
7605
   transcoding from UTF-16), but INT_MAX / 4 performs better in
7606
   both cases also and avoids partial characters overrunning the
7607
   length limit in MultiByteToWideChar on Windows */
7608
#define DECODING_CHUNK_SIZE (INT_MAX/4)
7609
7610
#ifndef WC_ERR_INVALID_CHARS
7611
#  define WC_ERR_INVALID_CHARS 0x0080
7612
#endif
7613
7614
static const char*
7615
code_page_name(UINT code_page, PyObject **obj)
7616
{
7617
    *obj = NULL;
7618
    if (code_page == CP_ACP)
7619
        return "mbcs";
7620
7621
    *obj = PyBytes_FromFormat("cp%u", code_page);
7622
    if (*obj == NULL)
7623
        return NULL;
7624
    return PyBytes_AS_STRING(*obj);
7625
}
7626
7627
static DWORD
7628
decode_code_page_flags(UINT code_page)
7629
{
7630
    if (code_page == CP_UTF7) {
7631
        /* The CP_UTF7 decoder only supports flags=0 */
7632
        return 0;
7633
    }
7634
    else
7635
        return MB_ERR_INVALID_CHARS;
7636
}
7637
7638
/*
7639
 * Decode a byte string from a Windows code page into unicode object in strict
7640
 * mode.
7641
 *
7642
 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7643
 * OSError and returns -1 on other error.
7644
 */
7645
static int
7646
decode_code_page_strict(UINT code_page,
7647
                        wchar_t **buf,
7648
                        Py_ssize_t *bufsize,
7649
                        const char *in,
7650
                        int insize)
7651
{
7652
    DWORD flags = MB_ERR_INVALID_CHARS;
7653
    wchar_t *out;
7654
    DWORD outsize;
7655
7656
    /* First get the size of the result */
7657
    assert(insize > 0);
7658
    while ((outsize = MultiByteToWideChar(code_page, flags,
7659
                                          in, insize, NULL, 0)) <= 0)
7660
    {
7661
        if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7662
            goto error;
7663
        }
7664
        /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7665
        flags = 0;
7666
    }
7667
7668
    /* Extend a wchar_t* buffer */
7669
    Py_ssize_t n = *bufsize;   /* Get the current length */
7670
    if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7671
        return -1;
7672
    }
7673
    out = *buf + n;
7674
7675
    /* Do the conversion */
7676
    outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7677
    if (outsize <= 0)
7678
        goto error;
7679
    return insize;
7680
7681
error:
7682
    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7683
        return -2;
7684
    PyErr_SetFromWindowsErr(0);
7685
    return -1;
7686
}
7687
7688
/*
7689
 * Decode a byte string from a code page into unicode object with an error
7690
 * handler.
7691
 *
7692
 * Returns consumed size if succeed, or raise an OSError or
7693
 * UnicodeDecodeError exception and returns -1 on error.
7694
 */
7695
static int
7696
decode_code_page_errors(UINT code_page,
7697
                        wchar_t **buf,
7698
                        Py_ssize_t *bufsize,
7699
                        const char *in, const int size,
7700
                        const char *errors, int final)
7701
{
7702
    const char *startin = in;
7703
    const char *endin = in + size;
7704
    DWORD flags = MB_ERR_INVALID_CHARS;
7705
    /* Ideally, we should get reason from FormatMessage. This is the Windows
7706
       2000 English version of the message. */
7707
    const char *reason = "No mapping for the Unicode character exists "
7708
                         "in the target code page.";
7709
    /* each step cannot decode more than 1 character, but a character can be
7710
       represented as a surrogate pair */
7711
    wchar_t buffer[2], *out;
7712
    int insize;
7713
    Py_ssize_t outsize;
7714
    PyObject *errorHandler = NULL;
7715
    PyObject *exc = NULL;
7716
    PyObject *encoding_obj = NULL;
7717
    const char *encoding;
7718
    DWORD err;
7719
    int ret = -1;
7720
7721
    assert(size > 0);
7722
7723
    encoding = code_page_name(code_page, &encoding_obj);
7724
    if (encoding == NULL)
7725
        return -1;
7726
7727
    if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
7728
        /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7729
           UnicodeDecodeError. */
7730
        make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7731
        if (exc != NULL) {
7732
            PyCodec_StrictErrors(exc);
7733
            Py_CLEAR(exc);
7734
        }
7735
        goto error;
7736
    }
7737
7738
    /* Extend a wchar_t* buffer */
7739
    Py_ssize_t n = *bufsize;   /* Get the current length */
7740
    if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7741
        PyErr_NoMemory();
7742
        goto error;
7743
    }
7744
    if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7745
        goto error;
7746
    }
7747
    out = *buf + n;
7748
7749
    /* Decode the byte string character per character */
7750
    while (in < endin)
7751
    {
7752
        /* Decode a character */
7753
        insize = 1;
7754
        do
7755
        {
7756
            outsize = MultiByteToWideChar(code_page, flags,
7757
                                          in, insize,
7758
                                          buffer, Py_ARRAY_LENGTH(buffer));
7759
            if (outsize > 0)
7760
                break;
7761
            err = GetLastError();
7762
            if (err == ERROR_INVALID_FLAGS && flags) {
7763
                /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7764
                flags = 0;
7765
                continue;
7766
            }
7767
            if (err != ERROR_NO_UNICODE_TRANSLATION
7768
                && err != ERROR_INSUFFICIENT_BUFFER)
7769
            {
7770
                PyErr_SetFromWindowsErr(err);
7771
                goto error;
7772
            }
7773
            insize++;
7774
        }
7775
        /* 4=maximum length of a UTF-8 sequence */
7776
        while (insize <= 4 && (in + insize) <= endin);
7777
7778
        if (outsize <= 0) {
7779
            Py_ssize_t startinpos, endinpos, outpos;
7780
7781
            /* last character in partial decode? */
7782
            if (in + insize >= endin && !final)
7783
                break;
7784
7785
            startinpos = in - startin;
7786
            endinpos = startinpos + 1;
7787
            outpos = out - *buf;
7788
            if (unicode_decode_call_errorhandler_wchar(
7789
                    errors, &errorHandler,
7790
                    encoding, reason,
7791
                    &startin, &endin, &startinpos, &endinpos, &exc, &in,
7792
                    buf, bufsize, &outpos))
7793
            {
7794
                goto error;
7795
            }
7796
            out = *buf + outpos;
7797
        }
7798
        else {
7799
            in += insize;
7800
            memcpy(out, buffer, outsize * sizeof(wchar_t));
7801
            out += outsize;
7802
        }
7803
    }
7804
7805
    /* Shrink the buffer */
7806
    assert(out - *buf <= *bufsize);
7807
    *bufsize = out - *buf;
7808
    /* (in - startin) <= size and size is an int */
7809
    ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
7810
7811
error:
7812
    Py_XDECREF(encoding_obj);
7813
    Py_XDECREF(errorHandler);
7814
    Py_XDECREF(exc);
7815
    return ret;
7816
}
7817
7818
static PyObject *
7819
decode_code_page_stateful(int code_page,
7820
                          const char *s, Py_ssize_t size,
7821
                          const char *errors, Py_ssize_t *consumed)
7822
{
7823
    wchar_t *buf = NULL;
7824
    Py_ssize_t bufsize = 0;
7825
    int chunk_size, final, converted, done;
7826
7827
    if (code_page < 0) {
7828
        PyErr_SetString(PyExc_ValueError, "invalid code page number");
7829
        return NULL;
7830
    }
7831
    if (size < 0) {
7832
        PyErr_BadInternalCall();
7833
        return NULL;
7834
    }
7835
7836
    if (consumed)
7837
        *consumed = 0;
7838
7839
    do
7840
    {
7841
#ifdef NEED_RETRY
7842
        if (size > DECODING_CHUNK_SIZE) {
7843
            chunk_size = DECODING_CHUNK_SIZE;
7844
            final = 0;
7845
            done = 0;
7846
        }
7847
        else
7848
#endif
7849
        {
7850
            chunk_size = (int)size;
7851
            final = (consumed == NULL);
7852
            done = 1;
7853
        }
7854
7855
        if (chunk_size == 0 && done) {
7856
            if (buf != NULL)
7857
                break;
7858
            _Py_RETURN_UNICODE_EMPTY();
7859
        }
7860
7861
        converted = decode_code_page_strict(code_page, &buf, &bufsize,
7862
                                            s, chunk_size);
7863
        if (converted == -2)
7864
            converted = decode_code_page_errors(code_page, &buf, &bufsize,
7865
                                                s, chunk_size,
7866
                                                errors, final);
7867
        assert(converted != 0 || done);
7868
7869
        if (converted < 0) {
7870
            PyMem_Free(buf);
7871
            return NULL;
7872
        }
7873
7874
        if (consumed)
7875
            *consumed += converted;
7876
7877
        s += converted;
7878
        size -= converted;
7879
    } while (!done);
7880
7881
    PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7882
    PyMem_Free(buf);
7883
    return v;
7884
}
7885
7886
PyObject *
7887
PyUnicode_DecodeCodePageStateful(int code_page,
7888
                                 const char *s,
7889
                                 Py_ssize_t size,
7890
                                 const char *errors,
7891
                                 Py_ssize_t *consumed)
7892
{
7893
    return decode_code_page_stateful(code_page, s, size, errors, consumed);
7894
}
7895
7896
PyObject *
7897
PyUnicode_DecodeMBCSStateful(const char *s,
7898
                             Py_ssize_t size,
7899
                             const char *errors,
7900
                             Py_ssize_t *consumed)
7901
{
7902
    return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7903
}
7904
7905
PyObject *
7906
PyUnicode_DecodeMBCS(const char *s,
7907
                     Py_ssize_t size,
7908
                     const char *errors)
7909
{
7910
    return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7911
}
7912
7913
static DWORD
7914
encode_code_page_flags(UINT code_page, const char *errors)
7915
{
7916
    if (code_page == CP_UTF8) {
7917
        return WC_ERR_INVALID_CHARS;
7918
    }
7919
    else if (code_page == CP_UTF7) {
7920
        /* CP_UTF7 only supports flags=0 */
7921
        return 0;
7922
    }
7923
    else {
7924
        if (errors != NULL && strcmp(errors, "replace") == 0)
7925
            return 0;
7926
        else
7927
            return WC_NO_BEST_FIT_CHARS;
7928
    }
7929
}
7930
7931
/*
7932
 * Encode a Unicode string to a Windows code page into a byte string in strict
7933
 * mode.
7934
 *
7935
 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7936
 * an OSError and returns -1 on other error.
7937
 */
7938
static int
7939
encode_code_page_strict(UINT code_page, PyBytesWriter **writer,
7940
                        PyObject *unicode, Py_ssize_t offset, int len,
7941
                        const char* errors)
7942
{
7943
    BOOL usedDefaultChar = FALSE;
7944
    BOOL *pusedDefaultChar = &usedDefaultChar;
7945
    int outsize;
7946
    wchar_t *p;
7947
    Py_ssize_t size;
7948
    const DWORD flags = encode_code_page_flags(code_page, NULL);
7949
    char *out;
7950
    /* Create a substring so that we can get the UTF-16 representation
7951
       of just the slice under consideration. */
7952
    PyObject *substring;
7953
    int ret = -1;
7954
7955
    assert(len > 0);
7956
7957
    if (code_page != CP_UTF8 && code_page != CP_UTF7)
7958
        pusedDefaultChar = &usedDefaultChar;
7959
    else
7960
        pusedDefaultChar = NULL;
7961
7962
    substring = PyUnicode_Substring(unicode, offset, offset+len);
7963
    if (substring == NULL)
7964
        return -1;
7965
    p = PyUnicode_AsWideCharString(substring, &size);
7966
    Py_CLEAR(substring);
7967
    if (p == NULL) {
7968
        return -1;
7969
    }
7970
    assert(size <= INT_MAX);
7971
7972
    /* First get the size of the result */
7973
    outsize = WideCharToMultiByte(code_page, flags,
7974
                                  p, (int)size,
7975
                                  NULL, 0,
7976
                                  NULL, pusedDefaultChar);
7977
    if (outsize <= 0)
7978
        goto error;
7979
    /* If we used a default char, then we failed! */
7980
    if (pusedDefaultChar && *pusedDefaultChar) {
7981
        ret = -2;
7982
        goto done;
7983
    }
7984
7985
    if (*writer == NULL) {
7986
        /* Create string object */
7987
        *writer = PyBytesWriter_Create(outsize);
7988
        if (*writer == NULL) {
7989
            goto done;
7990
        }
7991
        out = PyBytesWriter_GetData(*writer);
7992
    }
7993
    else {
7994
        /* Extend string object */
7995
        Py_ssize_t n = PyBytesWriter_GetSize(*writer);
7996
        if (PyBytesWriter_Grow(*writer, outsize) < 0) {
7997
            goto done;
7998
        }
7999
        out = (char*)PyBytesWriter_GetData(*writer) + n;
8000
    }
8001
8002
    /* Do the conversion */
8003
    outsize = WideCharToMultiByte(code_page, flags,
8004
                                  p, (int)size,
8005
                                  out, outsize,
8006
                                  NULL, pusedDefaultChar);
8007
    if (outsize <= 0)
8008
        goto error;
8009
    if (pusedDefaultChar && *pusedDefaultChar) {
8010
        ret = -2;
8011
        goto done;
8012
    }
8013
    ret = 0;
8014
8015
done:
8016
    PyMem_Free(p);
8017
    return ret;
8018
8019
error:
8020
    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
8021
        ret = -2;
8022
        goto done;
8023
    }
8024
    PyErr_SetFromWindowsErr(0);
8025
    goto done;
8026
}
8027
8028
/*
8029
 * Encode a Unicode string to a Windows code page into a byte string using an
8030
 * error handler.
8031
 *
8032
 * Returns consumed characters if succeed, or raise an OSError and returns
8033
 * -1 on other error.
8034
 */
8035
static int
8036
encode_code_page_errors(UINT code_page, PyBytesWriter **writer,
8037
                        PyObject *unicode, Py_ssize_t unicode_offset,
8038
                        Py_ssize_t insize, const char* errors)
8039
{
8040
    const DWORD flags = encode_code_page_flags(code_page, errors);
8041
    Py_ssize_t pos = unicode_offset;
8042
    Py_ssize_t endin = unicode_offset + insize;
8043
    /* Ideally, we should get reason from FormatMessage. This is the Windows
8044
       2000 English version of the message. */
8045
    const char *reason = "invalid character";
8046
    /* 4=maximum length of a UTF-8 sequence */
8047
    char buffer[4];
8048
    BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
8049
    Py_ssize_t outsize;
8050
    char *out;
8051
    PyObject *errorHandler = NULL;
8052
    PyObject *exc = NULL;
8053
    PyObject *encoding_obj = NULL;
8054
    const char *encoding;
8055
    Py_ssize_t newpos;
8056
    PyObject *rep;
8057
    int ret = -1;
8058
8059
    assert(insize > 0);
8060
8061
    encoding = code_page_name(code_page, &encoding_obj);
8062
    if (encoding == NULL)
8063
        return -1;
8064
8065
    if (errors == NULL || strcmp(errors, "strict") == 0) {
8066
        /* The last error was ERROR_NO_UNICODE_TRANSLATION,
8067
           then we raise a UnicodeEncodeError. */
8068
        make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
8069
        if (exc != NULL) {
8070
            PyCodec_StrictErrors(exc);
8071
            Py_DECREF(exc);
8072
        }
8073
        Py_XDECREF(encoding_obj);
8074
        return -1;
8075
    }
8076
8077
    if (code_page != CP_UTF8 && code_page != CP_UTF7)
8078
        pusedDefaultChar = &usedDefaultChar;
8079
    else
8080
        pusedDefaultChar = NULL;
8081
8082
    if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
8083
        PyErr_NoMemory();
8084
        goto error;
8085
    }
8086
    outsize = insize * Py_ARRAY_LENGTH(buffer);
8087
8088
    if (*writer == NULL) {
8089
        /* Create string object */
8090
        *writer = PyBytesWriter_Create(outsize);
8091
        if (*writer == NULL) {
8092
            goto error;
8093
        }
8094
        out = PyBytesWriter_GetData(*writer);
8095
    }
8096
    else {
8097
        /* Extend string object */
8098
        Py_ssize_t n = PyBytesWriter_GetSize(*writer);
8099
        if (PyBytesWriter_Grow(*writer, outsize) < 0) {
8100
            goto error;
8101
        }
8102
        out = (char*)PyBytesWriter_GetData(*writer) + n;
8103
    }
8104
8105
    /* Encode the string character per character */
8106
    while (pos < endin)
8107
    {
8108
        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
8109
        wchar_t chars[2];
8110
        int charsize;
8111
        if (ch < 0x10000) {
8112
            chars[0] = (wchar_t)ch;
8113
            charsize = 1;
8114
        }
8115
        else {
8116
            chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
8117
            chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
8118
            charsize = 2;
8119
        }
8120
8121
        outsize = WideCharToMultiByte(code_page, flags,
8122
                                      chars, charsize,
8123
                                      buffer, Py_ARRAY_LENGTH(buffer),
8124
                                      NULL, pusedDefaultChar);
8125
        if (outsize > 0) {
8126
            if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
8127
            {
8128
                pos++;
8129
                memcpy(out, buffer, outsize);
8130
                out += outsize;
8131
                continue;
8132
            }
8133
        }
8134
        else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
8135
            PyErr_SetFromWindowsErr(0);
8136
            goto error;
8137
        }
8138
8139
        rep = unicode_encode_call_errorhandler(
8140
                  errors, &errorHandler, encoding, reason,
8141
                  unicode, &exc,
8142
                  pos, pos + 1, &newpos);
8143
        if (rep == NULL)
8144
            goto error;
8145
8146
        Py_ssize_t morebytes = pos - newpos;
8147
        if (PyBytes_Check(rep)) {
8148
            outsize = PyBytes_GET_SIZE(rep);
8149
            morebytes += outsize;
8150
            if (morebytes > 0) {
8151
                out = PyBytesWriter_GrowAndUpdatePointer(*writer, morebytes, out);
8152
                if (out == NULL) {
8153
                    Py_DECREF(rep);
8154
                    goto error;
8155
                }
8156
            }
8157
            memcpy(out, PyBytes_AS_STRING(rep), outsize);
8158
            out += outsize;
8159
        }
8160
        else {
8161
            Py_ssize_t i;
8162
            int kind;
8163
            const void *data;
8164
8165
            outsize = PyUnicode_GET_LENGTH(rep);
8166
            morebytes += outsize;
8167
            if (morebytes > 0) {
8168
                out = PyBytesWriter_GrowAndUpdatePointer(*writer, morebytes, out);
8169
                if (out == NULL) {
8170
                    Py_DECREF(rep);
8171
                    goto error;
8172
                }
8173
            }
8174
            kind = PyUnicode_KIND(rep);
8175
            data = PyUnicode_DATA(rep);
8176
            for (i=0; i < outsize; i++) {
8177
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8178
                if (ch > 127) {
8179
                    raise_encode_exception(&exc,
8180
                        encoding, unicode,
8181
                        pos, pos + 1,
8182
                        "unable to encode error handler result to ASCII");
8183
                    Py_DECREF(rep);
8184
                    goto error;
8185
                }
8186
                *out = (unsigned char)ch;
8187
                out++;
8188
            }
8189
        }
8190
        pos = newpos;
8191
        Py_DECREF(rep);
8192
    }
8193
    /* write a NUL byte */
8194
    *out = 0;
8195
    outsize = out - (char*)PyBytesWriter_GetData(*writer);
8196
    assert(outsize <= PyBytesWriter_GetSize(*writer));
8197
    if (PyBytesWriter_Resize(*writer, outsize) < 0) {
8198
        goto error;
8199
    }
8200
    ret = 0;
8201
8202
error:
8203
    Py_XDECREF(encoding_obj);
8204
    Py_XDECREF(errorHandler);
8205
    Py_XDECREF(exc);
8206
    return ret;
8207
}
8208
8209
8210
PyObject *
8211
PyUnicode_EncodeCodePage(int code_page,
8212
                         PyObject *unicode,
8213
                         const char *errors)
8214
{
8215
    Py_ssize_t len;
8216
    PyBytesWriter *writer = NULL;
8217
    Py_ssize_t offset;
8218
    int chunk_len, ret, done;
8219
8220
    if (!PyUnicode_Check(unicode)) {
8221
        PyErr_BadArgument();
8222
        return NULL;
8223
    }
8224
8225
    len = PyUnicode_GET_LENGTH(unicode);
8226
8227
    if (code_page < 0) {
8228
        PyErr_SetString(PyExc_ValueError, "invalid code page number");
8229
        return NULL;
8230
    }
8231
8232
    if (len == 0)
8233
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
8234
8235
    offset = 0;
8236
    do
8237
    {
8238
#ifdef NEED_RETRY
8239
        if (len > DECODING_CHUNK_SIZE) {
8240
            chunk_len = DECODING_CHUNK_SIZE;
8241
            done = 0;
8242
        }
8243
        else
8244
#endif
8245
        {
8246
            chunk_len = (int)len;
8247
            done = 1;
8248
        }
8249
8250
        ret = encode_code_page_strict(code_page, &writer,
8251
                                      unicode, offset, chunk_len,
8252
                                      errors);
8253
        if (ret == -2)
8254
            ret = encode_code_page_errors(code_page, &writer,
8255
                                          unicode, offset,
8256
                                          chunk_len, errors);
8257
        if (ret < 0) {
8258
            PyBytesWriter_Discard(writer);
8259
            return NULL;
8260
        }
8261
8262
        offset += chunk_len;
8263
        len -= chunk_len;
8264
    } while (!done);
8265
8266
    return PyBytesWriter_Finish(writer);
8267
}
8268
8269
8270
PyObject *
8271
PyUnicode_AsMBCSString(PyObject *unicode)
8272
{
8273
    return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
8274
}
8275
8276
#undef NEED_RETRY
8277
8278
#endif /* MS_WINDOWS */
8279
8280
/* --- iconv Codec -------------------------------------------------------- */
8281
8282
#ifdef _Py_HAVE_ICONV
8283
8284
/* iconv pivot: native-endian UTF-32, a raw array of Py_UCS4.  One input unit is
8285
   one code point, so error handlers get the exact position.  A platform whose
8286
   iconv lacks a UTF-32 endpoint (e.g. UTF-8-only OpenBSD) reports every encoding
8287
   as unavailable. */
8288
#if PY_BIG_ENDIAN
8289
#  define ICONV_PIVOT "UTF-32BE"
8290
#else
8291
7.63k
#  define ICONV_PIVOT "UTF-32LE"
8292
#endif
8293
8294
/* A 2-byte string can be fed to iconv as "UCS-2" only where that is a strict
8295
   array of independent code points.  Some implementations alias "UCS-2" to
8296
   "UTF-16" and would combine an adjacent surrogate pair (a 2-byte string may
8297
   hold one as two code points); there the 2-byte kind is widened to UTF-32.
8298
   glibc and GNU libiconv keep UCS-2 and UTF-16 separate. */
8299
#if defined(__GLIBC__) || defined(_LIBICONV_VERSION)
8300
#  if PY_BIG_ENDIAN
8301
#    define ICONV_UCS2_PIVOT "UCS-2BE"
8302
#  else
8303
0
#    define ICONV_UCS2_PIVOT "UCS-2LE"
8304
#  endif
8305
#endif
8306
8307
static iconv_t
8308
iconv_open_or_set_error(const char *tocode, const char *fromcode,
8309
                        const char *encoding)
8310
72.2k
{
8311
72.2k
    iconv_t cd = iconv_open(tocode, fromcode);
8312
72.2k
    if (cd == (iconv_t)-1) {
8313
64.4k
        if (errno == EINVAL) {
8314
64.4k
            PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding);
8315
64.4k
        }
8316
0
        else {
8317
0
            PyErr_SetFromErrno(PyExc_OSError);
8318
0
        }
8319
64.4k
    }
8320
72.2k
    return cd;
8321
72.2k
}
8322
8323
/*
8324
 * Decode bytes with iconv() into a str.
8325
 *
8326
 * The input is converted to native-endian UTF-32 one chunk at a time and
8327
 * appended to a _PyUnicodeWriter.  If *consumed* is non-NULL the decode is
8328
 * stateful: a trailing incomplete sequence stops and sets *consumed*.
8329
 */
8330
PyObject *
8331
_PyUnicode_DecodeIconv(const char *encoding,
8332
                       const char *s, Py_ssize_t size,
8333
                       const char *errors, Py_ssize_t *consumed)
8334
7.63k
{
8335
7.63k
    if (size < 0) {
8336
0
        PyErr_BadInternalCall();
8337
0
        return NULL;
8338
0
    }
8339
8340
7.63k
    iconv_t cd = iconv_open_or_set_error(ICONV_PIVOT, encoding, encoding);
8341
7.63k
    if (cd == (iconv_t)-1) {
8342
0
        return NULL;
8343
0
    }
8344
8345
    /* Scratch buffer for one iconv() output chunk, as UTF-32 code points. */
8346
7.63k
    Py_UCS4 chunk[1024];
8347
7.63k
    const char *starts = s;
8348
7.63k
    const char *in = s;
8349
7.63k
    const char *inend = s + size;
8350
7.63k
    _PyUnicodeWriter writer;
8351
7.63k
    PyObject *errorHandler = NULL;
8352
7.63k
    PyObject *exc = NULL;
8353
8354
7.63k
    _PyUnicodeWriter_Init(&writer);
8355
7.63k
    writer.min_length = size;
8356
8357
66.6k
    while (in < inend) {
8358
64.9k
        char *inptr = (char *)in;
8359
64.9k
        size_t inleft = (size_t)(inend - in);
8360
64.9k
        char *outptr = (char *)chunk;
8361
64.9k
        size_t outleft = sizeof(chunk);
8362
8363
        /* Cast the input buffer through void*: iconv() declares its second
8364
           argument as "char **" on most systems but "const char **" on some
8365
           (e.g. illumos), and void* converts to either without a warning. */
8366
64.9k
        size_t ret = iconv(cd, (void *)&inptr, &inleft, &outptr, &outleft);
8367
64.9k
        int err = errno;
8368
64.9k
        in = inptr;
8369
8370
        /* Append whatever code points this call produced. */
8371
64.9k
        Py_ssize_t nch = (Py_UCS4 *)outptr - chunk;
8372
64.9k
        if (nch > 0 && PyUnicodeWriter_WriteUCS4((PyUnicodeWriter *)&writer,
8373
21.7k
                                                 chunk, nch) < 0) {
8374
0
            goto error;
8375
0
        }
8376
8377
64.9k
        if (ret != (size_t)-1) {
8378
4.71k
            assert(in == inend);
8379
4.71k
            break;
8380
4.71k
        }
8381
8382
60.2k
        if (err == E2BIG) {
8383
            /* The scratch buffer filled up; drain it and continue. */
8384
798
            continue;
8385
798
        }
8386
8387
59.4k
        const char *reason;
8388
59.4k
        if (err == EINVAL) {
8389
            /* Incomplete multibyte sequence at the end of the input. */
8390
17
            if (consumed != NULL) {
8391
                /* Stateful decoding: stop and report the consumed bytes. */
8392
0
                break;
8393
0
            }
8394
17
            reason = "incomplete multibyte sequence";
8395
17
        }
8396
59.4k
        else if (err == EILSEQ) {
8397
59.4k
            reason = "invalid multibyte sequence";
8398
59.4k
        }
8399
0
        else {
8400
0
            errno = err;
8401
0
            PyErr_SetFromErrno(PyExc_OSError);
8402
0
            goto error;
8403
0
        }
8404
8405
59.4k
        Py_ssize_t startinpos = in - starts;
8406
59.4k
        Py_ssize_t endinpos = startinpos + 1;
8407
59.4k
        if (unicode_decode_call_errorhandler_writer(
8408
59.4k
                errors, &errorHandler, encoding, reason,
8409
59.4k
                &starts, &inend, &startinpos, &endinpos, &exc, &in,
8410
59.4k
                &writer)) {
8411
1.23k
            goto error;
8412
1.23k
        }
8413
        /* The error handler may have skipped bytes; reset the conversion
8414
           descriptor to the initial shift state before continuing. */
8415
58.2k
        iconv(cd, NULL, NULL, NULL, NULL);
8416
58.2k
    }
8417
8418
6.40k
    if (consumed != NULL) {
8419
0
        *consumed = in - starts;
8420
0
    }
8421
6.40k
    iconv_close(cd);
8422
6.40k
    Py_XDECREF(errorHandler);
8423
6.40k
    Py_XDECREF(exc);
8424
6.40k
    return _PyUnicodeWriter_Finish(&writer);
8425
8426
1.23k
error:
8427
1.23k
    iconv_close(cd);
8428
1.23k
    _PyUnicodeWriter_Dealloc(&writer);
8429
1.23k
    Py_XDECREF(errorHandler);
8430
1.23k
    Py_XDECREF(exc);
8431
1.23k
    return NULL;
8432
7.63k
}
8433
8434
/* Grow the output buffer of a PyBytesWriter, keeping the raw cursor *pout and
8435
   the end pointer *poutend valid.  Returns 0 on success, -1 on error. */
8436
static int
8437
iconv_grow_writer(PyBytesWriter *writer, char **pout, char **poutend)
8438
0
{
8439
0
    char *base = PyBytesWriter_GetData(writer);
8440
0
    Py_ssize_t used = *pout - base;
8441
0
    Py_ssize_t cursize = PyBytesWriter_GetSize(writer);
8442
0
    Py_ssize_t growby = cursize > 0 ? cursize : 16;
8443
0
    if (PyBytesWriter_Grow(writer, growby) < 0) {
8444
0
        return -1;
8445
0
    }
8446
0
    base = PyBytesWriter_GetData(writer);
8447
0
    *pout = base + used;
8448
0
    *poutend = base + PyBytesWriter_GetSize(writer);
8449
0
    return 0;
8450
0
}
8451
8452
/*
8453
 * Encode a str to bytes with iconv().
8454
 *
8455
 * The string's own buffer is fed to iconv() using the source encoding for its
8456
 * kind, avoiding a widening copy: Latin-1 for 1-byte (not ASCII: it may hold
8457
 * U+0080..U+00FF), UTF-32 for 4-byte, and UCS-2 -- or a UTF-32 copy where that
8458
 * is unsafe (see ICONV_UCS2_PIVOT) -- for 2-byte.  One input unit is one code
8459
 * point, so the unit index is the string position.
8460
 */
8461
PyObject *
8462
_PyUnicode_EncodeIconv(const char *encoding, PyObject *unicode,
8463
                       const char *errors)
8464
64.6k
{
8465
64.6k
    if (!PyUnicode_Check(unicode)) {
8466
0
        PyErr_BadArgument();
8467
0
        return NULL;
8468
0
    }
8469
8470
64.6k
    Py_ssize_t ulen = PyUnicode_GET_LENGTH(unicode);
8471
64.6k
    const char *source;         /* iconv source encoding for this kind */
8472
64.6k
    const char *data;           /* the units to encode */
8473
64.6k
    Py_ssize_t unit;            /* bytes per code point in *data */
8474
64.6k
    Py_UCS4 *widened = NULL;    /* owned UTF-32 copy of a 2-byte string */
8475
64.6k
    int kind = PyUnicode_KIND(unicode);
8476
64.6k
    if (kind == PyUnicode_1BYTE_KIND) {
8477
64.6k
        source = "ISO-8859-1";
8478
64.6k
        data = (const char *)PyUnicode_1BYTE_DATA(unicode);
8479
64.6k
        unit = 1;
8480
64.6k
    }
8481
0
    else if (kind == PyUnicode_4BYTE_KIND) {
8482
0
        source = ICONV_PIVOT;
8483
0
        data = (const char *)PyUnicode_4BYTE_DATA(unicode);
8484
0
        unit = 4;
8485
0
    }
8486
0
    else {
8487
0
#ifdef ICONV_UCS2_PIVOT
8488
        /* Known-strict UCS-2: feed the 2-byte buffer directly. */
8489
0
        source = ICONV_UCS2_PIVOT;
8490
0
        data = (const char *)PyUnicode_2BYTE_DATA(unicode);
8491
0
        unit = 2;
8492
#else
8493
        /* UCS-2 may be aliased to UTF-16 here; widen to UTF-32 to be safe. */
8494
        widened = PyUnicode_AsUCS4Copy(unicode);
8495
        if (widened == NULL) {
8496
            return NULL;
8497
        }
8498
        source = ICONV_PIVOT;
8499
        data = (const char *)widened;
8500
        unit = 4;
8501
#endif
8502
0
    }
8503
8504
64.6k
    iconv_t cd = iconv_open_or_set_error(encoding, source, encoding);
8505
64.6k
    if (cd == (iconv_t)-1) {
8506
64.4k
        PyMem_Free(widened);
8507
64.4k
        return NULL;
8508
64.4k
    }
8509
8510
229
    PyBytesWriter *writer = NULL;
8511
229
    PyObject *errorHandler = NULL;
8512
229
    PyObject *exc = NULL;
8513
229
    PyObject *result = NULL;
8514
229
    const char *ustart = data;
8515
229
    const char *up = data;
8516
229
    const char *uend = data + (size_t)ulen * unit;
8517
229
    int flushing = 0;
8518
229
    int careful = 0;            /* feed one code point per iconv() call */
8519
8520
    /* A generous initial estimate for the output size. */
8521
229
    writer = PyBytesWriter_Create(ulen + (ulen >> 1) + 16);
8522
229
    if (writer == NULL) {
8523
0
        goto done;
8524
0
    }
8525
229
    char *out = PyBytesWriter_GetData(writer);
8526
229
    char *outend = out + PyBytesWriter_GetSize(writer);
8527
8528
458
    for (;;) {
8529
458
        char *inptr = (char *)up;
8530
458
        size_t inleft = (size_t)(uend - up);
8531
        /* One code point at a time, to pin a substitution to its position. */
8532
458
        if (careful && inleft > (size_t)unit) {
8533
0
            inleft = (size_t)unit;
8534
0
        }
8535
458
        char *out_before = out;
8536
458
        size_t outleft = (size_t)(outend - out);
8537
        /* When the whole string is converted, a final iconv() call with a
8538
           NULL input flushes any pending shift sequence (e.g. ISO-2022). */
8539
        /* See the note above on the void* cast of the iconv() input buffer. */
8540
458
        size_t ret = iconv(cd, flushing ? NULL : (void *)&inptr, &inleft, &out, &outleft);
8541
458
        if (!flushing) {
8542
229
            up = inptr;
8543
229
        }
8544
8545
458
        if (ret != (size_t)-1) {
8546
458
            if (flushing) {
8547
229
                break;
8548
229
            }
8549
            /* A positive result counts nonreversible conversions: iconv()
8550
               substituted an unencodable character instead of failing with
8551
               EILSEQ (musl and *BSD citrus do this).  Treat it as unencodable
8552
               and re-run one code point at a time to locate it. */
8553
229
            if (ret > 0) {
8554
0
                if (!careful) {
8555
0
                    careful = 1;
8556
0
                    iconv(cd, NULL, NULL, NULL, NULL);
8557
0
                    out = PyBytesWriter_GetData(writer);
8558
0
                    outend = out + PyBytesWriter_GetSize(writer);
8559
0
                    up = ustart;
8560
0
                    continue;
8561
0
                }
8562
                /* This code point was substituted; drop it and report it. */
8563
0
                out = out_before;
8564
0
                up -= unit;
8565
0
            }
8566
229
            else if (careful && up < uend) {
8567
0
                continue;
8568
0
            }
8569
229
            else {
8570
                /* All input consumed; switch to flushing the shift state. */
8571
229
                flushing = 1;
8572
229
                continue;
8573
229
            }
8574
229
        }
8575
0
        else if (errno == E2BIG) {
8576
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8577
0
                goto done;
8578
0
            }
8579
0
            continue;
8580
0
        }
8581
0
        else if (errno != EILSEQ && errno != EINVAL) {
8582
0
            PyErr_SetFromErrno(PyExc_OSError);
8583
0
            goto done;
8584
0
        }
8585
8586
        /* An unencodable code point at *up; one input unit is one code point. */
8587
0
        Py_ssize_t pos = (up - ustart) / unit;
8588
0
        Py_ssize_t newpos;
8589
0
        PyObject *rep = unicode_encode_call_errorhandler(
8590
0
                errors, &errorHandler, encoding, "invalid character",
8591
0
                unicode, &exc, pos, pos + 1, &newpos);
8592
0
        if (rep == NULL) {
8593
0
            goto done;
8594
0
        }
8595
8596
0
        const char *repdata;
8597
0
        Py_ssize_t replen;
8598
0
        PyObject *repbytes = NULL;
8599
0
        if (PyBytes_Check(rep)) {
8600
0
            repdata = PyBytes_AS_STRING(rep);
8601
0
            replen = PyBytes_GET_SIZE(rep);
8602
0
        }
8603
0
        else {
8604
            /* A str replacement is encoded through the same codec, but
8605
               strictly: handling its errors in turn could never terminate. */
8606
0
            assert(PyUnicode_Check(rep));
8607
0
            repbytes = _PyUnicode_EncodeIconv(encoding, rep, NULL);
8608
0
            Py_DECREF(rep);
8609
0
            if (repbytes == NULL) {
8610
0
                if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
8611
                    /* Report the input the caller knows about, not the
8612
                       replacement. */
8613
0
                    PyErr_Clear();
8614
0
                    raise_encode_exception(&exc, encoding, unicode, pos, pos + 1,
8615
0
                            "unable to encode error handler result");
8616
0
                }
8617
0
                goto done;
8618
0
            }
8619
0
            repdata = PyBytes_AS_STRING(repbytes);
8620
0
            replen = PyBytes_GET_SIZE(repbytes);
8621
0
        }
8622
8623
0
        while (outend - out < replen) {
8624
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8625
0
                if (repbytes != NULL) {
8626
0
                    Py_DECREF(repbytes);
8627
0
                }
8628
0
                else {
8629
0
                    Py_DECREF(rep);
8630
0
                }
8631
0
                goto done;
8632
0
            }
8633
0
        }
8634
0
        memcpy(out, repdata, replen);
8635
0
        out += replen;
8636
0
        if (repbytes != NULL) {
8637
0
            Py_DECREF(repbytes);
8638
0
        }
8639
0
        else {
8640
0
            Py_DECREF(rep);
8641
0
        }
8642
0
        up = ustart + (size_t)newpos * unit;
8643
        /* Reset the shift state after the injected replacement bytes. */
8644
0
        iconv(cd, NULL, NULL, NULL, NULL);
8645
0
    }
8646
8647
229
    result = PyBytesWriter_FinishWithPointer(writer, out);
8648
229
    writer = NULL;
8649
8650
229
done:
8651
229
    if (writer != NULL) {
8652
0
        PyBytesWriter_Discard(writer);
8653
0
    }
8654
229
    iconv_close(cd);
8655
229
    PyMem_Free(widened);
8656
229
    Py_XDECREF(errorHandler);
8657
229
    Py_XDECREF(exc);
8658
229
    return result;
8659
229
}
8660
8661
#endif /* _Py_HAVE_ICONV */
8662
8663
/* --- Character Mapping Codec -------------------------------------------- */
8664
8665
static int
8666
charmap_decode_string(const char *s,
8667
                      Py_ssize_t size,
8668
                      PyObject *mapping,
8669
                      const char *errors,
8670
                      _PyUnicodeWriter *writer)
8671
537k
{
8672
537k
    const char *starts = s;
8673
537k
    const char *e;
8674
537k
    Py_ssize_t startinpos, endinpos;
8675
537k
    PyObject *errorHandler = NULL, *exc = NULL;
8676
537k
    Py_ssize_t maplen;
8677
537k
    int mapkind;
8678
537k
    const void *mapdata;
8679
537k
    Py_UCS4 x;
8680
537k
    unsigned char ch;
8681
8682
537k
    maplen = PyUnicode_GET_LENGTH(mapping);
8683
537k
    mapdata = PyUnicode_DATA(mapping);
8684
537k
    mapkind = PyUnicode_KIND(mapping);
8685
8686
537k
    e = s + size;
8687
8688
537k
    if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
8689
        /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
8690
         * is disabled in encoding aliases, latin1 is preferred because
8691
         * its implementation is faster. */
8692
116
        const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
8693
116
        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8694
116
        Py_UCS4 maxchar = writer->maxchar;
8695
8696
116
        assert (writer->kind == PyUnicode_1BYTE_KIND);
8697
138k
        while (s < e) {
8698
137k
            ch = *s;
8699
137k
            x = mapdata_ucs1[ch];
8700
137k
            if (x > maxchar) {
8701
108
                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8702
0
                    goto onError;
8703
108
                maxchar = writer->maxchar;
8704
108
                outdata = (Py_UCS1 *)writer->data;
8705
108
            }
8706
137k
            outdata[writer->pos] = x;
8707
137k
            writer->pos++;
8708
137k
            ++s;
8709
137k
        }
8710
116
        return 0;
8711
116
    }
8712
8713
645k
    while (s < e) {
8714
630k
        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8715
630k
            int outkind = writer->kind;
8716
630k
            const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
8717
630k
            if (outkind == PyUnicode_1BYTE_KIND) {
8718
569k
                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8719
569k
                Py_UCS4 maxchar = writer->maxchar;
8720
11.2M
                while (s < e) {
8721
10.7M
                    ch = *s;
8722
10.7M
                    x = mapdata_ucs2[ch];
8723
10.7M
                    if (x > maxchar)
8724
71.2k
                        goto Error;
8725
10.6M
                    outdata[writer->pos] = x;
8726
10.6M
                    writer->pos++;
8727
10.6M
                    ++s;
8728
10.6M
                }
8729
498k
                break;
8730
569k
            }
8731
60.0k
            else if (outkind == PyUnicode_2BYTE_KIND) {
8732
60.0k
                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8733
16.3M
                while (s < e) {
8734
16.3M
                    ch = *s;
8735
16.3M
                    x = mapdata_ucs2[ch];
8736
16.3M
                    if (x == 0xFFFE)
8737
37.0k
                        goto Error;
8738
16.2M
                    outdata[writer->pos] = x;
8739
16.2M
                    writer->pos++;
8740
16.2M
                    ++s;
8741
16.2M
                }
8742
23.0k
                break;
8743
60.0k
            }
8744
630k
        }
8745
0
        ch = *s;
8746
8747
0
        if (ch < maplen)
8748
0
            x = PyUnicode_READ(mapkind, mapdata, ch);
8749
0
        else
8750
0
            x = 0xfffe; /* invalid value */
8751
108k
Error:
8752
108k
        if (x == 0xfffe)
8753
55.7k
        {
8754
            /* undefined mapping */
8755
55.7k
            startinpos = s-starts;
8756
55.7k
            endinpos = startinpos+1;
8757
55.7k
            if (unicode_decode_call_errorhandler_writer(
8758
55.7k
                    errors, &errorHandler,
8759
55.7k
                    "charmap", "character maps to <undefined>",
8760
55.7k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
8761
55.7k
                    writer)) {
8762
22
                goto onError;
8763
22
            }
8764
55.7k
            continue;
8765
55.7k
        }
8766
8767
52.5k
        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8768
0
            goto onError;
8769
52.5k
        ++s;
8770
52.5k
    }
8771
537k
    Py_XDECREF(errorHandler);
8772
537k
    Py_XDECREF(exc);
8773
537k
    return 0;
8774
8775
22
onError:
8776
22
    Py_XDECREF(errorHandler);
8777
22
    Py_XDECREF(exc);
8778
22
    return -1;
8779
537k
}
8780
8781
static int
8782
charmap_decode_mapping(const char *s,
8783
                       Py_ssize_t size,
8784
                       PyObject *mapping,
8785
                       const char *errors,
8786
                       _PyUnicodeWriter *writer)
8787
0
{
8788
0
    const char *starts = s;
8789
0
    const char *e;
8790
0
    Py_ssize_t startinpos, endinpos;
8791
0
    PyObject *errorHandler = NULL, *exc = NULL;
8792
0
    unsigned char ch;
8793
0
    PyObject *key, *item = NULL;
8794
8795
0
    e = s + size;
8796
8797
0
    while (s < e) {
8798
0
        ch = *s;
8799
8800
        /* Get mapping (char ordinal -> integer, Unicode char or None) */
8801
0
        key = PyLong_FromLong((long)ch);
8802
0
        if (key == NULL)
8803
0
            goto onError;
8804
8805
0
        int rc = PyMapping_GetOptionalItem(mapping, key, &item);
8806
0
        Py_DECREF(key);
8807
0
        if (rc == 0) {
8808
            /* No mapping found means: mapping is undefined. */
8809
0
            goto Undefined;
8810
0
        }
8811
0
        if (item == NULL) {
8812
0
            if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8813
                /* No mapping found means: mapping is undefined. */
8814
0
                PyErr_Clear();
8815
0
                goto Undefined;
8816
0
            } else
8817
0
                goto onError;
8818
0
        }
8819
8820
        /* Apply mapping */
8821
0
        if (item == Py_None)
8822
0
            goto Undefined;
8823
0
        if (PyLong_Check(item)) {
8824
0
            long value = PyLong_AsLong(item);
8825
0
            if (value == 0xFFFE)
8826
0
                goto Undefined;
8827
0
            if (value < 0 || value > MAX_UNICODE) {
8828
0
                PyErr_Format(PyExc_TypeError,
8829
0
                             "character mapping must be in range(0x%lx)",
8830
0
                             (unsigned long)MAX_UNICODE + 1);
8831
0
                goto onError;
8832
0
            }
8833
8834
0
            if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8835
0
                goto onError;
8836
0
        }
8837
0
        else if (PyUnicode_Check(item)) {
8838
0
            if (PyUnicode_GET_LENGTH(item) == 1) {
8839
0
                Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8840
0
                if (value == 0xFFFE)
8841
0
                    goto Undefined;
8842
0
                if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8843
0
                    goto onError;
8844
0
            }
8845
0
            else {
8846
0
                writer->overallocate = 1;
8847
0
                if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8848
0
                    goto onError;
8849
0
            }
8850
0
        }
8851
0
        else {
8852
            /* wrong return value */
8853
0
            PyErr_SetString(PyExc_TypeError,
8854
0
                            "character mapping must return integer, None or str");
8855
0
            goto onError;
8856
0
        }
8857
0
        Py_CLEAR(item);
8858
0
        ++s;
8859
0
        continue;
8860
8861
0
Undefined:
8862
        /* undefined mapping */
8863
0
        Py_CLEAR(item);
8864
0
        startinpos = s-starts;
8865
0
        endinpos = startinpos+1;
8866
0
        if (unicode_decode_call_errorhandler_writer(
8867
0
                errors, &errorHandler,
8868
0
                "charmap", "character maps to <undefined>",
8869
0
                &starts, &e, &startinpos, &endinpos, &exc, &s,
8870
0
                writer)) {
8871
0
            goto onError;
8872
0
        }
8873
0
    }
8874
0
    Py_XDECREF(errorHandler);
8875
0
    Py_XDECREF(exc);
8876
0
    return 0;
8877
8878
0
onError:
8879
0
    Py_XDECREF(item);
8880
0
    Py_XDECREF(errorHandler);
8881
0
    Py_XDECREF(exc);
8882
0
    return -1;
8883
0
}
8884
8885
PyObject *
8886
PyUnicode_DecodeCharmap(const char *s,
8887
                        Py_ssize_t size,
8888
                        PyObject *mapping,
8889
                        const char *errors)
8890
537k
{
8891
537k
    _PyUnicodeWriter writer;
8892
8893
    /* Default to Latin-1 */
8894
537k
    if (mapping == NULL)
8895
20
        return PyUnicode_DecodeLatin1(s, size, errors);
8896
8897
537k
    if (size == 0)
8898
0
        _Py_RETURN_UNICODE_EMPTY();
8899
537k
    _PyUnicodeWriter_Init(&writer);
8900
537k
    writer.min_length = size;
8901
537k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
8902
0
        goto onError;
8903
8904
537k
    if (PyUnicode_CheckExact(mapping)) {
8905
537k
        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8906
22
            goto onError;
8907
537k
    }
8908
0
    else {
8909
0
        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8910
0
            goto onError;
8911
0
    }
8912
537k
    return _PyUnicodeWriter_Finish(&writer);
8913
8914
22
  onError:
8915
22
    _PyUnicodeWriter_Dealloc(&writer);
8916
22
    return NULL;
8917
537k
}
8918
8919
/* Charmap encoding: the lookup table */
8920
8921
/*[clinic input]
8922
class EncodingMap "struct encoding_map *" "&EncodingMapType"
8923
[clinic start generated code]*/
8924
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=14e46bbb6c522d22]*/
8925
8926
struct encoding_map {
8927
    PyObject_HEAD
8928
    unsigned char level1[32];
8929
    int count2, count3;
8930
    unsigned char level23[1];
8931
};
8932
8933
/*[clinic input]
8934
EncodingMap.size
8935
8936
Return the size (in bytes) of this object.
8937
[clinic start generated code]*/
8938
8939
static PyObject *
8940
EncodingMap_size_impl(struct encoding_map *self)
8941
/*[clinic end generated code: output=c4c969e4c99342a4 input=004ff13f26bb5366]*/
8942
0
{
8943
0
    return PyLong_FromLong((sizeof(*self) - 1) + 16*self->count2 +
8944
0
                           128*self->count3);
8945
0
}
8946
8947
static PyMethodDef encoding_map_methods[] = {
8948
    ENCODINGMAP_SIZE_METHODDEF
8949
    {NULL, NULL}
8950
};
8951
8952
static PyTypeObject EncodingMapType = {
8953
    PyVarObject_HEAD_INIT(NULL, 0)
8954
    .tp_name = "EncodingMap",
8955
    .tp_basicsize = sizeof(struct encoding_map),
8956
    /* methods */
8957
    .tp_flags = Py_TPFLAGS_DEFAULT,
8958
    .tp_methods = encoding_map_methods,
8959
};
8960
8961
PyObject*
8962
PyUnicode_BuildEncodingMap(PyObject* string)
8963
136
{
8964
136
    PyObject *result;
8965
136
    struct encoding_map *mresult;
8966
136
    int i;
8967
136
    int need_dict = 0;
8968
136
    unsigned char level1[32];
8969
136
    unsigned char level2[512];
8970
136
    unsigned char *mlevel1, *mlevel2, *mlevel3;
8971
136
    int count2 = 0, count3 = 0;
8972
136
    int kind;
8973
136
    const void *data;
8974
136
    int length;
8975
136
    Py_UCS4 ch;
8976
8977
136
    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
8978
0
        PyErr_BadArgument();
8979
0
        return NULL;
8980
0
    }
8981
136
    kind = PyUnicode_KIND(string);
8982
136
    data = PyUnicode_DATA(string);
8983
136
    length = (int)Py_MIN(PyUnicode_GET_LENGTH(string), 256);
8984
136
    memset(level1, 0xFF, sizeof level1);
8985
136
    memset(level2, 0xFF, sizeof level2);
8986
8987
    /* If there isn't a one-to-one mapping of NULL to \0,
8988
       or if there are non-BMP characters, we need to use
8989
       a mapping dictionary. */
8990
136
    if (PyUnicode_READ(kind, data, 0) != 0)
8991
0
        need_dict = 1;
8992
34.8k
    for (i = 1; i < length; i++) {
8993
34.6k
        int l1, l2;
8994
34.6k
        ch = PyUnicode_READ(kind, data, i);
8995
34.6k
        if (ch == 0 || ch > 0xFFFF) {
8996
0
            need_dict = 1;
8997
0
            break;
8998
0
        }
8999
34.6k
        if (ch == 0xFFFE)
9000
            /* unmapped character */
9001
915
            continue;
9002
33.7k
        l1 = ch >> 11;
9003
33.7k
        l2 = ch >> 7;
9004
33.7k
        if (level1[l1] == 0xFF)
9005
248
            level1[l1] = count2++;
9006
33.7k
        if (level2[l2] == 0xFF)
9007
728
            level2[l2] = count3++;
9008
33.7k
    }
9009
9010
136
    if (count2 >= 0xFF || count3 >= 0xFF)
9011
0
        need_dict = 1;
9012
9013
136
    if (need_dict) {
9014
0
        PyObject *result = PyDict_New();
9015
0
        if (!result)
9016
0
            return NULL;
9017
0
        for (i = 0; i < length; i++) {
9018
0
            Py_UCS4 c = PyUnicode_READ(kind, data, i);
9019
0
            PyObject *key = PyLong_FromLong(c);
9020
0
            if (key == NULL) {
9021
0
                Py_DECREF(result);
9022
0
                return NULL;
9023
0
            }
9024
0
            PyObject *value = PyLong_FromLong(i);
9025
0
            if (value == NULL) {
9026
0
                Py_DECREF(key);
9027
0
                Py_DECREF(result);
9028
0
                return NULL;
9029
0
            }
9030
0
            int rc = PyDict_SetItem(result, key, value);
9031
0
            Py_DECREF(key);
9032
0
            Py_DECREF(value);
9033
0
            if (rc < 0) {
9034
0
                Py_DECREF(result);
9035
0
                return NULL;
9036
0
            }
9037
0
        }
9038
0
        return result;
9039
0
    }
9040
9041
    /* Create a three-level trie */
9042
136
    result = PyObject_Malloc(sizeof(struct encoding_map) +
9043
136
                             16*count2 + 128*count3 - 1);
9044
136
    if (!result) {
9045
0
        return PyErr_NoMemory();
9046
0
    }
9047
9048
136
    _PyObject_Init(result, &EncodingMapType);
9049
136
    mresult = (struct encoding_map*)result;
9050
136
    mresult->count2 = count2;
9051
136
    mresult->count3 = count3;
9052
136
    mlevel1 = mresult->level1;
9053
136
    mlevel2 = mresult->level23;
9054
136
    mlevel3 = mresult->level23 + 16*count2;
9055
136
    memcpy(mlevel1, level1, 32);
9056
136
    memset(mlevel2, 0xFF, 16*count2);
9057
136
    memset(mlevel3, 0, 128*count3);
9058
136
    count3 = 0;
9059
34.8k
    for (i = 1; i < length; i++) {
9060
34.6k
        int o1, o2, o3, i2, i3;
9061
34.6k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9062
34.6k
        if (ch == 0xFFFE)
9063
            /* unmapped character */
9064
915
            continue;
9065
33.7k
        o1 = ch>>11;
9066
33.7k
        o2 = (ch>>7) & 0xF;
9067
33.7k
        i2 = 16*mlevel1[o1] + o2;
9068
33.7k
        if (mlevel2[i2] == 0xFF)
9069
728
            mlevel2[i2] = count3++;
9070
33.7k
        o3 = ch & 0x7F;
9071
33.7k
        i3 = 128*mlevel2[i2] + o3;
9072
33.7k
        mlevel3[i3] = i;
9073
33.7k
    }
9074
136
    return result;
9075
136
}
9076
9077
static int
9078
encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
9079
0
{
9080
0
    struct encoding_map *map = (struct encoding_map*)mapping;
9081
0
    int l1 = c>>11;
9082
0
    int l2 = (c>>7) & 0xF;
9083
0
    int l3 = c & 0x7F;
9084
0
    int i;
9085
9086
0
    if (c > 0xFFFF)
9087
0
        return -1;
9088
0
    if (c == 0)
9089
0
        return 0;
9090
    /* level 1*/
9091
0
    i = map->level1[l1];
9092
0
    if (i == 0xFF) {
9093
0
        return -1;
9094
0
    }
9095
    /* level 2*/
9096
0
    i = map->level23[16*i+l2];
9097
0
    if (i == 0xFF) {
9098
0
        return -1;
9099
0
    }
9100
    /* level 3 */
9101
0
    i = map->level23[16*map->count2 + 128*i + l3];
9102
0
    if (i == 0) {
9103
0
        return -1;
9104
0
    }
9105
0
    return i;
9106
0
}
9107
9108
/* Lookup the character in the mapping.
9109
   On success, return PyLong, PyBytes or None (if the character can't be found).
9110
   If the result is PyLong, put its value in replace.
9111
   On error, return NULL.
9112
   */
9113
static PyObject *
9114
charmapencode_lookup(Py_UCS4 c, PyObject *mapping, unsigned char *replace)
9115
0
{
9116
0
    PyObject *w = PyLong_FromLong((long)c);
9117
0
    PyObject *x;
9118
9119
0
    if (w == NULL)
9120
0
        return NULL;
9121
0
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9122
0
    Py_DECREF(w);
9123
0
    if (rc == 0) {
9124
        /* No mapping found means: mapping is undefined. */
9125
0
        Py_RETURN_NONE;
9126
0
    }
9127
0
    if (x == NULL) {
9128
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9129
            /* No mapping found means: mapping is undefined. */
9130
0
            PyErr_Clear();
9131
0
            Py_RETURN_NONE;
9132
0
        } else
9133
0
            return NULL;
9134
0
    }
9135
0
    else if (x == Py_None)
9136
0
        return x;
9137
0
    else if (PyLong_Check(x)) {
9138
0
        long value = PyLong_AsLong(x);
9139
0
        if (value < 0 || value > 255) {
9140
0
            PyErr_SetString(PyExc_TypeError,
9141
0
                            "character mapping must be in range(256)");
9142
0
            Py_DECREF(x);
9143
0
            return NULL;
9144
0
        }
9145
0
        *replace = (unsigned char)value;
9146
0
        return x;
9147
0
    }
9148
0
    else if (PyBytes_Check(x))
9149
0
        return x;
9150
0
    else {
9151
        /* wrong return value */
9152
0
        PyErr_Format(PyExc_TypeError,
9153
0
                     "character mapping must return integer, bytes or None, not %.400s",
9154
0
                     Py_TYPE(x)->tp_name);
9155
0
        Py_DECREF(x);
9156
0
        return NULL;
9157
0
    }
9158
0
}
9159
9160
static int
9161
charmapencode_resize(PyBytesWriter *writer, Py_ssize_t *outpos, Py_ssize_t requiredsize)
9162
0
{
9163
0
    Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9164
    /* exponentially overallocate to minimize reallocations */
9165
0
    if (requiredsize < 2 * outsize)
9166
0
        requiredsize = 2 * outsize;
9167
0
    return PyBytesWriter_Resize(writer, requiredsize);
9168
0
}
9169
9170
typedef enum charmapencode_result {
9171
    enc_SUCCESS, enc_FAILED, enc_EXCEPTION
9172
} charmapencode_result;
9173
/* lookup the character, put the result in the output string and adjust
9174
   various state variables. Resize the output bytes object if not enough
9175
   space is available. Return a new reference to the object that
9176
   was put in the output buffer, or Py_None, if the mapping was undefined
9177
   (in which case no character was written) or NULL, if a
9178
   reallocation error occurred. The caller must decref the result */
9179
static charmapencode_result
9180
charmapencode_output(Py_UCS4 c, PyObject *mapping,
9181
                     PyBytesWriter *writer, Py_ssize_t *outpos)
9182
0
{
9183
0
    PyObject *rep;
9184
0
    unsigned char replace;
9185
0
    char *outstart;
9186
0
    Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9187
9188
0
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9189
0
        int res = encoding_map_lookup(c, mapping);
9190
0
        Py_ssize_t requiredsize = *outpos+1;
9191
0
        if (res == -1) {
9192
0
            return enc_FAILED;
9193
0
        }
9194
9195
0
        if (outsize<requiredsize) {
9196
0
            if (charmapencode_resize(writer, outpos, requiredsize)) {
9197
0
                return enc_EXCEPTION;
9198
0
            }
9199
0
        }
9200
0
        outstart = _PyBytesWriter_GetData(writer);
9201
0
        outstart[(*outpos)++] = (char)res;
9202
0
        return enc_SUCCESS;
9203
0
    }
9204
9205
0
    rep = charmapencode_lookup(c, mapping, &replace);
9206
0
    if (rep==NULL)
9207
0
        return enc_EXCEPTION;
9208
0
    else if (rep==Py_None) {
9209
0
        Py_DECREF(rep);
9210
0
        return enc_FAILED;
9211
0
    } else {
9212
0
        if (PyLong_Check(rep)) {
9213
0
            Py_ssize_t requiredsize = *outpos+1;
9214
0
            if (outsize<requiredsize)
9215
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9216
0
                    Py_DECREF(rep);
9217
0
                    return enc_EXCEPTION;
9218
0
                }
9219
0
            outstart = _PyBytesWriter_GetData(writer);
9220
0
            outstart[(*outpos)++] = (char)replace;
9221
0
        }
9222
0
        else {
9223
0
            const char *repchars = PyBytes_AS_STRING(rep);
9224
0
            Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
9225
0
            Py_ssize_t requiredsize = *outpos+repsize;
9226
0
            if (outsize<requiredsize)
9227
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9228
0
                    Py_DECREF(rep);
9229
0
                    return enc_EXCEPTION;
9230
0
                }
9231
0
            outstart = _PyBytesWriter_GetData(writer);
9232
0
            memcpy(outstart + *outpos, repchars, repsize);
9233
0
            *outpos += repsize;
9234
0
        }
9235
0
    }
9236
0
    Py_DECREF(rep);
9237
0
    return enc_SUCCESS;
9238
0
}
9239
9240
/* handle an error in _PyUnicode_EncodeCharmap()
9241
   Return 0 on success, -1 on error */
9242
static int
9243
charmap_encoding_error(
9244
    PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
9245
    PyObject **exceptionObject,
9246
    _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
9247
    PyBytesWriter *writer, Py_ssize_t *respos)
9248
0
{
9249
0
    PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9250
0
    Py_ssize_t size, repsize;
9251
0
    Py_ssize_t newpos;
9252
0
    int kind;
9253
0
    const void *data;
9254
0
    Py_ssize_t index;
9255
    /* startpos for collecting unencodable chars */
9256
0
    Py_ssize_t collstartpos = *inpos;
9257
0
    Py_ssize_t collendpos = *inpos+1;
9258
0
    Py_ssize_t collpos;
9259
0
    const char *encoding = "charmap";
9260
0
    const char *reason = "character maps to <undefined>";
9261
0
    charmapencode_result x;
9262
0
    Py_UCS4 ch;
9263
0
    int val;
9264
9265
0
    size = PyUnicode_GET_LENGTH(unicode);
9266
    /* find all unencodable characters */
9267
0
    while (collendpos < size) {
9268
0
        PyObject *rep;
9269
0
        unsigned char replace;
9270
0
        if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9271
0
            ch = PyUnicode_READ_CHAR(unicode, collendpos);
9272
0
            val = encoding_map_lookup(ch, mapping);
9273
0
            if (val != -1)
9274
0
                break;
9275
0
            ++collendpos;
9276
0
            continue;
9277
0
        }
9278
9279
0
        ch = PyUnicode_READ_CHAR(unicode, collendpos);
9280
0
        rep = charmapencode_lookup(ch, mapping, &replace);
9281
0
        if (rep==NULL)
9282
0
            return -1;
9283
0
        else if (rep!=Py_None) {
9284
0
            Py_DECREF(rep);
9285
0
            break;
9286
0
        }
9287
0
        Py_DECREF(rep);
9288
0
        ++collendpos;
9289
0
    }
9290
    /* cache callback name lookup
9291
     * (if not done yet, i.e. it's the first error) */
9292
0
    if (*error_handler == _Py_ERROR_UNKNOWN)
9293
0
        *error_handler = _Py_GetErrorHandler(errors);
9294
9295
0
    switch (*error_handler) {
9296
0
    case _Py_ERROR_STRICT:
9297
0
        raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9298
0
        return -1;
9299
9300
0
    case _Py_ERROR_REPLACE:
9301
0
        for (collpos = collstartpos; collpos<collendpos; ++collpos) {
9302
0
            x = charmapencode_output('?', mapping, writer, respos);
9303
0
            if (x==enc_EXCEPTION) {
9304
0
                return -1;
9305
0
            }
9306
0
            else if (x==enc_FAILED) {
9307
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9308
0
                return -1;
9309
0
            }
9310
0
        }
9311
0
        _Py_FALLTHROUGH;
9312
0
    case _Py_ERROR_IGNORE:
9313
0
        *inpos = collendpos;
9314
0
        break;
9315
9316
0
    case _Py_ERROR_XMLCHARREFREPLACE:
9317
        /* generate replacement (temporarily (mis)uses p) */
9318
0
        for (collpos = collstartpos; collpos < collendpos; ++collpos) {
9319
0
            char buffer[2+29+1+1];
9320
0
            char *cp;
9321
0
            sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
9322
0
            for (cp = buffer; *cp; ++cp) {
9323
0
                x = charmapencode_output(*cp, mapping, writer, respos);
9324
0
                if (x==enc_EXCEPTION)
9325
0
                    return -1;
9326
0
                else if (x==enc_FAILED) {
9327
0
                    raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9328
0
                    return -1;
9329
0
                }
9330
0
            }
9331
0
        }
9332
0
        *inpos = collendpos;
9333
0
        break;
9334
9335
0
    default:
9336
0
        repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
9337
0
                                                      encoding, reason, unicode, exceptionObject,
9338
0
                                                      collstartpos, collendpos, &newpos);
9339
0
        if (repunicode == NULL)
9340
0
            return -1;
9341
0
        if (PyBytes_Check(repunicode)) {
9342
            /* Directly copy bytes result to output. */
9343
0
            Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9344
0
            Py_ssize_t requiredsize;
9345
0
            repsize = PyBytes_Size(repunicode);
9346
0
            requiredsize = *respos + repsize;
9347
0
            if (requiredsize > outsize)
9348
                /* Make room for all additional bytes. */
9349
0
                if (charmapencode_resize(writer, respos, requiredsize)) {
9350
0
                    Py_DECREF(repunicode);
9351
0
                    return -1;
9352
0
                }
9353
0
            memcpy((char*)PyBytesWriter_GetData(writer) + *respos,
9354
0
                   PyBytes_AsString(repunicode),  repsize);
9355
0
            *respos += repsize;
9356
0
            *inpos = newpos;
9357
0
            Py_DECREF(repunicode);
9358
0
            break;
9359
0
        }
9360
        /* generate replacement  */
9361
0
        repsize = PyUnicode_GET_LENGTH(repunicode);
9362
0
        data = PyUnicode_DATA(repunicode);
9363
0
        kind = PyUnicode_KIND(repunicode);
9364
0
        for (index = 0; index < repsize; index++) {
9365
0
            Py_UCS4 repch = PyUnicode_READ(kind, data, index);
9366
0
            x = charmapencode_output(repch, mapping, writer, respos);
9367
0
            if (x==enc_EXCEPTION) {
9368
0
                Py_DECREF(repunicode);
9369
0
                return -1;
9370
0
            }
9371
0
            else if (x==enc_FAILED) {
9372
0
                Py_DECREF(repunicode);
9373
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9374
0
                return -1;
9375
0
            }
9376
0
        }
9377
0
        *inpos = newpos;
9378
0
        Py_DECREF(repunicode);
9379
0
    }
9380
0
    return 0;
9381
0
}
9382
9383
PyObject *
9384
_PyUnicode_EncodeCharmap(PyObject *unicode,
9385
                         PyObject *mapping,
9386
                         const char *errors)
9387
0
{
9388
    /* Default to Latin-1 */
9389
0
    if (mapping == NULL) {
9390
0
        return unicode_encode_ucs1(unicode, errors, 256);
9391
0
    }
9392
9393
0
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
9394
0
    if (size == 0) {
9395
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
9396
0
    }
9397
0
    const void *data = PyUnicode_DATA(unicode);
9398
0
    int kind = PyUnicode_KIND(unicode);
9399
9400
0
    PyObject *error_handler_obj = NULL;
9401
0
    PyObject *exc = NULL;
9402
9403
    /* output object */
9404
0
    PyBytesWriter *writer;
9405
    /* allocate enough for a simple encoding without
9406
       replacements, if we need more, we'll resize */
9407
0
    writer = PyBytesWriter_Create(size);
9408
0
    if (writer == NULL) {
9409
0
        goto onError;
9410
0
    }
9411
9412
    /* current input position */
9413
0
    Py_ssize_t inpos = 0;
9414
    /* current output position */
9415
0
    Py_ssize_t respos = 0;
9416
0
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
9417
9418
0
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9419
0
        char *outstart = _PyBytesWriter_GetData(writer);
9420
0
        Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9421
9422
0
        while (inpos<size) {
9423
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9424
9425
            /* try to encode it */
9426
0
            int res = encoding_map_lookup(ch, mapping);
9427
0
            Py_ssize_t requiredsize = respos+1;
9428
0
            if (res == -1) {
9429
0
                goto enc_FAILED;
9430
0
            }
9431
9432
0
            if (outsize<requiredsize) {
9433
0
                if (charmapencode_resize(writer, &respos, requiredsize)) {
9434
0
                    goto onError;
9435
0
                }
9436
0
                outstart = _PyBytesWriter_GetData(writer);
9437
0
                outsize = _PyBytesWriter_GetSize(writer);
9438
0
            }
9439
0
            outstart[respos++] = (char)res;
9440
9441
            /* done with this character => adjust input position */
9442
0
            ++inpos;
9443
0
            continue;
9444
9445
0
enc_FAILED:
9446
0
            if (charmap_encoding_error(unicode, &inpos, mapping,
9447
0
                                       &exc,
9448
0
                                       &error_handler, &error_handler_obj, errors,
9449
0
                                       writer, &respos)) {
9450
0
                goto onError;
9451
0
            }
9452
0
            outstart = _PyBytesWriter_GetData(writer);
9453
0
            outsize = _PyBytesWriter_GetSize(writer);
9454
0
        }
9455
0
    }
9456
0
    else {
9457
0
        while (inpos<size) {
9458
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9459
            /* try to encode it */
9460
0
            charmapencode_result x = charmapencode_output(ch, mapping, writer, &respos);
9461
0
            if (x==enc_EXCEPTION) { /* error */
9462
0
                goto onError;
9463
0
            }
9464
0
            if (x==enc_FAILED) { /* unencodable character */
9465
0
                if (charmap_encoding_error(unicode, &inpos, mapping,
9466
0
                                           &exc,
9467
0
                                           &error_handler, &error_handler_obj, errors,
9468
0
                                           writer, &respos)) {
9469
0
                    goto onError;
9470
0
                }
9471
0
            }
9472
0
            else {
9473
                /* done with this character => adjust input position */
9474
0
                ++inpos;
9475
0
            }
9476
0
        }
9477
0
    }
9478
9479
0
    Py_XDECREF(exc);
9480
0
    Py_XDECREF(error_handler_obj);
9481
9482
    /* Resize if we allocated too much */
9483
0
    return PyBytesWriter_FinishWithSize(writer, respos);
9484
9485
0
  onError:
9486
0
    PyBytesWriter_Discard(writer);
9487
0
    Py_XDECREF(exc);
9488
0
    Py_XDECREF(error_handler_obj);
9489
0
    return NULL;
9490
0
}
9491
9492
PyObject *
9493
PyUnicode_AsCharmapString(PyObject *unicode,
9494
                          PyObject *mapping)
9495
0
{
9496
0
    if (!PyUnicode_Check(unicode) || mapping == NULL) {
9497
0
        PyErr_BadArgument();
9498
0
        return NULL;
9499
0
    }
9500
0
    return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
9501
0
}
9502
9503
/* create or adjust a UnicodeTranslateError */
9504
static void
9505
make_translate_exception(PyObject **exceptionObject,
9506
                         PyObject *unicode,
9507
                         Py_ssize_t startpos, Py_ssize_t endpos,
9508
                         const char *reason)
9509
0
{
9510
0
    if (*exceptionObject == NULL) {
9511
0
        *exceptionObject = _PyUnicodeTranslateError_Create(
9512
0
            unicode, startpos, endpos, reason);
9513
0
    }
9514
0
    else {
9515
0
        if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
9516
0
            goto onError;
9517
0
        if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
9518
0
            goto onError;
9519
0
        if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
9520
0
            goto onError;
9521
0
        return;
9522
0
      onError:
9523
0
        Py_CLEAR(*exceptionObject);
9524
0
    }
9525
0
}
9526
9527
/* error handling callback helper:
9528
   build arguments, call the callback and check the arguments,
9529
   put the result into newpos and return the replacement string, which
9530
   has to be freed by the caller */
9531
static PyObject *
9532
unicode_translate_call_errorhandler(const char *errors,
9533
                                    PyObject **errorHandler,
9534
                                    const char *reason,
9535
                                    PyObject *unicode, PyObject **exceptionObject,
9536
                                    Py_ssize_t startpos, Py_ssize_t endpos,
9537
                                    Py_ssize_t *newpos)
9538
0
{
9539
0
    static const char *argparse = "Un;translating error handler must return (str, int) tuple";
9540
9541
0
    Py_ssize_t i_newpos;
9542
0
    PyObject *restuple;
9543
0
    PyObject *resunicode;
9544
9545
0
    if (*errorHandler == NULL) {
9546
0
        *errorHandler = PyCodec_LookupError(errors);
9547
0
        if (*errorHandler == NULL)
9548
0
            return NULL;
9549
0
    }
9550
9551
0
    make_translate_exception(exceptionObject,
9552
0
                             unicode, startpos, endpos, reason);
9553
0
    if (*exceptionObject == NULL)
9554
0
        return NULL;
9555
9556
0
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
9557
0
    if (restuple == NULL)
9558
0
        return NULL;
9559
0
    if (!PyTuple_Check(restuple)) {
9560
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
9561
0
        Py_DECREF(restuple);
9562
0
        return NULL;
9563
0
    }
9564
0
    if (!PyArg_ParseTuple(restuple, argparse,
9565
0
                          &resunicode, &i_newpos)) {
9566
0
        Py_DECREF(restuple);
9567
0
        return NULL;
9568
0
    }
9569
0
    if (i_newpos<0)
9570
0
        *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
9571
0
    else
9572
0
        *newpos = i_newpos;
9573
0
    if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
9574
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
9575
0
        Py_DECREF(restuple);
9576
0
        return NULL;
9577
0
    }
9578
0
    Py_INCREF(resunicode);
9579
0
    Py_DECREF(restuple);
9580
0
    return resunicode;
9581
0
}
9582
9583
/* Lookup the character ch in the mapping and put the result in result,
9584
   which must be decrefed by the caller.
9585
   The result can be PyLong, PyUnicode, None or NULL.
9586
   If the result is PyLong, put its value in replace.
9587
   Return 0 on success, -1 on error */
9588
static int
9589
charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result, Py_UCS4 *replace)
9590
18.2k
{
9591
18.2k
    PyObject *w = PyLong_FromLong((long)c);
9592
18.2k
    PyObject *x;
9593
9594
18.2k
    if (w == NULL)
9595
0
        return -1;
9596
18.2k
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9597
18.2k
    Py_DECREF(w);
9598
18.2k
    if (rc == 0) {
9599
        /* No mapping found means: use 1:1 mapping. */
9600
6.15k
        *result = NULL;
9601
6.15k
        return 0;
9602
6.15k
    }
9603
12.0k
    if (x == NULL) {
9604
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9605
            /* No mapping found means: use 1:1 mapping. */
9606
0
            PyErr_Clear();
9607
0
            *result = NULL;
9608
0
            return 0;
9609
0
        } else
9610
0
            return -1;
9611
0
    }
9612
12.0k
    else if (x == Py_None) {
9613
0
        *result = x;
9614
0
        return 0;
9615
0
    }
9616
12.0k
    else if (PyLong_Check(x)) {
9617
0
        long value = PyLong_AsLong(x);
9618
0
        if (value < 0 || value > MAX_UNICODE) {
9619
0
            PyErr_Format(PyExc_ValueError,
9620
0
                         "character mapping must be in range(0x%lx)",
9621
0
                         (unsigned long)MAX_UNICODE + 1);
9622
0
            Py_DECREF(x);
9623
0
            return -1;
9624
0
        }
9625
0
        *result = x;
9626
0
        *replace = (Py_UCS4)value;
9627
0
        return 0;
9628
0
    }
9629
12.0k
    else if (PyUnicode_Check(x)) {
9630
12.0k
        *result = x;
9631
12.0k
        return 0;
9632
12.0k
    }
9633
0
    else {
9634
        /* wrong return value */
9635
0
        PyErr_SetString(PyExc_TypeError,
9636
0
                        "character mapping must return integer, None or str");
9637
0
        Py_DECREF(x);
9638
0
        return -1;
9639
0
    }
9640
12.0k
}
9641
9642
/* lookup the character, write the result into the writer.
9643
   Return 1 if the result was written into the writer, return 0 if the mapping
9644
   was undefined, raise an exception return -1 on error. */
9645
static int
9646
charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
9647
                        _PyUnicodeWriter *writer)
9648
6.20k
{
9649
6.20k
    PyObject *item;
9650
6.20k
    Py_UCS4 replace;
9651
9652
6.20k
    if (charmaptranslate_lookup(ch, mapping, &item, &replace))
9653
0
        return -1;
9654
9655
6.20k
    if (item == NULL) {
9656
        /* not found => default to 1:1 mapping */
9657
117
        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
9658
0
            return -1;
9659
0
        }
9660
117
        return 1;
9661
117
    }
9662
9663
6.08k
    if (item == Py_None) {
9664
0
        Py_DECREF(item);
9665
0
        return 0;
9666
0
    }
9667
9668
6.08k
    if (PyLong_Check(item)) {
9669
0
        if (_PyUnicodeWriter_WriteCharInline(writer, replace) < 0) {
9670
0
            Py_DECREF(item);
9671
0
            return -1;
9672
0
        }
9673
0
        Py_DECREF(item);
9674
0
        return 1;
9675
0
    }
9676
9677
6.08k
    if (!PyUnicode_Check(item)) {
9678
0
        Py_DECREF(item);
9679
0
        return -1;
9680
0
    }
9681
9682
6.08k
    if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
9683
0
        Py_DECREF(item);
9684
0
        return -1;
9685
0
    }
9686
9687
6.08k
    Py_DECREF(item);
9688
6.08k
    return 1;
9689
6.08k
}
9690
9691
static int
9692
unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
9693
                              Py_UCS1 *translate)
9694
12.0k
{
9695
12.0k
    PyObject *item = NULL;
9696
12.0k
    Py_UCS4 replace;
9697
12.0k
    int ret = 0;
9698
9699
12.0k
    if (charmaptranslate_lookup(ch, mapping, &item, &replace)) {
9700
0
        return -1;
9701
0
    }
9702
9703
12.0k
    if (item == Py_None) {
9704
        /* deletion */
9705
0
        translate[ch] = 0xfe;
9706
0
    }
9707
12.0k
    else if (item == NULL) {
9708
        /* not found => default to 1:1 mapping */
9709
6.03k
        translate[ch] = ch;
9710
6.03k
        return 1;
9711
6.03k
    }
9712
5.98k
    else if (PyLong_Check(item)) {
9713
0
        if (replace > 127) {
9714
            /* invalid character or character outside ASCII:
9715
               skip the fast translate */
9716
0
            goto exit;
9717
0
        }
9718
0
        translate[ch] = (Py_UCS1)replace;
9719
0
    }
9720
5.98k
    else if (PyUnicode_Check(item)) {
9721
5.98k
        if (PyUnicode_GET_LENGTH(item) != 1)
9722
5.98k
            goto exit;
9723
9724
0
        replace = PyUnicode_READ_CHAR(item, 0);
9725
0
        if (replace > 127)
9726
0
            goto exit;
9727
0
        translate[ch] = (Py_UCS1)replace;
9728
0
    }
9729
0
    else {
9730
        /* not None, NULL, long or unicode */
9731
0
        goto exit;
9732
0
    }
9733
0
    ret = 1;
9734
9735
5.98k
  exit:
9736
5.98k
    Py_DECREF(item);
9737
5.98k
    return ret;
9738
0
}
9739
9740
/* Fast path for ascii => ascii translation. Return 1 if the whole string
9741
   was translated into writer, return 0 if the input string was partially
9742
   translated into writer, raise an exception and return -1 on error. */
9743
static int
9744
unicode_fast_translate(PyObject *input, PyObject *mapping,
9745
                       _PyUnicodeWriter *writer, int ignore,
9746
                       Py_ssize_t *input_pos)
9747
11.9k
{
9748
11.9k
    Py_UCS1 ascii_table[128], ch, ch2;
9749
11.9k
    Py_ssize_t len;
9750
11.9k
    const Py_UCS1 *in, *end;
9751
11.9k
    Py_UCS1 *out;
9752
11.9k
    int res = 0;
9753
9754
11.9k
    len = PyUnicode_GET_LENGTH(input);
9755
9756
11.9k
    memset(ascii_table, 0xff, 128);
9757
9758
11.9k
    in = PyUnicode_1BYTE_DATA(input);
9759
11.9k
    end = in + len;
9760
9761
11.9k
    assert(PyUnicode_IS_ASCII(writer->buffer));
9762
11.9k
    assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9763
11.9k
    out = PyUnicode_1BYTE_DATA(writer->buffer);
9764
9765
18.0k
    for (; in < end; in++) {
9766
12.0k
        ch = *in;
9767
12.0k
        ch2 = ascii_table[ch];
9768
12.0k
        if (ch2 == 0xff) {
9769
12.0k
            int translate = unicode_fast_translate_lookup(mapping, ch,
9770
12.0k
                                                          ascii_table);
9771
12.0k
            if (translate < 0)
9772
0
                return -1;
9773
12.0k
            if (translate == 0)
9774
5.98k
                goto exit;
9775
6.03k
            ch2 = ascii_table[ch];
9776
6.03k
        }
9777
6.07k
        if (ch2 == 0xfe) {
9778
0
            if (ignore)
9779
0
                continue;
9780
0
            goto exit;
9781
0
        }
9782
6.07k
        assert(ch2 < 128);
9783
6.07k
        *out = ch2;
9784
6.07k
        out++;
9785
6.07k
    }
9786
5.96k
    res = 1;
9787
9788
11.9k
exit:
9789
11.9k
    writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
9790
11.9k
    *input_pos = in - PyUnicode_1BYTE_DATA(input);
9791
11.9k
    return res;
9792
5.96k
}
9793
9794
static PyObject *
9795
_PyUnicode_TranslateCharmap(PyObject *input,
9796
                            PyObject *mapping,
9797
                            const char *errors)
9798
11.9k
{
9799
    /* input object */
9800
11.9k
    const void *data;
9801
11.9k
    Py_ssize_t size, i;
9802
11.9k
    int kind;
9803
    /* output buffer */
9804
11.9k
    _PyUnicodeWriter writer;
9805
    /* error handler */
9806
11.9k
    const char *reason = "character maps to <undefined>";
9807
11.9k
    PyObject *errorHandler = NULL;
9808
11.9k
    PyObject *exc = NULL;
9809
11.9k
    int ignore;
9810
11.9k
    int res;
9811
9812
11.9k
    if (mapping == NULL) {
9813
0
        PyErr_BadArgument();
9814
0
        return NULL;
9815
0
    }
9816
9817
11.9k
    data = PyUnicode_DATA(input);
9818
11.9k
    kind = PyUnicode_KIND(input);
9819
11.9k
    size = PyUnicode_GET_LENGTH(input);
9820
9821
11.9k
    if (size == 0)
9822
0
        return PyUnicode_FromObject(input);
9823
9824
    /* allocate enough for a simple 1:1 translation without
9825
       replacements, if we need more, we'll resize */
9826
11.9k
    _PyUnicodeWriter_Init(&writer);
9827
11.9k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
9828
0
        goto onError;
9829
9830
11.9k
    ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9831
9832
11.9k
    if (PyUnicode_IS_ASCII(input)) {
9833
11.9k
        res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9834
11.9k
        if (res < 0) {
9835
0
            _PyUnicodeWriter_Dealloc(&writer);
9836
0
            return NULL;
9837
0
        }
9838
11.9k
        if (res == 1)
9839
5.96k
            return _PyUnicodeWriter_Finish(&writer);
9840
11.9k
    }
9841
0
    else {
9842
0
        i = 0;
9843
0
    }
9844
9845
12.1k
    while (i<size) {
9846
        /* try to encode it */
9847
6.20k
        int translate;
9848
6.20k
        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9849
6.20k
        Py_ssize_t newpos;
9850
        /* startpos for collecting untranslatable chars */
9851
6.20k
        Py_ssize_t collstart;
9852
6.20k
        Py_ssize_t collend;
9853
6.20k
        Py_UCS4 ch;
9854
9855
6.20k
        ch = PyUnicode_READ(kind, data, i);
9856
6.20k
        translate = charmaptranslate_output(ch, mapping, &writer);
9857
6.20k
        if (translate < 0)
9858
0
            goto onError;
9859
9860
6.20k
        if (translate != 0) {
9861
            /* it worked => adjust input pointer */
9862
6.20k
            ++i;
9863
6.20k
            continue;
9864
6.20k
        }
9865
9866
        /* untranslatable character */
9867
0
        collstart = i;
9868
0
        collend = i+1;
9869
9870
        /* find all untranslatable characters */
9871
0
        while (collend < size) {
9872
0
            PyObject *x;
9873
0
            Py_UCS4 replace;
9874
0
            ch = PyUnicode_READ(kind, data, collend);
9875
0
            if (charmaptranslate_lookup(ch, mapping, &x, &replace))
9876
0
                goto onError;
9877
0
            Py_XDECREF(x);
9878
0
            if (x != Py_None)
9879
0
                break;
9880
0
            ++collend;
9881
0
        }
9882
9883
0
        if (ignore) {
9884
0
            i = collend;
9885
0
        }
9886
0
        else {
9887
0
            repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9888
0
                                                             reason, input, &exc,
9889
0
                                                             collstart, collend, &newpos);
9890
0
            if (repunicode == NULL)
9891
0
                goto onError;
9892
0
            if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
9893
0
                Py_DECREF(repunicode);
9894
0
                goto onError;
9895
0
            }
9896
0
            Py_DECREF(repunicode);
9897
0
            i = newpos;
9898
0
        }
9899
0
    }
9900
5.98k
    Py_XDECREF(exc);
9901
5.98k
    Py_XDECREF(errorHandler);
9902
5.98k
    return _PyUnicodeWriter_Finish(&writer);
9903
9904
0
  onError:
9905
0
    _PyUnicodeWriter_Dealloc(&writer);
9906
0
    Py_XDECREF(exc);
9907
0
    Py_XDECREF(errorHandler);
9908
0
    return NULL;
9909
5.98k
}
9910
9911
PyObject *
9912
PyUnicode_Translate(PyObject *str,
9913
                    PyObject *mapping,
9914
                    const char *errors)
9915
0
{
9916
0
    if (ensure_unicode(str) < 0)
9917
0
        return NULL;
9918
0
    return _PyUnicode_TranslateCharmap(str, mapping, errors);
9919
0
}
9920
9921
PyObject *
9922
_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9923
9.45M
{
9924
9.45M
    if (!PyUnicode_Check(unicode)) {
9925
0
        PyErr_BadInternalCall();
9926
0
        return NULL;
9927
0
    }
9928
9.45M
    if (PyUnicode_IS_ASCII(unicode)) {
9929
        /* If the string is already ASCII, just return the same string */
9930
9.44M
        return Py_NewRef(unicode);
9931
9.44M
    }
9932
9933
2.08k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9934
2.08k
    PyObject *result = PyUnicode_New(len, 127);
9935
2.08k
    if (result == NULL) {
9936
0
        return NULL;
9937
0
    }
9938
9939
2.08k
    Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9940
2.08k
    int kind = PyUnicode_KIND(unicode);
9941
2.08k
    const void *data = PyUnicode_DATA(unicode);
9942
2.08k
    Py_ssize_t i;
9943
39.6k
    for (i = 0; i < len; ++i) {
9944
37.8k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9945
37.8k
        if (ch < 127) {
9946
35.5k
            out[i] = ch;
9947
35.5k
        }
9948
2.33k
        else if (Py_UNICODE_ISSPACE(ch)) {
9949
749
            out[i] = ' ';
9950
749
        }
9951
1.58k
        else {
9952
1.58k
            int decimal = Py_UNICODE_TODECIMAL(ch);
9953
1.58k
            if (decimal < 0) {
9954
253
                out[i] = '?';
9955
253
                out[i+1] = '\0';
9956
253
                _PyUnicode_LENGTH(result) = i + 1;
9957
253
                break;
9958
253
            }
9959
1.32k
            out[i] = '0' + decimal;
9960
1.32k
        }
9961
37.8k
    }
9962
9963
2.08k
    assert(_PyUnicode_CheckConsistency(result, 1));
9964
2.08k
    return result;
9965
2.08k
}
9966
9967
/* --- Helpers ------------------------------------------------------------ */
9968
9969
/* helper macro to fixup start/end slice values */
9970
#define ADJUST_INDICES(start, end, len) \
9971
81.0M
    do {                                \
9972
81.0M
        if (end > len) {                \
9973
57.1M
            end = len;                  \
9974
57.1M
        }                               \
9975
81.0M
        else if (end < 0) {             \
9976
0
            end += len;                 \
9977
0
            if (end < 0) {              \
9978
0
                end = 0;                \
9979
0
            }                           \
9980
0
        }                               \
9981
81.0M
        if (start < 0) {                \
9982
20.6k
            start += len;               \
9983
20.6k
            if (start < 0) {            \
9984
0
                start = 0;              \
9985
0
            }                           \
9986
20.6k
        }                               \
9987
81.0M
    } while (0)
9988
9989
static Py_ssize_t
9990
any_find_slice(PyObject* s1, PyObject* s2,
9991
               Py_ssize_t start,
9992
               Py_ssize_t end,
9993
               int direction)
9994
22.0M
{
9995
22.0M
    int kind1, kind2;
9996
22.0M
    const void *buf1, *buf2;
9997
22.0M
    Py_ssize_t len1, len2, result;
9998
9999
22.0M
    kind1 = PyUnicode_KIND(s1);
10000
22.0M
    kind2 = PyUnicode_KIND(s2);
10001
22.0M
    if (kind1 < kind2)
10002
0
        return -1;
10003
10004
22.0M
    len1 = PyUnicode_GET_LENGTH(s1);
10005
22.0M
    len2 = PyUnicode_GET_LENGTH(s2);
10006
22.0M
    ADJUST_INDICES(start, end, len1);
10007
22.0M
    if (end - start < len2)
10008
3.21M
        return -1;
10009
10010
18.8M
    buf1 = PyUnicode_DATA(s1);
10011
18.8M
    buf2 = PyUnicode_DATA(s2);
10012
18.8M
    if (len2 == 1) {
10013
18.8M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10014
18.8M
        result = findchar((const char *)buf1 + kind1*start,
10015
18.8M
                          kind1, end - start, ch, direction);
10016
18.8M
        if (result == -1)
10017
3.56M
            return -1;
10018
15.3M
        else
10019
15.3M
            return start + result;
10020
18.8M
    }
10021
10022
7.87k
    if (kind2 != kind1) {
10023
3.62k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10024
3.62k
        if (!buf2)
10025
0
            return -2;
10026
3.62k
    }
10027
10028
7.87k
    if (direction > 0) {
10029
7.87k
        switch (kind1) {
10030
4.25k
        case PyUnicode_1BYTE_KIND:
10031
4.25k
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
10032
454
                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
10033
3.79k
            else
10034
3.79k
                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
10035
4.25k
            break;
10036
2.90k
        case PyUnicode_2BYTE_KIND:
10037
2.90k
            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
10038
2.90k
            break;
10039
717
        case PyUnicode_4BYTE_KIND:
10040
717
            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
10041
717
            break;
10042
0
        default:
10043
0
            Py_UNREACHABLE();
10044
7.87k
        }
10045
7.87k
    }
10046
0
    else {
10047
0
        switch (kind1) {
10048
0
        case PyUnicode_1BYTE_KIND:
10049
0
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
10050
0
                result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
10051
0
            else
10052
0
                result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
10053
0
            break;
10054
0
        case PyUnicode_2BYTE_KIND:
10055
0
            result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
10056
0
            break;
10057
0
        case PyUnicode_4BYTE_KIND:
10058
0
            result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
10059
0
            break;
10060
0
        default:
10061
0
            Py_UNREACHABLE();
10062
0
        }
10063
0
    }
10064
10065
7.87k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
10066
7.87k
    if (kind2 != kind1)
10067
3.62k
        PyMem_Free((void *)buf2);
10068
10069
7.87k
    return result;
10070
7.87k
}
10071
10072
10073
Py_ssize_t
10074
PyUnicode_Count(PyObject *str,
10075
                PyObject *substr,
10076
                Py_ssize_t start,
10077
                Py_ssize_t end)
10078
0
{
10079
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10080
0
        return -1;
10081
10082
0
    return unicode_count_impl(str, substr, start, end);
10083
0
}
10084
10085
Py_ssize_t
10086
PyUnicode_Find(PyObject *str,
10087
               PyObject *substr,
10088
               Py_ssize_t start,
10089
               Py_ssize_t end,
10090
               int direction)
10091
0
{
10092
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10093
0
        return -2;
10094
10095
0
    return any_find_slice(str, substr, start, end, direction);
10096
0
}
10097
10098
Py_ssize_t
10099
PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
10100
                   Py_ssize_t start, Py_ssize_t end,
10101
                   int direction)
10102
3.48M
{
10103
3.48M
    int kind;
10104
3.48M
    Py_ssize_t len, result;
10105
3.48M
    len = PyUnicode_GET_LENGTH(str);
10106
3.48M
    ADJUST_INDICES(start, end, len);
10107
3.48M
    if (end - start < 1)
10108
0
        return -1;
10109
3.48M
    kind = PyUnicode_KIND(str);
10110
3.48M
    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
10111
3.48M
                      kind, end-start, ch, direction);
10112
3.48M
    if (result == -1)
10113
2.62M
        return -1;
10114
860k
    else
10115
860k
        return start + result;
10116
3.48M
}
10117
10118
static int
10119
tailmatch(PyObject *self,
10120
          PyObject *substring,
10121
          Py_ssize_t start,
10122
          Py_ssize_t end,
10123
          int direction)
10124
32.8M
{
10125
32.8M
    int kind_self;
10126
32.8M
    int kind_sub;
10127
32.8M
    const void *data_self;
10128
32.8M
    const void *data_sub;
10129
32.8M
    Py_ssize_t offset;
10130
32.8M
    Py_ssize_t i;
10131
32.8M
    Py_ssize_t end_sub;
10132
10133
32.8M
    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
10134
32.8M
    end -= PyUnicode_GET_LENGTH(substring);
10135
32.8M
    if (end < start)
10136
9.66M
        return 0;
10137
10138
23.1M
    if (PyUnicode_GET_LENGTH(substring) == 0)
10139
0
        return 1;
10140
10141
23.1M
    kind_self = PyUnicode_KIND(self);
10142
23.1M
    data_self = PyUnicode_DATA(self);
10143
23.1M
    kind_sub = PyUnicode_KIND(substring);
10144
23.1M
    data_sub = PyUnicode_DATA(substring);
10145
23.1M
    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
10146
10147
23.1M
    if (direction > 0)
10148
6.80M
        offset = end;
10149
16.3M
    else
10150
16.3M
        offset = start;
10151
10152
23.1M
    if (PyUnicode_READ(kind_self, data_self, offset) ==
10153
23.1M
        PyUnicode_READ(kind_sub, data_sub, 0) &&
10154
9.44M
        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
10155
9.44M
        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
10156
        /* If both are of the same kind, memcmp is sufficient */
10157
4.69M
        if (kind_self == kind_sub) {
10158
4.39M
            return ! memcmp((char *)data_self +
10159
4.39M
                                (offset * PyUnicode_KIND(substring)),
10160
4.39M
                            data_sub,
10161
4.39M
                            PyUnicode_GET_LENGTH(substring) *
10162
4.39M
                                PyUnicode_KIND(substring));
10163
4.39M
        }
10164
        /* otherwise we have to compare each character by first accessing it */
10165
299k
        else {
10166
            /* We do not need to compare 0 and len(substring)-1 because
10167
               the if statement above ensured already that they are equal
10168
               when we end up here. */
10169
347k
            for (i = 1; i < end_sub; ++i) {
10170
117k
                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
10171
117k
                    PyUnicode_READ(kind_sub, data_sub, i))
10172
68.9k
                    return 0;
10173
117k
            }
10174
230k
            return 1;
10175
299k
        }
10176
4.69M
    }
10177
10178
18.4M
    return 0;
10179
23.1M
}
10180
10181
Py_ssize_t
10182
PyUnicode_Tailmatch(PyObject *str,
10183
                    PyObject *substr,
10184
                    Py_ssize_t start,
10185
                    Py_ssize_t end,
10186
                    int direction)
10187
462
{
10188
462
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10189
0
        return -1;
10190
10191
462
    return tailmatch(str, substr, start, end, direction);
10192
462
}
10193
10194
static PyObject *
10195
ascii_upper_or_lower(PyObject *self, int lower)
10196
67.8M
{
10197
67.8M
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
10198
67.8M
    const char *data = PyUnicode_DATA(self);
10199
67.8M
    char *resdata;
10200
67.8M
    PyObject *res;
10201
10202
67.8M
    res = PyUnicode_New(len, 127);
10203
67.8M
    if (res == NULL)
10204
0
        return NULL;
10205
67.8M
    resdata = PyUnicode_DATA(res);
10206
67.8M
    if (lower)
10207
67.8M
        _Py_bytes_lower(resdata, data, len);
10208
306
    else
10209
306
        _Py_bytes_upper(resdata, data, len);
10210
67.8M
    return res;
10211
67.8M
}
10212
10213
static Py_UCS4
10214
handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
10215
9.12k
{
10216
9.12k
    Py_ssize_t j;
10217
9.12k
    int final_sigma;
10218
9.12k
    Py_UCS4 c = 0;   /* initialize to prevent gcc warning */
10219
    /* U+03A3 is in the Final_Sigma context when, it is found like this:
10220
10221
     \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
10222
10223
    where ! is a negation and \p{xxx} is a character with property xxx.
10224
    */
10225
11.9k
    for (j = i - 1; j >= 0; j--) {
10226
10.4k
        c = PyUnicode_READ(kind, data, j);
10227
10.4k
        if (!_PyUnicode_IsCaseIgnorable(c))
10228
7.59k
            break;
10229
10.4k
    }
10230
9.12k
    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
10231
9.12k
    if (final_sigma) {
10232
7.78k
        for (j = i + 1; j < length; j++) {
10233
6.82k
            c = PyUnicode_READ(kind, data, j);
10234
6.82k
            if (!_PyUnicode_IsCaseIgnorable(c))
10235
4.97k
                break;
10236
6.82k
        }
10237
5.93k
        final_sigma = j == length || !_PyUnicode_IsCased(c);
10238
5.93k
    }
10239
9.12k
    return (final_sigma) ? 0x3C2 : 0x3C3;
10240
9.12k
}
10241
10242
static int
10243
lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
10244
           Py_UCS4 c, Py_UCS4 *mapped)
10245
150M
{
10246
    /* Obscure special case. */
10247
150M
    if (c == 0x3A3) {
10248
9.12k
        mapped[0] = handle_capital_sigma(kind, data, length, i);
10249
9.12k
        return 1;
10250
9.12k
    }
10251
150M
    return _PyUnicode_ToLowerFull(c, mapped);
10252
150M
}
10253
10254
static Py_ssize_t
10255
do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10256
0
{
10257
0
    Py_ssize_t i, k = 0;
10258
0
    int n_res, j;
10259
0
    Py_UCS4 c, mapped[3];
10260
10261
0
    c = PyUnicode_READ(kind, data, 0);
10262
0
    n_res = _PyUnicode_ToTitleFull(c, mapped);
10263
0
    for (j = 0; j < n_res; j++) {
10264
0
        *maxchar = Py_MAX(*maxchar, mapped[j]);
10265
0
        res[k++] = mapped[j];
10266
0
    }
10267
0
    for (i = 1; i < length; i++) {
10268
0
        c = PyUnicode_READ(kind, data, i);
10269
0
        n_res = lower_ucs4(kind, data, length, i, c, mapped);
10270
0
        for (j = 0; j < n_res; j++) {
10271
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10272
0
            res[k++] = mapped[j];
10273
0
        }
10274
0
    }
10275
0
    return k;
10276
0
}
10277
10278
static Py_ssize_t
10279
0
do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
10280
0
    Py_ssize_t i, k = 0;
10281
10282
0
    for (i = 0; i < length; i++) {
10283
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10284
0
        int n_res, j;
10285
0
        if (Py_UNICODE_ISUPPER(c)) {
10286
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10287
0
        }
10288
0
        else if (Py_UNICODE_ISLOWER(c)) {
10289
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10290
0
        }
10291
0
        else {
10292
0
            n_res = 1;
10293
0
            mapped[0] = c;
10294
0
        }
10295
0
        for (j = 0; j < n_res; j++) {
10296
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10297
0
            res[k++] = mapped[j];
10298
0
        }
10299
0
    }
10300
0
    return k;
10301
0
}
10302
10303
static Py_ssize_t
10304
do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
10305
                  Py_UCS4 *maxchar, int lower)
10306
9.35M
{
10307
9.35M
    Py_ssize_t i, k = 0;
10308
10309
159M
    for (i = 0; i < length; i++) {
10310
150M
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10311
150M
        int n_res, j;
10312
150M
        if (lower)
10313
150M
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10314
0
        else
10315
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10316
301M
        for (j = 0; j < n_res; j++) {
10317
150M
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10318
150M
            res[k++] = mapped[j];
10319
150M
        }
10320
150M
    }
10321
9.35M
    return k;
10322
9.35M
}
10323
10324
static Py_ssize_t
10325
do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10326
0
{
10327
0
    return do_upper_or_lower(kind, data, length, res, maxchar, 0);
10328
0
}
10329
10330
static Py_ssize_t
10331
do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10332
9.35M
{
10333
9.35M
    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
10334
9.35M
}
10335
10336
static Py_ssize_t
10337
do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10338
0
{
10339
0
    Py_ssize_t i, k = 0;
10340
10341
0
    for (i = 0; i < length; i++) {
10342
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i);
10343
0
        Py_UCS4 mapped[3];
10344
0
        int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
10345
0
        for (j = 0; j < n_res; j++) {
10346
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10347
0
            res[k++] = mapped[j];
10348
0
        }
10349
0
    }
10350
0
    return k;
10351
0
}
10352
10353
static Py_ssize_t
10354
do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10355
0
{
10356
0
    Py_ssize_t i, k = 0;
10357
0
    int previous_is_cased;
10358
10359
0
    previous_is_cased = 0;
10360
0
    for (i = 0; i < length; i++) {
10361
0
        const Py_UCS4 c = PyUnicode_READ(kind, data, i);
10362
0
        Py_UCS4 mapped[3];
10363
0
        int n_res, j;
10364
10365
0
        if (previous_is_cased)
10366
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10367
0
        else
10368
0
            n_res = _PyUnicode_ToTitleFull(c, mapped);
10369
10370
0
        for (j = 0; j < n_res; j++) {
10371
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10372
0
            res[k++] = mapped[j];
10373
0
        }
10374
10375
0
        previous_is_cased = _PyUnicode_IsCased(c);
10376
0
    }
10377
0
    return k;
10378
0
}
10379
10380
static PyObject *
10381
case_operation(PyObject *self,
10382
               Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
10383
9.35M
{
10384
9.35M
    PyObject *res = NULL;
10385
9.35M
    Py_ssize_t length, newlength = 0;
10386
9.35M
    int kind, outkind;
10387
9.35M
    const void *data;
10388
9.35M
    void *outdata;
10389
9.35M
    Py_UCS4 maxchar = 0, *tmp, *tmpend;
10390
10391
9.35M
    kind = PyUnicode_KIND(self);
10392
9.35M
    data = PyUnicode_DATA(self);
10393
9.35M
    length = PyUnicode_GET_LENGTH(self);
10394
9.35M
    if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
10395
0
        PyErr_SetString(PyExc_OverflowError, "string is too long");
10396
0
        return NULL;
10397
0
    }
10398
9.35M
    tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
10399
9.35M
    if (tmp == NULL)
10400
0
        return PyErr_NoMemory();
10401
9.35M
    newlength = perform(kind, data, length, tmp, &maxchar);
10402
9.35M
    res = PyUnicode_New(newlength, maxchar);
10403
9.35M
    if (res == NULL)
10404
0
        goto leave;
10405
9.35M
    tmpend = tmp + newlength;
10406
9.35M
    outdata = PyUnicode_DATA(res);
10407
9.35M
    outkind = PyUnicode_KIND(res);
10408
9.35M
    switch (outkind) {
10409
701k
    case PyUnicode_1BYTE_KIND:
10410
701k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10411
701k
        break;
10412
8.35M
    case PyUnicode_2BYTE_KIND:
10413
8.35M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10414
8.35M
        break;
10415
294k
    case PyUnicode_4BYTE_KIND:
10416
294k
        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10417
294k
        break;
10418
0
    default:
10419
0
        Py_UNREACHABLE();
10420
9.35M
    }
10421
9.35M
  leave:
10422
9.35M
    PyMem_Free(tmp);
10423
9.35M
    return res;
10424
9.35M
}
10425
10426
PyObject *
10427
PyUnicode_Join(PyObject *separator, PyObject *seq)
10428
30.8M
{
10429
30.8M
    PyObject *res;
10430
30.8M
    PyObject *fseq;
10431
30.8M
    Py_ssize_t seqlen;
10432
30.8M
    PyObject **items;
10433
10434
30.8M
    fseq = PySequence_Fast(seq, "can only join an iterable");
10435
30.8M
    if (fseq == NULL) {
10436
644
        return NULL;
10437
644
    }
10438
10439
30.8M
    Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(seq);
10440
10441
30.8M
    items = PySequence_Fast_ITEMS(fseq);
10442
30.8M
    seqlen = PySequence_Fast_GET_SIZE(fseq);
10443
30.8M
    res = _PyUnicode_JoinArray(separator, items, seqlen);
10444
10445
30.8M
    Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
10446
10447
30.8M
    Py_DECREF(fseq);
10448
30.8M
    return res;
10449
30.8M
}
10450
10451
PyObject *
10452
_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
10453
49.6M
{
10454
49.6M
    PyObject *res = NULL; /* the result */
10455
49.6M
    PyObject *sep = NULL;
10456
49.6M
    Py_ssize_t seplen;
10457
49.6M
    PyObject *item;
10458
49.6M
    Py_ssize_t sz, i, res_offset;
10459
49.6M
    Py_UCS4 maxchar;
10460
49.6M
    Py_UCS4 item_maxchar;
10461
49.6M
    int use_memcpy;
10462
49.6M
    unsigned char *res_data = NULL, *sep_data = NULL;
10463
49.6M
    PyObject *last_obj;
10464
49.6M
    int kind = 0;
10465
10466
    /* If empty sequence, return u"". */
10467
49.6M
    if (seqlen == 0) {
10468
7.07M
        _Py_RETURN_UNICODE_EMPTY();
10469
7.07M
    }
10470
10471
    /* If singleton sequence with an exact Unicode, return that. */
10472
42.5M
    last_obj = NULL;
10473
42.5M
    if (seqlen == 1) {
10474
15.9M
        if (PyUnicode_CheckExact(items[0])) {
10475
14.5M
            res = items[0];
10476
14.5M
            return Py_NewRef(res);
10477
14.5M
        }
10478
1.40M
        seplen = 0;
10479
1.40M
        maxchar = 0;
10480
1.40M
    }
10481
26.6M
    else {
10482
        /* Set up sep and seplen */
10483
26.6M
        if (separator == NULL) {
10484
            /* fall back to a blank space separator */
10485
0
            sep = PyUnicode_FromOrdinal(' ');
10486
0
            if (!sep)
10487
0
                goto onError;
10488
0
            seplen = 1;
10489
0
            maxchar = 32;
10490
0
        }
10491
26.6M
        else {
10492
26.6M
            if (!PyUnicode_Check(separator)) {
10493
0
                PyErr_Format(PyExc_TypeError,
10494
0
                             "separator: expected str instance,"
10495
0
                             " %.80s found",
10496
0
                             Py_TYPE(separator)->tp_name);
10497
0
                goto onError;
10498
0
            }
10499
26.6M
            sep = separator;
10500
26.6M
            seplen = PyUnicode_GET_LENGTH(separator);
10501
26.6M
            maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10502
            /* inc refcount to keep this code path symmetric with the
10503
               above case of a blank separator */
10504
26.6M
            Py_INCREF(sep);
10505
26.6M
        }
10506
26.6M
        last_obj = sep;
10507
26.6M
    }
10508
10509
    /* There are at least two things to join, or else we have a subclass
10510
     * of str in the sequence.
10511
     * Do a pre-pass to figure out the total amount of space we'll
10512
     * need (sz), and see whether all argument are strings.
10513
     */
10514
28.0M
    sz = 0;
10515
#ifdef Py_DEBUG
10516
    use_memcpy = 0;
10517
#else
10518
28.0M
    use_memcpy = 1;
10519
28.0M
#endif
10520
237M
    for (i = 0; i < seqlen; i++) {
10521
209M
        size_t add_sz;
10522
209M
        item = items[i];
10523
209M
        if (!PyUnicode_Check(item)) {
10524
0
            PyErr_Format(PyExc_TypeError,
10525
0
                         "sequence item %zd: expected str instance,"
10526
0
                         " %.80s found",
10527
0
                         i, Py_TYPE(item)->tp_name);
10528
0
            goto onError;
10529
0
        }
10530
209M
        add_sz = PyUnicode_GET_LENGTH(item);
10531
209M
        item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
10532
209M
        maxchar = Py_MAX(maxchar, item_maxchar);
10533
209M
        if (i != 0) {
10534
181M
            add_sz += seplen;
10535
181M
        }
10536
209M
        if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
10537
0
            PyErr_SetString(PyExc_OverflowError,
10538
0
                            "join() result is too long for a Python string");
10539
0
            goto onError;
10540
0
        }
10541
209M
        sz += add_sz;
10542
209M
        if (use_memcpy && last_obj != NULL) {
10543
133M
            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10544
3.48M
                use_memcpy = 0;
10545
133M
        }
10546
209M
        last_obj = item;
10547
209M
    }
10548
10549
28.0M
    res = PyUnicode_New(sz, maxchar);
10550
28.0M
    if (res == NULL)
10551
0
        goto onError;
10552
10553
    /* Catenate everything. */
10554
#ifdef Py_DEBUG
10555
    use_memcpy = 0;
10556
#else
10557
28.0M
    if (use_memcpy) {
10558
24.5M
        res_data = PyUnicode_1BYTE_DATA(res);
10559
24.5M
        kind = PyUnicode_KIND(res);
10560
24.5M
        if (seplen != 0)
10561
249k
            sep_data = PyUnicode_1BYTE_DATA(sep);
10562
24.5M
    }
10563
28.0M
#endif
10564
28.0M
    if (use_memcpy) {
10565
138M
        for (i = 0; i < seqlen; ++i) {
10566
114M
            Py_ssize_t itemlen;
10567
114M
            item = items[i];
10568
10569
            /* Copy item, and maybe the separator. */
10570
114M
            if (i && seplen != 0) {
10571
1.09M
                memcpy(res_data,
10572
1.09M
                          sep_data,
10573
1.09M
                          kind * seplen);
10574
1.09M
                res_data += kind * seplen;
10575
1.09M
            }
10576
10577
114M
            itemlen = PyUnicode_GET_LENGTH(item);
10578
114M
            if (itemlen != 0) {
10579
104M
                memcpy(res_data,
10580
104M
                          PyUnicode_DATA(item),
10581
104M
                          kind * itemlen);
10582
104M
                res_data += kind * itemlen;
10583
104M
            }
10584
114M
        }
10585
24.5M
        assert(res_data == PyUnicode_1BYTE_DATA(res)
10586
24.5M
                           + kind * PyUnicode_GET_LENGTH(res));
10587
24.5M
    }
10588
3.48M
    else {
10589
99.0M
        for (i = 0, res_offset = 0; i < seqlen; ++i) {
10590
95.5M
            Py_ssize_t itemlen;
10591
95.5M
            item = items[i];
10592
10593
            /* Copy item, and maybe the separator. */
10594
95.5M
            if (i && seplen != 0) {
10595
3.65M
                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10596
3.65M
                res_offset += seplen;
10597
3.65M
            }
10598
10599
95.5M
            itemlen = PyUnicode_GET_LENGTH(item);
10600
95.5M
            if (itemlen != 0) {
10601
92.7M
                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
10602
92.7M
                res_offset += itemlen;
10603
92.7M
            }
10604
95.5M
        }
10605
3.48M
        assert(res_offset == PyUnicode_GET_LENGTH(res));
10606
3.48M
    }
10607
10608
28.0M
    Py_XDECREF(sep);
10609
28.0M
    assert(_PyUnicode_CheckConsistency(res, 1));
10610
28.0M
    return res;
10611
10612
0
  onError:
10613
0
    Py_XDECREF(sep);
10614
0
    Py_XDECREF(res);
10615
0
    return NULL;
10616
28.0M
}
10617
10618
void
10619
_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10620
                    Py_UCS4 fill_char)
10621
15.1k
{
10622
15.1k
    const int kind = PyUnicode_KIND(unicode);
10623
15.1k
    void *data = PyUnicode_DATA(unicode);
10624
15.1k
    assert(_PyUnicode_IsModifiable(unicode));
10625
15.1k
    assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10626
15.1k
    assert(start >= 0);
10627
15.1k
    assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10628
15.1k
    _PyUnicode_Fill(kind, data, fill_char, start, length);
10629
15.1k
}
10630
10631
Py_ssize_t
10632
PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10633
               Py_UCS4 fill_char)
10634
583
{
10635
583
    Py_ssize_t maxlen;
10636
10637
583
    if (!PyUnicode_Check(unicode)) {
10638
0
        PyErr_BadInternalCall();
10639
0
        return -1;
10640
0
    }
10641
583
    if (unicode_check_modifiable(unicode))
10642
0
        return -1;
10643
10644
583
    if (start < 0) {
10645
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
10646
0
        return -1;
10647
0
    }
10648
583
    if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10649
0
        PyErr_SetString(PyExc_ValueError,
10650
0
                         "fill character is bigger than "
10651
0
                         "the string maximum character");
10652
0
        return -1;
10653
0
    }
10654
10655
583
    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10656
583
    length = Py_MIN(maxlen, length);
10657
583
    if (length <= 0)
10658
0
        return 0;
10659
10660
583
    _PyUnicode_FastFill(unicode, start, length, fill_char);
10661
583
    return length;
10662
583
}
10663
10664
static PyObject *
10665
pad(PyObject *self,
10666
    Py_ssize_t left,
10667
    Py_ssize_t right,
10668
    Py_UCS4 fill)
10669
773
{
10670
773
    PyObject *u;
10671
773
    Py_UCS4 maxchar;
10672
773
    int kind;
10673
773
    void *data;
10674
10675
773
    if (left < 0)
10676
0
        left = 0;
10677
773
    if (right < 0)
10678
0
        right = 0;
10679
10680
773
    if (left == 0 && right == 0)
10681
0
        return unicode_result_unchanged(self);
10682
10683
773
    if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10684
773
        right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
10685
0
        PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10686
0
        return NULL;
10687
0
    }
10688
773
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10689
773
    maxchar = Py_MAX(maxchar, fill);
10690
773
    u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
10691
773
    if (!u)
10692
0
        return NULL;
10693
10694
773
    kind = PyUnicode_KIND(u);
10695
773
    data = PyUnicode_DATA(u);
10696
773
    if (left)
10697
0
        _PyUnicode_Fill(kind, data, fill, 0, left);
10698
773
    if (right)
10699
773
        _PyUnicode_Fill(kind, data, fill,
10700
773
                        left + _PyUnicode_LENGTH(self), right);
10701
773
    _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
10702
773
    assert(_PyUnicode_CheckConsistency(u, 1));
10703
773
    return u;
10704
773
}
10705
10706
PyObject *
10707
PyUnicode_Splitlines(PyObject *string, int keepends)
10708
16.4k
{
10709
16.4k
    PyObject *list;
10710
10711
16.4k
    if (ensure_unicode(string) < 0)
10712
0
        return NULL;
10713
10714
16.4k
    switch (PyUnicode_KIND(string)) {
10715
5.09k
    case PyUnicode_1BYTE_KIND:
10716
5.09k
        if (PyUnicode_IS_ASCII(string))
10717
4.07k
            list = asciilib_splitlines(
10718
4.07k
                string, PyUnicode_1BYTE_DATA(string),
10719
4.07k
                PyUnicode_GET_LENGTH(string), keepends);
10720
1.01k
        else
10721
1.01k
            list = ucs1lib_splitlines(
10722
1.01k
                string, PyUnicode_1BYTE_DATA(string),
10723
1.01k
                PyUnicode_GET_LENGTH(string), keepends);
10724
5.09k
        break;
10725
8.12k
    case PyUnicode_2BYTE_KIND:
10726
8.12k
        list = ucs2lib_splitlines(
10727
8.12k
            string, PyUnicode_2BYTE_DATA(string),
10728
8.12k
            PyUnicode_GET_LENGTH(string), keepends);
10729
8.12k
        break;
10730
3.25k
    case PyUnicode_4BYTE_KIND:
10731
3.25k
        list = ucs4lib_splitlines(
10732
3.25k
            string, PyUnicode_4BYTE_DATA(string),
10733
3.25k
            PyUnicode_GET_LENGTH(string), keepends);
10734
3.25k
        break;
10735
0
    default:
10736
0
        Py_UNREACHABLE();
10737
16.4k
    }
10738
16.4k
    return list;
10739
16.4k
}
10740
10741
static PyObject *
10742
split(PyObject *self,
10743
      PyObject *substring,
10744
      Py_ssize_t maxcount)
10745
22.7M
{
10746
22.7M
    int kind1, kind2;
10747
22.7M
    const void *buf1, *buf2;
10748
22.7M
    Py_ssize_t len1, len2;
10749
22.7M
    PyObject* out;
10750
22.7M
    len1 = PyUnicode_GET_LENGTH(self);
10751
22.7M
    kind1 = PyUnicode_KIND(self);
10752
10753
22.7M
    if (substring == NULL) {
10754
174k
        if (maxcount < 0) {
10755
155k
            maxcount = (len1 - 1) / 2 + 1;
10756
155k
        }
10757
174k
        switch (kind1) {
10758
97.5k
        case PyUnicode_1BYTE_KIND:
10759
97.5k
            if (PyUnicode_IS_ASCII(self))
10760
72.0k
                return asciilib_split_whitespace(
10761
72.0k
                    self,  PyUnicode_1BYTE_DATA(self),
10762
72.0k
                    len1, maxcount
10763
72.0k
                    );
10764
25.5k
            else
10765
25.5k
                return ucs1lib_split_whitespace(
10766
25.5k
                    self,  PyUnicode_1BYTE_DATA(self),
10767
25.5k
                    len1, maxcount
10768
25.5k
                    );
10769
63.7k
        case PyUnicode_2BYTE_KIND:
10770
63.7k
            return ucs2lib_split_whitespace(
10771
63.7k
                self,  PyUnicode_2BYTE_DATA(self),
10772
63.7k
                len1, maxcount
10773
63.7k
                );
10774
13.4k
        case PyUnicode_4BYTE_KIND:
10775
13.4k
            return ucs4lib_split_whitespace(
10776
13.4k
                self,  PyUnicode_4BYTE_DATA(self),
10777
13.4k
                len1, maxcount
10778
13.4k
                );
10779
0
        default:
10780
0
            Py_UNREACHABLE();
10781
174k
        }
10782
174k
    }
10783
10784
22.5M
    kind2 = PyUnicode_KIND(substring);
10785
22.5M
    len2 = PyUnicode_GET_LENGTH(substring);
10786
22.5M
    if (maxcount < 0) {
10787
        // if len2 == 0, it will raise ValueError.
10788
15.3M
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10789
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10790
15.3M
        maxcount = maxcount < 0 ? len1 : maxcount;
10791
15.3M
    }
10792
22.5M
    if (kind1 < kind2 || len1 < len2) {
10793
2.91M
        out = PyList_New(1);
10794
2.91M
        if (out == NULL)
10795
0
            return NULL;
10796
2.91M
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10797
2.91M
        return out;
10798
2.91M
    }
10799
19.6M
    buf1 = PyUnicode_DATA(self);
10800
19.6M
    buf2 = PyUnicode_DATA(substring);
10801
19.6M
    if (kind2 != kind1) {
10802
271k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10803
271k
        if (!buf2)
10804
0
            return NULL;
10805
271k
    }
10806
10807
19.6M
    switch (kind1) {
10808
19.3M
    case PyUnicode_1BYTE_KIND:
10809
19.3M
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10810
18.1M
            out = asciilib_split(
10811
18.1M
                self,  buf1, len1, buf2, len2, maxcount);
10812
1.17M
        else
10813
1.17M
            out = ucs1lib_split(
10814
1.17M
                self,  buf1, len1, buf2, len2, maxcount);
10815
19.3M
        break;
10816
231k
    case PyUnicode_2BYTE_KIND:
10817
231k
        out = ucs2lib_split(
10818
231k
            self,  buf1, len1, buf2, len2, maxcount);
10819
231k
        break;
10820
40.6k
    case PyUnicode_4BYTE_KIND:
10821
40.6k
        out = ucs4lib_split(
10822
40.6k
            self,  buf1, len1, buf2, len2, maxcount);
10823
40.6k
        break;
10824
0
    default:
10825
0
        out = NULL;
10826
19.6M
    }
10827
19.6M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10828
19.6M
    if (kind2 != kind1)
10829
271k
        PyMem_Free((void *)buf2);
10830
19.6M
    return out;
10831
19.6M
}
10832
10833
static PyObject *
10834
rsplit(PyObject *self,
10835
       PyObject *substring,
10836
       Py_ssize_t maxcount)
10837
66
{
10838
66
    int kind1, kind2;
10839
66
    const void *buf1, *buf2;
10840
66
    Py_ssize_t len1, len2;
10841
66
    PyObject* out;
10842
10843
66
    len1 = PyUnicode_GET_LENGTH(self);
10844
66
    kind1 = PyUnicode_KIND(self);
10845
10846
66
    if (substring == NULL) {
10847
0
        if (maxcount < 0) {
10848
0
            maxcount = (len1 - 1) / 2 + 1;
10849
0
        }
10850
0
        switch (kind1) {
10851
0
        case PyUnicode_1BYTE_KIND:
10852
0
            if (PyUnicode_IS_ASCII(self))
10853
0
                return asciilib_rsplit_whitespace(
10854
0
                    self,  PyUnicode_1BYTE_DATA(self),
10855
0
                    len1, maxcount
10856
0
                    );
10857
0
            else
10858
0
                return ucs1lib_rsplit_whitespace(
10859
0
                    self,  PyUnicode_1BYTE_DATA(self),
10860
0
                    len1, maxcount
10861
0
                    );
10862
0
        case PyUnicode_2BYTE_KIND:
10863
0
            return ucs2lib_rsplit_whitespace(
10864
0
                self,  PyUnicode_2BYTE_DATA(self),
10865
0
                len1, maxcount
10866
0
                );
10867
0
        case PyUnicode_4BYTE_KIND:
10868
0
            return ucs4lib_rsplit_whitespace(
10869
0
                self,  PyUnicode_4BYTE_DATA(self),
10870
0
                len1, maxcount
10871
0
                );
10872
0
        default:
10873
0
            Py_UNREACHABLE();
10874
0
        }
10875
0
    }
10876
66
    kind2 = PyUnicode_KIND(substring);
10877
66
    len2 = PyUnicode_GET_LENGTH(substring);
10878
66
    if (maxcount < 0) {
10879
        // if len2 == 0, it will raise ValueError.
10880
0
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10881
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10882
0
        maxcount = maxcount < 0 ? len1 : maxcount;
10883
0
    }
10884
66
    if (kind1 < kind2 || len1 < len2) {
10885
0
        out = PyList_New(1);
10886
0
        if (out == NULL)
10887
0
            return NULL;
10888
0
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10889
0
        return out;
10890
0
    }
10891
66
    buf1 = PyUnicode_DATA(self);
10892
66
    buf2 = PyUnicode_DATA(substring);
10893
66
    if (kind2 != kind1) {
10894
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10895
0
        if (!buf2)
10896
0
            return NULL;
10897
0
    }
10898
10899
66
    switch (kind1) {
10900
66
    case PyUnicode_1BYTE_KIND:
10901
66
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10902
66
            out = asciilib_rsplit(
10903
66
                self,  buf1, len1, buf2, len2, maxcount);
10904
0
        else
10905
0
            out = ucs1lib_rsplit(
10906
0
                self,  buf1, len1, buf2, len2, maxcount);
10907
66
        break;
10908
0
    case PyUnicode_2BYTE_KIND:
10909
0
        out = ucs2lib_rsplit(
10910
0
            self,  buf1, len1, buf2, len2, maxcount);
10911
0
        break;
10912
0
    case PyUnicode_4BYTE_KIND:
10913
0
        out = ucs4lib_rsplit(
10914
0
            self,  buf1, len1, buf2, len2, maxcount);
10915
0
        break;
10916
0
    default:
10917
0
        out = NULL;
10918
66
    }
10919
66
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10920
66
    if (kind2 != kind1)
10921
0
        PyMem_Free((void *)buf2);
10922
66
    return out;
10923
66
}
10924
10925
static Py_ssize_t
10926
anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
10927
            PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
10928
22.8M
{
10929
22.8M
    switch (kind) {
10930
9.02M
    case PyUnicode_1BYTE_KIND:
10931
9.02M
        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10932
4.25M
            return asciilib_find(buf1, len1, buf2, len2, offset);
10933
4.77M
        else
10934
4.77M
            return ucs1lib_find(buf1, len1, buf2, len2, offset);
10935
6.50M
    case PyUnicode_2BYTE_KIND:
10936
6.50M
        return ucs2lib_find(buf1, len1, buf2, len2, offset);
10937
7.35M
    case PyUnicode_4BYTE_KIND:
10938
7.35M
        return ucs4lib_find(buf1, len1, buf2, len2, offset);
10939
22.8M
    }
10940
22.8M
    Py_UNREACHABLE();
10941
22.8M
}
10942
10943
static Py_ssize_t
10944
anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
10945
             PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
10946
10.1M
{
10947
10.1M
    switch (kind) {
10948
9.36M
    case PyUnicode_1BYTE_KIND:
10949
9.36M
        return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10950
670k
    case PyUnicode_2BYTE_KIND:
10951
670k
        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10952
80.1k
    case PyUnicode_4BYTE_KIND:
10953
80.1k
        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10954
10.1M
    }
10955
10.1M
    Py_UNREACHABLE();
10956
10.1M
}
10957
10958
static void
10959
replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10960
                      Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10961
61.0k
{
10962
61.0k
    int kind = PyUnicode_KIND(u);
10963
61.0k
    void *data = PyUnicode_DATA(u);
10964
61.0k
    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10965
61.0k
    if (kind == PyUnicode_1BYTE_KIND) {
10966
37.5k
        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10967
37.5k
                                      (Py_UCS1 *)data + len,
10968
37.5k
                                      u1, u2, maxcount);
10969
37.5k
    }
10970
23.5k
    else if (kind == PyUnicode_2BYTE_KIND) {
10971
19.5k
        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10972
19.5k
                                      (Py_UCS2 *)data + len,
10973
19.5k
                                      u1, u2, maxcount);
10974
19.5k
    }
10975
3.99k
    else {
10976
3.99k
        assert(kind == PyUnicode_4BYTE_KIND);
10977
3.99k
        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10978
3.99k
                                      (Py_UCS4 *)data + len,
10979
3.99k
                                      u1, u2, maxcount);
10980
3.99k
    }
10981
61.0k
}
10982
10983
static PyObject *
10984
replace(PyObject *self, PyObject *str1,
10985
        PyObject *str2, Py_ssize_t maxcount)
10986
20.6M
{
10987
20.6M
    PyObject *u;
10988
20.6M
    const char *sbuf = PyUnicode_DATA(self);
10989
20.6M
    const void *buf1 = PyUnicode_DATA(str1);
10990
20.6M
    const void *buf2 = PyUnicode_DATA(str2);
10991
20.6M
    int srelease = 0, release1 = 0, release2 = 0;
10992
20.6M
    int skind = PyUnicode_KIND(self);
10993
20.6M
    int kind1 = PyUnicode_KIND(str1);
10994
20.6M
    int kind2 = PyUnicode_KIND(str2);
10995
20.6M
    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10996
20.6M
    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10997
20.6M
    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
10998
20.6M
    int mayshrink;
10999
20.6M
    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
11000
11001
20.6M
    if (slen < len1)
11002
10.1M
        goto nothing;
11003
11004
10.5M
    if (maxcount < 0)
11005
10.5M
        maxcount = PY_SSIZE_T_MAX;
11006
0
    else if (maxcount == 0)
11007
0
        goto nothing;
11008
11009
10.5M
    if (str1 == str2)
11010
0
        goto nothing;
11011
11012
10.5M
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
11013
10.5M
    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
11014
10.5M
    if (maxchar < maxchar_str1)
11015
        /* substring too wide to be present */
11016
0
        goto nothing;
11017
10.5M
    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
11018
    /* Replacing str1 with str2 may cause a maxchar reduction in the
11019
       result string. */
11020
10.5M
    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
11021
10.5M
    maxchar = Py_MAX(maxchar, maxchar_str2);
11022
11023
10.5M
    if (len1 == len2) {
11024
        /* same length */
11025
453k
        if (len1 == 0)
11026
0
            goto nothing;
11027
453k
        if (len1 == 1) {
11028
            /* replace characters */
11029
447k
            Py_UCS4 u1, u2;
11030
447k
            Py_ssize_t pos;
11031
11032
447k
            u1 = PyUnicode_READ(kind1, buf1, 0);
11033
447k
            pos = findchar(sbuf, skind, slen, u1, 1);
11034
447k
            if (pos < 0)
11035
386k
                goto nothing;
11036
61.0k
            u2 = PyUnicode_READ(kind2, buf2, 0);
11037
61.0k
            u = PyUnicode_New(slen, maxchar);
11038
61.0k
            if (!u)
11039
0
                goto error;
11040
11041
61.0k
            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
11042
61.0k
            replace_1char_inplace(u, pos, u1, u2, maxcount);
11043
61.0k
        }
11044
5.32k
        else {
11045
5.32k
            int rkind = skind;
11046
5.32k
            char *res;
11047
5.32k
            Py_ssize_t i;
11048
11049
5.32k
            if (kind1 < rkind) {
11050
                /* widen substring */
11051
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
11052
0
                if (!buf1) goto error;
11053
0
                release1 = 1;
11054
0
            }
11055
5.32k
            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
11056
5.32k
            if (i < 0)
11057
5.32k
                goto nothing;
11058
0
            if (rkind > kind2) {
11059
                /* widen replacement */
11060
0
                buf2 = unicode_askind(kind2, buf2, len2, rkind);
11061
0
                if (!buf2) goto error;
11062
0
                release2 = 1;
11063
0
            }
11064
0
            else if (rkind < kind2) {
11065
                /* widen self and buf1 */
11066
0
                rkind = kind2;
11067
0
                if (release1) {
11068
0
                    assert(buf1 != PyUnicode_DATA(str1));
11069
0
                    PyMem_Free((void *)buf1);
11070
0
                    buf1 = PyUnicode_DATA(str1);
11071
0
                    release1 = 0;
11072
0
                }
11073
0
                sbuf = unicode_askind(skind, sbuf, slen, rkind);
11074
0
                if (!sbuf) goto error;
11075
0
                srelease = 1;
11076
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
11077
0
                if (!buf1) goto error;
11078
0
                release1 = 1;
11079
0
            }
11080
0
            u = PyUnicode_New(slen, maxchar);
11081
0
            if (!u)
11082
0
                goto error;
11083
0
            assert(PyUnicode_KIND(u) == rkind);
11084
0
            res = PyUnicode_DATA(u);
11085
11086
0
            memcpy(res, sbuf, rkind * slen);
11087
            /* change everything in-place, starting with this one */
11088
0
            memcpy(res + rkind * i,
11089
0
                   buf2,
11090
0
                   rkind * len2);
11091
0
            i += len1;
11092
11093
0
            while ( --maxcount > 0) {
11094
0
                i = anylib_find(rkind, self,
11095
0
                                sbuf+rkind*i, slen-i,
11096
0
                                str1, buf1, len1, i);
11097
0
                if (i == -1)
11098
0
                    break;
11099
0
                memcpy(res + rkind * i,
11100
0
                       buf2,
11101
0
                       rkind * len2);
11102
0
                i += len1;
11103
0
            }
11104
0
        }
11105
453k
    }
11106
10.1M
    else {
11107
10.1M
        Py_ssize_t n, i, j, ires;
11108
10.1M
        Py_ssize_t new_size;
11109
10.1M
        int rkind = skind;
11110
10.1M
        char *res;
11111
11112
10.1M
        if (kind1 < rkind) {
11113
            /* widen substring */
11114
750k
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11115
750k
            if (!buf1) goto error;
11116
750k
            release1 = 1;
11117
750k
        }
11118
10.1M
        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
11119
10.1M
        if (n == 0)
11120
8.96M
            goto nothing;
11121
1.15M
        if (kind2 < rkind) {
11122
            /* widen replacement */
11123
40.6k
            buf2 = unicode_askind(kind2, buf2, len2, rkind);
11124
40.6k
            if (!buf2) goto error;
11125
40.6k
            release2 = 1;
11126
40.6k
        }
11127
1.11M
        else if (kind2 > rkind) {
11128
            /* widen self and buf1 */
11129
0
            rkind = kind2;
11130
0
            sbuf = unicode_askind(skind, sbuf, slen, rkind);
11131
0
            if (!sbuf) goto error;
11132
0
            srelease = 1;
11133
0
            if (release1) {
11134
0
                assert(buf1 != PyUnicode_DATA(str1));
11135
0
                PyMem_Free((void *)buf1);
11136
0
                buf1 = PyUnicode_DATA(str1);
11137
0
                release1 = 0;
11138
0
            }
11139
0
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11140
0
            if (!buf1) goto error;
11141
0
            release1 = 1;
11142
0
        }
11143
        /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
11144
           PyUnicode_GET_LENGTH(str1)); */
11145
1.15M
        if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
11146
0
                PyErr_SetString(PyExc_OverflowError,
11147
0
                                "replace string is too long");
11148
0
                goto error;
11149
0
        }
11150
1.15M
        new_size = slen + n * (len2 - len1);
11151
1.15M
        if (new_size == 0) {
11152
4
            u = _PyUnicode_GetEmpty();
11153
4
            goto done;
11154
4
        }
11155
1.15M
        if (new_size > (PY_SSIZE_T_MAX / rkind)) {
11156
0
            PyErr_SetString(PyExc_OverflowError,
11157
0
                            "replace string is too long");
11158
0
            goto error;
11159
0
        }
11160
1.15M
        u = PyUnicode_New(new_size, maxchar);
11161
1.15M
        if (!u)
11162
0
            goto error;
11163
1.15M
        assert(PyUnicode_KIND(u) == rkind);
11164
1.15M
        res = PyUnicode_DATA(u);
11165
1.15M
        ires = i = 0;
11166
1.15M
        if (len1 > 0) {
11167
24.0M
            while (n-- > 0) {
11168
                /* look for next match */
11169
22.8M
                j = anylib_find(rkind, self,
11170
22.8M
                                sbuf + rkind * i, slen-i,
11171
22.8M
                                str1, buf1, len1, i);
11172
22.8M
                if (j == -1)
11173
0
                    break;
11174
22.8M
                else if (j > i) {
11175
                    /* copy unchanged part [i:j] */
11176
3.97M
                    memcpy(res + rkind * ires,
11177
3.97M
                           sbuf + rkind * i,
11178
3.97M
                           rkind * (j-i));
11179
3.97M
                    ires += j - i;
11180
3.97M
                }
11181
                /* copy substitution string */
11182
22.8M
                if (len2 > 0) {
11183
22.6M
                    memcpy(res + rkind * ires,
11184
22.6M
                           buf2,
11185
22.6M
                           rkind * len2);
11186
22.6M
                    ires += len2;
11187
22.6M
                }
11188
22.8M
                i = j + len1;
11189
22.8M
            }
11190
1.15M
            if (i < slen)
11191
                /* copy tail [i:] */
11192
1.14M
                memcpy(res + rkind * ires,
11193
1.14M
                       sbuf + rkind * i,
11194
1.14M
                       rkind * (slen-i));
11195
1.15M
        }
11196
0
        else {
11197
            /* interleave */
11198
0
            while (n > 0) {
11199
0
                memcpy(res + rkind * ires,
11200
0
                       buf2,
11201
0
                       rkind * len2);
11202
0
                ires += len2;
11203
0
                if (--n <= 0)
11204
0
                    break;
11205
0
                memcpy(res + rkind * ires,
11206
0
                       sbuf + rkind * i,
11207
0
                       rkind);
11208
0
                ires++;
11209
0
                i++;
11210
0
            }
11211
0
            memcpy(res + rkind * ires,
11212
0
                   sbuf + rkind * i,
11213
0
                   rkind * (slen-i));
11214
0
        }
11215
1.15M
    }
11216
11217
1.21M
    if (mayshrink) {
11218
0
        unicode_adjust_maxchar(&u);
11219
0
        if (u == NULL)
11220
0
            goto error;
11221
0
    }
11222
11223
1.21M
  done:
11224
1.21M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11225
1.21M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11226
1.21M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11227
1.21M
    if (srelease)
11228
0
        PyMem_Free((void *)sbuf);
11229
1.21M
    if (release1)
11230
40.6k
        PyMem_Free((void *)buf1);
11231
1.21M
    if (release2)
11232
40.6k
        PyMem_Free((void *)buf2);
11233
1.21M
    assert(_PyUnicode_CheckConsistency(u, 1));
11234
1.21M
    return u;
11235
11236
19.4M
  nothing:
11237
    /* nothing to replace; return original string (when possible) */
11238
19.4M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11239
19.4M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11240
19.4M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11241
19.4M
    if (srelease)
11242
0
        PyMem_Free((void *)sbuf);
11243
19.4M
    if (release1)
11244
710k
        PyMem_Free((void *)buf1);
11245
19.4M
    if (release2)
11246
0
        PyMem_Free((void *)buf2);
11247
19.4M
    return unicode_result_unchanged(self);
11248
11249
0
  error:
11250
0
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11251
0
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11252
0
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11253
0
    if (srelease)
11254
0
        PyMem_Free((void *)sbuf);
11255
0
    if (release1)
11256
0
        PyMem_Free((void *)buf1);
11257
0
    if (release2)
11258
0
        PyMem_Free((void *)buf2);
11259
0
    return NULL;
11260
1.21M
}
11261
11262
/* --- Unicode Object Methods --------------------------------------------- */
11263
11264
/*[clinic input]
11265
str.title as unicode_title
11266
11267
Return a version of the string where each word is titlecased.
11268
11269
More specifically, words start with uppercased characters and all
11270
remaining cased characters have lower case.
11271
[clinic start generated code]*/
11272
11273
static PyObject *
11274
unicode_title_impl(PyObject *self)
11275
/*[clinic end generated code: output=c75ae03809574902 input=2a07e2c7df94627a]*/
11276
0
{
11277
0
    return case_operation(self, do_title);
11278
0
}
11279
11280
/*[clinic input]
11281
str.capitalize as unicode_capitalize
11282
11283
Return a capitalized version of the string.
11284
11285
More specifically, make the first character have upper case and the
11286
rest lower case.
11287
[clinic start generated code]*/
11288
11289
static PyObject *
11290
unicode_capitalize_impl(PyObject *self)
11291
/*[clinic end generated code: output=e49a4c333cdb7667 input=e50e50ed45a654cf]*/
11292
0
{
11293
0
    if (PyUnicode_GET_LENGTH(self) == 0)
11294
0
        return unicode_result_unchanged(self);
11295
0
    return case_operation(self, do_capitalize);
11296
0
}
11297
11298
/*[clinic input]
11299
str.casefold as unicode_casefold
11300
11301
Return a version of the string suitable for caseless comparisons.
11302
[clinic start generated code]*/
11303
11304
static PyObject *
11305
unicode_casefold_impl(PyObject *self)
11306
/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
11307
0
{
11308
0
    if (PyUnicode_IS_ASCII(self))
11309
0
        return ascii_upper_or_lower(self, 1);
11310
0
    return case_operation(self, do_casefold);
11311
0
}
11312
11313
11314
/* Argument converter. Accepts a single Unicode character. */
11315
11316
static int
11317
convert_uc(PyObject *obj, void *addr)
11318
1.13k
{
11319
1.13k
    Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
11320
11321
1.13k
    if (!PyUnicode_Check(obj)) {
11322
0
        PyErr_Format(PyExc_TypeError,
11323
0
                     "The fill character must be a unicode character, "
11324
0
                     "not %.100s", Py_TYPE(obj)->tp_name);
11325
0
        return 0;
11326
0
    }
11327
1.13k
    if (PyUnicode_GET_LENGTH(obj) != 1) {
11328
0
        PyErr_SetString(PyExc_TypeError,
11329
0
                        "The fill character must be exactly one character long");
11330
0
        return 0;
11331
0
    }
11332
1.13k
    *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
11333
1.13k
    return 1;
11334
1.13k
}
11335
11336
/*[clinic input]
11337
str.center as unicode_center
11338
11339
    width: Py_ssize_t
11340
    fillchar: Py_UCS4 = ' '
11341
    /
11342
11343
Return a centered string of length width.
11344
11345
Padding is done using the specified fill character (default is
11346
a space).
11347
[clinic start generated code]*/
11348
11349
static PyObject *
11350
unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
11351
/*[clinic end generated code: output=420c8859effc7c0c input=df91017dfd186a78]*/
11352
0
{
11353
0
    Py_ssize_t marg, left;
11354
11355
0
    if (PyUnicode_GET_LENGTH(self) >= width)
11356
0
        return unicode_result_unchanged(self);
11357
11358
0
    marg = width - PyUnicode_GET_LENGTH(self);
11359
0
    left = marg / 2 + (marg & width & 1);
11360
11361
0
    return pad(self, left, marg - left, fillchar);
11362
0
}
11363
11364
/* This function assumes that str1 and str2 are readied by the caller. */
11365
11366
static int
11367
unicode_compare(PyObject *str1, PyObject *str2)
11368
22.6M
{
11369
22.6M
#define COMPARE(TYPE1, TYPE2) \
11370
22.6M
    do { \
11371
21.4M
        TYPE1* p1 = (TYPE1 *)data1; \
11372
21.4M
        TYPE2* p2 = (TYPE2 *)data2; \
11373
21.4M
        TYPE1* end = p1 + len; \
11374
21.4M
        Py_UCS4 c1, c2; \
11375
21.4M
        for (; p1 != end; p1++, p2++) { \
11376
21.4M
            c1 = *p1; \
11377
21.4M
            c2 = *p2; \
11378
21.4M
            if (c1 != c2) \
11379
21.4M
                return (c1 < c2) ? -1 : 1; \
11380
21.4M
        } \
11381
21.4M
    } \
11382
21.4M
    while (0)
11383
11384
22.6M
    int kind1, kind2;
11385
22.6M
    const void *data1, *data2;
11386
22.6M
    Py_ssize_t len1, len2, len;
11387
11388
22.6M
    kind1 = PyUnicode_KIND(str1);
11389
22.6M
    kind2 = PyUnicode_KIND(str2);
11390
22.6M
    data1 = PyUnicode_DATA(str1);
11391
22.6M
    data2 = PyUnicode_DATA(str2);
11392
22.6M
    len1 = PyUnicode_GET_LENGTH(str1);
11393
22.6M
    len2 = PyUnicode_GET_LENGTH(str2);
11394
22.6M
    len = Py_MIN(len1, len2);
11395
11396
22.6M
    switch(kind1) {
11397
5.02M
    case PyUnicode_1BYTE_KIND:
11398
5.02M
    {
11399
5.02M
        switch(kind2) {
11400
761k
        case PyUnicode_1BYTE_KIND:
11401
761k
        {
11402
761k
            int cmp = memcmp(data1, data2, len);
11403
            /* normalize result of memcmp() into the range [-1; 1] */
11404
761k
            if (cmp < 0)
11405
665k
                return -1;
11406
96.1k
            if (cmp > 0)
11407
90.5k
                return 1;
11408
5.52k
            break;
11409
96.1k
        }
11410
3.18M
        case PyUnicode_2BYTE_KIND:
11411
3.18M
            COMPARE(Py_UCS1, Py_UCS2);
11412
0
            break;
11413
1.07M
        case PyUnicode_4BYTE_KIND:
11414
1.07M
            COMPARE(Py_UCS1, Py_UCS4);
11415
0
            break;
11416
0
        default:
11417
0
            Py_UNREACHABLE();
11418
5.02M
        }
11419
5.52k
        break;
11420
5.02M
    }
11421
17.2M
    case PyUnicode_2BYTE_KIND:
11422
17.2M
    {
11423
17.2M
        switch(kind2) {
11424
9.03k
        case PyUnicode_1BYTE_KIND:
11425
9.03k
            COMPARE(Py_UCS2, Py_UCS1);
11426
0
            break;
11427
17.2M
        case PyUnicode_2BYTE_KIND:
11428
17.2M
        {
11429
17.2M
            COMPARE(Py_UCS2, Py_UCS2);
11430
0
            break;
11431
17.2M
        }
11432
3.17k
        case PyUnicode_4BYTE_KIND:
11433
3.17k
            COMPARE(Py_UCS2, Py_UCS4);
11434
0
            break;
11435
0
        default:
11436
0
            Py_UNREACHABLE();
11437
17.2M
        }
11438
0
        break;
11439
17.2M
    }
11440
359k
    case PyUnicode_4BYTE_KIND:
11441
359k
    {
11442
359k
        switch(kind2) {
11443
592
        case PyUnicode_1BYTE_KIND:
11444
592
            COMPARE(Py_UCS4, Py_UCS1);
11445
0
            break;
11446
3.21k
        case PyUnicode_2BYTE_KIND:
11447
3.21k
            COMPARE(Py_UCS4, Py_UCS2);
11448
0
            break;
11449
355k
        case PyUnicode_4BYTE_KIND:
11450
355k
        {
11451
355k
#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11452
355k
            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11453
            /* normalize result of wmemcmp() into the range [-1; 1] */
11454
355k
            if (cmp < 0)
11455
159k
                return -1;
11456
195k
            if (cmp > 0)
11457
195k
                return 1;
11458
#else
11459
            COMPARE(Py_UCS4, Py_UCS4);
11460
#endif
11461
0
            break;
11462
195k
        }
11463
0
        default:
11464
0
            Py_UNREACHABLE();
11465
359k
        }
11466
0
        break;
11467
359k
    }
11468
0
    default:
11469
0
        Py_UNREACHABLE();
11470
22.6M
    }
11471
11472
5.52k
    if (len1 == len2)
11473
5.49k
        return 0;
11474
37
    if (len1 < len2)
11475
12
        return -1;
11476
25
    else
11477
25
        return 1;
11478
11479
37
#undef COMPARE
11480
37
}
11481
11482
11483
int
11484
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
11485
613M
{
11486
613M
    assert(PyUnicode_Check(str1));
11487
613M
    assert(PyUnicode_Check(str2));
11488
613M
    if (str1 == str2) {
11489
83.7M
        return 1;
11490
83.7M
    }
11491
529M
    return unicode_eq(str1, str2);
11492
613M
}
11493
11494
11495
int
11496
PyUnicode_Equal(PyObject *str1, PyObject *str2)
11497
0
{
11498
0
    if (!PyUnicode_Check(str1)) {
11499
0
        PyErr_Format(PyExc_TypeError,
11500
0
                     "first argument must be str, not %T", str1);
11501
0
        return -1;
11502
0
    }
11503
0
    if (!PyUnicode_Check(str2)) {
11504
0
        PyErr_Format(PyExc_TypeError,
11505
0
                     "second argument must be str, not %T", str2);
11506
0
        return -1;
11507
0
    }
11508
11509
0
    return _PyUnicode_Equal(str1, str2);
11510
0
}
11511
11512
11513
int
11514
PyUnicode_Compare(PyObject *left, PyObject *right)
11515
240k
{
11516
240k
    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11517
        /* a string is equal to itself */
11518
240k
        if (left == right)
11519
0
            return 0;
11520
11521
240k
        return unicode_compare(left, right);
11522
240k
    }
11523
0
    PyErr_Format(PyExc_TypeError,
11524
0
                 "Can't compare %.100s and %.100s",
11525
0
                 Py_TYPE(left)->tp_name,
11526
0
                 Py_TYPE(right)->tp_name);
11527
0
    return -1;
11528
240k
}
11529
11530
int
11531
PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11532
27.0M
{
11533
27.0M
    Py_ssize_t i;
11534
27.0M
    int kind;
11535
27.0M
    Py_UCS4 chr;
11536
11537
27.0M
    assert(_PyUnicode_CHECK(uni));
11538
27.0M
    kind = PyUnicode_KIND(uni);
11539
27.0M
    if (kind == PyUnicode_1BYTE_KIND) {
11540
27.0M
        const void *data = PyUnicode_1BYTE_DATA(uni);
11541
27.0M
        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
11542
27.0M
        size_t len, len2 = strlen(str);
11543
27.0M
        int cmp;
11544
11545
27.0M
        len = Py_MIN(len1, len2);
11546
27.0M
        cmp = memcmp(data, str, len);
11547
27.0M
        if (cmp != 0) {
11548
15.6M
            if (cmp < 0)
11549
40.8k
                return -1;
11550
15.5M
            else
11551
15.5M
                return 1;
11552
15.6M
        }
11553
11.4M
        if (len1 > len2)
11554
198
            return 1; /* uni is longer */
11555
11.4M
        if (len1 < len2)
11556
957
            return -1; /* str is longer */
11557
11.4M
        return 0;
11558
11.4M
    }
11559
2.15k
    else {
11560
2.15k
        const void *data = PyUnicode_DATA(uni);
11561
        /* Compare Unicode string and source character set string */
11562
3.65k
        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
11563
3.43k
            if (chr != (unsigned char)str[i])
11564
1.94k
                return (chr < (unsigned char)(str[i])) ? -1 : 1;
11565
        /* This check keeps Python strings that end in '\0' from comparing equal
11566
         to C strings identical up to that point. */
11567
219
        if (PyUnicode_GET_LENGTH(uni) != i || chr)
11568
219
            return 1; /* uni is longer */
11569
0
        if (str[i])
11570
0
            return -1; /* str is longer */
11571
0
        return 0;
11572
0
    }
11573
27.0M
}
11574
11575
int
11576
PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
11577
24
{
11578
24
    return PyUnicode_EqualToUTF8AndSize(unicode, str, strlen(str));
11579
24
}
11580
11581
int
11582
PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t size)
11583
24
{
11584
24
    assert(_PyUnicode_CHECK(unicode));
11585
24
    assert(str);
11586
11587
24
    if (PyUnicode_IS_ASCII(unicode)) {
11588
24
        Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11589
24
        return size == len &&
11590
0
            memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11591
24
    }
11592
0
    if (PyUnicode_UTF8(unicode) != NULL) {
11593
0
        Py_ssize_t len = PyUnicode_UTF8_LENGTH(unicode);
11594
0
        return size == len &&
11595
0
            memcmp(PyUnicode_UTF8(unicode), str, len) == 0;
11596
0
    }
11597
11598
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11599
0
    if ((size_t)len >= (size_t)size || (size_t)len < (size_t)size / 4) {
11600
0
        return 0;
11601
0
    }
11602
0
    const unsigned char *s = (const unsigned char *)str;
11603
0
    const unsigned char *ends = s + (size_t)size;
11604
0
    int kind = PyUnicode_KIND(unicode);
11605
0
    const void *data = PyUnicode_DATA(unicode);
11606
    /* Compare Unicode string and UTF-8 string */
11607
0
    for (Py_ssize_t i = 0; i < len; i++) {
11608
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11609
0
        if (ch < 0x80) {
11610
0
            if (ends == s || s[0] != ch) {
11611
0
                return 0;
11612
0
            }
11613
0
            s += 1;
11614
0
        }
11615
0
        else if (ch < 0x800) {
11616
0
            if ((ends - s) < 2 ||
11617
0
                s[0] != (0xc0 | (ch >> 6)) ||
11618
0
                s[1] != (0x80 | (ch & 0x3f)))
11619
0
            {
11620
0
                return 0;
11621
0
            }
11622
0
            s += 2;
11623
0
        }
11624
0
        else if (ch < 0x10000) {
11625
0
            if (Py_UNICODE_IS_SURROGATE(ch) ||
11626
0
                (ends - s) < 3 ||
11627
0
                s[0] != (0xe0 | (ch >> 12)) ||
11628
0
                s[1] != (0x80 | ((ch >> 6) & 0x3f)) ||
11629
0
                s[2] != (0x80 | (ch & 0x3f)))
11630
0
            {
11631
0
                return 0;
11632
0
            }
11633
0
            s += 3;
11634
0
        }
11635
0
        else {
11636
0
            assert(ch <= MAX_UNICODE);
11637
0
            if ((ends - s) < 4 ||
11638
0
                s[0] != (0xf0 | (ch >> 18)) ||
11639
0
                s[1] != (0x80 | ((ch >> 12) & 0x3f)) ||
11640
0
                s[2] != (0x80 | ((ch >> 6) & 0x3f)) ||
11641
0
                s[3] != (0x80 | (ch & 0x3f)))
11642
0
            {
11643
0
                return 0;
11644
0
            }
11645
0
            s += 4;
11646
0
        }
11647
0
    }
11648
0
    return s == ends;
11649
0
}
11650
11651
int
11652
_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11653
2.49M
{
11654
2.49M
    size_t len;
11655
2.49M
    assert(_PyUnicode_CHECK(unicode));
11656
2.49M
    assert(str);
11657
#ifndef NDEBUG
11658
    for (const char *p = str; *p; p++) {
11659
        assert((unsigned char)*p < 128);
11660
    }
11661
#endif
11662
2.49M
    if (!PyUnicode_IS_ASCII(unicode))
11663
10.6k
        return 0;
11664
2.48M
    len = (size_t)PyUnicode_GET_LENGTH(unicode);
11665
2.48M
    return strlen(str) == len &&
11666
314k
           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11667
2.49M
}
11668
11669
PyObject *
11670
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
11671
51.3M
{
11672
51.3M
    int result;
11673
11674
51.3M
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11675
196k
        Py_RETURN_NOTIMPLEMENTED;
11676
11677
51.1M
    if (left == right) {
11678
3.14k
        switch (op) {
11679
2.84k
        case Py_EQ:
11680
2.84k
        case Py_LE:
11681
2.84k
        case Py_GE:
11682
            /* a string is equal to itself */
11683
2.84k
            Py_RETURN_TRUE;
11684
303
        case Py_NE:
11685
303
        case Py_LT:
11686
303
        case Py_GT:
11687
303
            Py_RETURN_FALSE;
11688
0
        default:
11689
0
            PyErr_BadArgument();
11690
0
            return NULL;
11691
3.14k
        }
11692
3.14k
    }
11693
51.1M
    else if (op == Py_EQ || op == Py_NE) {
11694
28.7M
        result = unicode_eq(left, right);
11695
28.7M
        result ^= (op == Py_NE);
11696
28.7M
        return PyBool_FromLong(result);
11697
28.7M
    }
11698
22.3M
    else {
11699
22.3M
        result = unicode_compare(left, right);
11700
22.3M
        Py_RETURN_RICHCOMPARE(result, 0, op);
11701
22.3M
    }
11702
51.1M
}
11703
11704
int
11705
PyUnicode_Contains(PyObject *str, PyObject *substr)
11706
212M
{
11707
212M
    int kind1, kind2;
11708
212M
    const void *buf1, *buf2;
11709
212M
    Py_ssize_t len1, len2;
11710
212M
    int result;
11711
11712
212M
    if (!PyUnicode_Check(substr)) {
11713
0
        PyErr_Format(PyExc_TypeError,
11714
0
                     "'in <string>' requires string as left operand, not %.100s",
11715
0
                     Py_TYPE(substr)->tp_name);
11716
0
        return -1;
11717
0
    }
11718
212M
    if (ensure_unicode(str) < 0)
11719
0
        return -1;
11720
11721
212M
    kind1 = PyUnicode_KIND(str);
11722
212M
    kind2 = PyUnicode_KIND(substr);
11723
212M
    if (kind1 < kind2)
11724
18.9M
        return 0;
11725
193M
    len1 = PyUnicode_GET_LENGTH(str);
11726
193M
    len2 = PyUnicode_GET_LENGTH(substr);
11727
193M
    if (len1 < len2)
11728
1.01M
        return 0;
11729
192M
    buf1 = PyUnicode_DATA(str);
11730
192M
    buf2 = PyUnicode_DATA(substr);
11731
192M
    if (len2 == 1) {
11732
169M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11733
169M
        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11734
169M
        return result;
11735
169M
    }
11736
23.3M
    if (kind2 != kind1) {
11737
17.3k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11738
17.3k
        if (!buf2)
11739
0
            return -1;
11740
17.3k
    }
11741
11742
23.3M
    switch (kind1) {
11743
23.3M
    case PyUnicode_1BYTE_KIND:
11744
23.3M
        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11745
23.3M
        break;
11746
12.3k
    case PyUnicode_2BYTE_KIND:
11747
12.3k
        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11748
12.3k
        break;
11749
5.00k
    case PyUnicode_4BYTE_KIND:
11750
5.00k
        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11751
5.00k
        break;
11752
0
    default:
11753
0
        Py_UNREACHABLE();
11754
23.3M
    }
11755
11756
23.3M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
11757
23.3M
    if (kind2 != kind1)
11758
17.3k
        PyMem_Free((void *)buf2);
11759
11760
23.3M
    return result;
11761
23.3M
}
11762
11763
/* Concat to string or Unicode object giving a new Unicode object. */
11764
11765
PyObject *
11766
PyUnicode_Concat(PyObject *left, PyObject *right)
11767
27.8M
{
11768
27.8M
    PyObject *result;
11769
27.8M
    Py_UCS4 maxchar, maxchar2;
11770
27.8M
    Py_ssize_t left_len, right_len, new_len;
11771
11772
27.8M
    if (ensure_unicode(left) < 0)
11773
0
        return NULL;
11774
11775
27.8M
    if (!PyUnicode_Check(right)) {
11776
0
        PyErr_Format(PyExc_TypeError,
11777
0
            "can only concatenate str (not \"%.200s\") to str",
11778
0
            Py_TYPE(right)->tp_name);
11779
0
        return NULL;
11780
0
    }
11781
11782
    /* Shortcuts */
11783
27.8M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11784
27.8M
    if (left == empty) {
11785
1.21M
        return PyUnicode_FromObject(right);
11786
1.21M
    }
11787
26.6M
    if (right == empty) {
11788
2.51M
        return PyUnicode_FromObject(left);
11789
2.51M
    }
11790
11791
24.1M
    left_len = PyUnicode_GET_LENGTH(left);
11792
24.1M
    right_len = PyUnicode_GET_LENGTH(right);
11793
24.1M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11794
0
        PyErr_SetString(PyExc_OverflowError,
11795
0
                        "strings are too large to concat");
11796
0
        return NULL;
11797
0
    }
11798
24.1M
    new_len = left_len + right_len;
11799
11800
24.1M
    maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11801
24.1M
    maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11802
24.1M
    maxchar = Py_MAX(maxchar, maxchar2);
11803
11804
    /* Concat the two Unicode strings */
11805
24.1M
    result = PyUnicode_New(new_len, maxchar);
11806
24.1M
    if (result == NULL)
11807
0
        return NULL;
11808
24.1M
    _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11809
24.1M
    _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11810
24.1M
    assert(_PyUnicode_CheckConsistency(result, 1));
11811
24.1M
    return result;
11812
24.1M
}
11813
11814
void
11815
PyUnicode_Append(PyObject **p_left, PyObject *right)
11816
8.38M
{
11817
8.38M
    PyObject *left, *res;
11818
8.38M
    Py_UCS4 maxchar, maxchar2;
11819
8.38M
    Py_ssize_t left_len, right_len, new_len;
11820
11821
8.38M
    if (p_left == NULL) {
11822
0
        if (!PyErr_Occurred())
11823
0
            PyErr_BadInternalCall();
11824
0
        return;
11825
0
    }
11826
8.38M
    left = *p_left;
11827
8.38M
    if (right == NULL || left == NULL
11828
8.38M
        || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
11829
0
        if (!PyErr_Occurred())
11830
0
            PyErr_BadInternalCall();
11831
0
        goto error;
11832
0
    }
11833
11834
    /* Shortcuts */
11835
8.38M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11836
8.38M
    if (left == empty) {
11837
524k
        Py_DECREF(left);
11838
524k
        *p_left = Py_NewRef(right);
11839
524k
        return;
11840
524k
    }
11841
7.86M
    if (right == empty) {
11842
10.0k
        return;
11843
10.0k
    }
11844
11845
7.85M
    left_len = PyUnicode_GET_LENGTH(left);
11846
7.85M
    right_len = PyUnicode_GET_LENGTH(right);
11847
7.85M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11848
0
        PyErr_SetString(PyExc_OverflowError,
11849
0
                        "strings are too large to concat");
11850
0
        goto error;
11851
0
    }
11852
7.85M
    new_len = left_len + right_len;
11853
11854
7.85M
    if (_PyUnicode_IsModifiable(left)
11855
7.85M
        && PyUnicode_CheckExact(right)
11856
7.85M
        && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
11857
        /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11858
           to change the structure size, but characters are stored just after
11859
           the structure, and so it requires to move all characters which is
11860
           not so different than duplicating the string. */
11861
3.28M
        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11862
3.28M
    {
11863
        /* append inplace */
11864
3.28M
        if (unicode_resize(p_left, new_len) != 0)
11865
0
            goto error;
11866
11867
        /* copy 'right' into the newly allocated area of 'left' */
11868
3.28M
        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
11869
3.28M
    }
11870
4.57M
    else {
11871
4.57M
        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11872
4.57M
        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11873
4.57M
        maxchar = Py_MAX(maxchar, maxchar2);
11874
11875
        /* Concat the two Unicode strings */
11876
4.57M
        res = PyUnicode_New(new_len, maxchar);
11877
4.57M
        if (res == NULL)
11878
0
            goto error;
11879
4.57M
        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11880
4.57M
        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
11881
4.57M
        Py_DECREF(left);
11882
4.57M
        *p_left = res;
11883
4.57M
    }
11884
7.85M
    assert(_PyUnicode_CheckConsistency(*p_left, 1));
11885
7.85M
    return;
11886
11887
0
error:
11888
0
    Py_CLEAR(*p_left);
11889
0
}
11890
11891
void
11892
PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11893
8
{
11894
8
    PyUnicode_Append(pleft, right);
11895
8
    Py_XDECREF(right);
11896
8
}
11897
11898
/*[clinic input]
11899
@permit_long_summary
11900
@text_signature "($self, sub[, start[, end]], /)"
11901
str.count as unicode_count -> Py_ssize_t
11902
11903
    self as str: self
11904
    sub as substr: unicode
11905
    start: slice_index(accept={int, NoneType}, c_default='0') = None
11906
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
11907
    /
11908
11909
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
11910
11911
Optional arguments start and end are interpreted as in slice
11912
notation.
11913
[clinic start generated code]*/
11914
11915
static Py_ssize_t
11916
unicode_count_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
11917
                   Py_ssize_t end)
11918
/*[clinic end generated code: output=8fcc3aef0b18edbf input=c9209e05438cc352]*/
11919
22.6M
{
11920
22.6M
    assert(PyUnicode_Check(str));
11921
22.6M
    assert(PyUnicode_Check(substr));
11922
11923
22.6M
    Py_ssize_t result;
11924
22.6M
    int kind1, kind2;
11925
22.6M
    const void *buf1 = NULL, *buf2 = NULL;
11926
22.6M
    Py_ssize_t len1, len2;
11927
11928
22.6M
    kind1 = PyUnicode_KIND(str);
11929
22.6M
    kind2 = PyUnicode_KIND(substr);
11930
22.6M
    if (kind1 < kind2)
11931
0
        return 0;
11932
11933
22.6M
    len1 = PyUnicode_GET_LENGTH(str);
11934
22.6M
    len2 = PyUnicode_GET_LENGTH(substr);
11935
22.6M
    ADJUST_INDICES(start, end, len1);
11936
22.6M
    if (end - start < len2)
11937
7.04M
        return 0;
11938
11939
15.5M
    buf1 = PyUnicode_DATA(str);
11940
15.5M
    buf2 = PyUnicode_DATA(substr);
11941
15.5M
    if (kind2 != kind1) {
11942
189k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11943
189k
        if (!buf2)
11944
0
            goto onError;
11945
189k
    }
11946
11947
    // We don't reuse `anylib_count` here because of the explicit casts.
11948
15.5M
    switch (kind1) {
11949
15.3M
    case PyUnicode_1BYTE_KIND:
11950
15.3M
        result = ucs1lib_count(
11951
15.3M
            ((const Py_UCS1*)buf1) + start, end - start,
11952
15.3M
            buf2, len2, PY_SSIZE_T_MAX
11953
15.3M
            );
11954
15.3M
        break;
11955
150k
    case PyUnicode_2BYTE_KIND:
11956
150k
        result = ucs2lib_count(
11957
150k
            ((const Py_UCS2*)buf1) + start, end - start,
11958
150k
            buf2, len2, PY_SSIZE_T_MAX
11959
150k
            );
11960
150k
        break;
11961
38.8k
    case PyUnicode_4BYTE_KIND:
11962
38.8k
        result = ucs4lib_count(
11963
38.8k
            ((const Py_UCS4*)buf1) + start, end - start,
11964
38.8k
            buf2, len2, PY_SSIZE_T_MAX
11965
38.8k
            );
11966
38.8k
        break;
11967
0
    default:
11968
0
        Py_UNREACHABLE();
11969
15.5M
    }
11970
11971
15.5M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11972
15.5M
    if (kind2 != kind1)
11973
189k
        PyMem_Free((void *)buf2);
11974
11975
15.5M
    return result;
11976
0
  onError:
11977
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11978
0
    if (kind2 != kind1)
11979
0
        PyMem_Free((void *)buf2);
11980
0
    return -1;
11981
15.5M
}
11982
11983
/*[clinic input]
11984
str.encode as unicode_encode
11985
11986
    encoding: str(c_default="NULL") = 'utf-8'
11987
        The encoding in which to encode the string.
11988
    errors: str(c_default="NULL") = 'strict'
11989
        The error handling scheme to use for encoding errors.
11990
        The default is 'strict' meaning that encoding errors raise a
11991
        UnicodeEncodeError.  Other possible values are 'ignore', 'replace'
11992
        and 'xmlcharrefreplace' as well as any other name registered with
11993
        codecs.register_error that can handle UnicodeEncodeErrors.
11994
11995
Encode the string using the codec registered for encoding.
11996
[clinic start generated code]*/
11997
11998
static PyObject *
11999
unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
12000
/*[clinic end generated code: output=bf78b6e2a9470e3c input=b85a9645cb33b729]*/
12001
21.4M
{
12002
21.4M
    return PyUnicode_AsEncodedString(self, encoding, errors);
12003
21.4M
}
12004
12005
/*[clinic input]
12006
str.expandtabs as unicode_expandtabs
12007
12008
    tabsize: int = 8
12009
12010
Return a copy where all tab characters are expanded using spaces.
12011
12012
If tabsize is not given, a tab size of 8 characters is assumed.
12013
[clinic start generated code]*/
12014
12015
static PyObject *
12016
unicode_expandtabs_impl(PyObject *self, int tabsize)
12017
/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
12018
1.08M
{
12019
1.08M
    Py_ssize_t i, j, line_pos, src_len, incr;
12020
1.08M
    Py_UCS4 ch;
12021
1.08M
    PyObject *u;
12022
1.08M
    const void *src_data;
12023
1.08M
    void *dest_data;
12024
1.08M
    int kind;
12025
1.08M
    int found;
12026
12027
    /* First pass: determine size of output string */
12028
1.08M
    src_len = PyUnicode_GET_LENGTH(self);
12029
1.08M
    i = j = line_pos = 0;
12030
1.08M
    kind = PyUnicode_KIND(self);
12031
1.08M
    src_data = PyUnicode_DATA(self);
12032
1.08M
    found = 0;
12033
2.39M
    for (; i < src_len; i++) {
12034
1.30M
        ch = PyUnicode_READ(kind, src_data, i);
12035
1.30M
        if (ch == '\t') {
12036
353k
            found = 1;
12037
353k
            if (tabsize > 0) {
12038
353k
                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
12039
353k
                if (j > PY_SSIZE_T_MAX - incr)
12040
0
                    goto overflow;
12041
353k
                line_pos += incr;
12042
353k
                j += incr;
12043
353k
            }
12044
353k
        }
12045
951k
        else {
12046
951k
            if (j > PY_SSIZE_T_MAX - 1)
12047
0
                goto overflow;
12048
951k
            line_pos++;
12049
951k
            j++;
12050
951k
            if (ch == '\n' || ch == '\r')
12051
2.65k
                line_pos = 0;
12052
951k
        }
12053
1.30M
    }
12054
1.08M
    if (!found)
12055
1.04M
        return unicode_result_unchanged(self);
12056
12057
    /* Second pass: create output string and fill it */
12058
36.4k
    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
12059
36.4k
    if (!u)
12060
0
        return NULL;
12061
36.4k
    dest_data = PyUnicode_DATA(u);
12062
12063
36.4k
    i = j = line_pos = 0;
12064
12065
695k
    for (; i < src_len; i++) {
12066
658k
        ch = PyUnicode_READ(kind, src_data, i);
12067
658k
        if (ch == '\t') {
12068
353k
            if (tabsize > 0) {
12069
353k
                incr = tabsize - (line_pos % tabsize);
12070
353k
                line_pos += incr;
12071
353k
                _PyUnicode_Fill(kind, dest_data, ' ', j, incr);
12072
353k
                j += incr;
12073
353k
            }
12074
353k
        }
12075
304k
        else {
12076
304k
            line_pos++;
12077
304k
            PyUnicode_WRITE(kind, dest_data, j, ch);
12078
304k
            j++;
12079
304k
            if (ch == '\n' || ch == '\r')
12080
0
                line_pos = 0;
12081
304k
        }
12082
658k
    }
12083
36.4k
    assert (j == PyUnicode_GET_LENGTH(u));
12084
36.4k
    return unicode_result(u);
12085
12086
0
  overflow:
12087
0
    PyErr_SetString(PyExc_OverflowError, "new string is too long");
12088
0
    return NULL;
12089
36.4k
}
12090
12091
/*[clinic input]
12092
@permit_long_summary
12093
str.find as unicode_find = str.count
12094
12095
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12096
12097
Optional arguments start and end are interpreted as in slice
12098
notation.  Return -1 on failure.
12099
[clinic start generated code]*/
12100
12101
static Py_ssize_t
12102
unicode_find_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12103
                  Py_ssize_t end)
12104
/*[clinic end generated code: output=51dbe6255712e278 input=f57e93c59d1ee927]*/
12105
21.8M
{
12106
21.8M
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12107
21.8M
    if (result < 0) {
12108
6.76M
        return -1;
12109
6.76M
    }
12110
15.0M
    return result;
12111
21.8M
}
12112
12113
static PyObject *
12114
unicode_getitem(PyObject *self, Py_ssize_t index)
12115
57.1M
{
12116
57.1M
    const void *data;
12117
57.1M
    int kind;
12118
57.1M
    Py_UCS4 ch;
12119
12120
57.1M
    if (!PyUnicode_Check(self)) {
12121
0
        PyErr_BadArgument();
12122
0
        return NULL;
12123
0
    }
12124
57.1M
    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
12125
13.7k
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12126
13.7k
        return NULL;
12127
13.7k
    }
12128
57.1M
    kind = PyUnicode_KIND(self);
12129
57.1M
    data = PyUnicode_DATA(self);
12130
57.1M
    ch = PyUnicode_READ(kind, data, index);
12131
57.1M
    return unicode_char(ch);
12132
57.1M
}
12133
12134
/* Believe it or not, this produces the same value for ASCII strings
12135
   as bytes_hash(). */
12136
static Py_hash_t
12137
unicode_hash(PyObject *self)
12138
495M
{
12139
495M
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
12140
12141
#ifdef Py_DEBUG
12142
    assert(_Py_HashSecret_Initialized);
12143
#endif
12144
495M
    Py_hash_t hash = PyUnicode_HASH(self);
12145
495M
    if (hash != -1) {
12146
442M
        return hash;
12147
442M
    }
12148
52.5M
    x = Py_HashBuffer(PyUnicode_DATA(self),
12149
52.5M
                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
12150
12151
52.5M
    PyUnicode_SET_HASH(self, x);
12152
52.5M
    return x;
12153
495M
}
12154
12155
/*[clinic input]
12156
@permit_long_summary
12157
str.index as unicode_index = str.count
12158
12159
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12160
12161
Optional arguments start and end are interpreted as in slice
12162
notation.  Raises ValueError when the substring is not found.
12163
[clinic start generated code]*/
12164
12165
static Py_ssize_t
12166
unicode_index_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12167
                   Py_ssize_t end)
12168
/*[clinic end generated code: output=77558288837cdf40 input=5900ab84de55e628]*/
12169
42.3k
{
12170
42.3k
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12171
42.3k
    if (result == -1) {
12172
537
        PyErr_SetString(PyExc_ValueError, "substring not found");
12173
537
    }
12174
41.7k
    else if (result < 0) {
12175
0
        return -1;
12176
0
    }
12177
42.3k
    return result;
12178
42.3k
}
12179
12180
/*[clinic input]
12181
@permit_long_summary
12182
str.isascii as unicode_isascii
12183
12184
Return True if all characters in the string are ASCII, False otherwise.
12185
12186
ASCII characters have code points in the range U+0000-U+007F.
12187
Empty string is ASCII too.
12188
[clinic start generated code]*/
12189
12190
static PyObject *
12191
unicode_isascii_impl(PyObject *self)
12192
/*[clinic end generated code: output=c5910d64b5a8003f input=dc74e1ced821159f]*/
12193
5.30k
{
12194
5.30k
    return PyBool_FromLong(PyUnicode_IS_ASCII(self));
12195
5.30k
}
12196
12197
/*[clinic input]
12198
str.islower as unicode_islower
12199
12200
Return True if the string is a lowercase string, False otherwise.
12201
12202
A string is lowercase if all cased characters in the string are
12203
lowercase and there is at least one cased character in the string.
12204
[clinic start generated code]*/
12205
12206
static PyObject *
12207
unicode_islower_impl(PyObject *self)
12208
/*[clinic end generated code: output=dbd41995bd005b81 input=1879b48dfc628366]*/
12209
0
{
12210
0
    Py_ssize_t i, length;
12211
0
    int kind;
12212
0
    const void *data;
12213
0
    int cased;
12214
12215
0
    length = PyUnicode_GET_LENGTH(self);
12216
0
    kind = PyUnicode_KIND(self);
12217
0
    data = PyUnicode_DATA(self);
12218
12219
    /* Shortcut for single character strings */
12220
0
    if (length == 1)
12221
0
        return PyBool_FromLong(
12222
0
            Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
12223
12224
    /* Special case for empty strings */
12225
0
    if (length == 0)
12226
0
        Py_RETURN_FALSE;
12227
12228
0
    cased = 0;
12229
0
    for (i = 0; i < length; i++) {
12230
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12231
12232
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
12233
0
            Py_RETURN_FALSE;
12234
0
        else if (!cased && Py_UNICODE_ISLOWER(ch))
12235
0
            cased = 1;
12236
0
    }
12237
0
    return PyBool_FromLong(cased);
12238
0
}
12239
12240
/*[clinic input]
12241
str.isupper as unicode_isupper
12242
12243
Return True if the string is an uppercase string, False otherwise.
12244
12245
A string is uppercase if all cased characters in the string are
12246
uppercase and there is at least one cased character in the string.
12247
[clinic start generated code]*/
12248
12249
static PyObject *
12250
unicode_isupper_impl(PyObject *self)
12251
/*[clinic end generated code: output=049209c8e7f15f59 input=77d29904aef0e3a0]*/
12252
10.7k
{
12253
10.7k
    Py_ssize_t i, length;
12254
10.7k
    int kind;
12255
10.7k
    const void *data;
12256
10.7k
    int cased;
12257
12258
10.7k
    length = PyUnicode_GET_LENGTH(self);
12259
10.7k
    kind = PyUnicode_KIND(self);
12260
10.7k
    data = PyUnicode_DATA(self);
12261
12262
    /* Shortcut for single character strings */
12263
10.7k
    if (length == 1)
12264
0
        return PyBool_FromLong(
12265
0
            Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
12266
12267
    /* Special case for empty strings */
12268
10.7k
    if (length == 0)
12269
0
        Py_RETURN_FALSE;
12270
12271
10.7k
    cased = 0;
12272
135k
    for (i = 0; i < length; i++) {
12273
126k
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12274
12275
126k
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
12276
1.36k
            Py_RETURN_FALSE;
12277
124k
        else if (!cased && Py_UNICODE_ISUPPER(ch))
12278
9.56k
            cased = 1;
12279
126k
    }
12280
9.42k
    return PyBool_FromLong(cased);
12281
10.7k
}
12282
12283
/*[clinic input]
12284
str.istitle as unicode_istitle
12285
12286
Return True if the string is a title-cased string, False otherwise.
12287
12288
In a title-cased string, upper- and title-case characters may only
12289
follow uncased characters and lowercase characters only cased ones.
12290
[clinic start generated code]*/
12291
12292
static PyObject *
12293
unicode_istitle_impl(PyObject *self)
12294
/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
12295
0
{
12296
0
    Py_ssize_t i, length;
12297
0
    int kind;
12298
0
    const void *data;
12299
0
    int cased, previous_is_cased;
12300
12301
0
    length = PyUnicode_GET_LENGTH(self);
12302
0
    kind = PyUnicode_KIND(self);
12303
0
    data = PyUnicode_DATA(self);
12304
12305
    /* Shortcut for single character strings */
12306
0
    if (length == 1) {
12307
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12308
0
        return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
12309
0
                               (Py_UNICODE_ISUPPER(ch) != 0));
12310
0
    }
12311
12312
    /* Special case for empty strings */
12313
0
    if (length == 0)
12314
0
        Py_RETURN_FALSE;
12315
12316
0
    cased = 0;
12317
0
    previous_is_cased = 0;
12318
0
    for (i = 0; i < length; i++) {
12319
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12320
12321
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
12322
0
            if (previous_is_cased)
12323
0
                Py_RETURN_FALSE;
12324
0
            previous_is_cased = 1;
12325
0
            cased = 1;
12326
0
        }
12327
0
        else if (Py_UNICODE_ISLOWER(ch)) {
12328
0
            if (!previous_is_cased)
12329
0
                Py_RETURN_FALSE;
12330
0
            previous_is_cased = 1;
12331
0
            cased = 1;
12332
0
        }
12333
0
        else
12334
0
            previous_is_cased = 0;
12335
0
    }
12336
0
    return PyBool_FromLong(cased);
12337
0
}
12338
12339
/*[clinic input]
12340
str.isspace as unicode_isspace
12341
12342
Return True if the string is a whitespace string, False otherwise.
12343
12344
A string is whitespace if all characters in the string are
12345
whitespace and there is at least one character in the string.
12346
[clinic start generated code]*/
12347
12348
static PyObject *
12349
unicode_isspace_impl(PyObject *self)
12350
/*[clinic end generated code: output=163a63bfa08ac2b9 input=29e09560fc23fbeb]*/
12351
1.58M
{
12352
1.58M
    Py_ssize_t i, length;
12353
1.58M
    int kind;
12354
1.58M
    const void *data;
12355
12356
1.58M
    length = PyUnicode_GET_LENGTH(self);
12357
1.58M
    kind = PyUnicode_KIND(self);
12358
1.58M
    data = PyUnicode_DATA(self);
12359
12360
    /* Shortcut for single character strings */
12361
1.58M
    if (length == 1)
12362
1.57M
        return PyBool_FromLong(
12363
1.57M
            Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
12364
12365
    /* Special case for empty strings */
12366
1.33k
    if (length == 0)
12367
284
        Py_RETURN_FALSE;
12368
12369
7.60k
    for (i = 0; i < length; i++) {
12370
7.50k
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12371
7.50k
        if (!Py_UNICODE_ISSPACE(ch))
12372
944
            Py_RETURN_FALSE;
12373
7.50k
    }
12374
1.04k
    Py_RETURN_TRUE;
12375
1.04k
}
12376
12377
/*[clinic input]
12378
str.isalpha as unicode_isalpha
12379
12380
Return True if the string is an alphabetic string, False otherwise.
12381
12382
A string is alphabetic if all characters in the string are
12383
alphabetic and there is at least one character in the string.
12384
[clinic start generated code]*/
12385
12386
static PyObject *
12387
unicode_isalpha_impl(PyObject *self)
12388
/*[clinic end generated code: output=cc81b9ac3883ec4f input=9906a07f3e04892e]*/
12389
20
{
12390
20
    Py_ssize_t i, length;
12391
20
    int kind;
12392
20
    const void *data;
12393
12394
20
    length = PyUnicode_GET_LENGTH(self);
12395
20
    kind = PyUnicode_KIND(self);
12396
20
    data = PyUnicode_DATA(self);
12397
12398
    /* Shortcut for single character strings */
12399
20
    if (length == 1)
12400
16
        return PyBool_FromLong(
12401
16
            Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
12402
12403
    /* Special case for empty strings */
12404
4
    if (length == 0)
12405
0
        Py_RETURN_FALSE;
12406
12407
4
    for (i = 0; i < length; i++) {
12408
4
        if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
12409
4
            Py_RETURN_FALSE;
12410
4
    }
12411
4
    Py_RETURN_TRUE;
12412
4
}
12413
12414
/*[clinic input]
12415
@permit_long_summary
12416
str.isalnum as unicode_isalnum
12417
12418
Return True if the string is an alpha-numeric string, False otherwise.
12419
12420
A string is alpha-numeric if all characters in the string are
12421
alpha-numeric and there is at least one character in the string.
12422
[clinic start generated code]*/
12423
12424
static PyObject *
12425
unicode_isalnum_impl(PyObject *self)
12426
/*[clinic end generated code: output=a5a23490ffc3660c input=892f64ebc171fd4f]*/
12427
256
{
12428
256
    int kind;
12429
256
    const void *data;
12430
256
    Py_ssize_t len, i;
12431
12432
256
    kind = PyUnicode_KIND(self);
12433
256
    data = PyUnicode_DATA(self);
12434
256
    len = PyUnicode_GET_LENGTH(self);
12435
12436
    /* Shortcut for single character strings */
12437
256
    if (len == 1) {
12438
256
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12439
256
        return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12440
256
    }
12441
12442
    /* Special case for empty strings */
12443
0
    if (len == 0)
12444
0
        Py_RETURN_FALSE;
12445
12446
0
    for (i = 0; i < len; i++) {
12447
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12448
0
        if (!Py_UNICODE_ISALNUM(ch))
12449
0
            Py_RETURN_FALSE;
12450
0
    }
12451
0
    Py_RETURN_TRUE;
12452
0
}
12453
12454
/*[clinic input]
12455
str.isdecimal as unicode_isdecimal
12456
12457
Return True if the string is a decimal string, False otherwise.
12458
12459
A string is a decimal string if all characters in the string are
12460
decimal and there is at least one character in the string.
12461
[clinic start generated code]*/
12462
12463
static PyObject *
12464
unicode_isdecimal_impl(PyObject *self)
12465
/*[clinic end generated code: output=fb2dcdb62d3fc548 input=63b0453c48cad0af]*/
12466
1.16k
{
12467
1.16k
    Py_ssize_t i, length;
12468
1.16k
    int kind;
12469
1.16k
    const void *data;
12470
12471
1.16k
    length = PyUnicode_GET_LENGTH(self);
12472
1.16k
    kind = PyUnicode_KIND(self);
12473
1.16k
    data = PyUnicode_DATA(self);
12474
12475
    /* Shortcut for single character strings */
12476
1.16k
    if (length == 1)
12477
262
        return PyBool_FromLong(
12478
262
            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
12479
12480
    /* Special case for empty strings */
12481
899
    if (length == 0)
12482
0
        Py_RETURN_FALSE;
12483
12484
5.88k
    for (i = 0; i < length; i++) {
12485
5.50k
        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
12486
519
            Py_RETURN_FALSE;
12487
5.50k
    }
12488
899
    Py_RETURN_TRUE;
12489
899
}
12490
12491
/*[clinic input]
12492
str.isdigit as unicode_isdigit
12493
12494
Return True if the string is a digit string, False otherwise.
12495
12496
A string is a digit string if all characters in the string are
12497
digits and there is at least one character in the string.
12498
[clinic start generated code]*/
12499
12500
static PyObject *
12501
unicode_isdigit_impl(PyObject *self)
12502
/*[clinic end generated code: output=10a6985311da6858 input=353b03747b062e4b]*/
12503
1.27M
{
12504
1.27M
    Py_ssize_t i, length;
12505
1.27M
    int kind;
12506
1.27M
    const void *data;
12507
12508
1.27M
    length = PyUnicode_GET_LENGTH(self);
12509
1.27M
    kind = PyUnicode_KIND(self);
12510
1.27M
    data = PyUnicode_DATA(self);
12511
12512
    /* Shortcut for single character strings */
12513
1.27M
    if (length == 1) {
12514
1.27M
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12515
1.27M
        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12516
1.27M
    }
12517
12518
    /* Special case for empty strings */
12519
408
    if (length == 0)
12520
0
        Py_RETURN_FALSE;
12521
12522
1.45k
    for (i = 0; i < length; i++) {
12523
1.04k
        if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
12524
0
            Py_RETURN_FALSE;
12525
1.04k
    }
12526
408
    Py_RETURN_TRUE;
12527
408
}
12528
12529
/*[clinic input]
12530
str.isnumeric as unicode_isnumeric
12531
12532
Return True if the string is a numeric string, False otherwise.
12533
12534
A string is numeric if all characters in the string are numeric and
12535
there is at least one character in the string.
12536
[clinic start generated code]*/
12537
12538
static PyObject *
12539
unicode_isnumeric_impl(PyObject *self)
12540
/*[clinic end generated code: output=9172a32d9013051a input=83b2a072ed7aff48]*/
12541
0
{
12542
0
    Py_ssize_t i, length;
12543
0
    int kind;
12544
0
    const void *data;
12545
12546
0
    length = PyUnicode_GET_LENGTH(self);
12547
0
    kind = PyUnicode_KIND(self);
12548
0
    data = PyUnicode_DATA(self);
12549
12550
    /* Shortcut for single character strings */
12551
0
    if (length == 1)
12552
0
        return PyBool_FromLong(
12553
0
            Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
12554
12555
    /* Special case for empty strings */
12556
0
    if (length == 0)
12557
0
        Py_RETURN_FALSE;
12558
12559
0
    for (i = 0; i < length; i++) {
12560
0
        if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
12561
0
            Py_RETURN_FALSE;
12562
0
    }
12563
0
    Py_RETURN_TRUE;
12564
0
}
12565
12566
Py_ssize_t
12567
_PyUnicode_ScanIdentifier(PyObject *self)
12568
51.9k
{
12569
51.9k
    Py_ssize_t i;
12570
51.9k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12571
51.9k
    if (len == 0) {
12572
        /* an empty string is not a valid identifier */
12573
0
        return 0;
12574
0
    }
12575
12576
51.9k
    int kind = PyUnicode_KIND(self);
12577
51.9k
    const void *data = PyUnicode_DATA(self);
12578
51.9k
    Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12579
    /* PEP 3131 says that the first character must be in
12580
       XID_Start and subsequent characters in XID_Continue,
12581
       and for the ASCII range, the 2.x rules apply (i.e
12582
       start with letters and underscore, continue with
12583
       letters, digits, underscore). However, given the current
12584
       definition of XID_Start and XID_Continue, it is sufficient
12585
       to check just for these, except that _ must be allowed
12586
       as starting an identifier.  */
12587
51.9k
    if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12588
784
        return 0;
12589
784
    }
12590
12591
439k
    for (i = 1; i < len; i++) {
12592
388k
        ch = PyUnicode_READ(kind, data, i);
12593
388k
        if (!_PyUnicode_IsXidContinue(ch)) {
12594
320
            return i;
12595
320
        }
12596
388k
    }
12597
50.8k
    return i;
12598
51.1k
}
12599
12600
int
12601
PyUnicode_IsIdentifier(PyObject *self)
12602
38.9k
{
12603
38.9k
    Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12604
38.9k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12605
    /* an empty string is not a valid identifier */
12606
38.9k
    return len && i == len;
12607
38.9k
}
12608
12609
/*[clinic input]
12610
@permit_long_summary
12611
str.isidentifier as unicode_isidentifier
12612
12613
Return True if the string is a valid Python identifier, False otherwise.
12614
12615
Call keyword.iskeyword(s) to test whether string s is a reserved
12616
identifier, such as "def" or "class".
12617
[clinic start generated code]*/
12618
12619
static PyObject *
12620
unicode_isidentifier_impl(PyObject *self)
12621
/*[clinic end generated code: output=fe585a9666572905 input=cabde62c20a3be6b]*/
12622
36.5k
{
12623
36.5k
    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12624
36.5k
}
12625
12626
/*[clinic input]
12627
@permit_long_summary
12628
str.isprintable as unicode_isprintable
12629
12630
Return True if all characters in the string are printable, False otherwise.
12631
12632
A character is printable if repr() may use it in its output.
12633
[clinic start generated code]*/
12634
12635
static PyObject *
12636
unicode_isprintable_impl(PyObject *self)
12637
/*[clinic end generated code: output=3ab9626cd32dd1a0 input=18345ba847084ec5]*/
12638
1.41M
{
12639
1.41M
    Py_ssize_t i, length;
12640
1.41M
    int kind;
12641
1.41M
    const void *data;
12642
12643
1.41M
    length = PyUnicode_GET_LENGTH(self);
12644
1.41M
    kind = PyUnicode_KIND(self);
12645
1.41M
    data = PyUnicode_DATA(self);
12646
12647
    /* Shortcut for single character strings */
12648
1.41M
    if (length == 1)
12649
1.41M
        return PyBool_FromLong(
12650
1.41M
            Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
12651
12652
0
    for (i = 0; i < length; i++) {
12653
0
        if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
12654
0
            Py_RETURN_FALSE;
12655
0
        }
12656
0
    }
12657
0
    Py_RETURN_TRUE;
12658
0
}
12659
12660
/*[clinic input]
12661
str.join as unicode_join
12662
12663
    iterable: object
12664
    /
12665
12666
Concatenate any number of strings.
12667
12668
The string whose method is called is inserted in between each given
12669
string.  The result is returned as a new string.
12670
12671
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12672
[clinic start generated code]*/
12673
12674
static PyObject *
12675
unicode_join(PyObject *self, PyObject *iterable)
12676
/*[clinic end generated code: output=6857e7cecfe7bf98 input=fd330a11ee845fb2]*/
12677
23.0M
{
12678
23.0M
    return PyUnicode_Join(self, iterable);
12679
23.0M
}
12680
12681
static Py_ssize_t
12682
unicode_length(PyObject *self)
12683
39.9M
{
12684
39.9M
    return PyUnicode_GET_LENGTH(self);
12685
39.9M
}
12686
12687
/*[clinic input]
12688
str.ljust as unicode_ljust
12689
12690
    width: Py_ssize_t
12691
    fillchar: Py_UCS4 = ' '
12692
    /
12693
12694
Return a left-justified string of length width.
12695
12696
Padding is done using the specified fill character (default is
12697
a space).
12698
[clinic start generated code]*/
12699
12700
static PyObject *
12701
unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12702
/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=8a55f06694c20ed6]*/
12703
1.13k
{
12704
1.13k
    if (PyUnicode_GET_LENGTH(self) >= width)
12705
357
        return unicode_result_unchanged(self);
12706
12707
773
    return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
12708
1.13k
}
12709
12710
/*[clinic input]
12711
str.lower as unicode_lower
12712
12713
Return a copy of the string converted to lowercase.
12714
[clinic start generated code]*/
12715
12716
static PyObject *
12717
unicode_lower_impl(PyObject *self)
12718
/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
12719
77.1M
{
12720
77.1M
    if (PyUnicode_IS_ASCII(self))
12721
67.8M
        return ascii_upper_or_lower(self, 1);
12722
9.35M
    return case_operation(self, do_lower);
12723
77.1M
}
12724
12725
68.6M
#define LEFTSTRIP 0
12726
84.0M
#define RIGHTSTRIP 1
12727
47.1M
#define BOTHSTRIP 2
12728
12729
/* Arrays indexed by above */
12730
static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
12731
12732
0
#define STRIPNAME(i) (stripfuncnames[i])
12733
12734
/* externally visible for str.strip(unicode) */
12735
PyObject *
12736
_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
12737
2.50M
{
12738
2.50M
    const void *data;
12739
2.50M
    int kind;
12740
2.50M
    Py_ssize_t i, j, len;
12741
2.50M
    BLOOM_MASK sepmask;
12742
2.50M
    Py_ssize_t seplen;
12743
12744
2.50M
    kind = PyUnicode_KIND(self);
12745
2.50M
    data = PyUnicode_DATA(self);
12746
2.50M
    len = PyUnicode_GET_LENGTH(self);
12747
2.50M
    seplen = PyUnicode_GET_LENGTH(sepobj);
12748
2.50M
    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12749
2.50M
                              PyUnicode_DATA(sepobj),
12750
2.50M
                              seplen);
12751
12752
2.50M
    i = 0;
12753
2.50M
    if (striptype != RIGHTSTRIP) {
12754
474k
        while (i < len) {
12755
471k
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12756
471k
            if (!BLOOM(sepmask, ch))
12757
430k
                break;
12758
40.5k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12759
3.13k
                break;
12760
37.3k
            i++;
12761
37.3k
        }
12762
436k
    }
12763
12764
2.50M
    j = len;
12765
2.50M
    if (striptype != LEFTSTRIP) {
12766
2.06M
        j--;
12767
2.66M
        while (j >= i) {
12768
1.72M
            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12769
1.72M
            if (!BLOOM(sepmask, ch))
12770
967k
                break;
12771
757k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12772
160k
                break;
12773
597k
            j--;
12774
597k
        }
12775
12776
2.06M
        j++;
12777
2.06M
    }
12778
12779
2.50M
    return PyUnicode_Substring(self, i, j);
12780
2.50M
}
12781
12782
PyObject*
12783
_PyUnicode_BinarySlice(PyObject *container, PyObject *start_o, PyObject *stop_o)
12784
25.7M
{
12785
25.7M
    assert(PyUnicode_CheckExact(container));
12786
25.7M
    Py_ssize_t len = PyUnicode_GET_LENGTH(container);
12787
25.7M
    Py_ssize_t istart, istop;
12788
25.7M
    if (!_PyEval_UnpackIndices(start_o, stop_o, len, &istart, &istop)) {
12789
0
        return NULL;
12790
0
    }
12791
25.7M
    return PyUnicode_Substring(container, istart, istop);
12792
25.7M
}
12793
12794
PyObject*
12795
PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12796
218M
{
12797
218M
    const unsigned char *data;
12798
218M
    int kind;
12799
218M
    Py_ssize_t length;
12800
12801
218M
    length = PyUnicode_GET_LENGTH(self);
12802
218M
    end = Py_MIN(end, length);
12803
12804
218M
    if (start == 0 && end == length)
12805
70.6M
        return unicode_result_unchanged(self);
12806
12807
147M
    if (start < 0 || end < 0) {
12808
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12809
0
        return NULL;
12810
0
    }
12811
147M
    if (start >= length || end < start)
12812
6.89M
        _Py_RETURN_UNICODE_EMPTY();
12813
12814
141M
    length = end - start;
12815
141M
    if (PyUnicode_IS_ASCII(self)) {
12816
49.9M
        data = PyUnicode_1BYTE_DATA(self);
12817
49.9M
        return _PyUnicode_FromASCII((const char*)(data + start), length);
12818
49.9M
    }
12819
91.0M
    else {
12820
91.0M
        kind = PyUnicode_KIND(self);
12821
91.0M
        data = PyUnicode_1BYTE_DATA(self);
12822
91.0M
        return PyUnicode_FromKindAndData(kind,
12823
91.0M
                                         data + kind * start,
12824
91.0M
                                         length);
12825
91.0M
    }
12826
141M
}
12827
12828
static PyObject *
12829
do_strip(PyObject *self, int striptype)
12830
64.0M
{
12831
64.0M
    Py_ssize_t len, i, j;
12832
12833
64.0M
    len = PyUnicode_GET_LENGTH(self);
12834
12835
64.0M
    if (PyUnicode_IS_ASCII(self)) {
12836
50.1M
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12837
12838
50.1M
        i = 0;
12839
50.1M
        if (striptype != RIGHTSTRIP) {
12840
44.2M
            while (i < len) {
12841
32.4M
                Py_UCS1 ch = data[i];
12842
32.4M
                if (!_Py_ascii_whitespace[ch])
12843
26.7M
                    break;
12844
5.75M
                i++;
12845
5.75M
            }
12846
38.4M
        }
12847
12848
50.1M
        j = len;
12849
50.1M
        if (striptype != LEFTSTRIP) {
12850
49.8M
            j--;
12851
55.7M
            while (j >= i) {
12852
37.8M
                Py_UCS1 ch = data[j];
12853
37.8M
                if (!_Py_ascii_whitespace[ch])
12854
31.9M
                    break;
12855
5.89M
                j--;
12856
5.89M
            }
12857
49.8M
            j++;
12858
49.8M
        }
12859
50.1M
    }
12860
13.8M
    else {
12861
13.8M
        int kind = PyUnicode_KIND(self);
12862
13.8M
        const void *data = PyUnicode_DATA(self);
12863
12864
13.8M
        i = 0;
12865
13.8M
        if (striptype != RIGHTSTRIP) {
12866
12.5M
            while (i < len) {
12867
12.5M
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12868
12.5M
                if (!Py_UNICODE_ISSPACE(ch))
12869
10.2M
                    break;
12870
2.29M
                i++;
12871
2.29M
            }
12872
10.2M
        }
12873
12874
13.8M
        j = len;
12875
13.8M
        if (striptype != LEFTSTRIP) {
12876
12.6M
            j--;
12877
15.9M
            while (j >= i) {
12878
15.9M
                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12879
15.9M
                if (!Py_UNICODE_ISSPACE(ch))
12880
12.5M
                    break;
12881
3.32M
                j--;
12882
3.32M
            }
12883
12.6M
            j++;
12884
12.6M
        }
12885
13.8M
    }
12886
12887
64.0M
    return PyUnicode_Substring(self, i, j);
12888
64.0M
}
12889
12890
12891
static PyObject *
12892
do_argstrip(PyObject *self, int striptype, PyObject *sep)
12893
66.5M
{
12894
66.5M
    if (sep != Py_None) {
12895
2.50M
        if (PyUnicode_Check(sep))
12896
2.50M
            return _PyUnicode_XStrip(self, striptype, sep);
12897
0
        else {
12898
0
            PyErr_Format(PyExc_TypeError,
12899
0
                         "%s arg must be None or str",
12900
0
                         STRIPNAME(striptype));
12901
0
            return NULL;
12902
0
        }
12903
2.50M
    }
12904
12905
64.0M
    return do_strip(self, striptype);
12906
66.5M
}
12907
12908
12909
/*[clinic input]
12910
@permit_long_summary
12911
str.strip as unicode_strip
12912
12913
    chars: object = None
12914
    /
12915
12916
Return a copy of the string with leading and trailing whitespace removed.
12917
12918
If chars is given and not None, remove characters in chars instead.
12919
[clinic start generated code]*/
12920
12921
static PyObject *
12922
unicode_strip_impl(PyObject *self, PyObject *chars)
12923
/*[clinic end generated code: output=ca19018454345d57 input=8bc6353450345fbd]*/
12924
47.1M
{
12925
47.1M
    return do_argstrip(self, BOTHSTRIP, chars);
12926
47.1M
}
12927
12928
12929
/*[clinic input]
12930
str.lstrip as unicode_lstrip
12931
12932
    chars: object = None
12933
    /
12934
12935
Return a copy of the string with leading whitespace removed.
12936
12937
If chars is given and not None, remove characters in chars instead.
12938
[clinic start generated code]*/
12939
12940
static PyObject *
12941
unicode_lstrip_impl(PyObject *self, PyObject *chars)
12942
/*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
12943
2.03M
{
12944
2.03M
    return do_argstrip(self, LEFTSTRIP, chars);
12945
2.03M
}
12946
12947
12948
/*[clinic input]
12949
str.rstrip as unicode_rstrip
12950
12951
    chars: object = None
12952
    /
12953
12954
Return a copy of the string with trailing whitespace removed.
12955
12956
If chars is given and not None, remove characters in chars instead.
12957
[clinic start generated code]*/
12958
12959
static PyObject *
12960
unicode_rstrip_impl(PyObject *self, PyObject *chars)
12961
/*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
12962
17.4M
{
12963
17.4M
    return do_argstrip(self, RIGHTSTRIP, chars);
12964
17.4M
}
12965
12966
12967
PyObject *
12968
_PyUnicode_Repeat(PyObject *str, Py_ssize_t len)
12969
279k
{
12970
279k
    PyObject *u;
12971
279k
    Py_ssize_t nchars, n;
12972
12973
279k
    if (len < 1)
12974
36.5k
        _Py_RETURN_UNICODE_EMPTY();
12975
12976
    /* no repeat, return original string */
12977
243k
    if (len == 1)
12978
31.0k
        return unicode_result_unchanged(str);
12979
12980
212k
    if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
12981
0
        PyErr_SetString(PyExc_OverflowError,
12982
0
                        "repeated string is too long");
12983
0
        return NULL;
12984
0
    }
12985
212k
    nchars = len * PyUnicode_GET_LENGTH(str);
12986
12987
212k
    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
12988
212k
    if (!u)
12989
0
        return NULL;
12990
212k
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
12991
12992
212k
    if (PyUnicode_GET_LENGTH(str) == 1) {
12993
209k
        int kind = PyUnicode_KIND(str);
12994
209k
        Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12995
209k
        if (kind == PyUnicode_1BYTE_KIND) {
12996
209k
            void *to = PyUnicode_DATA(u);
12997
209k
            memset(to, (unsigned char)fill_char, len);
12998
209k
        }
12999
0
        else if (kind == PyUnicode_2BYTE_KIND) {
13000
0
            Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
13001
0
            for (n = 0; n < len; ++n)
13002
0
                ucs2[n] = fill_char;
13003
0
        } else {
13004
0
            Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
13005
0
            assert(kind == PyUnicode_4BYTE_KIND);
13006
0
            for (n = 0; n < len; ++n)
13007
0
                ucs4[n] = fill_char;
13008
0
        }
13009
209k
    }
13010
2.45k
    else {
13011
2.45k
        Py_ssize_t char_size = PyUnicode_KIND(str);
13012
2.45k
        char *to = (char *) PyUnicode_DATA(u);
13013
2.45k
        _PyBytes_RepeatBuffer(to, nchars * char_size, PyUnicode_DATA(str),
13014
2.45k
            PyUnicode_GET_LENGTH(str) * char_size);
13015
2.45k
    }
13016
13017
212k
    assert(_PyUnicode_CheckConsistency(u, 1));
13018
212k
    return u;
13019
212k
}
13020
13021
PyObject *
13022
PyUnicode_Replace(PyObject *str,
13023
                  PyObject *substr,
13024
                  PyObject *replstr,
13025
                  Py_ssize_t maxcount)
13026
0
{
13027
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
13028
0
            ensure_unicode(replstr) < 0)
13029
0
        return NULL;
13030
0
    return replace(str, substr, replstr, maxcount);
13031
0
}
13032
13033
/*[clinic input]
13034
str.replace as unicode_replace
13035
13036
    old: unicode
13037
    new: unicode
13038
    /
13039
    count: Py_ssize_t = -1
13040
        Maximum number of occurrences to replace.
13041
        -1 (the default value) means replace all occurrences.
13042
13043
Return a copy with all occurrences of substring old replaced by new.
13044
13045
If count is given, only the first count occurrences are replaced.
13046
If count is not specified or -1, then all occurrences are replaced.
13047
[clinic start generated code]*/
13048
13049
static PyObject *
13050
unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
13051
                     Py_ssize_t count)
13052
/*[clinic end generated code: output=b63f1a8b5eebf448 input=d15a6886b05e2edc]*/
13053
20.6M
{
13054
20.6M
    return replace(self, old, new, count);
13055
20.6M
}
13056
13057
/*[clinic input]
13058
str.removeprefix as unicode_removeprefix
13059
13060
    prefix: unicode
13061
    /
13062
13063
Return a str with the given prefix string removed if present.
13064
13065
If the string starts with the prefix string, return
13066
string[len(prefix):].  Otherwise, return a copy of the original
13067
string.
13068
[clinic start generated code]*/
13069
13070
static PyObject *
13071
unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
13072
/*[clinic end generated code: output=f1e5945e9763bcb9 input=90d162724944bfa7]*/
13073
1.48k
{
13074
1.48k
    int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
13075
1.48k
    if (match == -1) {
13076
0
        return NULL;
13077
0
    }
13078
1.48k
    if (match) {
13079
34
        return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
13080
34
                                   PyUnicode_GET_LENGTH(self));
13081
34
    }
13082
1.45k
    return unicode_result_unchanged(self);
13083
1.48k
}
13084
13085
/*[clinic input]
13086
str.removesuffix as unicode_removesuffix
13087
13088
    suffix: unicode
13089
    /
13090
13091
Return a str with the given suffix string removed if present.
13092
13093
If the string ends with the suffix string and that suffix is not
13094
empty, return string[:-len(suffix)].  Otherwise, return a copy of
13095
the original string.
13096
[clinic start generated code]*/
13097
13098
static PyObject *
13099
unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
13100
/*[clinic end generated code: output=d36629e227636822 input=6efc96152d4bfcd5]*/
13101
0
{
13102
0
    int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
13103
0
    if (match == -1) {
13104
0
        return NULL;
13105
0
    }
13106
0
    if (match) {
13107
0
        return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
13108
0
                                            - PyUnicode_GET_LENGTH(suffix));
13109
0
    }
13110
0
    return unicode_result_unchanged(self);
13111
0
}
13112
13113
static PyObject *
13114
unicode_repr(PyObject *unicode)
13115
14.5M
{
13116
14.5M
    Py_ssize_t isize = PyUnicode_GET_LENGTH(unicode);
13117
14.5M
    const void *idata = PyUnicode_DATA(unicode);
13118
13119
    /* Compute length of output, quote characters, and
13120
       maximum character */
13121
14.5M
    Py_ssize_t osize = 0;
13122
14.5M
    Py_UCS4 maxch = 127;
13123
14.5M
    Py_ssize_t squote = 0;
13124
14.5M
    Py_ssize_t dquote = 0;
13125
14.5M
    int ikind = PyUnicode_KIND(unicode);
13126
310M
    for (Py_ssize_t i = 0; i < isize; i++) {
13127
295M
        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
13128
295M
        Py_ssize_t incr = 1;
13129
295M
        switch (ch) {
13130
408k
        case '\'': squote++; break;
13131
387k
        case '"':  dquote++; break;
13132
6.62M
        case '\\': case '\t': case '\r': case '\n':
13133
6.62M
            incr = 2;
13134
6.62M
            break;
13135
288M
        default:
13136
            /* Fast-path ASCII */
13137
288M
            if (ch < ' ' || ch == 0x7f)
13138
149M
                incr = 4; /* \xHH */
13139
138M
            else if (ch < 0x7f)
13140
125M
                ;
13141
12.7M
            else if (Py_UNICODE_ISPRINTABLE(ch))
13142
11.5M
                maxch = (ch > maxch) ? ch : maxch;
13143
1.14M
            else if (ch < 0x100)
13144
81.5k
                incr = 4; /* \xHH */
13145
1.06M
            else if (ch < 0x10000)
13146
98.8k
                incr = 6; /* \uHHHH */
13147
966k
            else
13148
966k
                incr = 10; /* \uHHHHHHHH */
13149
295M
        }
13150
295M
        if (osize > PY_SSIZE_T_MAX - incr) {
13151
0
            PyErr_SetString(PyExc_OverflowError,
13152
0
                            "string is too long to generate repr");
13153
0
            return NULL;
13154
0
        }
13155
295M
        osize += incr;
13156
295M
    }
13157
13158
14.5M
    Py_UCS4 quote = '\'';
13159
14.5M
    int changed = (osize != isize);
13160
14.5M
    if (squote) {
13161
91.5k
        changed = 1;
13162
91.5k
        if (dquote)
13163
            /* Both squote and dquote present. Use squote,
13164
               and escape them */
13165
8.04k
            osize += squote;
13166
83.4k
        else
13167
83.4k
            quote = '"';
13168
91.5k
    }
13169
14.5M
    osize += 2;   /* quotes */
13170
13171
14.5M
    PyObject *repr = PyUnicode_New(osize, maxch);
13172
14.5M
    if (repr == NULL)
13173
0
        return NULL;
13174
14.5M
    int okind = PyUnicode_KIND(repr);
13175
14.5M
    void *odata = PyUnicode_DATA(repr);
13176
13177
14.5M
    if (!changed) {
13178
7.48M
        PyUnicode_WRITE(okind, odata, 0, quote);
13179
13180
7.48M
        _PyUnicode_FastCopyCharacters(repr, 1,
13181
7.48M
                                      unicode, 0,
13182
7.48M
                                      isize);
13183
13184
7.48M
        PyUnicode_WRITE(okind, odata, osize-1, quote);
13185
7.48M
    }
13186
7.10M
    else {
13187
7.10M
        switch (okind) {
13188
6.79M
        case PyUnicode_1BYTE_KIND:
13189
6.79M
            ucs1lib_repr(unicode, quote, odata);
13190
6.79M
            break;
13191
294k
        case PyUnicode_2BYTE_KIND:
13192
294k
            ucs2lib_repr(unicode, quote, odata);
13193
294k
            break;
13194
8.06k
        default:
13195
8.06k
            assert(okind == PyUnicode_4BYTE_KIND);
13196
8.06k
            ucs4lib_repr(unicode, quote, odata);
13197
7.10M
        }
13198
7.10M
    }
13199
13200
14.5M
    assert(_PyUnicode_CheckConsistency(repr, 1));
13201
14.5M
    return repr;
13202
14.5M
}
13203
13204
/*[clinic input]
13205
@permit_long_summary
13206
str.rfind as unicode_rfind = str.count
13207
13208
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13209
13210
Optional arguments start and end are interpreted as in slice
13211
notation.  Return -1 on failure.
13212
[clinic start generated code]*/
13213
13214
static Py_ssize_t
13215
unicode_rfind_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13216
                   Py_ssize_t end)
13217
/*[clinic end generated code: output=880b29f01dd014c8 input=2e67789533baf2f5]*/
13218
196k
{
13219
196k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13220
196k
    if (result < 0) {
13221
16.3k
        return -1;
13222
16.3k
    }
13223
180k
    return result;
13224
196k
}
13225
13226
/*[clinic input]
13227
@permit_long_summary
13228
str.rindex as unicode_rindex = str.count
13229
13230
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13231
13232
Optional arguments start and end are interpreted as in slice
13233
notation.  Raises ValueError when the substring is not found.
13234
[clinic start generated code]*/
13235
13236
static Py_ssize_t
13237
unicode_rindex_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13238
                    Py_ssize_t end)
13239
/*[clinic end generated code: output=5f3aef124c867fe1 input=e29d446c8234c9d9]*/
13240
2.34k
{
13241
2.34k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13242
2.34k
    if (result == -1) {
13243
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
13244
0
    }
13245
2.34k
    else if (result < 0) {
13246
0
        return -1;
13247
0
    }
13248
2.34k
    return result;
13249
2.34k
}
13250
13251
/*[clinic input]
13252
str.rjust as unicode_rjust
13253
13254
    width: Py_ssize_t
13255
    fillchar: Py_UCS4 = ' '
13256
    /
13257
13258
Return a right-justified string of length width.
13259
13260
Padding is done using the specified fill character (default is
13261
a space).
13262
[clinic start generated code]*/
13263
13264
static PyObject *
13265
unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
13266
/*[clinic end generated code: output=804a1a57fbe8d5cf input=1256a8d659589907]*/
13267
0
{
13268
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13269
0
        return unicode_result_unchanged(self);
13270
13271
0
    return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
13272
0
}
13273
13274
PyObject *
13275
PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13276
0
{
13277
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13278
0
        return NULL;
13279
13280
0
    return split(s, sep, maxsplit);
13281
0
}
13282
13283
/*[clinic input]
13284
@permit_long_summary
13285
str.split as unicode_split
13286
13287
    sep: object = None
13288
        The separator used to split the string.
13289
13290
        When set to None (the default value), will split on any
13291
        whitespace character (including \n \r \t \f and spaces) and
13292
        will discard empty strings from the result.
13293
    maxsplit: Py_ssize_t = -1
13294
        Maximum number of splits.
13295
        -1 (the default value) means no limit.
13296
13297
Return a list of the substrings in the string, using sep as the separator string.
13298
13299
Splitting starts at the front of the string and works to the end.
13300
13301
Note, str.split() is mainly useful for data that has been
13302
intentionally delimited.  With natural text that includes
13303
punctuation, consider using the regular expression module.
13304
13305
[clinic start generated code]*/
13306
13307
static PyObject *
13308
unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13309
/*[clinic end generated code: output=3a65b1db356948dc input=288cfd6bc8828f5a]*/
13310
22.7M
{
13311
22.7M
    if (sep == Py_None)
13312
174k
        return split(self, NULL, maxsplit);
13313
22.5M
    if (PyUnicode_Check(sep))
13314
22.5M
        return split(self, sep, maxsplit);
13315
13316
0
    PyErr_Format(PyExc_TypeError,
13317
0
                 "must be str or None, not %.100s",
13318
0
                 Py_TYPE(sep)->tp_name);
13319
0
    return NULL;
13320
22.5M
}
13321
13322
PyObject *
13323
PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
13324
8.50M
{
13325
8.50M
    PyObject* out;
13326
8.50M
    int kind1, kind2;
13327
8.50M
    const void *buf1, *buf2;
13328
8.50M
    Py_ssize_t len1, len2;
13329
13330
8.50M
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13331
0
        return NULL;
13332
13333
8.50M
    kind1 = PyUnicode_KIND(str_obj);
13334
8.50M
    kind2 = PyUnicode_KIND(sep_obj);
13335
8.50M
    len1 = PyUnicode_GET_LENGTH(str_obj);
13336
8.50M
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13337
8.50M
    if (kind1 < kind2 || len1 < len2) {
13338
1.09k
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13339
1.09k
        return PyTuple_Pack(3, str_obj, empty, empty);
13340
1.09k
    }
13341
8.50M
    buf1 = PyUnicode_DATA(str_obj);
13342
8.50M
    buf2 = PyUnicode_DATA(sep_obj);
13343
8.50M
    if (kind2 != kind1) {
13344
86.2k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13345
86.2k
        if (!buf2)
13346
0
            return NULL;
13347
86.2k
    }
13348
13349
8.50M
    switch (kind1) {
13350
8.41M
    case PyUnicode_1BYTE_KIND:
13351
8.41M
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13352
2.79M
            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13353
5.61M
        else
13354
5.61M
            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13355
8.41M
        break;
13356
74.4k
    case PyUnicode_2BYTE_KIND:
13357
74.4k
        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13358
74.4k
        break;
13359
11.8k
    case PyUnicode_4BYTE_KIND:
13360
11.8k
        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13361
11.8k
        break;
13362
0
    default:
13363
0
        Py_UNREACHABLE();
13364
8.50M
    }
13365
13366
8.50M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13367
8.50M
    if (kind2 != kind1)
13368
86.2k
        PyMem_Free((void *)buf2);
13369
13370
8.50M
    return out;
13371
8.50M
}
13372
13373
13374
PyObject *
13375
PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
13376
51.6k
{
13377
51.6k
    PyObject* out;
13378
51.6k
    int kind1, kind2;
13379
51.6k
    const void *buf1, *buf2;
13380
51.6k
    Py_ssize_t len1, len2;
13381
13382
51.6k
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13383
0
        return NULL;
13384
13385
51.6k
    kind1 = PyUnicode_KIND(str_obj);
13386
51.6k
    kind2 = PyUnicode_KIND(sep_obj);
13387
51.6k
    len1 = PyUnicode_GET_LENGTH(str_obj);
13388
51.6k
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13389
51.6k
    if (kind1 < kind2 || len1 < len2) {
13390
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13391
0
        return PyTuple_Pack(3, empty, empty, str_obj);
13392
0
    }
13393
51.6k
    buf1 = PyUnicode_DATA(str_obj);
13394
51.6k
    buf2 = PyUnicode_DATA(sep_obj);
13395
51.6k
    if (kind2 != kind1) {
13396
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13397
0
        if (!buf2)
13398
0
            return NULL;
13399
0
    }
13400
13401
51.6k
    switch (kind1) {
13402
51.6k
    case PyUnicode_1BYTE_KIND:
13403
51.6k
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13404
51.6k
            out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13405
0
        else
13406
0
            out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13407
51.6k
        break;
13408
0
    case PyUnicode_2BYTE_KIND:
13409
0
        out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13410
0
        break;
13411
0
    case PyUnicode_4BYTE_KIND:
13412
0
        out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13413
0
        break;
13414
0
    default:
13415
0
        Py_UNREACHABLE();
13416
51.6k
    }
13417
13418
51.6k
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13419
51.6k
    if (kind2 != kind1)
13420
0
        PyMem_Free((void *)buf2);
13421
13422
51.6k
    return out;
13423
51.6k
}
13424
13425
/*[clinic input]
13426
str.partition as unicode_partition
13427
13428
    sep: object
13429
    /
13430
13431
Partition the string into three parts using the given separator.
13432
13433
This will search for the separator in the string.  If the separator
13434
is found, returns a 3-tuple containing the part before the
13435
separator, the separator itself, and the part after it.
13436
13437
If the separator is not found, returns a 3-tuple containing
13438
the original string and two empty strings.
13439
[clinic start generated code]*/
13440
13441
static PyObject *
13442
unicode_partition(PyObject *self, PyObject *sep)
13443
/*[clinic end generated code: output=e4ced7bd253ca3c4 input=e45faa8c26270cb1]*/
13444
8.50M
{
13445
8.50M
    return PyUnicode_Partition(self, sep);
13446
8.50M
}
13447
13448
/*[clinic input]
13449
str.rpartition as unicode_rpartition = str.partition
13450
13451
Partition the string into three parts using the given separator.
13452
13453
This will search for the separator in the string, starting at the
13454
end.  If the separator is found, returns a 3-tuple containing the
13455
part before the separator, the separator itself, and the part after
13456
it.
13457
13458
If the separator is not found, returns a 3-tuple containing two
13459
empty strings and the original string.
13460
[clinic start generated code]*/
13461
13462
static PyObject *
13463
unicode_rpartition(PyObject *self, PyObject *sep)
13464
/*[clinic end generated code: output=1aa13cf1156572aa input=53a7f8cb19975b7c]*/
13465
51.6k
{
13466
51.6k
    return PyUnicode_RPartition(self, sep);
13467
51.6k
}
13468
13469
PyObject *
13470
PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13471
0
{
13472
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13473
0
        return NULL;
13474
13475
0
    return rsplit(s, sep, maxsplit);
13476
0
}
13477
13478
/*[clinic input]
13479
@permit_long_summary
13480
str.rsplit as unicode_rsplit = str.split
13481
13482
Return a list of the substrings in the string, using sep as the separator string.
13483
13484
Splitting starts at the end of the string and works to the front.
13485
[clinic start generated code]*/
13486
13487
static PyObject *
13488
unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13489
/*[clinic end generated code: output=c2b815c63bcabffc input=0f762e30d267fa83]*/
13490
66
{
13491
66
    if (sep == Py_None)
13492
0
        return rsplit(self, NULL, maxsplit);
13493
66
    if (PyUnicode_Check(sep))
13494
66
        return rsplit(self, sep, maxsplit);
13495
13496
0
    PyErr_Format(PyExc_TypeError,
13497
0
                 "must be str or None, not %.100s",
13498
0
                 Py_TYPE(sep)->tp_name);
13499
0
    return NULL;
13500
66
}
13501
13502
/*[clinic input]
13503
@permit_long_summary
13504
str.splitlines as unicode_splitlines
13505
13506
    keepends: bool = False
13507
13508
Return a list of the lines in the string, breaking at line boundaries.
13509
13510
Line breaks are not included in the resulting list unless keepends
13511
is given and true.
13512
[clinic start generated code]*/
13513
13514
static PyObject *
13515
unicode_splitlines_impl(PyObject *self, int keepends)
13516
/*[clinic end generated code: output=f664dcdad153ec40 input=b45ea0f87645a06d]*/
13517
16.4k
{
13518
16.4k
    return PyUnicode_Splitlines(self, keepends);
13519
16.4k
}
13520
13521
static
13522
PyObject *unicode_str(PyObject *self)
13523
2.70M
{
13524
2.70M
    return unicode_result_unchanged(self);
13525
2.70M
}
13526
13527
/*[clinic input]
13528
@permit_long_summary
13529
str.swapcase as unicode_swapcase
13530
13531
Convert uppercase characters to lowercase and lowercase characters to uppercase.
13532
[clinic start generated code]*/
13533
13534
static PyObject *
13535
unicode_swapcase_impl(PyObject *self)
13536
/*[clinic end generated code: output=5d28966bf6d7b2af input=85bc39a9b4e8ee91]*/
13537
0
{
13538
0
    return case_operation(self, do_swapcase);
13539
0
}
13540
13541
static int
13542
unicode_maketrans_from_dict(PyObject *x, PyObject *newdict)
13543
0
{
13544
0
    PyObject *key, *value;
13545
0
    Py_ssize_t i = 0;
13546
0
    int res;
13547
0
    while (PyDict_Next(x, &i, &key, &value)) {
13548
0
        if (PyUnicode_Check(key)) {
13549
0
            PyObject *newkey;
13550
0
            int kind;
13551
0
            const void *data;
13552
0
            if (PyUnicode_GET_LENGTH(key) != 1) {
13553
0
                PyErr_SetString(PyExc_ValueError, "string keys in translate"
13554
0
                                "table must be of length 1");
13555
0
                return -1;
13556
0
            }
13557
0
            kind = PyUnicode_KIND(key);
13558
0
            data = PyUnicode_DATA(key);
13559
0
            newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
13560
0
            if (!newkey)
13561
0
                return -1;
13562
0
            res = PyDict_SetItem(newdict, newkey, value);
13563
0
            Py_DECREF(newkey);
13564
0
            if (res < 0)
13565
0
                return -1;
13566
0
        }
13567
0
        else if (PyLong_Check(key)) {
13568
0
            if (PyDict_SetItem(newdict, key, value) < 0)
13569
0
                return -1;
13570
0
        }
13571
0
        else {
13572
0
            PyErr_SetString(PyExc_TypeError, "keys in translate table must"
13573
0
                            "be strings or integers");
13574
0
            return -1;
13575
0
        }
13576
0
    }
13577
0
    return 0;
13578
0
}
13579
13580
/*[clinic input]
13581
13582
@staticmethod
13583
str.maketrans as unicode_maketrans
13584
13585
  x: object
13586
13587
  y: unicode=NULL
13588
13589
  z: unicode=NULL
13590
13591
  /
13592
13593
Return a translation table usable for str.translate().
13594
13595
If there is only one argument, it must be a dictionary mapping
13596
Unicode ordinals (integers) or characters to Unicode ordinals,
13597
strings or None.  Character keys will be then converted to ordinals.
13598
If there are two arguments, they must be strings of equal length,
13599
and in the resulting dictionary, each character in x will be mapped
13600
to the character at the same position in y.  If there is a third
13601
argument, it must be a string, whose characters will be mapped to
13602
None in the result.
13603
[clinic start generated code]*/
13604
13605
static PyObject *
13606
unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
13607
/*[clinic end generated code: output=a925c89452bd5881 input=66bc00a1b4258a6e]*/
13608
4
{
13609
4
    PyObject *new = NULL, *key, *value;
13610
4
    Py_ssize_t i = 0;
13611
4
    int res;
13612
13613
4
    new = PyDict_New();
13614
4
    if (!new)
13615
0
        return NULL;
13616
4
    if (y != NULL) {
13617
4
        int x_kind, y_kind, z_kind;
13618
4
        const void *x_data, *y_data, *z_data;
13619
13620
        /* x must be a string too, of equal length */
13621
4
        if (!PyUnicode_Check(x)) {
13622
0
            PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13623
0
                            "be a string if there is a second argument");
13624
0
            goto err;
13625
0
        }
13626
4
        if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
13627
0
            PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13628
0
                            "arguments must have equal length");
13629
0
            goto err;
13630
0
        }
13631
        /* create entries for translating chars in x to those in y */
13632
4
        x_kind = PyUnicode_KIND(x);
13633
4
        y_kind = PyUnicode_KIND(y);
13634
4
        x_data = PyUnicode_DATA(x);
13635
4
        y_data = PyUnicode_DATA(y);
13636
36
        for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13637
32
            key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
13638
32
            if (!key)
13639
0
                goto err;
13640
32
            value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
13641
32
            if (!value) {
13642
0
                Py_DECREF(key);
13643
0
                goto err;
13644
0
            }
13645
32
            res = PyDict_SetItem(new, key, value);
13646
32
            Py_DECREF(key);
13647
32
            Py_DECREF(value);
13648
32
            if (res < 0)
13649
0
                goto err;
13650
32
        }
13651
        /* create entries for deleting chars in z */
13652
4
        if (z != NULL) {
13653
0
            z_kind = PyUnicode_KIND(z);
13654
0
            z_data = PyUnicode_DATA(z);
13655
0
            for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
13656
0
                key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
13657
0
                if (!key)
13658
0
                    goto err;
13659
0
                res = PyDict_SetItem(new, key, Py_None);
13660
0
                Py_DECREF(key);
13661
0
                if (res < 0)
13662
0
                    goto err;
13663
0
            }
13664
0
        }
13665
4
    } else {
13666
        /* x must be a dict */
13667
0
        if (!PyAnyDict_CheckExact(x)) {
13668
0
            PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13669
0
                            "to maketrans it must be a dict");
13670
0
            goto err;
13671
0
        }
13672
        /* copy entries into the new dict, converting string keys to int keys */
13673
0
        int errcode;
13674
0
        Py_BEGIN_CRITICAL_SECTION(x);
13675
0
        errcode = unicode_maketrans_from_dict(x, new);
13676
0
        Py_END_CRITICAL_SECTION();
13677
0
        if (errcode < 0)
13678
0
            goto err;
13679
0
    }
13680
4
    return new;
13681
0
  err:
13682
0
    Py_DECREF(new);
13683
0
    return NULL;
13684
4
}
13685
13686
/*[clinic input]
13687
@permit_long_summary
13688
str.translate as unicode_translate
13689
13690
    table: object
13691
        Translation table, which must be a mapping of Unicode ordinals
13692
        to Unicode ordinals, strings, or None.
13693
    /
13694
13695
Replace each character in the string using the given translation table.
13696
13697
The table must implement lookup/indexing via __getitem__, for
13698
instance a dictionary or list.  If this operation raises
13699
LookupError, the character is left untouched.  Characters mapped to
13700
None are deleted.
13701
[clinic start generated code]*/
13702
13703
static PyObject *
13704
unicode_translate(PyObject *self, PyObject *table)
13705
/*[clinic end generated code: output=3cb448ff2fd96bf3 input=48cf0efe06bc1b75]*/
13706
11.9k
{
13707
11.9k
    return _PyUnicode_TranslateCharmap(self, table, "ignore");
13708
11.9k
}
13709
13710
/*[clinic input]
13711
str.upper as unicode_upper
13712
13713
Return a copy of the string converted to uppercase.
13714
[clinic start generated code]*/
13715
13716
static PyObject *
13717
unicode_upper_impl(PyObject *self)
13718
/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
13719
306
{
13720
306
    if (PyUnicode_IS_ASCII(self))
13721
306
        return ascii_upper_or_lower(self, 0);
13722
0
    return case_operation(self, do_upper);
13723
306
}
13724
13725
/*[clinic input]
13726
@permit_long_summary
13727
str.zfill as unicode_zfill
13728
13729
    width: Py_ssize_t
13730
    /
13731
13732
Pad a numeric string with zeros on the left, to fill a field of the given width.
13733
13734
The string is never truncated.
13735
[clinic start generated code]*/
13736
13737
static PyObject *
13738
unicode_zfill_impl(PyObject *self, Py_ssize_t width)
13739
/*[clinic end generated code: output=e13fb6bdf8e3b9df input=25a4ee0ea3e58ce0]*/
13740
0
{
13741
0
    Py_ssize_t fill;
13742
0
    PyObject *u;
13743
0
    int kind;
13744
0
    const void *data;
13745
0
    Py_UCS4 chr;
13746
13747
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13748
0
        return unicode_result_unchanged(self);
13749
13750
0
    fill = width - PyUnicode_GET_LENGTH(self);
13751
13752
0
    u = pad(self, fill, 0, '0');
13753
13754
0
    if (u == NULL)
13755
0
        return NULL;
13756
13757
0
    kind = PyUnicode_KIND(u);
13758
0
    data = PyUnicode_DATA(u);
13759
0
    chr = PyUnicode_READ(kind, data, fill);
13760
13761
0
    if (chr == '+' || chr == '-') {
13762
        /* move sign to beginning of string */
13763
0
        PyUnicode_WRITE(kind, data, 0, chr);
13764
0
        PyUnicode_WRITE(kind, data, fill, '0');
13765
0
    }
13766
13767
0
    assert(_PyUnicode_CheckConsistency(u, 1));
13768
0
    return u;
13769
0
}
13770
13771
/*[clinic input]
13772
@permit_long_summary
13773
@text_signature "($self, prefix[, start[, end]], /)"
13774
str.startswith as unicode_startswith
13775
13776
    prefix as subobj: object
13777
        A string or a tuple of strings to try.
13778
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13779
        Optional start position. Default: start of the string.
13780
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13781
        Optional stop position. Default: end of the string.
13782
    /
13783
13784
Return True if the string starts with the specified prefix, False otherwise.
13785
[clinic start generated code]*/
13786
13787
static PyObject *
13788
unicode_startswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13789
                        Py_ssize_t end)
13790
/*[clinic end generated code: output=4bd7cfd0803051d4 input=766bdbd33df251dc]*/
13791
20.6M
{
13792
20.6M
    if (PyTuple_Check(subobj)) {
13793
1.42M
        Py_ssize_t i;
13794
5.21M
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13795
3.80M
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13796
3.80M
            if (!PyUnicode_Check(substring)) {
13797
0
                PyErr_Format(PyExc_TypeError,
13798
0
                             "tuple for startswith must only contain str, "
13799
0
                             "not %.100s",
13800
0
                             Py_TYPE(substring)->tp_name);
13801
0
                return NULL;
13802
0
            }
13803
3.80M
            int result = tailmatch(self, substring, start, end, -1);
13804
3.80M
            if (result < 0) {
13805
0
                return NULL;
13806
0
            }
13807
3.80M
            if (result) {
13808
19.2k
                Py_RETURN_TRUE;
13809
19.2k
            }
13810
3.80M
        }
13811
        /* nothing matched */
13812
1.42M
        Py_RETURN_FALSE;
13813
1.42M
    }
13814
19.2M
    if (!PyUnicode_Check(subobj)) {
13815
0
        PyErr_Format(PyExc_TypeError,
13816
0
                     "startswith first arg must be str or "
13817
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13818
0
        return NULL;
13819
0
    }
13820
19.2M
    int result = tailmatch(self, subobj, start, end, -1);
13821
19.2M
    if (result < 0) {
13822
0
        return NULL;
13823
0
    }
13824
19.2M
    return PyBool_FromLong(result);
13825
19.2M
}
13826
13827
13828
/*[clinic input]
13829
@permit_long_summary
13830
@text_signature "($self, suffix[, start[, end]], /)"
13831
str.endswith as unicode_endswith
13832
13833
    suffix as subobj: object
13834
        A string or a tuple of strings to try.
13835
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13836
        Optional start position. Default: start of the string.
13837
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13838
        Optional stop position. Default: end of the string.
13839
    /
13840
13841
Return True if the string ends with the specified suffix, False otherwise.
13842
[clinic start generated code]*/
13843
13844
static PyObject *
13845
unicode_endswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13846
                      Py_ssize_t end)
13847
/*[clinic end generated code: output=cce6f8ceb0102ca9 input=b66bf6d5547ba1aa]*/
13848
9.73M
{
13849
9.73M
    if (PyTuple_Check(subobj)) {
13850
156k
        Py_ssize_t i;
13851
274k
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13852
258k
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13853
258k
            if (!PyUnicode_Check(substring)) {
13854
0
                PyErr_Format(PyExc_TypeError,
13855
0
                             "tuple for endswith must only contain str, "
13856
0
                             "not %.100s",
13857
0
                             Py_TYPE(substring)->tp_name);
13858
0
                return NULL;
13859
0
            }
13860
258k
            int result = tailmatch(self, substring, start, end, +1);
13861
258k
            if (result < 0) {
13862
0
                return NULL;
13863
0
            }
13864
258k
            if (result) {
13865
140k
                Py_RETURN_TRUE;
13866
140k
            }
13867
258k
        }
13868
156k
        Py_RETURN_FALSE;
13869
156k
    }
13870
9.57M
    if (!PyUnicode_Check(subobj)) {
13871
0
        PyErr_Format(PyExc_TypeError,
13872
0
                     "endswith first arg must be str or "
13873
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13874
0
        return NULL;
13875
0
    }
13876
9.57M
    int result = tailmatch(self, subobj, start, end, +1);
13877
9.57M
    if (result < 0) {
13878
0
        return NULL;
13879
0
    }
13880
9.57M
    return PyBool_FromLong(result);
13881
9.57M
}
13882
13883
13884
#include "stringlib/unicode_format.h"
13885
13886
PyDoc_STRVAR(format__doc__,
13887
             "format($self, /, *args, **kwargs)\n\
13888
--\n\
13889
\n\
13890
Return a formatted version of the string, using substitutions from args and kwargs.\n\
13891
The substitutions are identified by braces ('{' and '}').");
13892
13893
PyDoc_STRVAR(format_map__doc__,
13894
             "format_map($self, mapping, /)\n\
13895
--\n\
13896
\n\
13897
Return a formatted version of the string, using substitutions from mapping.\n\
13898
The substitutions are identified by braces ('{' and '}').");
13899
13900
/*[clinic input]
13901
@permit_long_summary
13902
str.__format__ as unicode___format__
13903
13904
    format_spec: unicode
13905
    /
13906
13907
Return a formatted version of the string as described by format_spec.
13908
[clinic start generated code]*/
13909
13910
static PyObject *
13911
unicode___format___impl(PyObject *self, PyObject *format_spec)
13912
/*[clinic end generated code: output=45fceaca6d2ba4c8 input=77a2a19f3f7969f2]*/
13913
0
{
13914
0
    _PyUnicodeWriter writer;
13915
0
    int ret;
13916
13917
0
    _PyUnicodeWriter_Init(&writer);
13918
0
    ret = _PyUnicode_FormatAdvancedWriter(&writer,
13919
0
                                          self, format_spec, 0,
13920
0
                                          PyUnicode_GET_LENGTH(format_spec));
13921
0
    if (ret == -1) {
13922
0
        _PyUnicodeWriter_Dealloc(&writer);
13923
0
        return NULL;
13924
0
    }
13925
0
    return _PyUnicodeWriter_Finish(&writer);
13926
0
}
13927
13928
/*[clinic input]
13929
str.__sizeof__ as unicode_sizeof
13930
13931
Return the size of the string in memory, in bytes.
13932
[clinic start generated code]*/
13933
13934
static PyObject *
13935
unicode_sizeof_impl(PyObject *self)
13936
/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
13937
0
{
13938
0
    Py_ssize_t size;
13939
13940
    /* If it's a compact object, account for base structure +
13941
       character data. */
13942
0
    if (PyUnicode_IS_COMPACT_ASCII(self)) {
13943
0
        size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13944
0
    }
13945
0
    else if (PyUnicode_IS_COMPACT(self)) {
13946
0
        size = sizeof(PyCompactUnicodeObject) +
13947
0
            (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
13948
0
    }
13949
0
    else {
13950
        /* If it is a two-block object, account for base object, and
13951
           for character block if present. */
13952
0
        size = sizeof(PyUnicodeObject);
13953
0
        if (_PyUnicode_DATA_ANY(self))
13954
0
            size += (PyUnicode_GET_LENGTH(self) + 1) *
13955
0
                PyUnicode_KIND(self);
13956
0
    }
13957
0
    if (_PyUnicode_HAS_UTF8_MEMORY(self))
13958
0
        size += PyUnicode_UTF8_LENGTH(self) + 1;
13959
13960
0
    return PyLong_FromSsize_t(size);
13961
0
}
13962
13963
static PyObject *
13964
unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
13965
0
{
13966
0
    PyObject *copy = _PyUnicode_Copy(v);
13967
0
    if (!copy)
13968
0
        return NULL;
13969
0
    return Py_BuildValue("(N)", copy);
13970
0
}
13971
13972
/*
13973
This function searchs the longest common leading whitespace
13974
of all lines in the [src, end).
13975
It returns the length of the common leading whitespace and sets `output` to
13976
point to the beginning of the common leading whitespace if length > 0.
13977
*/
13978
static Py_ssize_t
13979
search_longest_common_leading_whitespace(
13980
    const char *const src,
13981
    const char *const end,
13982
    const char **output)
13983
0
{
13984
    // [_start, _start + _len)
13985
    // describes the current longest common leading whitespace
13986
0
    const char *_start = NULL;
13987
0
    Py_ssize_t _len = 0;
13988
13989
0
    for (const char *iter = src; iter < end; ++iter) {
13990
0
        const char *line_start = iter;
13991
0
        const char *leading_whitespace_end = NULL;
13992
13993
        // scan the whole line
13994
0
        while (iter < end && *iter != '\n') {
13995
0
            if (!leading_whitespace_end && *iter != ' ' && *iter != '\t') {
13996
                /* `iter` points to the first non-whitespace character
13997
                   in this line */
13998
0
                if (iter == line_start) {
13999
                    // some line has no indent, fast exit!
14000
0
                    return 0;
14001
0
                }
14002
0
                leading_whitespace_end = iter;
14003
0
            }
14004
0
            ++iter;
14005
0
        }
14006
14007
        // if this line has all white space, skip it
14008
0
        if (!leading_whitespace_end) {
14009
0
            continue;
14010
0
        }
14011
14012
0
        if (!_start) {
14013
            // update the first leading whitespace
14014
0
            _start = line_start;
14015
0
            _len = leading_whitespace_end - line_start;
14016
0
            assert(_len > 0);
14017
0
        }
14018
0
        else {
14019
            /* We then compare with the current longest leading whitespace.
14020
14021
               [line_start, leading_whitespace_end) is the leading
14022
               whitespace of this line,
14023
14024
               [_start, _start + _len) is the leading whitespace of the
14025
               current longest leading whitespace. */
14026
0
            Py_ssize_t new_len = 0;
14027
0
            const char *_iter = _start, *line_iter = line_start;
14028
14029
0
            while (_iter < _start + _len && line_iter < leading_whitespace_end
14030
0
                   && *_iter == *line_iter)
14031
0
            {
14032
0
                ++_iter;
14033
0
                ++line_iter;
14034
0
                ++new_len;
14035
0
            }
14036
14037
0
            _len = new_len;
14038
0
            if (_len == 0) {
14039
                // No common things now, fast exit!
14040
0
                return 0;
14041
0
            }
14042
0
        }
14043
0
    }
14044
14045
0
    assert(_len >= 0);
14046
0
    if (_len > 0) {
14047
0
        *output = _start;
14048
0
    }
14049
0
    return _len;
14050
0
}
14051
14052
/* Dedent a string.
14053
   Intended to dedent Python source. Unlike `textwrap.dedent`, this
14054
   only supports spaces and tabs and doesn't normalize empty lines.
14055
   Return a new reference on success, NULL with exception set on error.
14056
   */
14057
PyObject *
14058
_PyUnicode_Dedent(PyObject *unicode)
14059
0
{
14060
0
    Py_ssize_t src_len = 0;
14061
0
    const char *src = PyUnicode_AsUTF8AndSize(unicode, &src_len);
14062
0
    if (!src) {
14063
0
        return NULL;
14064
0
    }
14065
0
    assert(src_len >= 0);
14066
0
    if (src_len == 0) {
14067
0
        return Py_NewRef(unicode);
14068
0
    }
14069
14070
0
    const char *const end = src + src_len;
14071
14072
    // [whitespace_start, whitespace_start + whitespace_len)
14073
    // describes the current longest common leading whitespace
14074
0
    const char *whitespace_start = NULL;
14075
0
    Py_ssize_t whitespace_len = search_longest_common_leading_whitespace(
14076
0
        src, end, &whitespace_start);
14077
14078
0
    if (whitespace_len == 0) {
14079
0
        return Py_NewRef(unicode);
14080
0
    }
14081
14082
    // now we should trigger a dedent
14083
0
    char *dest = PyMem_Malloc(src_len);
14084
0
    if (!dest) {
14085
0
        PyErr_NoMemory();
14086
0
        return NULL;
14087
0
    }
14088
0
    char *dest_iter = dest;
14089
14090
0
    for (const char *iter = src; iter < end; ++iter) {
14091
0
        const char *line_start = iter;
14092
0
        bool in_leading_space = true;
14093
14094
        // iterate over a line to find the end of a line
14095
0
        while (iter < end && *iter != '\n') {
14096
0
            if (in_leading_space && *iter != ' ' && *iter != '\t') {
14097
0
                in_leading_space = false;
14098
0
            }
14099
0
            ++iter;
14100
0
        }
14101
14102
        // invariant: *iter == '\n' or iter == end
14103
0
        bool append_newline = iter < end;
14104
14105
        // if this line has all white space, write '\n' and continue
14106
0
        if (in_leading_space && append_newline) {
14107
0
            *dest_iter++ = '\n';
14108
0
            continue;
14109
0
        }
14110
14111
        /* copy [new_line_start + whitespace_len, iter) to buffer, then
14112
            conditionally append '\n' */
14113
14114
0
        Py_ssize_t new_line_len = iter - line_start - whitespace_len;
14115
0
        assert(new_line_len >= 0);
14116
0
        memcpy(dest_iter, line_start + whitespace_len, new_line_len);
14117
14118
0
        dest_iter += new_line_len;
14119
14120
0
        if (append_newline) {
14121
0
            *dest_iter++ = '\n';
14122
0
        }
14123
0
    }
14124
14125
0
    PyObject *res = PyUnicode_FromStringAndSize(dest, dest_iter - dest);
14126
0
    PyMem_Free(dest);
14127
0
    return res;
14128
0
}
14129
14130
static PyMethodDef unicode_methods[] = {
14131
    UNICODE_ENCODE_METHODDEF
14132
    UNICODE_REPLACE_METHODDEF
14133
    UNICODE_SPLIT_METHODDEF
14134
    UNICODE_RSPLIT_METHODDEF
14135
    UNICODE_JOIN_METHODDEF
14136
    UNICODE_CAPITALIZE_METHODDEF
14137
    UNICODE_CASEFOLD_METHODDEF
14138
    UNICODE_TITLE_METHODDEF
14139
    UNICODE_CENTER_METHODDEF
14140
    UNICODE_COUNT_METHODDEF
14141
    UNICODE_EXPANDTABS_METHODDEF
14142
    UNICODE_FIND_METHODDEF
14143
    UNICODE_PARTITION_METHODDEF
14144
    UNICODE_INDEX_METHODDEF
14145
    UNICODE_LJUST_METHODDEF
14146
    UNICODE_LOWER_METHODDEF
14147
    UNICODE_LSTRIP_METHODDEF
14148
    UNICODE_RFIND_METHODDEF
14149
    UNICODE_RINDEX_METHODDEF
14150
    UNICODE_RJUST_METHODDEF
14151
    UNICODE_RSTRIP_METHODDEF
14152
    UNICODE_RPARTITION_METHODDEF
14153
    UNICODE_SPLITLINES_METHODDEF
14154
    UNICODE_STRIP_METHODDEF
14155
    UNICODE_SWAPCASE_METHODDEF
14156
    UNICODE_TRANSLATE_METHODDEF
14157
    UNICODE_UPPER_METHODDEF
14158
    UNICODE_STARTSWITH_METHODDEF
14159
    UNICODE_ENDSWITH_METHODDEF
14160
    UNICODE_REMOVEPREFIX_METHODDEF
14161
    UNICODE_REMOVESUFFIX_METHODDEF
14162
    UNICODE_ISASCII_METHODDEF
14163
    UNICODE_ISLOWER_METHODDEF
14164
    UNICODE_ISUPPER_METHODDEF
14165
    UNICODE_ISTITLE_METHODDEF
14166
    UNICODE_ISSPACE_METHODDEF
14167
    UNICODE_ISDECIMAL_METHODDEF
14168
    UNICODE_ISDIGIT_METHODDEF
14169
    UNICODE_ISNUMERIC_METHODDEF
14170
    UNICODE_ISALPHA_METHODDEF
14171
    UNICODE_ISALNUM_METHODDEF
14172
    UNICODE_ISIDENTIFIER_METHODDEF
14173
    UNICODE_ISPRINTABLE_METHODDEF
14174
    UNICODE_ZFILL_METHODDEF
14175
    {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
14176
    {"format_map", do_string_format_map, METH_O, format_map__doc__},
14177
    UNICODE___FORMAT___METHODDEF
14178
    UNICODE_MAKETRANS_METHODDEF
14179
    UNICODE_SIZEOF_METHODDEF
14180
    {"__getnewargs__",  unicode_getnewargs, METH_NOARGS},
14181
    {NULL, NULL}
14182
};
14183
14184
static PyObject *
14185
unicode_mod(PyObject *v, PyObject *w)
14186
12.5M
{
14187
12.5M
    if (!PyUnicode_Check(v))
14188
0
        Py_RETURN_NOTIMPLEMENTED;
14189
12.5M
    return PyUnicode_Format(v, w);
14190
12.5M
}
14191
14192
static PyNumberMethods unicode_as_number = {
14193
    0,              /*nb_add*/
14194
    0,              /*nb_subtract*/
14195
    0,              /*nb_multiply*/
14196
    unicode_mod,            /*nb_remainder*/
14197
};
14198
14199
static PySequenceMethods unicode_as_sequence = {
14200
    unicode_length,     /* sq_length */
14201
    PyUnicode_Concat,   /* sq_concat */
14202
    _PyUnicode_Repeat,  /* sq_repeat */
14203
    unicode_getitem,    /* sq_item */
14204
    0,                  /* sq_slice */
14205
    0,                  /* sq_ass_item */
14206
    0,                  /* sq_ass_slice */
14207
    PyUnicode_Contains, /* sq_contains */
14208
};
14209
14210
static PyObject*
14211
unicode_subscript(PyObject* self, PyObject* item)
14212
67.3M
{
14213
67.3M
    if (_PyIndex_Check(item)) {
14214
57.1M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
14215
57.1M
        if (i == -1 && PyErr_Occurred())
14216
0
            return NULL;
14217
57.1M
        if (i < 0)
14218
61.5k
            i += PyUnicode_GET_LENGTH(self);
14219
57.1M
        return unicode_getitem(self, i);
14220
57.1M
    } else if (PySlice_Check(item)) {
14221
10.2M
        Py_ssize_t start, stop, step, slicelength, i;
14222
10.2M
        size_t cur;
14223
10.2M
        PyObject *result;
14224
10.2M
        const void *src_data;
14225
10.2M
        void *dest_data;
14226
10.2M
        int src_kind, dest_kind;
14227
10.2M
        Py_UCS4 ch, max_char, kind_limit;
14228
14229
10.2M
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
14230
0
            return NULL;
14231
0
        }
14232
10.2M
        slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14233
10.2M
                                            &start, &stop, step);
14234
14235
10.2M
        if (slicelength <= 0) {
14236
1.05M
            _Py_RETURN_UNICODE_EMPTY();
14237
9.18M
        } else if (start == 0 && step == 1 &&
14238
247k
                   slicelength == PyUnicode_GET_LENGTH(self)) {
14239
1.95k
            return unicode_result_unchanged(self);
14240
9.18M
        } else if (step == 1) {
14241
9.18M
            return PyUnicode_Substring(self,
14242
9.18M
                                       start, start + slicelength);
14243
9.18M
        }
14244
        /* General case */
14245
0
        src_kind = PyUnicode_KIND(self);
14246
0
        src_data = PyUnicode_DATA(self);
14247
0
        if (!PyUnicode_IS_ASCII(self)) {
14248
0
            kind_limit = kind_maxchar_limit(src_kind);
14249
0
            max_char = 0;
14250
0
            for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14251
0
                ch = PyUnicode_READ(src_kind, src_data, cur);
14252
0
                if (ch > max_char) {
14253
0
                    max_char = ch;
14254
0
                    if (max_char >= kind_limit)
14255
0
                        break;
14256
0
                }
14257
0
            }
14258
0
        }
14259
0
        else
14260
0
            max_char = 127;
14261
0
        result = PyUnicode_New(slicelength, max_char);
14262
0
        if (result == NULL)
14263
0
            return NULL;
14264
0
        dest_kind = PyUnicode_KIND(result);
14265
0
        dest_data = PyUnicode_DATA(result);
14266
14267
0
        for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14268
0
            Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14269
0
            PyUnicode_WRITE(dest_kind, dest_data, i, ch);
14270
0
        }
14271
0
        assert(_PyUnicode_CheckConsistency(result, 1));
14272
0
        return result;
14273
0
    } else {
14274
0
        PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
14275
0
                     Py_TYPE(item)->tp_name);
14276
0
        return NULL;
14277
0
    }
14278
67.3M
}
14279
14280
static PyMappingMethods unicode_as_mapping = {
14281
    unicode_length,     /* mp_length */
14282
    unicode_subscript,  /* mp_subscript */
14283
    0,                  /* mp_ass_subscript */
14284
};
14285
14286
14287
static PyObject *
14288
unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
14289
14290
/*[clinic input]
14291
@classmethod
14292
str.__new__ as unicode_new
14293
14294
    object as x: object = NULL
14295
    encoding: str = NULL
14296
    errors: str = NULL
14297
14298
[clinic start generated code]*/
14299
14300
static PyObject *
14301
unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
14302
                 const char *errors)
14303
/*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
14304
17.2M
{
14305
17.2M
    PyObject *unicode;
14306
17.2M
    if (x == NULL) {
14307
0
        unicode = _PyUnicode_GetEmpty();
14308
0
    }
14309
17.2M
    else if (encoding == NULL && errors == NULL) {
14310
17.2M
        unicode = PyObject_Str(x);
14311
17.2M
    }
14312
0
    else {
14313
0
        unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
14314
0
    }
14315
14316
17.2M
    if (unicode != NULL && type != &PyUnicode_Type) {
14317
17.2M
        Py_SETREF(unicode, unicode_subtype_new(type, unicode));
14318
17.2M
    }
14319
17.2M
    return unicode;
14320
17.2M
}
14321
14322
static const char *
14323
arg_as_utf8(PyObject *obj, const char *name)
14324
9.93M
{
14325
9.93M
    if (!PyUnicode_Check(obj)) {
14326
0
        PyErr_Format(PyExc_TypeError,
14327
0
                     "str() argument '%s' must be str, not %T",
14328
0
                     name, obj);
14329
0
        return NULL;
14330
0
    }
14331
9.93M
    return _PyUnicode_AsUTF8NoNUL(obj);
14332
9.93M
}
14333
14334
static PyObject *
14335
unicode_vectorcall(PyObject *type, PyObject *const *args,
14336
                   size_t nargsf, PyObject *kwnames)
14337
9.33M
{
14338
9.33M
    assert(Py_Is(_PyType_CAST(type), &PyUnicode_Type));
14339
14340
9.33M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
14341
9.33M
    if (kwnames != NULL && PyTuple_GET_SIZE(kwnames) != 0) {
14342
        // Fallback to unicode_new()
14343
0
        PyObject *tuple = PyTuple_FromArray(args, nargs);
14344
0
        if (tuple == NULL) {
14345
0
            return NULL;
14346
0
        }
14347
0
        PyObject *dict = _PyStack_AsDict(args + nargs, kwnames);
14348
0
        if (dict == NULL) {
14349
0
            Py_DECREF(tuple);
14350
0
            return NULL;
14351
0
        }
14352
0
        PyObject *ret = unicode_new(_PyType_CAST(type), tuple, dict);
14353
0
        Py_DECREF(tuple);
14354
0
        Py_DECREF(dict);
14355
0
        return ret;
14356
0
    }
14357
9.33M
    if (!_PyArg_CheckPositional("str", nargs, 0, 3)) {
14358
0
        return NULL;
14359
0
    }
14360
9.33M
    if (nargs == 0) {
14361
4.11k
        return _PyUnicode_GetEmpty();
14362
4.11k
    }
14363
9.32M
    PyObject *object = args[0];
14364
9.32M
    if (nargs == 1) {
14365
1.15k
        return PyObject_Str(object);
14366
1.15k
    }
14367
9.32M
    const char *encoding = arg_as_utf8(args[1], "encoding");
14368
9.32M
    if (encoding == NULL) {
14369
0
        return NULL;
14370
0
    }
14371
9.32M
    const char *errors = NULL;
14372
9.32M
    if (nargs == 3) {
14373
602k
        errors = arg_as_utf8(args[2], "errors");
14374
602k
        if (errors == NULL) {
14375
0
            return NULL;
14376
0
        }
14377
602k
    }
14378
9.32M
    return PyUnicode_FromEncodedObject(object, encoding, errors);
14379
9.32M
}
14380
14381
static PyObject *
14382
unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
14383
17.2M
{
14384
17.2M
    PyObject *self;
14385
17.2M
    Py_ssize_t length, char_size;
14386
17.2M
    int share_utf8;
14387
17.2M
    int kind;
14388
17.2M
    void *data;
14389
14390
17.2M
    assert(PyType_IsSubtype(type, &PyUnicode_Type));
14391
17.2M
    assert(_PyUnicode_CHECK(unicode));
14392
14393
17.2M
    self = type->tp_alloc(type, 0);
14394
17.2M
    if (self == NULL) {
14395
0
        return NULL;
14396
0
    }
14397
17.2M
    kind = PyUnicode_KIND(unicode);
14398
17.2M
    length = PyUnicode_GET_LENGTH(unicode);
14399
14400
17.2M
    _PyUnicode_LENGTH(self) = length;
14401
#ifdef Py_DEBUG
14402
    _PyUnicode_HASH(self) = -1;
14403
#else
14404
17.2M
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14405
17.2M
#endif
14406
17.2M
    _PyUnicode_STATE(self).interned = 0;
14407
17.2M
    _PyUnicode_STATE(self).kind = kind;
14408
17.2M
    _PyUnicode_STATE(self).compact = 0;
14409
17.2M
    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
14410
17.2M
    _PyUnicode_STATE(self).statically_allocated = 0;
14411
17.2M
    PyUnicode_SET_UTF8_LENGTH(self, 0);
14412
17.2M
    PyUnicode_SET_UTF8(self, NULL);
14413
17.2M
    _PyUnicode_DATA_ANY(self) = NULL;
14414
14415
17.2M
    share_utf8 = 0;
14416
17.2M
    if (kind == PyUnicode_1BYTE_KIND) {
14417
14.4M
        char_size = 1;
14418
14.4M
        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14419
14.4M
            share_utf8 = 1;
14420
14.4M
    }
14421
2.75M
    else if (kind == PyUnicode_2BYTE_KIND) {
14422
2.69M
        char_size = 2;
14423
2.69M
    }
14424
61.3k
    else {
14425
61.3k
        assert(kind == PyUnicode_4BYTE_KIND);
14426
61.3k
        char_size = 4;
14427
61.3k
    }
14428
14429
    /* Ensure we won't overflow the length. */
14430
17.2M
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14431
0
        PyErr_NoMemory();
14432
0
        goto onError;
14433
0
    }
14434
17.2M
    data = PyMem_Malloc((length + 1) * char_size);
14435
17.2M
    if (data == NULL) {
14436
0
        PyErr_NoMemory();
14437
0
        goto onError;
14438
0
    }
14439
14440
17.2M
    _PyUnicode_DATA_ANY(self) = data;
14441
17.2M
    if (share_utf8) {
14442
14.4M
        PyUnicode_SET_UTF8_LENGTH(self, length);
14443
14.4M
        PyUnicode_SET_UTF8(self, data);
14444
14.4M
    }
14445
14446
17.2M
    memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
14447
17.2M
    assert(_PyUnicode_CheckConsistency(self, 1));
14448
#ifdef Py_DEBUG
14449
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14450
#endif
14451
17.2M
    return self;
14452
14453
0
onError:
14454
0
    Py_DECREF(self);
14455
0
    return NULL;
14456
17.2M
}
14457
14458
static _PyObjectIndexPair
14459
unicode_iteritem(PyObject *obj, Py_ssize_t index)
14460
57.3M
{
14461
57.3M
    if (index >= PyUnicode_GET_LENGTH(obj)) {
14462
11.7M
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
14463
11.7M
    }
14464
45.6M
    const void *data = PyUnicode_DATA(obj);
14465
45.6M
    int kind = PyUnicode_KIND(obj);
14466
45.6M
    Py_UCS4 ch = PyUnicode_READ(kind, data, index);
14467
45.6M
    PyObject *result = unicode_char(ch);
14468
45.6M
    index = (result == NULL) ? -1 : index + 1;
14469
45.6M
    return (_PyObjectIndexPair) { .object = result, .index = index };
14470
57.3M
}
14471
14472
void
14473
_PyUnicode_ExactDealloc(PyObject *op)
14474
92.7M
{
14475
92.7M
    assert(PyUnicode_CheckExact(op));
14476
92.7M
    unicode_dealloc(op);
14477
92.7M
}
14478
14479
PyDoc_STRVAR(unicode_doc,
14480
"str(object='') -> str\n\
14481
str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
14482
\n\
14483
Create a new string object from the given object. If encoding or\n\
14484
errors is specified, then the object must expose a data buffer\n\
14485
that will be decoded using the given encoding and error handler.\n\
14486
Otherwise, returns the result of object.__str__() (if defined)\n\
14487
or repr(object).\n\
14488
encoding defaults to 'utf-8'.\n\
14489
errors defaults to 'strict'.");
14490
14491
static PyObject *unicode_iter(PyObject *seq);
14492
14493
PyTypeObject PyUnicode_Type = {
14494
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
14495
    "str",                        /* tp_name */
14496
    sizeof(PyUnicodeObject),      /* tp_basicsize */
14497
    0,                            /* tp_itemsize */
14498
    /* Slots */
14499
    unicode_dealloc,              /* tp_dealloc */
14500
    0,                            /* tp_vectorcall_offset */
14501
    0,                            /* tp_getattr */
14502
    0,                            /* tp_setattr */
14503
    0,                            /* tp_as_async */
14504
    unicode_repr,                 /* tp_repr */
14505
    &unicode_as_number,           /* tp_as_number */
14506
    &unicode_as_sequence,         /* tp_as_sequence */
14507
    &unicode_as_mapping,          /* tp_as_mapping */
14508
    unicode_hash,                 /* tp_hash*/
14509
    0,                            /* tp_call*/
14510
    unicode_str,                  /* tp_str */
14511
    PyObject_GenericGetAttr,      /* tp_getattro */
14512
    0,                            /* tp_setattro */
14513
    0,                            /* tp_as_buffer */
14514
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
14515
        Py_TPFLAGS_UNICODE_SUBCLASS |
14516
        _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
14517
    unicode_doc,                  /* tp_doc */
14518
    0,                            /* tp_traverse */
14519
    0,                            /* tp_clear */
14520
    PyUnicode_RichCompare,        /* tp_richcompare */
14521
    0,                            /* tp_weaklistoffset */
14522
    unicode_iter,                 /* tp_iter */
14523
    0,                            /* tp_iternext */
14524
    unicode_methods,              /* tp_methods */
14525
    0,                            /* tp_members */
14526
    0,                            /* tp_getset */
14527
    0,                            /* tp_base */
14528
    0,                            /* tp_dict */
14529
    0,                            /* tp_descr_get */
14530
    0,                            /* tp_descr_set */
14531
    0,                            /* tp_dictoffset */
14532
    0,                            /* tp_init */
14533
    0,                            /* tp_alloc */
14534
    unicode_new,                  /* tp_new */
14535
    PyObject_Free,                /* tp_free */
14536
    .tp_version_tag = _Py_TYPE_VERSION_STR,
14537
    .tp_vectorcall = unicode_vectorcall,
14538
    ._tp_iteritem = unicode_iteritem,
14539
};
14540
14541
/* Initialize the Unicode implementation */
14542
14543
static void
14544
_init_global_state(void)
14545
37
{
14546
37
    static int initialized = 0;
14547
37
    if (initialized) {
14548
0
        return;
14549
0
    }
14550
37
    initialized = 1;
14551
14552
    /* initialize the linebreak bloom filter */
14553
37
    const Py_UCS2 linebreak[] = {
14554
37
        0x000A, /* LINE FEED */
14555
37
        0x000D, /* CARRIAGE RETURN */
14556
37
        0x001C, /* FILE SEPARATOR */
14557
37
        0x001D, /* GROUP SEPARATOR */
14558
37
        0x001E, /* RECORD SEPARATOR */
14559
37
        0x0085, /* NEXT LINE */
14560
37
        0x2028, /* LINE SEPARATOR */
14561
37
        0x2029, /* PARAGRAPH SEPARATOR */
14562
37
    };
14563
37
    bloom_linebreak = make_bloom_mask(
14564
37
        PyUnicode_2BYTE_KIND, linebreak,
14565
37
        Py_ARRAY_LENGTH(linebreak));
14566
37
}
14567
14568
void
14569
_PyUnicode_InitState(PyInterpreterState *interp)
14570
37
{
14571
37
    if (!_Py_IsMainInterpreter(interp)) {
14572
0
        return;
14573
0
    }
14574
37
    _init_global_state();
14575
37
}
14576
14577
14578
PyStatus
14579
_PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
14580
37
{
14581
37
    if (_Py_IsMainInterpreter(interp)) {
14582
37
        PyStatus status = init_global_interned_strings(interp);
14583
37
        if (_PyStatus_EXCEPTION(status)) {
14584
0
            return status;
14585
0
        }
14586
37
    }
14587
37
    assert(INTERNED_STRINGS);
14588
14589
37
    if (init_interned_dict(interp)) {
14590
0
        PyErr_Clear();
14591
0
        return _PyStatus_ERR("failed to create interned dict");
14592
0
    }
14593
14594
37
    return _PyStatus_OK();
14595
37
}
14596
14597
14598
PyStatus
14599
_PyUnicode_InitTypes(PyInterpreterState *interp)
14600
37
{
14601
37
    if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
14602
0
        goto error;
14603
0
    }
14604
37
    if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
14605
0
        goto error;
14606
0
    }
14607
37
    if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
14608
0
        goto error;
14609
0
    }
14610
37
    return _PyStatus_OK();
14611
14612
0
error:
14613
0
    return _PyStatus_ERR("Can't initialize unicode types");
14614
37
}
14615
14616
static /* non-null */ PyObject*
14617
intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
14618
42.3k
{
14619
    // Note that this steals a reference to `s`, but in many cases that
14620
    // stolen ref is returned, requiring no decref/incref.
14621
14622
42.3k
    assert(s != NULL);
14623
42.3k
    assert(_PyUnicode_CHECK(s));
14624
42.3k
    assert(_PyUnicode_STATE(s).statically_allocated);
14625
42.3k
    assert(!PyUnicode_CHECK_INTERNED(s));
14626
14627
#ifdef Py_DEBUG
14628
    /* We must not add process-global interned string if there's already a
14629
     * per-interpreter interned_dict, which might contain duplicates.
14630
     */
14631
    PyObject *interned = get_interned_dict(interp);
14632
    assert(interned == NULL);
14633
#endif
14634
14635
    /* Look in the global cache first. */
14636
42.3k
    PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14637
    /* We should only init each string once */
14638
42.3k
    assert(r == NULL);
14639
    /* but just in case (for the non-debug build), handle this */
14640
42.3k
    if (r != NULL && r != s) {
14641
0
        assert(_PyUnicode_STATE(r).interned == SSTATE_INTERNED_IMMORTAL_STATIC);
14642
0
        assert(_PyUnicode_CHECK(r));
14643
0
        Py_DECREF(s);
14644
0
        return Py_NewRef(r);
14645
0
    }
14646
14647
42.3k
    if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < 0) {
14648
0
        Py_FatalError("failed to intern static string");
14649
0
    }
14650
14651
42.3k
    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
14652
42.3k
    return s;
14653
42.3k
}
14654
14655
void
14656
_PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
14657
42.3k
{
14658
    // This should only be called as part of runtime initialization
14659
42.3k
    assert(!Py_IsInitialized());
14660
14661
42.3k
    *p = intern_static(interp, *p);
14662
42.3k
    assert(*p);
14663
42.3k
}
14664
14665
static void
14666
immortalize_interned(PyObject *s)
14667
288k
{
14668
288k
    assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
14669
288k
    assert(!_Py_IsImmortal(s));
14670
#ifdef Py_REF_DEBUG
14671
    /* The reference count value should be excluded from the RefTotal.
14672
       The decrements to these objects will not be registered so they
14673
       need to be accounted for in here. */
14674
    for (Py_ssize_t i = 0; i < Py_REFCNT(s); i++) {
14675
        _Py_DecRefTotal(_PyThreadState_GET());
14676
    }
14677
#endif
14678
288k
    _Py_SetImmortal(s);
14679
    // The switch to SSTATE_INTERNED_IMMORTAL must be the last thing done here
14680
    // to synchronize with the check in intern_common() that avoids locking if
14681
    // the string is already immortal.
14682
288k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_IMMORTAL);
14683
288k
}
14684
14685
#ifdef Py_GIL_DISABLED
14686
static bool
14687
can_immortalize_safely(PyObject *s)
14688
{
14689
    if (_Py_IsOwnedByCurrentThread(s) || _Py_IsImmortal(s)) {
14690
        return true;
14691
    }
14692
    Py_ssize_t shared = _Py_atomic_load_ssize(&s->ob_ref_shared);
14693
    return _Py_REF_IS_MERGED(shared);
14694
}
14695
#endif
14696
14697
static /* non-null */ PyObject*
14698
intern_common(PyInterpreterState *interp, PyObject *s /* stolen */,
14699
              bool immortalize)
14700
92.2M
{
14701
    // Note that this steals a reference to `s`, but in many cases that
14702
    // stolen ref is returned, requiring no decref/incref.
14703
14704
#ifdef Py_DEBUG
14705
    assert(s != NULL);
14706
    assert(_PyUnicode_CHECK(s));
14707
#else
14708
92.2M
    if (s == NULL || !PyUnicode_Check(s)) {
14709
0
        return s;
14710
0
    }
14711
92.2M
#endif
14712
14713
    /* If it's a subclass, we don't really know what putting
14714
       it in the interned dict might do. */
14715
92.2M
    if (!PyUnicode_CheckExact(s)) {
14716
0
        return s;
14717
0
    }
14718
14719
    /* Is it already interned? */
14720
92.2M
    switch (PyUnicode_CHECK_INTERNED(s)) {
14721
6.78M
        case SSTATE_NOT_INTERNED:
14722
            // no, go on
14723
6.78M
            break;
14724
28.9k
        case SSTATE_INTERNED_MORTAL:
14725
28.9k
#ifndef Py_GIL_DISABLED
14726
            // yes but we might need to make it immortal
14727
28.9k
            if (immortalize) {
14728
1.97k
                immortalize_interned(s);
14729
1.97k
            }
14730
28.9k
            return s;
14731
#else
14732
            // not fully interned yet; fall through to the locking path
14733
            break;
14734
#endif
14735
85.3M
        default:
14736
            // all done
14737
85.3M
            return s;
14738
92.2M
    }
14739
14740
    /* Statically allocated strings must be already interned. */
14741
92.2M
    assert(!_PyUnicode_STATE(s).statically_allocated);
14742
14743
#if Py_GIL_DISABLED
14744
    /* In the free-threaded build, all interned strings are immortal */
14745
    immortalize = 1;
14746
#endif
14747
14748
    /* If it's already immortal, intern it as such */
14749
6.78M
    if (_Py_IsImmortal(s)) {
14750
0
        immortalize = 1;
14751
0
    }
14752
14753
    /* if it's a short string, get the singleton */
14754
6.78M
    if (PyUnicode_GET_LENGTH(s) == 1 &&
14755
5.59k
                PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) {
14756
0
        PyObject *r = LATIN1(*(unsigned char*)PyUnicode_DATA(s));
14757
0
        assert(PyUnicode_CHECK_INTERNED(r));
14758
0
        Py_DECREF(s);
14759
0
        return r;
14760
0
    }
14761
#ifdef Py_DEBUG
14762
    assert(!unicode_is_singleton(s));
14763
#endif
14764
14765
    /* Look in the global cache now. */
14766
6.78M
    {
14767
6.78M
        PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14768
6.78M
        if (r != NULL) {
14769
359k
            assert(_PyUnicode_STATE(r).statically_allocated);
14770
359k
            assert(r != s);  // r must be statically_allocated; s is not
14771
359k
            Py_DECREF(s);
14772
359k
            return Py_NewRef(r);
14773
359k
        }
14774
6.78M
    }
14775
14776
    /* Do a setdefault on the per-interpreter cache. */
14777
6.42M
    PyObject *interned = get_interned_dict(interp);
14778
6.42M
    assert(interned != NULL);
14779
#ifdef Py_GIL_DISABLED
14780
#  define INTERN_MUTEX &_Py_INTERP_CACHED_OBJECT(interp, interned_mutex)
14781
    // Lock-free fast path: check if there's already an interned copy that
14782
    // is in its final immortal state.
14783
    PyObject *r;
14784
    int res = PyDict_GetItemRef(interned, s, &r);
14785
    if (res < 0) {
14786
        PyErr_Clear();
14787
        return s;
14788
    }
14789
    if (res > 0) {
14790
        unsigned int state = _Py_atomic_load_uint8(&_PyUnicode_STATE(r).interned);
14791
        if (state == SSTATE_INTERNED_IMMORTAL) {
14792
            Py_DECREF(s);
14793
            return r;
14794
        }
14795
        // Not yet fully interned; fall through to the locking path.
14796
        Py_DECREF(r);
14797
    }
14798
#endif
14799
14800
#ifdef Py_GIL_DISABLED
14801
    // Immortalization writes to the refcount fields non-atomically. That
14802
    // races with Py_INCREF / Py_DECREF on the thread that owns `s`. If we
14803
    // don't own it (and its refcount hasn't been merged), intern a copy
14804
    // we own instead.
14805
    if (!can_immortalize_safely(s)) {
14806
        PyObject *copy = _PyUnicode_Copy(s);
14807
        if (copy == NULL) {
14808
            PyErr_Clear();
14809
            return s;
14810
        }
14811
        Py_DECREF(s);
14812
        s = copy;
14813
    }
14814
#endif
14815
14816
    // Why _Py_LOCK_DONT_DETACH is used here: waiting for the interned mutex
14817
    // must not detach the thread state. Extension code is expected to
14818
    // detach before blocking on opaque external synchronization. However,
14819
    // the lock used for C++ static initialization is hidden, making
14820
    // that difficult, and it is common for C++ extensions to call
14821
    // PyUnicode_InternFromString() from static initializers. Detaching here
14822
    // can therefore deadlock: a stop-the-world pause may prevent the lock
14823
    // owner from reattaching while the pause waits for another attached
14824
    // thread blocked on the hidden lock.
14825
6.42M
    FT_MUTEX_LOCK_FLAGS(INTERN_MUTEX, _Py_LOCK_DONT_DETACH);
14826
6.42M
    PyObject *t;
14827
6.42M
    {
14828
6.42M
        int res = PyDict_SetDefaultRef(interned, s, s, &t);
14829
6.42M
        if (res < 0) {
14830
0
            PyErr_Clear();
14831
0
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14832
0
            return s;
14833
0
        }
14834
6.42M
        else if (res == 1) {
14835
            // value was already present (not inserted)
14836
5.90M
            Py_DECREF(s);
14837
5.90M
            if (immortalize &&
14838
579k
                    PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
14839
9.55k
                immortalize_interned(t);
14840
9.55k
            }
14841
5.90M
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14842
5.90M
            return t;
14843
5.90M
        }
14844
525k
        else {
14845
            // value was newly inserted
14846
525k
            assert (s == t);
14847
525k
            Py_DECREF(t);
14848
525k
        }
14849
6.42M
    }
14850
14851
    /* NOT_INTERNED -> INTERNED_MORTAL */
14852
14853
6.42M
    assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
14854
14855
525k
    if (!_Py_IsImmortal(s)) {
14856
        /* The two references in interned dict (key and value) are not counted.
14857
        unicode_dealloc() and _PyUnicode_ClearInterned() take care of this. */
14858
525k
        Py_DECREF(s);
14859
525k
        Py_DECREF(s);
14860
525k
    }
14861
525k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_MORTAL);
14862
14863
    /* INTERNED_MORTAL -> INTERNED_IMMORTAL (if needed) */
14864
14865
#ifdef Py_DEBUG
14866
    if (_Py_IsImmortal(s)) {
14867
        assert(immortalize);
14868
    }
14869
#endif
14870
525k
    if (immortalize) {
14871
277k
        immortalize_interned(s);
14872
277k
    }
14873
14874
525k
    FT_MUTEX_UNLOCK(INTERN_MUTEX);
14875
525k
    return s;
14876
6.42M
}
14877
14878
void
14879
_PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
14880
2.95M
{
14881
2.95M
    *p = intern_common(interp, *p, 1);
14882
2.95M
    assert(*p);
14883
2.95M
}
14884
14885
void
14886
_PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
14887
89.2M
{
14888
89.2M
    *p = intern_common(interp, *p, 0);
14889
89.2M
    assert(*p);
14890
89.2M
}
14891
14892
14893
void
14894
_PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
14895
0
{
14896
0
    _PyUnicode_InternImmortal(interp, p);
14897
0
    return;
14898
0
}
14899
14900
void
14901
PyUnicode_InternInPlace(PyObject **p)
14902
8
{
14903
8
    PyInterpreterState *interp = _PyInterpreterState_GET();
14904
8
    _PyUnicode_InternMortal(interp, p);
14905
8
}
14906
14907
// Public-looking name kept for the stable ABI; user should not call this:
14908
PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
14909
void
14910
PyUnicode_InternImmortal(PyObject **p)
14911
0
{
14912
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14913
0
    _PyUnicode_InternImmortal(interp, p);
14914
0
}
14915
14916
PyObject *
14917
PyUnicode_InternFromString(const char *cp)
14918
1.15M
{
14919
1.15M
    PyObject *s = PyUnicode_FromString(cp);
14920
1.15M
    if (s == NULL) {
14921
0
        return NULL;
14922
0
    }
14923
1.15M
    PyInterpreterState *interp = _PyInterpreterState_GET();
14924
1.15M
    _PyUnicode_InternMortal(interp, &s);
14925
1.15M
    return s;
14926
1.15M
}
14927
14928
14929
void
14930
_PyUnicode_ClearInterned(PyInterpreterState *interp)
14931
0
{
14932
0
    PyObject *interned = get_interned_dict(interp);
14933
0
    if (interned == NULL) {
14934
0
        return;
14935
0
    }
14936
0
    assert(PyDict_CheckExact(interned));
14937
14938
0
    if (has_shared_intern_dict(interp)) {
14939
        // the dict doesn't belong to this interpreter, skip the debug
14940
        // checks on it and just clear the pointer to it
14941
0
        clear_interned_dict(interp);
14942
0
        return;
14943
0
    }
14944
14945
#ifdef INTERNED_STATS
14946
    fprintf(stderr, "releasing %zd interned strings\n",
14947
            PyDict_GET_SIZE(interned));
14948
14949
    Py_ssize_t total_length = 0;
14950
#endif
14951
0
    Py_ssize_t pos = 0;
14952
0
    PyObject *s, *ignored_value;
14953
0
    while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
14954
0
        int shared = 0;
14955
0
        switch (PyUnicode_CHECK_INTERNED(s)) {
14956
0
        case SSTATE_INTERNED_IMMORTAL:
14957
            /* Make immortal interned strings mortal again. */
14958
            // Skip the Immortal Instance check and restore
14959
            // the two references (key and value) ignored
14960
            // by PyUnicode_InternInPlace().
14961
0
            _Py_SetMortal(s, 2);
14962
#ifdef Py_REF_DEBUG
14963
            /* let's be pedantic with the ref total */
14964
            _Py_IncRefTotal(_PyThreadState_GET());
14965
            _Py_IncRefTotal(_PyThreadState_GET());
14966
#endif
14967
#ifdef INTERNED_STATS
14968
            total_length += PyUnicode_GET_LENGTH(s);
14969
#endif
14970
0
            break;
14971
0
        case SSTATE_INTERNED_IMMORTAL_STATIC:
14972
            /* It is shared between interpreters, so we should unmark it
14973
               only when this is the last interpreter in which it's
14974
               interned.  We immortalize all the statically initialized
14975
               strings during startup, so we can rely on the
14976
               main interpreter to be the last one. */
14977
0
            if (!_Py_IsMainInterpreter(interp)) {
14978
0
                shared = 1;
14979
0
            }
14980
0
            break;
14981
0
        case SSTATE_INTERNED_MORTAL:
14982
            // Restore 2 references held by the interned dict; these will
14983
            // be decref'd by clear_interned_dict's PyDict_Clear.
14984
0
            _Py_RefcntAdd(s, 2);
14985
#ifdef Py_REF_DEBUG
14986
            /* let's be pedantic with the ref total */
14987
            _Py_IncRefTotal(_PyThreadState_GET());
14988
            _Py_IncRefTotal(_PyThreadState_GET());
14989
#endif
14990
0
            break;
14991
0
        case SSTATE_NOT_INTERNED:
14992
0
            _Py_FALLTHROUGH;
14993
0
        default:
14994
0
            Py_UNREACHABLE();
14995
0
        }
14996
0
        if (!shared) {
14997
0
            FT_ATOMIC_STORE_UINT8_RELAXED(_PyUnicode_STATE(s).interned, SSTATE_NOT_INTERNED);
14998
0
        }
14999
0
    }
15000
#ifdef INTERNED_STATS
15001
    fprintf(stderr,
15002
            "total length of all interned strings: %zd characters\n",
15003
            total_length);
15004
#endif
15005
15006
0
    struct _Py_unicode_state *state = &interp->unicode;
15007
0
    struct _Py_unicode_ids *ids = &state->ids;
15008
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
15009
0
        Py_XINCREF(ids->array[i]);
15010
0
    }
15011
0
    clear_interned_dict(interp);
15012
0
    if (_Py_IsMainInterpreter(interp)) {
15013
0
        clear_global_interned_strings();
15014
0
    }
15015
0
}
15016
15017
15018
/********************* Unicode Iterator **************************/
15019
15020
typedef struct {
15021
    PyObject_HEAD
15022
    Py_ssize_t it_index;
15023
    PyObject *it_seq;    /* Set to NULL when iterator is exhausted */
15024
} unicodeiterobject;
15025
15026
static void
15027
unicodeiter_dealloc(PyObject *op)
15028
2.83M
{
15029
2.83M
    unicodeiterobject *it = (unicodeiterobject *)op;
15030
2.83M
    _PyObject_GC_UNTRACK(it);
15031
2.83M
    Py_XDECREF(it->it_seq);
15032
2.83M
    PyObject_GC_Del(it);
15033
2.83M
}
15034
15035
static int
15036
unicodeiter_traverse(PyObject *op, visitproc visit, void *arg)
15037
40
{
15038
40
    unicodeiterobject *it = (unicodeiterobject *)op;
15039
40
    Py_VISIT(it->it_seq);
15040
40
    return 0;
15041
40
}
15042
15043
static PyObject *
15044
unicodeiter_next(PyObject *op)
15045
141M
{
15046
141M
    unicodeiterobject *it = (unicodeiterobject *)op;
15047
141M
    PyObject *seq;
15048
15049
141M
    assert(it != NULL);
15050
141M
    seq = it->it_seq;
15051
141M
    if (seq == NULL)
15052
0
        return NULL;
15053
141M
    assert(_PyUnicode_CHECK(seq));
15054
15055
141M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15056
140M
        int kind = PyUnicode_KIND(seq);
15057
140M
        const void *data = PyUnicode_DATA(seq);
15058
140M
        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15059
140M
        it->it_index++;
15060
140M
        return unicode_char(chr);
15061
140M
    }
15062
15063
1.50M
    it->it_seq = NULL;
15064
1.50M
    Py_DECREF(seq);
15065
1.50M
    return NULL;
15066
141M
}
15067
15068
static PyObject *
15069
unicode_ascii_iter_next(PyObject *op)
15070
7.53M
{
15071
7.53M
    unicodeiterobject *it = (unicodeiterobject *)op;
15072
7.53M
    assert(it != NULL);
15073
7.53M
    PyObject *seq = it->it_seq;
15074
7.53M
    if (seq == NULL) {
15075
0
        return NULL;
15076
0
    }
15077
7.53M
    assert(_PyUnicode_CHECK(seq));
15078
7.53M
    assert(PyUnicode_IS_COMPACT_ASCII(seq));
15079
7.53M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15080
6.21M
        const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
15081
6.21M
        Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
15082
6.21M
                                              data, it->it_index);
15083
6.21M
        it->it_index++;
15084
6.21M
        return (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
15085
6.21M
    }
15086
1.31M
    it->it_seq = NULL;
15087
1.31M
    Py_DECREF(seq);
15088
1.31M
    return NULL;
15089
7.53M
}
15090
15091
static PyObject *
15092
unicodeiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
15093
1.45M
{
15094
1.45M
    unicodeiterobject *it = (unicodeiterobject *)op;
15095
1.45M
    Py_ssize_t len = 0;
15096
1.45M
    if (it->it_seq)
15097
1.45M
        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
15098
1.45M
    return PyLong_FromSsize_t(len);
15099
1.45M
}
15100
15101
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15102
15103
static PyObject *
15104
unicodeiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
15105
0
{
15106
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15107
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
15108
15109
    /* _PyEval_GetBuiltin can invoke arbitrary code,
15110
     * call must be before access of iterator pointers.
15111
     * see issue #101765 */
15112
15113
0
    if (it->it_seq != NULL) {
15114
0
        return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
15115
0
    } else {
15116
0
        PyObject *u = _PyUnicode_GetEmpty();
15117
0
        if (u == NULL) {
15118
0
            Py_XDECREF(iter);
15119
0
            return NULL;
15120
0
        }
15121
0
        return Py_BuildValue("N(N)", iter, u);
15122
0
    }
15123
0
}
15124
15125
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15126
15127
static PyObject *
15128
unicodeiter_setstate(PyObject *op, PyObject *state)
15129
0
{
15130
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15131
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
15132
0
    if (index == -1 && PyErr_Occurred())
15133
0
        return NULL;
15134
0
    if (it->it_seq != NULL) {
15135
0
        if (index < 0)
15136
0
            index = 0;
15137
0
        else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15138
0
            index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15139
0
        it->it_index = index;
15140
0
    }
15141
0
    Py_RETURN_NONE;
15142
0
}
15143
15144
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15145
15146
static PyMethodDef unicodeiter_methods[] = {
15147
    {"__length_hint__", unicodeiter_len, METH_NOARGS, length_hint_doc},
15148
    {"__reduce__",      unicodeiter_reduce, METH_NOARGS, reduce_doc},
15149
    {"__setstate__",    unicodeiter_setstate, METH_O, setstate_doc},
15150
    {NULL,      NULL}       /* sentinel */
15151
};
15152
15153
PyTypeObject PyUnicodeIter_Type = {
15154
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15155
    "str_iterator",         /* tp_name */
15156
    sizeof(unicodeiterobject),      /* tp_basicsize */
15157
    0,                  /* tp_itemsize */
15158
    /* methods */
15159
    unicodeiter_dealloc,/* tp_dealloc */
15160
    0,                  /* tp_vectorcall_offset */
15161
    0,                  /* tp_getattr */
15162
    0,                  /* tp_setattr */
15163
    0,                  /* tp_as_async */
15164
    0,                  /* tp_repr */
15165
    0,                  /* tp_as_number */
15166
    0,                  /* tp_as_sequence */
15167
    0,                  /* tp_as_mapping */
15168
    0,                  /* tp_hash */
15169
    0,                  /* tp_call */
15170
    0,                  /* tp_str */
15171
    PyObject_GenericGetAttr,        /* tp_getattro */
15172
    0,                  /* tp_setattro */
15173
    0,                  /* tp_as_buffer */
15174
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15175
    0,                  /* tp_doc */
15176
    unicodeiter_traverse, /* tp_traverse */
15177
    0,                  /* tp_clear */
15178
    0,                  /* tp_richcompare */
15179
    0,                  /* tp_weaklistoffset */
15180
    PyObject_SelfIter,          /* tp_iter */
15181
    unicodeiter_next,   /* tp_iternext */
15182
    unicodeiter_methods,            /* tp_methods */
15183
    0,
15184
};
15185
15186
PyTypeObject _PyUnicodeASCIIIter_Type = {
15187
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15188
    .tp_name = "str_ascii_iterator",
15189
    .tp_basicsize = sizeof(unicodeiterobject),
15190
    .tp_dealloc = unicodeiter_dealloc,
15191
    .tp_getattro = PyObject_GenericGetAttr,
15192
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
15193
    .tp_traverse = unicodeiter_traverse,
15194
    .tp_iter = PyObject_SelfIter,
15195
    .tp_iternext = unicode_ascii_iter_next,
15196
    .tp_methods = unicodeiter_methods,
15197
};
15198
15199
static PyObject *
15200
unicode_iter(PyObject *seq)
15201
2.83M
{
15202
2.83M
    unicodeiterobject *it;
15203
15204
2.83M
    if (!PyUnicode_Check(seq)) {
15205
0
        PyErr_BadInternalCall();
15206
0
        return NULL;
15207
0
    }
15208
2.83M
    if (PyUnicode_IS_COMPACT_ASCII(seq)) {
15209
1.33M
        it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
15210
1.33M
    }
15211
1.50M
    else {
15212
1.50M
        it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15213
1.50M
    }
15214
2.83M
    if (it == NULL)
15215
0
        return NULL;
15216
2.83M
    it->it_index = 0;
15217
2.83M
    it->it_seq = Py_NewRef(seq);
15218
2.83M
    _PyObject_GC_TRACK(it);
15219
2.83M
    return (PyObject *)it;
15220
2.83M
}
15221
15222
static int
15223
encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
15224
148
{
15225
148
    assert(str != NULL);
15226
15227
148
    size_t unused_output_length;
15228
148
    int res = _Py_EncodeUTF8(wstr, str, &unused_output_length,
15229
148
                             NULL, 1, _Py_ERROR_STRICT);
15230
148
    if (res == -2) {
15231
0
        PyErr_Format(PyExc_RuntimeError, "cannot encode %s", name);
15232
0
        return -1;
15233
0
    }
15234
148
    if (res < 0) {
15235
0
        PyErr_NoMemory();
15236
0
        return -1;
15237
0
    }
15238
148
    return 0;
15239
148
}
15240
15241
15242
static int
15243
config_get_codec_name(wchar_t **config_encoding)
15244
74
{
15245
74
    char *encoding;
15246
74
    if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15247
0
        return -1;
15248
0
    }
15249
15250
74
    PyObject *name_obj = NULL;
15251
74
    PyObject *codec = _PyCodec_Lookup(encoding);
15252
74
    PyMem_RawFree(encoding);
15253
15254
74
    if (!codec)
15255
0
        goto error;
15256
15257
74
    name_obj = PyObject_GetAttrString(codec, "name");
15258
74
    Py_CLEAR(codec);
15259
74
    if (!name_obj) {
15260
0
        goto error;
15261
0
    }
15262
15263
74
    wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
15264
74
    Py_DECREF(name_obj);
15265
74
    if (wname == NULL) {
15266
0
        goto error;
15267
0
    }
15268
15269
74
    wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
15270
74
    if (raw_wname == NULL) {
15271
0
        PyMem_Free(wname);
15272
0
        PyErr_NoMemory();
15273
0
        goto error;
15274
0
    }
15275
15276
74
    PyMem_RawFree(*config_encoding);
15277
74
    *config_encoding = raw_wname;
15278
15279
74
    PyMem_Free(wname);
15280
74
    return 0;
15281
15282
0
error:
15283
0
    Py_XDECREF(codec);
15284
0
    Py_XDECREF(name_obj);
15285
0
    return -1;
15286
74
}
15287
15288
15289
static PyStatus
15290
init_stdio_encoding(PyInterpreterState *interp)
15291
37
{
15292
    /* Update the stdio encoding to the normalized Python codec name. */
15293
37
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15294
37
    if (config->stdio_encoding == NULL) {
15295
        /* gh-86427: The encoding is determined for every stream. */
15296
0
        return _PyStatus_OK();
15297
0
    }
15298
37
    if (config_get_codec_name(&config->stdio_encoding) < 0) {
15299
0
        return _PyStatus_ERR("failed to get the Python codec name "
15300
0
                             "of the stdio encoding");
15301
0
    }
15302
37
    return _PyStatus_OK();
15303
37
}
15304
15305
15306
static int
15307
init_fs_codec(PyInterpreterState *interp)
15308
37
{
15309
37
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
15310
15311
37
    _Py_error_handler error_handler;
15312
37
    error_handler = get_error_handler_wide(config->filesystem_errors);
15313
37
    if (error_handler == _Py_ERROR_UNKNOWN) {
15314
0
        PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
15315
0
        return -1;
15316
0
    }
15317
15318
37
    char *encoding, *errors;
15319
37
    if (encode_wstr_utf8(config->filesystem_encoding,
15320
37
                         &encoding,
15321
37
                         "filesystem_encoding") < 0) {
15322
0
        return -1;
15323
0
    }
15324
15325
37
    if (encode_wstr_utf8(config->filesystem_errors,
15326
37
                         &errors,
15327
37
                         "filesystem_errors") < 0) {
15328
0
        PyMem_RawFree(encoding);
15329
0
        return -1;
15330
0
    }
15331
15332
37
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
15333
37
    PyMem_RawFree(fs_codec->encoding);
15334
37
    fs_codec->encoding = encoding;
15335
    /* encoding has been normalized by init_fs_encoding() */
15336
37
    fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
15337
37
    PyMem_RawFree(fs_codec->errors);
15338
37
    fs_codec->errors = errors;
15339
37
    fs_codec->error_handler = error_handler;
15340
15341
#ifdef _Py_FORCE_UTF8_FS_ENCODING
15342
    assert(fs_codec->utf8 == 1);
15343
#endif
15344
15345
    /* At this point, PyUnicode_EncodeFSDefault() and
15346
       PyUnicode_DecodeFSDefault() can now use the Python codec rather than
15347
       the C implementation of the filesystem encoding. */
15348
15349
    /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
15350
       global configuration variables. */
15351
37
    if (_Py_IsMainInterpreter(interp)) {
15352
15353
37
        if (_Py_SetFileSystemEncoding(fs_codec->encoding,
15354
37
                                      fs_codec->errors) < 0) {
15355
0
            PyErr_NoMemory();
15356
0
            return -1;
15357
0
        }
15358
37
    }
15359
37
    return 0;
15360
37
}
15361
15362
15363
static PyStatus
15364
init_fs_encoding(PyThreadState *tstate)
15365
37
{
15366
37
    PyInterpreterState *interp = tstate->interp;
15367
15368
    /* Update the filesystem encoding to the normalized Python codec name.
15369
       For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
15370
       (Python codec name). */
15371
37
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15372
37
    if (config_get_codec_name(&config->filesystem_encoding) < 0) {
15373
0
        _Py_DumpPathConfig(tstate);
15374
0
        return _PyStatus_ERR("failed to get the Python codec "
15375
0
                             "of the filesystem encoding");
15376
0
    }
15377
15378
37
    if (init_fs_codec(interp) < 0) {
15379
0
        return _PyStatus_ERR("cannot initialize filesystem codec");
15380
0
    }
15381
37
    return _PyStatus_OK();
15382
37
}
15383
15384
15385
PyStatus
15386
_PyUnicode_InitEncodings(PyThreadState *tstate)
15387
37
{
15388
37
    PyStatus status = _PyCodec_InitRegistry(tstate->interp);
15389
37
    if (_PyStatus_EXCEPTION(status)) {
15390
0
        return status;
15391
0
    }
15392
37
    status = init_fs_encoding(tstate);
15393
37
    if (_PyStatus_EXCEPTION(status)) {
15394
0
        return status;
15395
0
    }
15396
15397
37
    return init_stdio_encoding(tstate->interp);
15398
37
}
15399
15400
15401
static void
15402
_PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
15403
0
{
15404
0
    PyMem_RawFree(fs_codec->encoding);
15405
0
    fs_codec->encoding = NULL;
15406
0
    fs_codec->utf8 = 0;
15407
0
    PyMem_RawFree(fs_codec->errors);
15408
0
    fs_codec->errors = NULL;
15409
0
    fs_codec->error_handler = _Py_ERROR_UNKNOWN;
15410
0
}
15411
15412
15413
#ifdef Py_DEBUG
15414
static inline int
15415
unicode_is_finalizing(void)
15416
{
15417
    return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
15418
}
15419
#endif
15420
15421
15422
void
15423
_PyUnicode_FiniTypes(PyInterpreterState *interp)
15424
0
{
15425
0
    _PyStaticType_FiniBuiltin(interp, &EncodingMapType);
15426
0
    _PyStaticType_FiniBuiltin(interp, &PyFieldNameIter_Type);
15427
0
    _PyStaticType_FiniBuiltin(interp, &PyFormatterIter_Type);
15428
0
}
15429
15430
15431
void
15432
_PyUnicode_Fini(PyInterpreterState *interp)
15433
0
{
15434
0
    struct _Py_unicode_state *state = &interp->unicode;
15435
15436
0
    if (!has_shared_intern_dict(interp)) {
15437
        // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
15438
0
        assert(get_interned_dict(interp) == NULL);
15439
0
    }
15440
15441
0
    _PyUnicode_FiniEncodings(&state->fs_codec);
15442
15443
    // bpo-47182: force a unicodedata CAPI capsule re-import on
15444
    // subsequent initialization of interpreter.
15445
0
    interp->unicode.ucnhash_capi = NULL;
15446
15447
0
    unicode_clear_identifiers(state);
15448
0
}
15449
15450
/* A _string module, to export formatter_parser and formatter_field_name_split
15451
   to the string.Formatter class implemented in Python. */
15452
15453
static PyMethodDef _string_methods[] = {
15454
    {"formatter_field_name_split", formatter_field_name_split,
15455
     METH_O, PyDoc_STR("split the argument as a field name")},
15456
    {"formatter_parser", formatter_parser,
15457
     METH_O, PyDoc_STR("parse the argument as a format string")},
15458
    {NULL, NULL}
15459
};
15460
15461
static PyModuleDef_Slot module_slots[] = {
15462
    _Py_ABI_SLOT,
15463
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
15464
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
15465
    {0, NULL}
15466
};
15467
15468
static struct PyModuleDef _string_module = {
15469
    PyModuleDef_HEAD_INIT,
15470
    .m_name = "_string",
15471
    .m_doc = PyDoc_STR("string helper module"),
15472
    .m_size = 0,
15473
    .m_methods = _string_methods,
15474
    .m_slots = module_slots,
15475
};
15476
15477
PyMODINIT_FUNC
15478
PyInit__string(void)
15479
8
{
15480
8
    return PyModuleDef_Init(&_string_module);
15481
8
}
15482
15483
15484
#undef PyUnicode_KIND
15485
int PyUnicode_KIND(PyObject *op)
15486
0
{
15487
0
    if (!PyUnicode_Check(op)) {
15488
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15489
0
        return -1;
15490
0
    }
15491
0
    return _PyASCIIObject_CAST(op)->state.kind;
15492
0
}
15493
15494
#undef PyUnicode_DATA
15495
void* PyUnicode_DATA(PyObject *op)
15496
0
{
15497
0
    if (!PyUnicode_Check(op)) {
15498
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15499
0
        return NULL;
15500
0
    }
15501
0
    return _PyUnicode_DATA(op);
15502
0
}