Coverage Report

Created: 2026-10-31 06:21

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
26.4M
#define MAX_UNICODE _Py_MAX_UNICODE
109
247M
#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
298M
{
119
298M
    return FT_ATOMIC_LOAD_PTR_ACQUIRE(_PyCompactUnicodeObject_CAST(op)->utf8);
120
298M
}
121
122
static inline char* PyUnicode_UTF8(PyObject *op)
123
173M
{
124
173M
    assert(_PyUnicode_CHECK(op));
125
173M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
126
157M
        return ((char*)(_PyASCIIObject_CAST(op) + 1));
127
157M
    }
128
15.7M
    else {
129
15.7M
         return _PyUnicode_UTF8(op);
130
15.7M
    }
131
173M
}
132
133
static inline void PyUnicode_SET_UTF8(PyObject *op, char *utf8)
134
34.8M
{
135
34.8M
    FT_ATOMIC_STORE_PTR_RELEASE(_PyCompactUnicodeObject_CAST(op)->utf8, utf8);
136
34.8M
}
137
138
static inline Py_ssize_t PyUnicode_UTF8_LENGTH(PyObject *op)
139
82.2M
{
140
82.2M
    assert(_PyUnicode_CHECK(op));
141
82.2M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
142
78.8M
         return _PyASCIIObject_CAST(op)->length;
143
78.8M
    }
144
3.39M
    else {
145
3.39M
         return _PyCompactUnicodeObject_CAST(op)->utf8_length;
146
3.39M
    }
147
82.2M
}
148
149
static inline void PyUnicode_SET_UTF8_LENGTH(PyObject *op, Py_ssize_t length)
150
34.8M
{
151
34.8M
    _PyCompactUnicodeObject_CAST(op)->utf8_length = length;
152
34.8M
}
153
154
#define _PyUnicode_LENGTH(op)                           \
155
659M
    (_PyASCIIObject_CAST(op)->length)
156
#define _PyUnicode_STATE(op)                            \
157
4.25G
    (_PyASCIIObject_CAST(op)->state)
158
#define _PyUnicode_HASH(op)                             \
159
624M
    (_PyASCIIObject_CAST(op)->hash)
160
161
568M
#define PyUnicode_HASH PyUnstable_Unicode_GET_CACHED_HASH
162
163
static inline void PyUnicode_SET_HASH(PyObject *op, Py_hash_t hash)
164
53.5M
{
165
53.5M
    FT_ATOMIC_STORE_SSIZE_RELAXED(_PyASCIIObject_CAST(op)->hash, hash);
166
53.5M
}
167
168
#define _PyUnicode_DATA_ANY(op)                         \
169
75.1M
    (_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
658M
{
182
658M
    return (!PyUnicode_IS_COMPACT_ASCII(op)
183
266M
            && _PyUnicode_UTF8(op) != NULL
184
16.0M
            && _PyUnicode_UTF8(op) != PyUnicode_DATA(op));
185
658M
}
186
187
188
377M
#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
146M
{
208
146M
    _Py_DECLARE_STR(empty, "");
209
146M
    return &_Py_STR(empty);
210
146M
}
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
7.18M
{
217
7.18M
    return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
218
7.18M
}
219
220
/* This hashtable holds statically allocated interned strings.
221
 * See InternalDocs/string_interning.md for details.
222
 */
223
7.16M
#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
7.16M
{
260
7.16M
    return unicode_hash((PyObject *)key);
261
7.16M
}
262
263
static int
264
hashtable_unicode_compare(const void *key1, const void *key2)
265
357k
{
266
357k
    PyObject *obj1 = (PyObject *)key1;
267
357k
    PyObject *obj2 = (PyObject *)key2;
268
357k
    if (obj1 != NULL && obj2 != NULL) {
269
357k
        return unicode_eq(obj1, obj2);
270
357k
    }
271
0
    else {
272
0
        return obj1 == obj2;
273
0
    }
274
357k
}
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
80.6M
    do {                             \
380
80.6M
        return _PyUnicode_GetEmpty();\
381
80.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.12M
{
475
6.12M
    if (errors == NULL || strcmp(errors, "strict") == 0) {
476
5.49M
        return _Py_ERROR_STRICT;
477
5.49M
    }
478
625k
    if (strcmp(errors, "surrogateescape") == 0) {
479
422k
        return _Py_ERROR_SURROGATEESCAPE;
480
422k
    }
481
203k
    if (strcmp(errors, "replace") == 0) {
482
203k
        return _Py_ERROR_REPLACE;
483
203k
    }
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
55.0M
{
531
55.0M
    if (encoding == NULL && errors == NULL) {
532
12.8M
        return 0;
533
12.8M
    }
534
535
42.1M
    PyInterpreterState *interp = _PyInterpreterState_GET();
536
42.1M
#ifndef Py_DEBUG
537
    /* In release mode, only check in development mode (-X dev) */
538
42.1M
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
539
42.1M
        return 0;
540
42.1M
    }
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.49M
{
725
2.49M
    assert(_PyUnicode_CHECK(unicode));
726
727
2.49M
    Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
728
2.49M
    if (length == 0) {
729
282
        PyObject *empty = _PyUnicode_GetEmpty();
730
282
        if (unicode != empty) {
731
0
            Py_DECREF(unicode);
732
0
        }
733
282
        return empty;
734
282
    }
735
736
2.49M
    if (length == 1) {
737
611k
        int kind = PyUnicode_KIND(unicode);
738
611k
        if (kind == PyUnicode_1BYTE_KIND) {
739
67.5k
            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
740
67.5k
            Py_UCS1 ch = data[0];
741
67.5k
            PyObject *latin1_char = LATIN1(ch);
742
67.5k
            if (unicode != latin1_char) {
743
0
                Py_DECREF(unicode);
744
0
            }
745
67.5k
            return latin1_char;
746
67.5k
        }
747
611k
    }
748
749
2.49M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
750
2.42M
    return unicode;
751
2.49M
}
752
2.49M
#define unicode_result _PyUnicode_Result
753
754
static PyObject*
755
unicode_result_unchanged(PyObject *unicode)
756
96.3M
{
757
96.3M
    if (PyUnicode_CheckExact(unicode)) {
758
92.7M
        return Py_NewRef(unicode);
759
92.7M
    }
760
3.60M
    else
761
        /* Subtype -- return genuine unicode string with the same value. */
762
3.60M
        return _PyUnicode_Copy(unicode);
763
96.3M
}
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
22.2M
#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.21M
#define BLOOM_MASK unsigned long
921
922
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
923
924
33.2M
#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
925
926
#define BLOOM_LINEBREAK(ch)                                             \
927
147M
    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
928
147M
     (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.60M
{
933
2.60M
#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
934
2.60M
    do {                                               \
935
2.60M
        TYPE *data = (TYPE *)PTR;                      \
936
2.60M
        TYPE *end = data + LEN;                        \
937
2.60M
        Py_UCS4 ch;                                    \
938
7.11M
        for (; data != end; data++) {                  \
939
4.51M
            ch = *data;                                \
940
4.51M
            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
941
4.51M
        }                                              \
942
2.60M
        break;                                         \
943
2.60M
    } while (0)
944
945
    /* calculate simple bloom-style bitmask for a given unicode string */
946
947
2.60M
    BLOOM_MASK mask;
948
949
2.60M
    mask = 0;
950
2.60M
    switch (kind) {
951
2.60M
    case PyUnicode_1BYTE_KIND:
952
2.60M
        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
953
2.60M
        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.60M
    }
963
2.60M
    return mask;
964
965
2.60M
#undef BLOOM_UPDATE
966
2.60M
}
967
968
/* Compilation of templated routines */
969
970
850k
#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
189M
{
1023
189M
    switch (kind) {
1024
188M
    case PyUnicode_1BYTE_KIND:
1025
188M
        if ((Py_UCS1) ch != ch)
1026
5.32k
            return -1;
1027
188M
        if (direction > 0)
1028
187M
            return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1029
56.6k
        else
1030
56.6k
            return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1031
1.37M
    case PyUnicode_2BYTE_KIND:
1032
1.37M
        if ((Py_UCS2) ch != ch)
1033
0
            return -1;
1034
1.37M
        if (direction > 0)
1035
1.25M
            return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1036
121k
        else
1037
121k
            return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1038
480k
    case PyUnicode_4BYTE_KIND:
1039
480k
        if (direction > 0)
1040
470k
            return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
1041
9.95k
        else
1042
9.95k
            return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
1043
0
    default:
1044
0
        Py_UNREACHABLE();
1045
189M
    }
1046
189M
}
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.5M
{
1085
53.5M
    Py_ssize_t char_size;
1086
53.5M
    Py_ssize_t struct_size;
1087
53.5M
    Py_ssize_t new_size;
1088
53.5M
    PyObject *new_unicode;
1089
#ifdef Py_DEBUG
1090
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1091
#endif
1092
1093
53.5M
    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.5M
    assert(PyUnicode_IS_COMPACT(unicode));
1102
1103
53.5M
    char_size = PyUnicode_KIND(unicode);
1104
53.5M
    if (PyUnicode_IS_ASCII(unicode))
1105
38.2M
        struct_size = sizeof(PyASCIIObject);
1106
15.3M
    else
1107
15.3M
        struct_size = sizeof(PyCompactUnicodeObject);
1108
1109
53.5M
    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1110
0
        PyErr_NoMemory();
1111
0
        return NULL;
1112
0
    }
1113
53.5M
    new_size = (struct_size + (length + 1) * char_size);
1114
1115
53.5M
    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.5M
    _PyReftracerTrack(unicode, PyRefTracer_DESTROY);
1124
1125
53.5M
    new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
1126
53.5M
    if (new_unicode == NULL) {
1127
0
        _Py_NewReferenceNoTotal(unicode);
1128
0
        PyErr_NoMemory();
1129
0
        return NULL;
1130
0
    }
1131
53.5M
    unicode = new_unicode;
1132
53.5M
    _Py_NewReferenceNoTotal(unicode);
1133
1134
53.5M
    _PyUnicode_LENGTH(unicode) = length;
1135
#ifdef Py_DEBUG
1136
    unicode_fill_invalid(unicode, old_length);
1137
#endif
1138
53.5M
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1139
53.5M
                    length, 0);
1140
53.5M
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1141
53.5M
    return unicode;
1142
53.5M
}
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
614M
{
1289
    /* Optimization for empty strings */
1290
614M
    if (size == 0) {
1291
27.1M
        return _PyUnicode_GetEmpty();
1292
27.1M
    }
1293
1294
587M
    PyObject *obj;
1295
587M
    PyCompactUnicodeObject *unicode;
1296
587M
    void *data;
1297
587M
    int kind;
1298
587M
    int is_ascii;
1299
587M
    Py_ssize_t char_size;
1300
587M
    Py_ssize_t struct_size;
1301
1302
587M
    is_ascii = 0;
1303
587M
    struct_size = sizeof(PyCompactUnicodeObject);
1304
587M
    if (maxchar < 128) {
1305
354M
        kind = PyUnicode_1BYTE_KIND;
1306
354M
        char_size = 1;
1307
354M
        is_ascii = 1;
1308
354M
        struct_size = sizeof(PyASCIIObject);
1309
354M
    }
1310
232M
    else if (maxchar < 256) {
1311
15.2M
        kind = PyUnicode_1BYTE_KIND;
1312
15.2M
        char_size = 1;
1313
15.2M
    }
1314
217M
    else if (maxchar < 65536) {
1315
207M
        kind = PyUnicode_2BYTE_KIND;
1316
207M
        char_size = 2;
1317
207M
    }
1318
10.0M
    else {
1319
10.0M
        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
10.0M
        kind = PyUnicode_4BYTE_KIND;
1325
10.0M
        char_size = 4;
1326
10.0M
    }
1327
1328
    /* Ensure we won't overflow the size. */
1329
587M
    if (size < 0) {
1330
0
        PyErr_SetString(PyExc_SystemError,
1331
0
                        "Negative size passed to PyUnicode_New");
1332
0
        return NULL;
1333
0
    }
1334
587M
    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
587M
    obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
1342
587M
    if (obj == NULL) {
1343
0
        return PyErr_NoMemory();
1344
0
    }
1345
587M
    _PyObject_Init(obj, &PyUnicode_Type);
1346
1347
587M
    unicode = (PyCompactUnicodeObject *)obj;
1348
587M
    if (is_ascii)
1349
354M
        data = ((PyASCIIObject*)obj) + 1;
1350
232M
    else
1351
232M
        data = unicode + 1;
1352
587M
    _PyUnicode_LENGTH(unicode) = size;
1353
587M
    _PyUnicode_HASH(unicode) = -1;
1354
587M
    _PyUnicode_STATE(unicode).interned = 0;
1355
587M
    _PyUnicode_STATE(unicode).kind = kind;
1356
587M
    _PyUnicode_STATE(unicode).compact = 1;
1357
587M
    _PyUnicode_STATE(unicode).ascii = is_ascii;
1358
587M
    _PyUnicode_STATE(unicode).statically_allocated = 0;
1359
587M
    if (is_ascii) {
1360
354M
        ((char*)data)[size] = 0;
1361
354M
    }
1362
232M
    else if (kind == PyUnicode_1BYTE_KIND) {
1363
15.2M
        ((char*)data)[size] = 0;
1364
15.2M
        unicode->utf8 = NULL;
1365
15.2M
        unicode->utf8_length = 0;
1366
15.2M
    }
1367
217M
    else {
1368
217M
        unicode->utf8 = NULL;
1369
217M
        unicode->utf8_length = 0;
1370
217M
        if (kind == PyUnicode_2BYTE_KIND)
1371
207M
            ((Py_UCS2*)data)[size] = 0;
1372
10.0M
        else /* kind == PyUnicode_4BYTE_KIND */
1373
10.0M
            ((Py_UCS4*)data)[size] = 0;
1374
217M
    }
1375
#ifdef Py_DEBUG
1376
    unicode_fill_invalid((PyObject*)unicode, 0);
1377
#endif
1378
587M
    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
1379
587M
    return obj;
1380
587M
}
1381
1382
static int
1383
unicode_check_modifiable(PyObject *unicode)
1384
606
{
1385
606
    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
606
    return 0;
1391
606
}
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
278M
{
1398
278M
    int from_kind, to_kind;
1399
278M
    const void *from_data;
1400
278M
    void *to_data;
1401
1402
278M
    assert(0 <= how_many);
1403
278M
    assert(0 <= from_start);
1404
278M
    assert(0 <= to_start);
1405
278M
    assert(PyUnicode_Check(from));
1406
278M
    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
1407
1408
278M
    assert(to == NULL || PyUnicode_Check(to));
1409
1410
278M
    if (how_many == 0) {
1411
3.01M
        return 0;
1412
3.01M
    }
1413
1414
278M
    assert(to != NULL);
1415
275M
    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1416
1417
275M
    from_kind = PyUnicode_KIND(from);
1418
275M
    from_data = PyUnicode_DATA(from);
1419
275M
    to_kind = PyUnicode_KIND(to);
1420
275M
    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
275M
    if (from_kind == to_kind) {
1437
173M
        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
173M
        memcpy((char*)to_data + to_kind * to_start,
1449
173M
                  (const char*)from_data + from_kind * from_start,
1450
173M
                  to_kind * how_many);
1451
173M
    }
1452
102M
    else if (from_kind == PyUnicode_1BYTE_KIND
1453
99.0M
             && to_kind == PyUnicode_2BYTE_KIND)
1454
90.9M
    {
1455
90.9M
        _PyUnicode_CONVERT_BYTES(
1456
90.9M
            Py_UCS1, Py_UCS2,
1457
90.9M
            PyUnicode_1BYTE_DATA(from) + from_start,
1458
90.9M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1459
90.9M
            PyUnicode_2BYTE_DATA(to) + to_start
1460
90.9M
            );
1461
90.9M
    }
1462
11.1M
    else if (from_kind == PyUnicode_1BYTE_KIND
1463
8.05M
             && to_kind == PyUnicode_4BYTE_KIND)
1464
8.05M
    {
1465
8.05M
        _PyUnicode_CONVERT_BYTES(
1466
8.05M
            Py_UCS1, Py_UCS4,
1467
8.05M
            PyUnicode_1BYTE_DATA(from) + from_start,
1468
8.05M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1469
8.05M
            PyUnicode_4BYTE_DATA(to) + to_start
1470
8.05M
            );
1471
8.05M
    }
1472
3.05M
    else if (from_kind == PyUnicode_2BYTE_KIND
1473
3.04M
             && to_kind == PyUnicode_4BYTE_KIND)
1474
3.04M
    {
1475
3.04M
        _PyUnicode_CONVERT_BYTES(
1476
3.04M
            Py_UCS2, Py_UCS4,
1477
3.04M
            PyUnicode_2BYTE_DATA(from) + from_start,
1478
3.04M
            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1479
3.04M
            PyUnicode_4BYTE_DATA(to) + to_start
1480
3.04M
            );
1481
3.04M
    }
1482
17.4k
    else {
1483
17.4k
        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1484
1485
17.4k
        if (!check_maxchar) {
1486
17.4k
            if (from_kind == PyUnicode_2BYTE_KIND
1487
2.59k
                && to_kind == PyUnicode_1BYTE_KIND)
1488
2.59k
            {
1489
2.59k
                _PyUnicode_CONVERT_BYTES(
1490
2.59k
                    Py_UCS2, Py_UCS1,
1491
2.59k
                    PyUnicode_2BYTE_DATA(from) + from_start,
1492
2.59k
                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1493
2.59k
                    PyUnicode_1BYTE_DATA(to) + to_start
1494
2.59k
                    );
1495
2.59k
            }
1496
14.8k
            else if (from_kind == PyUnicode_4BYTE_KIND
1497
14.8k
                     && to_kind == PyUnicode_1BYTE_KIND)
1498
8.84k
            {
1499
8.84k
                _PyUnicode_CONVERT_BYTES(
1500
8.84k
                    Py_UCS4, Py_UCS1,
1501
8.84k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1502
8.84k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1503
8.84k
                    PyUnicode_1BYTE_DATA(to) + to_start
1504
8.84k
                    );
1505
8.84k
            }
1506
6.03k
            else if (from_kind == PyUnicode_4BYTE_KIND
1507
6.03k
                     && to_kind == PyUnicode_2BYTE_KIND)
1508
6.03k
            {
1509
6.03k
                _PyUnicode_CONVERT_BYTES(
1510
6.03k
                    Py_UCS4, Py_UCS2,
1511
6.03k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1512
6.03k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1513
6.03k
                    PyUnicode_2BYTE_DATA(to) + to_start
1514
6.03k
                    );
1515
6.03k
            }
1516
0
            else {
1517
0
                Py_UNREACHABLE();
1518
0
            }
1519
17.4k
        }
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
17.4k
    }
1533
275M
    return 0;
1534
275M
}
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
278M
{
1541
278M
    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1542
278M
}
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
363k
{
1614
363k
    const wchar_t *iter;
1615
363k
    Py_UCS4 ch;
1616
1617
363k
    assert(num_surrogates != NULL && maxchar != NULL);
1618
363k
    *num_surrogates = 0;
1619
363k
    *maxchar = 0;
1620
1621
10.6M
    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.3M
        {
1634
10.3M
            ch = *iter;
1635
10.3M
            iter++;
1636
10.3M
        }
1637
10.3M
        if (ch > *maxchar) {
1638
1.49M
            *maxchar = ch;
1639
1.49M
            if (*maxchar > MAX_UNICODE) {
1640
0
                unicode_invalid_character(PyExc_ValueError, ch);
1641
0
                return -1;
1642
0
            }
1643
1.49M
        }
1644
10.3M
    }
1645
363k
    return 0;
1646
363k
}
1647
1648
static void
1649
unicode_dealloc(PyObject *unicode)
1650
605M
{
1651
#ifdef Py_DEBUG
1652
    if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
1653
        _Py_FatalRefcountError("deallocating an Unicode singleton");
1654
    }
1655
#endif
1656
605M
    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
605M
    switch (_PyUnicode_STATE(unicode).interned) {
1668
604M
        case SSTATE_NOT_INTERNED:
1669
604M
            break;
1670
457k
        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
457k
            assert(Py_REFCNT(unicode) == 0);
1676
457k
            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
457k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1683
457k
            PyObject *interned = get_interned_dict(interp);
1684
457k
            assert(interned != NULL);
1685
457k
            PyObject *popped;
1686
457k
            int r = PyDict_Pop(interned, unicode, &popped);
1687
457k
            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
457k
            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
457k
            assert(popped == unicode);
1710
            // Only our `popped` reference should be left; remove it too.
1711
457k
            assert(Py_REFCNT(unicode) == 1);
1712
457k
            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
457k
            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
605M
    }
1726
605M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1727
179k
        PyMem_Free(_PyUnicode_UTF8(unicode));
1728
179k
    }
1729
605M
    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
1730
18.7M
        PyMem_Free(_PyUnicode_DATA_ANY(unicode));
1731
18.7M
    }
1732
1733
605M
    Py_TYPE(unicode)->tp_free(unicode);
1734
605M
}
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
63.9M
{
1759
63.9M
    assert(_PyUnicode_CHECK(unicode));
1760
63.9M
    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
63.9M
    if (!_PyObject_IsUniquelyReferenced(unicode))
1765
3.89M
        return 0;
1766
60.0M
    if (PyUnicode_HASH(unicode) != -1)
1767
0
        return 0;
1768
60.0M
    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
60.0M
    return 1;
1775
60.0M
}
1776
1777
static int
1778
unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1779
3.22M
{
1780
3.22M
    PyObject *unicode;
1781
3.22M
    Py_ssize_t old_length;
1782
1783
3.22M
    assert(p_unicode != NULL);
1784
3.22M
    unicode = *p_unicode;
1785
1786
3.22M
    assert(unicode != NULL);
1787
3.22M
    assert(PyUnicode_Check(unicode));
1788
3.22M
    assert(0 <= length);
1789
1790
3.22M
    old_length = PyUnicode_GET_LENGTH(unicode);
1791
3.22M
    if (old_length == length)
1792
0
        return 0;
1793
1794
3.22M
    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.22M
    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.22M
    if (PyUnicode_IS_COMPACT(unicode)) {
1809
3.22M
        PyObject *new_unicode = _PyUnicode_ResizeCompact(unicode, length);
1810
3.22M
        if (new_unicode == NULL)
1811
0
            return -1;
1812
3.22M
        *p_unicode = new_unicode;
1813
3.22M
        return 0;
1814
3.22M
    }
1815
0
    return resize_inplace(unicode, length);
1816
3.22M
}
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
377M
{
1838
377M
    PyObject *o = LATIN1(ch);
1839
377M
    return o;
1840
377M
}
1841
1842
static PyObject*
1843
unicode_char(Py_UCS4 ch)
1844
449M
{
1845
449M
    if (ch < 256) {
1846
290M
        return get_latin1_char(ch);
1847
290M
    }
1848
1849
    // Raise SystemError if the character is not in range [U+0000; MAX_UNICODE]
1850
158M
    PyObject *unicode = PyUnicode_New(1, ch);
1851
158M
    if (unicode == NULL) {
1852
0
        return NULL;
1853
0
    }
1854
1855
158M
    assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1856
158M
    if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
1857
152M
        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1858
152M
    } else {
1859
6.16M
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1860
6.16M
        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1861
6.16M
    }
1862
158M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
1863
158M
    return unicode;
1864
158M
}
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
363k
{
1872
363k
    switch (kind) {
1873
337k
    case PyUnicode_1BYTE_KIND:
1874
337k
        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, u, u + size, data);
1875
337k
        break;
1876
1877
23.8k
    case PyUnicode_2BYTE_KIND:
1878
#if SIZEOF_WCHAR_T == 2
1879
        memcpy(data, u, size * 2);
1880
#else
1881
23.8k
        _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2, u, u + size, data);
1882
23.8k
#endif
1883
23.8k
        break;
1884
1885
1.42k
    case PyUnicode_4BYTE_KIND:
1886
1.42k
    {
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.42k
        assert(num_surrogates == 0);
1912
1.42k
        memcpy(data, u, size * 4);
1913
1.42k
#endif
1914
1.42k
        break;
1915
0
    }
1916
0
    default:
1917
0
        Py_UNREACHABLE();
1918
363k
    }
1919
363k
}
1920
1921
1922
PyObject *
1923
PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
1924
656k
{
1925
656k
    PyObject *unicode;
1926
656k
    Py_UCS4 maxchar = 0;
1927
656k
    Py_ssize_t num_surrogates;
1928
1929
656k
    if (u == NULL && size != 0) {
1930
0
        PyErr_BadInternalCall();
1931
0
        return NULL;
1932
0
    }
1933
1934
656k
    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
656k
    if (size == 0)
1943
232k
        _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
424k
    if (size == 1 && (Py_UCS4)*u < 256)
1962
60.9k
        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
363k
    if (find_maxchar_surrogates(u, u + size,
1967
363k
                                &maxchar, &num_surrogates) == -1)
1968
0
        return NULL;
1969
1970
363k
    unicode = PyUnicode_New(size - num_surrogates, maxchar);
1971
363k
    if (!unicode)
1972
0
        return NULL;
1973
1974
363k
    unicode_write_widechar(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1975
363k
                           u, size, num_surrogates);
1976
1977
363k
    return unicode_result(unicode);
1978
363k
}
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
42.5M
{
2054
42.5M
    size_t size = strlen(u);
2055
42.5M
    if (size > PY_SSIZE_T_MAX) {
2056
0
        PyErr_SetString(PyExc_OverflowError, "input too long");
2057
0
        return NULL;
2058
0
    }
2059
42.5M
    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
2060
42.5M
}
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
109M
{
2149
109M
    const unsigned char *s = (const unsigned char *)buffer;
2150
109M
    PyObject *unicode;
2151
109M
    if (size == 1) {
2152
#ifdef Py_DEBUG
2153
        assert((unsigned char)s[0] < 128);
2154
#endif
2155
39.8M
        return get_latin1_char(s[0]);
2156
39.8M
    }
2157
70.1M
    unicode = PyUnicode_New(size, 127);
2158
70.1M
    if (!unicode)
2159
0
        return NULL;
2160
70.1M
    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2161
70.1M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
2162
70.1M
    return unicode;
2163
70.1M
}
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
55.1M
{
2183
55.1M
    PyObject *res;
2184
55.1M
    unsigned char max_char;
2185
2186
55.1M
    if (size == 0) {
2187
15.5M
        _Py_RETURN_UNICODE_EMPTY();
2188
15.5M
    }
2189
55.1M
    assert(size > 0);
2190
39.6M
    if (size == 1) {
2191
9.75M
        return get_latin1_char(u[0]);
2192
9.75M
    }
2193
2194
29.8M
    max_char = ucs1lib_find_max_char(u, u + size);
2195
29.8M
    res = PyUnicode_New(size, max_char);
2196
29.8M
    if (!res)
2197
0
        return NULL;
2198
29.8M
    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
2199
29.8M
    assert(_PyUnicode_CheckConsistency(res, 1));
2200
29.8M
    return res;
2201
29.8M
}
2202
2203
static PyObject*
2204
_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
2205
92.8M
{
2206
92.8M
    PyObject *res;
2207
92.8M
    Py_UCS2 max_char;
2208
2209
92.8M
    if (size == 0)
2210
17.4M
        _Py_RETURN_UNICODE_EMPTY();
2211
92.8M
    assert(size > 0);
2212
75.3M
    if (size == 1)
2213
53.3M
        return unicode_char(u[0]);
2214
2215
22.0M
    max_char = ucs2lib_find_max_char(u, u + size);
2216
22.0M
    res = PyUnicode_New(size, max_char);
2217
22.0M
    if (!res)
2218
0
        return NULL;
2219
22.0M
    if (max_char >= 256)
2220
17.0M
        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
2221
4.97M
    else {
2222
4.97M
        _PyUnicode_CONVERT_BYTES(
2223
4.97M
            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2224
4.97M
    }
2225
22.0M
    assert(_PyUnicode_CheckConsistency(res, 1));
2226
22.0M
    return res;
2227
22.0M
}
2228
2229
static PyObject*
2230
_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
2231
74.9M
{
2232
74.9M
    PyObject *res;
2233
2234
74.9M
    if (size == 0)
2235
18.5M
        _Py_RETURN_UNICODE_EMPTY();
2236
74.9M
    assert(size > 0);
2237
2238
56.4M
    if (size == 1) {
2239
        // Raise SystemError if the character is invalid
2240
40.0M
        return unicode_char(u[0]);
2241
40.0M
    }
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.4M
    Py_UCS4 max_char = ucs4lib_find_max_char(u, u + size);
2261
16.4M
#endif
2262
2263
16.4M
    res = PyUnicode_New(size, max_char);
2264
16.4M
    if (!res)
2265
0
        return NULL;
2266
16.4M
    if (max_char < 256)
2267
9.99M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2268
16.4M
                                 PyUnicode_1BYTE_DATA(res));
2269
6.40M
    else if (max_char < 0x10000)
2270
4.79M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2271
6.40M
                                 PyUnicode_2BYTE_DATA(res));
2272
1.61M
    else
2273
1.61M
        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
2274
16.4M
    assert(_PyUnicode_CheckConsistency(res, 1));
2275
16.4M
    return res;
2276
16.4M
}
2277
2278
2279
int
2280
PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *pub_writer,
2281
                          const Py_UCS4 *str,
2282
                          Py_ssize_t size)
2283
28.4k
{
2284
28.4k
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
2285
2286
28.4k
    if (size < 0) {
2287
0
        PyErr_SetString(PyExc_ValueError,
2288
0
                        "size must be positive");
2289
0
        return -1;
2290
0
    }
2291
2292
28.4k
    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
28.4k
    Py_UCS4 maxchar = ucs4lib_find_max_char(str, str + size);
2314
28.4k
#endif
2315
2316
28.4k
    if (_PyUnicodeWriter_Prepare(writer, size, maxchar) < 0) {
2317
0
        return -1;
2318
0
    }
2319
28.4k
    assert(_PyUnicodeWriter_CanWrite(writer));
2320
2321
28.4k
    int kind = writer->kind;
2322
28.4k
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2323
28.4k
    if (kind == PyUnicode_1BYTE_KIND) {
2324
5.25k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1,
2325
5.25k
                                 str, str + size,
2326
5.25k
                                 data);
2327
5.25k
    }
2328
23.2k
    else if (kind == PyUnicode_2BYTE_KIND) {
2329
23.2k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2,
2330
23.2k
                                 str, str + size,
2331
23.2k
                                 data);
2332
23.2k
    }
2333
6
    else {
2334
6
        memcpy(data, str, size * sizeof(Py_UCS4));
2335
6
    }
2336
28.4k
    writer->pos += size;
2337
2338
28.4k
    return 0;
2339
28.4k
}
2340
2341
2342
PyObject*
2343
PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2344
154M
{
2345
154M
    if (size < 0) {
2346
0
        PyErr_SetString(PyExc_ValueError, "size must be positive");
2347
0
        return NULL;
2348
0
    }
2349
154M
    switch (kind) {
2350
22.2M
    case PyUnicode_1BYTE_KIND:
2351
22.2M
        return _PyUnicode_FromUCS1(buffer, size);
2352
74.8M
    case PyUnicode_2BYTE_KIND:
2353
74.8M
        return _PyUnicode_FromUCS2(buffer, size);
2354
57.7M
    case PyUnicode_4BYTE_KIND:
2355
57.7M
        return _PyUnicode_FromUCS4(buffer, size);
2356
0
    default:
2357
0
        PyErr_SetString(PyExc_SystemError, "invalid kind");
2358
0
        return NULL;
2359
154M
    }
2360
154M
}
2361
2362
Py_UCS4
2363
_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2364
11.8M
{
2365
11.8M
    int kind;
2366
11.8M
    const void *startptr, *endptr;
2367
2368
11.8M
    assert(0 <= start);
2369
11.8M
    assert(end <= PyUnicode_GET_LENGTH(unicode));
2370
11.8M
    assert(start <= end);
2371
2372
11.8M
    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2373
44.3k
        return PyUnicode_MAX_CHAR_VALUE(unicode);
2374
2375
11.8M
    if (start == end)
2376
0
        return 127;
2377
2378
11.8M
    if (PyUnicode_IS_ASCII(unicode))
2379
11.8M
        return 127;
2380
2381
30.6k
    kind = PyUnicode_KIND(unicode);
2382
30.6k
    startptr = PyUnicode_DATA(unicode);
2383
30.6k
    endptr = (char *)startptr + end * kind;
2384
30.6k
    startptr = (char *)startptr + start * kind;
2385
30.6k
    switch(kind) {
2386
1.54k
    case PyUnicode_1BYTE_KIND:
2387
1.54k
        return ucs1lib_find_max_char(startptr, endptr);
2388
5.84k
    case PyUnicode_2BYTE_KIND:
2389
5.84k
        return ucs2lib_find_max_char(startptr, endptr);
2390
23.3k
    case PyUnicode_4BYTE_KIND:
2391
23.3k
        return ucs4lib_find_max_char(startptr, endptr);
2392
0
    default:
2393
0
        Py_UNREACHABLE();
2394
30.6k
    }
2395
30.6k
}
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
3.60M
{
2446
3.60M
    Py_ssize_t length;
2447
3.60M
    PyObject *copy;
2448
2449
3.60M
    if (!PyUnicode_Check(unicode)) {
2450
0
        PyErr_BadInternalCall();
2451
0
        return NULL;
2452
0
    }
2453
2454
3.60M
    length = PyUnicode_GET_LENGTH(unicode);
2455
3.60M
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
2456
3.60M
    if (!copy)
2457
0
        return NULL;
2458
3.60M
    assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2459
2460
3.60M
    memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2461
3.60M
              length * PyUnicode_KIND(unicode));
2462
3.60M
    assert(_PyUnicode_CheckConsistency(copy, 1));
2463
3.60M
    return copy;
2464
3.60M
}
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.33M
{
2473
1.33M
    void *result;
2474
2475
1.33M
    assert(skind < kind);
2476
1.33M
    switch (kind) {
2477
1.13M
    case PyUnicode_2BYTE_KIND:
2478
1.13M
        result = PyMem_New(Py_UCS2, len);
2479
1.13M
        if (!result)
2480
0
            return PyErr_NoMemory();
2481
1.13M
        assert(skind == PyUnicode_1BYTE_KIND);
2482
1.13M
        _PyUnicode_CONVERT_BYTES(
2483
1.13M
            Py_UCS1, Py_UCS2,
2484
1.13M
            (const Py_UCS1 *)data,
2485
1.13M
            ((const Py_UCS1 *)data) + len,
2486
1.13M
            result);
2487
1.13M
        return result;
2488
198k
    case PyUnicode_4BYTE_KIND:
2489
198k
        result = PyMem_New(Py_UCS4, len);
2490
198k
        if (!result)
2491
0
            return PyErr_NoMemory();
2492
198k
        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
198k
        else {
2500
198k
            assert(skind == PyUnicode_1BYTE_KIND);
2501
198k
            _PyUnicode_CONVERT_BYTES(
2502
198k
                Py_UCS1, Py_UCS4,
2503
198k
                (const Py_UCS1 *)data,
2504
198k
                ((const Py_UCS1 *)data) + len,
2505
198k
                result);
2506
198k
        }
2507
198k
        return result;
2508
0
    default:
2509
0
        Py_UNREACHABLE();
2510
0
        return NULL;
2511
1.33M
    }
2512
1.33M
}
2513
2514
static Py_UCS4*
2515
as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2516
        int copy_null)
2517
82.0k
{
2518
82.0k
    int kind;
2519
82.0k
    const void *data;
2520
82.0k
    Py_ssize_t len, targetlen;
2521
82.0k
    kind = PyUnicode_KIND(string);
2522
82.0k
    data = PyUnicode_DATA(string);
2523
82.0k
    len = PyUnicode_GET_LENGTH(string);
2524
82.0k
    targetlen = len;
2525
82.0k
    if (copy_null)
2526
0
        targetlen++;
2527
82.0k
    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
82.0k
    else {
2535
82.0k
        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
82.0k
    }
2543
82.0k
    if (kind == PyUnicode_1BYTE_KIND) {
2544
58.1k
        const Py_UCS1 *start = (const Py_UCS1 *) data;
2545
58.1k
        _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
2546
58.1k
    }
2547
23.9k
    else if (kind == PyUnicode_2BYTE_KIND) {
2548
17.4k
        const Py_UCS2 *start = (const Py_UCS2 *) data;
2549
17.4k
        _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2550
17.4k
    }
2551
6.47k
    else if (kind == PyUnicode_4BYTE_KIND) {
2552
6.47k
        memcpy(target, data, len * sizeof(Py_UCS4));
2553
6.47k
    }
2554
0
    else {
2555
0
        Py_UNREACHABLE();
2556
0
    }
2557
82.0k
    if (copy_null)
2558
0
        target[len] = 0;
2559
82.0k
    return target;
2560
82.0k
}
2561
2562
Py_UCS4*
2563
PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2564
                 int copy_null)
2565
82.0k
{
2566
82.0k
    if (target == NULL || targetsize < 0) {
2567
0
        PyErr_BadInternalCall();
2568
0
        return NULL;
2569
0
    }
2570
82.0k
    return as_ucs4(string, target, targetsize, copy_null);
2571
82.0k
}
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.07M
{
2589
5.07M
    Py_ssize_t length, fill, arglen;
2590
5.07M
    Py_UCS4 maxchar;
2591
2592
5.07M
    length = PyUnicode_GET_LENGTH(str);
2593
5.07M
    if ((precision == -1 || precision >= length) && width <= length) {
2594
5.07M
        return _PyUnicodeWriter_WriteStr(writer, str);
2595
5.07M
    }
2596
2597
48
    if (precision != -1)
2598
48
        length = Py_MIN(precision, length);
2599
2600
48
    arglen = Py_MAX(length, width);
2601
48
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2602
25
        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2603
23
    else
2604
23
        maxchar = writer->maxchar;
2605
2606
48
    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1) {
2607
0
        return -1;
2608
0
    }
2609
48
    assert(_PyUnicodeWriter_CanWrite(writer));
2610
2611
48
    fill = Py_MAX(width - length, 0);
2612
48
    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
48
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2619
48
                                  str, 0, length);
2620
48
    writer->pos += length;
2621
2622
48
    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
48
    return 0;
2629
48
}
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.04M
{
2635
    /* UTF-8 */
2636
2.04M
    Py_ssize_t *pconsumed = NULL;
2637
2.04M
    Py_ssize_t length;
2638
2.04M
    if (precision == -1) {
2639
729k
        length = strlen(str);
2640
729k
    }
2641
1.31M
    else {
2642
1.31M
        length = 0;
2643
21.3M
        while (length < precision && str[length]) {
2644
20.0M
            length++;
2645
20.0M
        }
2646
1.31M
        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.18k
            pconsumed = &length;
2653
2.18k
        }
2654
1.31M
    }
2655
2656
2.04M
    if (width < 0) {
2657
2.04M
        return _PyUnicode_DecodeUTF8Writer(writer, str, length,
2658
2.04M
                                           _Py_ERROR_REPLACE, "replace", pconsumed);
2659
2.04M
    }
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
44.1k
#define F_LONGLONG 2
2703
204k
#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.9M
{
2711
23.9M
    const char *p;
2712
23.9M
    Py_ssize_t len;
2713
23.9M
    int flags = 0;
2714
23.9M
    Py_ssize_t width;
2715
23.9M
    Py_ssize_t precision;
2716
2717
23.9M
    p = f;
2718
23.9M
    f++;
2719
23.9M
    if (*f == '%') {
2720
850k
        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
2721
0
            return NULL;
2722
850k
        f++;
2723
850k
        return f;
2724
850k
    }
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
23.0M
    while (1) {
2732
23.0M
        switch (*f++) {
2733
0
        case '-': flags |= F_LJUST; continue;
2734
1.94k
        case '0': flags |= F_ZERO; continue;
2735
0
        case '#': flags |= F_ALT; continue;
2736
23.0M
        }
2737
23.0M
        f--;
2738
23.0M
        break;
2739
23.0M
    }
2740
2741
    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2742
23.0M
    width = -1;
2743
23.0M
    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
23.0M
    else if (Py_ISDIGIT((unsigned)*f)) {
2752
1.94k
        width = *f - '0';
2753
1.94k
        f++;
2754
1.94k
        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.94k
    }
2764
23.0M
    precision = -1;
2765
23.0M
    if (*f == '.') {
2766
2.93M
        f++;
2767
2.93M
        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
2.93M
        else if (Py_ISDIGIT((unsigned)*f)) {
2775
2.93M
            precision = (*f - '0');
2776
2.93M
            f++;
2777
8.81M
            while (Py_ISDIGIT((unsigned)*f)) {
2778
5.87M
                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
5.87M
                precision = (precision * 10) + (*f - '0');
2784
5.87M
                f++;
2785
5.87M
            }
2786
2.93M
        }
2787
2.93M
    }
2788
2789
23.0M
    int sizemod = 0;
2790
23.0M
    if (*f == 'l') {
2791
22.0k
        if (f[1] == 'l') {
2792
22.0k
            sizemod = F_LONGLONG;
2793
22.0k
            f += 2;
2794
22.0k
        }
2795
0
        else {
2796
0
            sizemod = F_LONG;
2797
0
            ++f;
2798
0
        }
2799
22.0k
    }
2800
23.0M
    else if (*f == 'z') {
2801
102k
        sizemod = F_SIZE;
2802
102k
        ++f;
2803
102k
    }
2804
22.9M
    else if (*f == 't') {
2805
0
        sizemod = F_PTRDIFF;
2806
0
        ++f;
2807
0
    }
2808
22.9M
    else if (*f == 'j') {
2809
0
        sizemod = F_INTMAX;
2810
0
        ++f;
2811
0
    }
2812
23.0M
    if (f[0] != '\0' && f[1] == '\0')
2813
3.08M
        writer->overallocate = 0;
2814
2815
23.0M
    switch (*f) {
2816
14.6M
    case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
2817
14.6M
        break;
2818
1.29M
    case 'c': case 'p':
2819
1.29M
        if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
2820
1.29M
        break;
2821
2.03M
    case 's':
2822
2.04M
    case 'V':
2823
2.04M
        if (sizemod && sizemod != F_LONG) goto invalid_format;
2824
2.04M
        break;
2825
5.07M
    default:
2826
5.07M
        if (sizemod) goto invalid_format;
2827
5.07M
        break;
2828
23.0M
    }
2829
2830
23.0M
    switch (*f) {
2831
1.28M
    case 'c':
2832
1.28M
    {
2833
1.28M
        int ordinal = va_arg(*vargs, int);
2834
1.28M
        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.28M
        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
2840
0
            return NULL;
2841
1.28M
        break;
2842
1.28M
    }
2843
2844
14.6M
    case 'd': case 'i':
2845
14.6M
    case 'o': case 'u': case 'x': case 'X':
2846
14.6M
    {
2847
14.6M
        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
14.6M
        #define SPRINT(SIZE_SPEC, FMT_CHAR, TYPE) \
2861
14.6M
            sprintf(buffer, "%" SIZE_SPEC FMT_CHAR, va_arg(*vargs, TYPE))
2862
2863
        // One inner switch to handle all format variants
2864
14.6M
        #define DO_SPRINTS(SIZE_SPEC, SIGNED_TYPE, UNSIGNED_TYPE)             \
2865
14.6M
            switch (*f) {                                                     \
2866
110
                case 'o': len = SPRINT(SIZE_SPEC, "o", UNSIGNED_TYPE); break; \
2867
22.0k
                case 'u': len = SPRINT(SIZE_SPEC, "u", UNSIGNED_TYPE); break; \
2868
1.52k
                case 'x': len = SPRINT(SIZE_SPEC, "x", UNSIGNED_TYPE); break; \
2869
973
                case 'X': len = SPRINT(SIZE_SPEC, "X", UNSIGNED_TYPE); break; \
2870
14.6M
                default:  len = SPRINT(SIZE_SPEC, "d", SIGNED_TYPE); break;   \
2871
14.6M
            }
2872
2873
        // Outer switch to handle all the sizes/types
2874
14.6M
        switch (sizemod) {
2875
0
            case F_LONG:     DO_SPRINTS("l", long, unsigned long); break;
2876
22.0k
            case F_LONGLONG: DO_SPRINTS("ll", long long, unsigned long long); break;
2877
102k
            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
14.5M
            default:         DO_SPRINTS("", int, unsigned int); break;
2881
14.6M
        }
2882
14.6M
        #undef SPRINT
2883
14.6M
        #undef DO_SPRINTS
2884
2885
14.6M
        assert(len >= 1);
2886
2887
14.6M
        int sign = (buffer[0] == '-');
2888
14.6M
        len -= sign;
2889
2890
14.6M
        precision = Py_MAX(precision, len);
2891
14.6M
        width = Py_MAX(width, precision + sign);
2892
14.6M
        if ((flags & F_ZERO) && !(flags & F_LJUST)) {
2893
1.94k
            precision = width - sign;
2894
1.94k
        }
2895
2896
14.6M
        Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
2897
14.6M
        Py_ssize_t zeropad = Py_MAX(precision - len, 0);
2898
2899
14.6M
        if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1) {
2900
0
            return NULL;
2901
0
        }
2902
14.6M
        assert(_PyUnicodeWriter_CanWrite(writer));
2903
2904
14.6M
        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
14.6M
        if (sign) {
2911
743
            if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
2912
0
                return NULL;
2913
743
        }
2914
2915
14.6M
        if (zeropad) {
2916
606
            if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
2917
0
                return NULL;
2918
606
            writer->pos += zeropad;
2919
606
        }
2920
2921
14.6M
        if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
2922
0
            return NULL;
2923
2924
14.6M
        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
14.6M
        break;
2930
14.6M
    }
2931
2932
14.6M
    case 'p':
2933
7.07k
    {
2934
7.07k
        char number[MAX_INTMAX_CHARS];
2935
2936
7.07k
        len = sprintf(number, "%p", va_arg(*vargs, void*));
2937
7.07k
        assert(len >= 0);
2938
2939
        /* %p is ill-defined:  ensure leading 0x. */
2940
7.07k
        if (number[1] == 'X')
2941
0
            number[1] = 'x';
2942
7.07k
        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.07k
        if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
2951
0
            return NULL;
2952
7.07k
        break;
2953
7.07k
    }
2954
2955
2.03M
    case 's':
2956
2.03M
    {
2957
2.03M
        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.03M
        else {
2963
            /* UTF-8 */
2964
2.03M
            const char *s = va_arg(*vargs, const char*);
2965
2.03M
            if (unicode_fromformat_write_utf8(writer, s, width, precision, flags) < 0)
2966
0
                return NULL;
2967
2.03M
        }
2968
2.03M
        break;
2969
2.03M
    }
2970
2971
2.16M
    case 'U':
2972
2.16M
    {
2973
2.16M
        PyObject *obj = va_arg(*vargs, PyObject *);
2974
2.16M
        assert(obj && _PyUnicode_CHECK(obj));
2975
2976
2.16M
        if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2977
0
            return NULL;
2978
2.16M
        break;
2979
2.16M
    }
2980
2981
2.16M
    case 'V':
2982
558
    {
2983
558
        PyObject *obj = va_arg(*vargs, PyObject *);
2984
558
        const char *str;
2985
558
        const wchar_t *wstr;
2986
558
        if (sizemod) {
2987
0
            wstr = va_arg(*vargs, const wchar_t*);
2988
0
        }
2989
558
        else {
2990
558
            str = va_arg(*vargs, const char *);
2991
558
        }
2992
558
        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
558
        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
558
        else {
3003
558
            assert(str != NULL);
3004
558
            if (unicode_fromformat_write_utf8(writer, str, width, precision, flags) < 0)
3005
0
                return NULL;
3006
558
        }
3007
558
        break;
3008
558
    }
3009
3010
1.52k
    case 'S':
3011
1.52k
    {
3012
1.52k
        PyObject *obj = va_arg(*vargs, PyObject *);
3013
1.52k
        PyObject *str;
3014
1.52k
        assert(obj);
3015
1.52k
        str = PyObject_Str(obj);
3016
1.52k
        if (!str)
3017
0
            return NULL;
3018
1.52k
        if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
3019
0
            Py_DECREF(str);
3020
0
            return NULL;
3021
0
        }
3022
1.52k
        Py_DECREF(str);
3023
1.52k
        break;
3024
1.52k
    }
3025
3026
1.63M
    case 'R':
3027
1.63M
    {
3028
1.63M
        PyObject *obj = va_arg(*vargs, PyObject *);
3029
1.63M
        PyObject *repr;
3030
1.63M
        assert(obj);
3031
1.63M
        repr = PyObject_Repr(obj);
3032
1.63M
        if (!repr)
3033
0
            return NULL;
3034
1.63M
        if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
3035
0
            Py_DECREF(repr);
3036
0
            return NULL;
3037
0
        }
3038
1.63M
        Py_DECREF(repr);
3039
1.63M
        break;
3040
1.63M
    }
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.27M
    case 'T':
3059
1.27M
    {
3060
1.27M
        PyObject *obj = va_arg(*vargs, PyObject *);
3061
1.27M
        PyTypeObject *type = (PyTypeObject *)Py_NewRef(Py_TYPE(obj));
3062
3063
1.27M
        PyObject *type_name;
3064
1.27M
        if (flags & F_ALT) {
3065
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3066
0
        }
3067
1.27M
        else {
3068
1.27M
            type_name = PyType_GetFullyQualifiedName(type);
3069
1.27M
        }
3070
1.27M
        Py_DECREF(type);
3071
1.27M
        if (!type_name) {
3072
0
            return NULL;
3073
0
        }
3074
3075
1.27M
        if (unicode_fromformat_write_str(writer, type_name,
3076
1.27M
                                         width, precision, flags) == -1) {
3077
0
            Py_DECREF(type_name);
3078
0
            return NULL;
3079
0
        }
3080
1.27M
        Py_DECREF(type_name);
3081
1.27M
        break;
3082
1.27M
    }
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
23.0M
    }
3119
3120
23.0M
    f++;
3121
23.0M
    return f;
3122
23.0M
}
3123
3124
static int
3125
unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
3126
11.4M
{
3127
11.4M
    Py_ssize_t len = strlen(format);
3128
11.4M
    writer->min_length += len + 100;
3129
11.4M
    writer->overallocate = 1;
3130
3131
    // Copy varags to be able to pass a reference to a subfunction.
3132
11.4M
    va_list vargs2;
3133
11.4M
    va_copy(vargs2, vargs);
3134
3135
    // _PyUnicodeWriter_WriteASCIIString() below requires the format string
3136
    // to be encoded to ASCII.
3137
11.4M
    int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)format, (Py_UCS1*)format + len) < 128);
3138
11.4M
    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
65.5M
    for (const char *f = format; *f; ) {
3149
54.0M
        if (*f == '%') {
3150
23.9M
            f = unicode_fromformat_arg(writer, f, &vargs2);
3151
23.9M
            if (f == NULL)
3152
0
                goto fail;
3153
23.9M
        }
3154
30.1M
        else {
3155
30.1M
            const char *p = strchr(f, '%');
3156
30.1M
            if (p != NULL) {
3157
21.7M
                len = p - f;
3158
21.7M
            }
3159
8.38M
            else {
3160
8.38M
                len = strlen(f);
3161
8.38M
                writer->overallocate = 0;
3162
8.38M
            }
3163
3164
30.1M
            if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
3165
0
                goto fail;
3166
0
            }
3167
30.1M
            f += len;
3168
30.1M
        }
3169
54.0M
    }
3170
11.4M
    va_end(vargs2);
3171
11.4M
    return 0;
3172
3173
0
  fail:
3174
0
    va_end(vargs2);
3175
0
    return -1;
3176
11.4M
}
3177
3178
PyObject *
3179
PyUnicode_FromFormatV(const char *format, va_list vargs)
3180
11.4M
{
3181
11.4M
    _PyUnicodeWriter writer;
3182
11.4M
    _PyUnicodeWriter_Init(&writer);
3183
3184
11.4M
    if (unicode_from_format(&writer, format, vargs) < 0) {
3185
0
        _PyUnicodeWriter_Dealloc(&writer);
3186
0
        return NULL;
3187
0
    }
3188
11.4M
    return _PyUnicodeWriter_Finish(&writer);
3189
11.4M
}
3190
3191
PyObject *
3192
PyUnicode_FromFormat(const char *format, ...)
3193
484k
{
3194
484k
    PyObject* ret;
3195
484k
    va_list vargs;
3196
3197
484k
    va_start(vargs, format);
3198
484k
    ret = PyUnicode_FromFormatV(format, vargs);
3199
484k
    va_end(vargs);
3200
484k
    return ret;
3201
484k
}
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
157k
{
3236
157k
    Py_ssize_t res;
3237
3238
157k
    assert(unicode != NULL);
3239
157k
    assert(_PyUnicode_CHECK(unicode));
3240
3241
157k
    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
157k
    return res;
3254
157k
}
3255
3256
static void
3257
unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3258
157k
{
3259
157k
    assert(unicode != NULL);
3260
157k
    assert(_PyUnicode_CHECK(unicode));
3261
3262
157k
    if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
3263
1.42k
        memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
3264
1.42k
        return;
3265
1.42k
    }
3266
3267
156k
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3268
132k
        const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3269
3.68M
        for (; size--; ++s, ++w) {
3270
3.54M
            *w = *s;
3271
3.54M
        }
3272
132k
    }
3273
23.8k
    else {
3274
23.8k
#if SIZEOF_WCHAR_T == 4
3275
23.8k
        assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3276
23.8k
        const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3277
1.33M
        for (; size--; ++s, ++w) {
3278
1.30M
            *w = *s;
3279
1.30M
        }
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
23.8k
    }
3299
156k
}
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
157k
{
3357
157k
    wchar_t *buffer;
3358
157k
    Py_ssize_t buflen;
3359
3360
157k
    if (unicode == NULL) {
3361
0
        PyErr_BadInternalCall();
3362
0
        return NULL;
3363
0
    }
3364
157k
    if (!PyUnicode_Check(unicode)) {
3365
0
        PyErr_BadArgument();
3366
0
        return NULL;
3367
0
    }
3368
3369
157k
    buflen = unicode_get_widechar_size(unicode);
3370
157k
    buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
3371
157k
    if (buffer == NULL) {
3372
0
        PyErr_NoMemory();
3373
0
        return NULL;
3374
0
    }
3375
157k
    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
157k
    if (size != NULL) {
3388
154k
        *size = buflen;
3389
154k
    }
3390
3.03k
    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
157k
    return buffer;
3397
157k
}
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.6M
{
3452
13.6M
    if (ordinal < 0 || ordinal > MAX_UNICODE) {
3453
29
        PyErr_SetString(PyExc_ValueError,
3454
29
                        "chr() arg not in range(0x110000)");
3455
29
        return NULL;
3456
29
    }
3457
3458
13.6M
    return unicode_char((Py_UCS4)ordinal);
3459
13.6M
}
3460
3461
PyObject *
3462
PyUnicode_FromObject(PyObject *obj)
3463
4.24M
{
3464
    /* XXX Perhaps we should make this API an alias of
3465
       PyObject_Str() instead ?! */
3466
4.24M
    if (PyUnicode_CheckExact(obj)) {
3467
4.24M
        return Py_NewRef(obj);
3468
4.24M
    }
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
30.9M
{
3485
30.9M
    Py_buffer buffer;
3486
30.9M
    PyObject *v;
3487
3488
30.9M
    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
30.9M
    if (PyBytes_Check(obj)) {
3495
30.9M
        if (PyBytes_GET_SIZE(obj) == 0) {
3496
7.86M
            if (unicode_check_encoding_errors(encoding, errors) < 0) {
3497
0
                return NULL;
3498
0
            }
3499
7.86M
            _Py_RETURN_UNICODE_EMPTY();
3500
7.86M
        }
3501
23.1M
        return PyUnicode_Decode(
3502
23.1M
                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3503
23.1M
                encoding, errors);
3504
30.9M
    }
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
34.3M
{
3542
34.3M
    const char *e;
3543
34.3M
    char *l;
3544
34.3M
    char *l_end;
3545
34.3M
    int punct;
3546
3547
34.3M
    assert(encoding != NULL);
3548
3549
34.3M
    e = encoding;
3550
34.3M
    l = lower;
3551
34.3M
    l_end = &lower[lower_len - 1];
3552
34.3M
    punct = 0;
3553
231M
    while (1) {
3554
231M
        char c = *e;
3555
231M
        if (c == 0) {
3556
33.6M
            break;
3557
33.6M
        }
3558
3559
197M
        if (Py_ISALNUM(c) || c == '.') {
3560
178M
            if (punct && l != lower) {
3561
14.0M
                if (l == l_end) {
3562
1.93k
                    return 0;
3563
1.93k
                }
3564
14.0M
                *l++ = '_';
3565
14.0M
            }
3566
178M
            punct = 0;
3567
3568
178M
            if (l == l_end) {
3569
686k
                return 0;
3570
686k
            }
3571
178M
            *l++ = to_lower ? Py_TOLOWER(c) : c;
3572
178M
        }
3573
18.8M
        else {
3574
18.8M
            punct = 1;
3575
18.8M
        }
3576
3577
197M
        e++;
3578
197M
    }
3579
33.6M
    *l = '\0';
3580
33.6M
    return 1;
3581
34.3M
}
3582
3583
PyObject *
3584
PyUnicode_Decode(const char *s,
3585
                 Py_ssize_t size,
3586
                 const char *encoding,
3587
                 const char *errors)
3588
23.7M
{
3589
23.7M
    PyObject *buffer = NULL, *unicode;
3590
23.7M
    Py_buffer info;
3591
23.7M
    char buflower[11];   /* strlen("iso-8859-1\0") == 11, longest shortcut */
3592
3593
23.7M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3594
0
        return NULL;
3595
0
    }
3596
3597
23.7M
    if (size == 0) {
3598
0
        _Py_RETURN_UNICODE_EMPTY();
3599
0
    }
3600
3601
23.7M
    if (encoding == NULL) {
3602
50.2k
        return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3603
50.2k
    }
3604
3605
    /* Shortcuts for common default encodings */
3606
23.6M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3607
23.6M
        char *lower = buflower;
3608
3609
        /* Fast paths */
3610
23.6M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3611
4.02M
            lower += 3;
3612
4.02M
            if (*lower == '_') {
3613
                /* Match "utf8" and "utf_8" */
3614
4.02M
                lower++;
3615
4.02M
            }
3616
3617
4.02M
            if (lower[0] == '8' && lower[1] == 0) {
3618
3.99M
                return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3619
3.99M
            }
3620
24.8k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3621
215
                return PyUnicode_DecodeUTF16(s, size, errors, 0);
3622
215
            }
3623
24.6k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3624
145
                return PyUnicode_DecodeUTF32(s, size, errors, 0);
3625
145
            }
3626
4.02M
        }
3627
19.6M
        else {
3628
19.6M
            if (strcmp(lower, "ascii") == 0
3629
14.0M
                || strcmp(lower, "us_ascii") == 0) {
3630
14.0M
                return PyUnicode_DecodeASCII(s, size, errors);
3631
14.0M
            }
3632
    #ifdef MS_WINDOWS
3633
            else if (strcmp(lower, "mbcs") == 0) {
3634
                return PyUnicode_DecodeMBCS(s, size, errors);
3635
            }
3636
    #endif
3637
5.58M
            else if (strcmp(lower, "latin1") == 0
3638
5.58M
                     || strcmp(lower, "latin_1") == 0
3639
2.14M
                     || strcmp(lower, "iso_8859_1") == 0
3640
3.46M
                     || strcmp(lower, "iso8859_1") == 0) {
3641
3.46M
                return PyUnicode_DecodeLatin1(s, size, errors);
3642
3.46M
            }
3643
19.6M
        }
3644
23.6M
    }
3645
3646
    /* Decode via the codec registry */
3647
2.15M
    buffer = NULL;
3648
2.15M
    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
3649
0
        goto onError;
3650
2.15M
    buffer = PyMemoryView_FromBuffer(&info);
3651
2.15M
    if (buffer == NULL)
3652
0
        goto onError;
3653
2.15M
    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
3654
2.15M
    if (unicode == NULL)
3655
59.8k
        goto onError;
3656
2.09M
    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
2.09M
    Py_DECREF(buffer);
3666
2.09M
    return unicode_result(unicode);
3667
3668
59.8k
  onError:
3669
59.8k
    Py_XDECREF(buffer);
3670
59.8k
    return NULL;
3671
2.09M
}
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
687k
{
3812
687k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3813
687k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3814
687k
    if (fs_codec->utf8) {
3815
685k
        return unicode_encode_utf8(unicode,
3816
685k
                                   fs_codec->error_handler,
3817
685k
                                   fs_codec->errors);
3818
685k
    }
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
687k
}
3842
3843
PyObject *
3844
PyUnicode_AsEncodedString(PyObject *unicode,
3845
                          const char *encoding,
3846
                          const char *errors)
3847
23.4M
{
3848
23.4M
    PyObject *v;
3849
23.4M
    char buflower[11];   /* strlen("iso_8859_1\0") == 11, longest shortcut */
3850
3851
23.4M
    if (!PyUnicode_Check(unicode)) {
3852
0
        PyErr_BadArgument();
3853
0
        return NULL;
3854
0
    }
3855
3856
23.4M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3857
0
        return NULL;
3858
0
    }
3859
3860
23.4M
    if (encoding == NULL) {
3861
12.8M
        return _PyUnicode_AsUTF8String(unicode, errors);
3862
12.8M
    }
3863
3864
    /* Shortcuts for common default encodings */
3865
10.6M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3866
9.95M
        char *lower = buflower;
3867
3868
        /* Fast paths */
3869
9.95M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3870
5.62M
            lower += 3;
3871
5.62M
            if (*lower == '_') {
3872
                /* Match "utf8" and "utf_8" */
3873
5.62M
                lower++;
3874
5.62M
            }
3875
3876
5.62M
            if (lower[0] == '8' && lower[1] == 0) {
3877
5.61M
                return _PyUnicode_AsUTF8String(unicode, errors);
3878
5.61M
            }
3879
9.14k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3880
0
                return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3881
0
            }
3882
9.14k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3883
0
                return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3884
0
            }
3885
5.62M
        }
3886
4.33M
        else {
3887
4.33M
            if (strcmp(lower, "ascii") == 0
3888
2.95M
                || strcmp(lower, "us_ascii") == 0) {
3889
2.95M
                return _PyUnicode_AsASCIIString(unicode, errors);
3890
2.95M
            }
3891
#ifdef MS_WINDOWS
3892
            else if (strcmp(lower, "mbcs") == 0) {
3893
                return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3894
            }
3895
#endif
3896
1.38M
            else if (strcmp(lower, "latin1") == 0 ||
3897
1.38M
                     strcmp(lower, "latin_1") == 0 ||
3898
1.38M
                     strcmp(lower, "iso_8859_1") == 0 ||
3899
1.38M
                     strcmp(lower, "iso8859_1") == 0) {
3900
10
                return _PyUnicode_AsLatin1String(unicode, errors);
3901
10
            }
3902
4.33M
        }
3903
9.95M
    }
3904
3905
    /* Encode via the codec registry */
3906
2.07M
    v = _PyCodec_EncodeText(unicode, encoding, errors);
3907
2.07M
    if (v == NULL)
3908
0
        return NULL;
3909
3910
    /* The normal path */
3911
2.07M
    if (PyBytes_Check(v))
3912
2.07M
        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
248k
{
3981
248k
    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
248k
    wchar_t *wstr;
3987
248k
    size_t wlen;
3988
248k
    int res = _Py_DecodeLocale(str, &wstr, &wlen, current_locale, errors);
3989
248k
    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
248k
    PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
4014
248k
    PyMem_RawFree(wstr);
4015
248k
    return unicode;
4016
248k
}
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
236k
{
4029
236k
    Py_ssize_t size = (Py_ssize_t)strlen(str);
4030
236k
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
4031
236k
    return unicode_decode_locale(str, size, error_handler, 1);
4032
236k
}
4033
4034
4035
PyObject*
4036
1.03k
PyUnicode_DecodeFSDefault(const char *s) {
4037
1.03k
    Py_ssize_t size = (Py_ssize_t)strlen(s);
4038
1.03k
    return PyUnicode_DecodeFSDefaultAndSize(s, size);
4039
1.03k
}
4040
4041
PyObject*
4042
PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
4043
124k
{
4044
124k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4045
124k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
4046
124k
    if (fs_codec->utf8) {
4047
112k
        return unicode_decode_utf8(s, size,
4048
112k
                                   fs_codec->error_handler,
4049
112k
                                   fs_codec->errors,
4050
112k
                                   NULL);
4051
112k
    }
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
124k
}
4075
4076
4077
int
4078
PyUnicode_FSConverter(PyObject* arg, void* addr)
4079
170k
{
4080
170k
    PyObject *path = NULL;
4081
170k
    PyObject *output = NULL;
4082
170k
    Py_ssize_t size;
4083
170k
    const char *data;
4084
170k
    if (arg == NULL) {
4085
0
        Py_DECREF(*(PyObject**)addr);
4086
0
        *(PyObject**)addr = NULL;
4087
0
        return 1;
4088
0
    }
4089
170k
    path = PyOS_FSPath(arg);
4090
170k
    if (path == NULL) {
4091
0
        return 0;
4092
0
    }
4093
170k
    if (PyBytes_Check(path)) {
4094
0
        output = path;
4095
0
    }
4096
170k
    else {  // PyOS_FSPath() guarantees its returned value is bytes or str.
4097
170k
        output = PyUnicode_EncodeFSDefault(path);
4098
170k
        Py_DECREF(path);
4099
170k
        if (!output) {
4100
0
            return 0;
4101
0
        }
4102
170k
        assert(PyBytes_Check(output));
4103
170k
    }
4104
4105
170k
    size = PyBytes_GET_SIZE(output);
4106
170k
    data = PyBytes_AS_STRING(output);
4107
170k
    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
170k
    *(PyObject**)addr = output;
4113
170k
    return Py_CLEANUP_SUPPORTED;
4114
170k
}
4115
4116
4117
int
4118
PyUnicode_FSDecoder(PyObject* arg, void* addr)
4119
75.5k
{
4120
75.5k
    if (arg == NULL) {
4121
0
        Py_DECREF(*(PyObject**)addr);
4122
0
        *(PyObject**)addr = NULL;
4123
0
        return 1;
4124
0
    }
4125
4126
75.5k
    PyObject *path = PyOS_FSPath(arg);
4127
75.5k
    if (path == NULL) {
4128
0
        return 0;
4129
0
    }
4130
4131
75.5k
    PyObject *output = NULL;
4132
75.5k
    if (PyUnicode_Check(path)) {
4133
75.5k
        output = path;
4134
75.5k
    }
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
75.5k
    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
4152
75.5k
                 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
75.5k
    *(PyObject**)addr = output;
4158
75.5k
    return Py_CLEANUP_SUPPORTED;
4159
75.5k
}
4160
4161
4162
static int unicode_fill_utf8(PyObject *unicode);
4163
4164
4165
static int
4166
unicode_ensure_utf8(PyObject *unicode)
4167
71.9M
{
4168
71.9M
    int err = 0;
4169
71.9M
    if (PyUnicode_UTF8(unicode) == NULL) {
4170
181k
        Py_BEGIN_CRITICAL_SECTION(unicode);
4171
181k
        if (PyUnicode_UTF8(unicode) == NULL) {
4172
181k
            err = unicode_fill_utf8(unicode);
4173
181k
        }
4174
181k
        Py_END_CRITICAL_SECTION();
4175
181k
    }
4176
71.9M
    return err;
4177
71.9M
}
4178
4179
const char *
4180
PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
4181
71.9M
{
4182
71.9M
    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
71.9M
    if (unicode_ensure_utf8(unicode) == -1) {
4191
270
        if (psize) {
4192
270
            *psize = -1;
4193
270
        }
4194
270
        return NULL;
4195
270
    }
4196
4197
71.9M
    if (psize) {
4198
71.8M
        *psize = PyUnicode_UTF8_LENGTH(unicode);
4199
71.8M
    }
4200
71.9M
    return PyUnicode_UTF8(unicode);
4201
71.9M
}
4202
4203
const char *
4204
PyUnicode_AsUTF8(PyObject *unicode)
4205
188k
{
4206
188k
    return PyUnicode_AsUTF8AndSize(unicode, NULL);
4207
188k
}
4208
4209
const char *
4210
_PyUnicode_AsUTF8NoNUL(PyObject *unicode)
4211
61.3M
{
4212
61.3M
    Py_ssize_t size;
4213
61.3M
    const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
4214
61.3M
    if (s && strlen(s) != (size_t)size) {
4215
3.29k
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4216
3.29k
        return NULL;
4217
3.29k
    }
4218
61.3M
    return s;
4219
61.3M
}
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
27.0k
{
4240
27.0k
    if (!PyUnicode_Check(unicode)) {
4241
0
        PyErr_BadArgument();
4242
0
        return -1;
4243
0
    }
4244
27.0k
    return PyUnicode_GET_LENGTH(unicode);
4245
27.0k
}
4246
4247
Py_UCS4
4248
PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4249
3.27k
{
4250
3.27k
    const void *data;
4251
3.27k
    int kind;
4252
4253
3.27k
    if (!PyUnicode_Check(unicode)) {
4254
0
        PyErr_BadArgument();
4255
0
        return (Py_UCS4)-1;
4256
0
    }
4257
3.27k
    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
3.27k
    data = PyUnicode_DATA(unicode);
4262
3.27k
    kind = PyUnicode_KIND(unicode);
4263
3.27k
    return PyUnicode_READ(kind, data, index);
4264
3.27k
}
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.09M
{
4302
3.09M
    if (*exceptionObject == NULL) {
4303
2.66M
        *exceptionObject = PyUnicodeDecodeError_Create(
4304
2.66M
            encoding, input, length, startpos, endpos, reason);
4305
2.66M
    }
4306
432k
    else {
4307
432k
        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4308
0
            goto onError;
4309
432k
        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4310
0
            goto onError;
4311
432k
        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4312
0
            goto onError;
4313
432k
    }
4314
3.09M
    return;
4315
4316
3.09M
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.09M
{
4455
3.09M
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4456
4457
3.09M
    PyObject *restuple = NULL;
4458
3.09M
    PyObject *repunicode = NULL;
4459
3.09M
    Py_ssize_t insize;
4460
3.09M
    Py_ssize_t newpos;
4461
3.09M
    Py_ssize_t replen;
4462
3.09M
    Py_ssize_t remain;
4463
3.09M
    PyObject *inputobj = NULL;
4464
3.09M
    int need_to_grow = 0;
4465
3.09M
    const char *new_inptr;
4466
4467
3.09M
    if (*errorHandler == NULL) {
4468
2.66M
        *errorHandler = PyCodec_LookupError(errors);
4469
2.66M
        if (*errorHandler == NULL)
4470
0
            goto onError;
4471
2.66M
    }
4472
4473
3.09M
    make_decode_exception(exceptionObject,
4474
3.09M
        encoding,
4475
3.09M
        *input, *inend - *input,
4476
3.09M
        *startinpos, *endinpos,
4477
3.09M
        reason);
4478
3.09M
    if (*exceptionObject == NULL)
4479
0
        goto onError;
4480
4481
3.09M
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4482
3.09M
    if (restuple == NULL)
4483
2.61M
        goto onError;
4484
484k
    if (!PyTuple_Check(restuple)) {
4485
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4486
0
        goto onError;
4487
0
    }
4488
484k
    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
484k
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4494
484k
    if (!inputobj)
4495
0
        goto onError;
4496
484k
    remain = *inend - *input - *endinpos;
4497
484k
    *input = PyBytes_AS_STRING(inputobj);
4498
484k
    insize = PyBytes_GET_SIZE(inputobj);
4499
484k
    *inend = *input + insize;
4500
    /* we can DECREF safely, as the exception has another reference,
4501
       so the object won't go away. */
4502
484k
    Py_DECREF(inputobj);
4503
4504
484k
    if (newpos<0)
4505
0
        newpos = insize+newpos;
4506
484k
    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
484k
    replen = PyUnicode_GET_LENGTH(repunicode);
4512
484k
    if (replen > 1) {
4513
14.9k
        writer->min_length += replen - 1;
4514
14.9k
        need_to_grow = 1;
4515
14.9k
    }
4516
484k
    new_inptr = *input + newpos;
4517
484k
    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.96k
        writer->min_length += *inend - new_inptr - remain;
4524
6.96k
        need_to_grow = 1;
4525
6.96k
    }
4526
484k
    if (need_to_grow) {
4527
15.1k
        writer->overallocate = 1;
4528
15.1k
        if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
4529
15.1k
                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4530
0
            goto onError;
4531
15.1k
    }
4532
484k
    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4533
0
        goto onError;
4534
4535
484k
    *endinpos = newpos;
4536
484k
    *inptr = new_inptr;
4537
4538
    /* we made it! */
4539
484k
    Py_DECREF(restuple);
4540
484k
    return 0;
4541
4542
2.61M
  onError:
4543
2.61M
    Py_XDECREF(restuple);
4544
2.61M
    return -1;
4545
484k
}
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
321k
    (((c) >= 'A' && (c) <= 'Z') ||     \
4557
321k
     ((c) >= 'a' && (c) <= 'z') ||     \
4558
321k
     ((c) >= '0' && (c) <= '9') ||     \
4559
321k
     (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
269k
    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
4565
269k
     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
4566
194k
     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
4567
109k
     (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
7.50M
    ((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
20.1k
{
4646
20.1k
    const char *starts = s;
4647
20.1k
    Py_ssize_t startinpos;
4648
20.1k
    Py_ssize_t endinpos;
4649
20.1k
    const char *e;
4650
20.1k
    _PyUnicodeWriter writer;
4651
20.1k
    const char *errmsg = "";
4652
20.1k
    int inShift = 0;
4653
20.1k
    Py_ssize_t shiftOutStart;
4654
20.1k
    unsigned int base64bits = 0;
4655
20.1k
    unsigned long base64buffer = 0;
4656
20.1k
    Py_UCS4 surrogate = 0;
4657
20.1k
    PyObject *errorHandler = NULL;
4658
20.1k
    PyObject *exc = NULL;
4659
4660
20.1k
    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
20.1k
    _PyUnicodeWriter_Init(&writer);
4668
20.1k
    writer.min_length = size;
4669
4670
20.1k
    shiftOutStart = 0;
4671
20.1k
    e = s + size;
4672
4673
7.83M
    while (s < e) {
4674
7.82M
        Py_UCS4 ch;
4675
7.82M
      restart:
4676
7.82M
        ch = (unsigned char) *s;
4677
4678
7.82M
        if (inShift) { /* in a base-64 section */
4679
292k
            if (IS_BASE64(ch)) { /* consume a base-64 character */
4680
269k
                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4681
269k
                base64bits += 6;
4682
269k
                s++;
4683
269k
                if (base64bits >= 16) {
4684
                    /* we have enough bits for a UTF-16 value */
4685
94.3k
                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
4686
94.3k
                    base64bits -= 16;
4687
94.3k
                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4688
94.3k
                    assert(outCh <= 0xffff);
4689
94.3k
                    if (surrogate) {
4690
                        /* expecting a second surrogate */
4691
9.45k
                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4692
3.87k
                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
4693
3.87k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
4694
0
                                goto onError;
4695
3.87k
                            surrogate = 0;
4696
3.87k
                            continue;
4697
3.87k
                        }
4698
5.58k
                        else {
4699
5.58k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4700
0
                                goto onError;
4701
5.58k
                            surrogate = 0;
4702
5.58k
                        }
4703
9.45k
                    }
4704
90.4k
                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
4705
                        /* first surrogate */
4706
18.4k
                        surrogate = outCh;
4707
18.4k
                    }
4708
72.0k
                    else {
4709
72.0k
                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
4710
0
                            goto onError;
4711
72.0k
                    }
4712
90.4k
                }
4713
269k
            }
4714
22.6k
            else { /* now leaving a base-64 section */
4715
22.6k
                inShift = 0;
4716
22.6k
                if (base64bits > 0) { /* left-over bits */
4717
19.2k
                    if (base64bits >= 6) {
4718
                        /* We've seen at least one base-64 character */
4719
6.46k
                        s++;
4720
6.46k
                        errmsg = "partial character in shift sequence";
4721
6.46k
                        goto utf7Error;
4722
6.46k
                    }
4723
12.7k
                    else {
4724
                        /* Some bits remain; they should be zero */
4725
12.7k
                        if (base64buffer != 0) {
4726
1.69k
                            s++;
4727
1.69k
                            errmsg = "non-zero padding bits in shift sequence";
4728
1.69k
                            goto utf7Error;
4729
1.69k
                        }
4730
12.7k
                    }
4731
19.2k
                }
4732
14.4k
                if (surrogate && DECODE_DIRECT(ch)) {
4733
4.21k
                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4734
0
                        goto onError;
4735
4.21k
                }
4736
14.4k
                surrogate = 0;
4737
14.4k
                if (ch == '-') {
4738
                    /* '-' is absorbed; other terminating
4739
                       characters are preserved */
4740
1.78k
                    s++;
4741
1.78k
                }
4742
14.4k
            }
4743
292k
        }
4744
7.52M
        else if ( ch == '+' ) {
4745
32.1k
            startinpos = s-starts;
4746
32.1k
            s++; /* consume '+' */
4747
32.1k
            if (s < e && *s == '-') { /* '+-' encodes '+' */
4748
2.31k
                s++;
4749
2.31k
                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
4750
0
                    goto onError;
4751
2.31k
            }
4752
29.8k
            else if (s < e && !IS_BASE64(*s)) {
4753
3.71k
                s++;
4754
3.71k
                errmsg = "ill-formed sequence";
4755
3.71k
                goto utf7Error;
4756
3.71k
            }
4757
26.1k
            else { /* begin base64-encoded section */
4758
26.1k
                inShift = 1;
4759
26.1k
                surrogate = 0;
4760
26.1k
                shiftOutStart = writer.pos;
4761
26.1k
                base64bits = 0;
4762
26.1k
                base64buffer = 0;
4763
26.1k
            }
4764
32.1k
        }
4765
7.49M
        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
4766
7.39M
            s++;
4767
7.39M
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
4768
0
                goto onError;
4769
7.39M
        }
4770
103k
        else {
4771
103k
            startinpos = s-starts;
4772
103k
            s++;
4773
103k
            errmsg = "unexpected special character";
4774
103k
            goto utf7Error;
4775
103k
        }
4776
7.70M
        continue;
4777
7.70M
utf7Error:
4778
114k
        endinpos = s-starts;
4779
114k
        if (unicode_decode_call_errorhandler_writer(
4780
114k
                errors, &errorHandler,
4781
114k
                "utf7", errmsg,
4782
114k
                &starts, &e, &startinpos, &endinpos, &exc, &s,
4783
114k
                &writer))
4784
7.92k
            goto onError;
4785
114k
    }
4786
4787
    /* end of string */
4788
4789
12.1k
    if (inShift && !consumed) { /* in shift sequence, no more to follow */
4790
        /* if we're in an inconsistent state, that's an error */
4791
3.46k
        inShift = 0;
4792
3.46k
        if (surrogate ||
4793
3.22k
                (base64bits >= 6) ||
4794
2.07k
                (base64bits > 0 && base64buffer != 0)) {
4795
2.07k
            endinpos = size;
4796
2.07k
            if (unicode_decode_call_errorhandler_writer(
4797
2.07k
                    errors, &errorHandler,
4798
2.07k
                    "utf7", "unterminated shift sequence",
4799
2.07k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
4800
2.07k
                    &writer))
4801
1.65k
                goto onError;
4802
416
            if (s < e)
4803
0
                goto restart;
4804
416
        }
4805
3.46k
    }
4806
4807
    /* return state */
4808
10.5k
    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
10.5k
    Py_XDECREF(errorHandler);
4822
10.5k
    Py_XDECREF(exc);
4823
10.5k
    return _PyUnicodeWriter_Finish(&writer);
4824
4825
9.57k
  onError:
4826
9.57k
    Py_XDECREF(errorHandler);
4827
9.57k
    Py_XDECREF(exc);
4828
9.57k
    _PyUnicodeWriter_Dealloc(&writer);
4829
9.57k
    return NULL;
4830
10.5k
}
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
63.7M
{
4936
63.7M
    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4937
63.7M
}
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
203M
# define ASCII_CHAR_MASK 0x8080808080808080ULL
4959
// used to count codepoints in UTF-8 string.
4960
45.2M
# define VECTOR_0101     0x0101010101010101ULL
4961
938k
# 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.76M
{
4975
7.76M
    return __builtin_ctzll((unsigned long long)v);
4976
7.76M
}
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
78.9M
{
4999
78.9M
    union {
5000
78.9M
        size_t s;
5001
78.9M
        unsigned char b[SIZEOF_SIZE_T];
5002
78.9M
    } u;
5003
78.9M
    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
78.9M
    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.63M
    case 7:
5014
3.63M
        u.b[6] = p[6];
5015
3.63M
        _Py_FALLTHROUGH;
5016
11.5M
    case 6:
5017
11.5M
        u.b[5] = p[5];
5018
11.5M
        _Py_FALLTHROUGH;
5019
22.1M
    case 5:
5020
22.1M
        u.b[4] = p[4];
5021
22.1M
        _Py_FALLTHROUGH;
5022
22.1M
#endif
5023
33.6M
    case 4:
5024
33.6M
        u.b[3] = p[3];
5025
33.6M
        _Py_FALLTHROUGH;
5026
42.1M
    case 3:
5027
42.1M
        u.b[2] = p[2];
5028
42.1M
        _Py_FALLTHROUGH;
5029
72.6M
    case 2:
5030
72.6M
        u.b[1] = p[1];
5031
72.6M
        _Py_FALLTHROUGH;
5032
74.1M
    case 1:
5033
74.1M
        u.b[0] = p[0];
5034
74.1M
        break;
5035
4.85M
    case 0:
5036
4.85M
        break;
5037
78.9M
    }
5038
78.9M
    return u.s;
5039
78.9M
}
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
82.1M
{
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
82.1M
    const unsigned char *p = start;
5058
5059
82.1M
    if (end - start >= SIZEOF_SIZE_T) {
5060
        // Avoid unaligned read.
5061
22.1M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5062
22.1M
        size_t u;
5063
22.1M
        memcpy(&u, p, sizeof(size_t));
5064
22.1M
        u &= ASCII_CHAR_MASK;
5065
22.1M
        if (u) {
5066
2.06M
            return (ctz(u) - 7) / 8;
5067
2.06M
        }
5068
20.1M
        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
20.1M
        const unsigned char *e = end - SIZEOF_SIZE_T;
5080
109M
        while (p <= e) {
5081
90.3M
            size_t u = (*(const size_t *)p) & ASCII_CHAR_MASK;
5082
90.3M
            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
89.1M
            p += SIZEOF_SIZE_T;
5092
89.1M
        }
5093
20.1M
    }
5094
78.9M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5095
82.1M
    assert((end - p) < SIZEOF_SIZE_T);
5096
    // we can not use *(const size_t*)p to avoid buffer overrun.
5097
78.9M
    size_t u = load_unaligned(p, end - p) & ASCII_CHAR_MASK;
5098
78.9M
    if (u) {
5099
4.57M
        return p - start + (ctz(u) - 7) / 8;
5100
4.57M
    }
5101
74.3M
    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
78.9M
}
5112
5113
static inline int
5114
scalar_utf8_start_char(unsigned int ch)
5115
5.25M
{
5116
    // 0xxxxxxx or 11xxxxxx are first byte.
5117
5.25M
    return (~ch >> 7 | ch >> 6) & 1;
5118
5.25M
}
5119
5120
static inline size_t
5121
vector_utf8_start_chars(size_t v)
5122
45.2M
{
5123
45.2M
    return ((~v >> 7) | (v >> 6)) & VECTOR_0101;
5124
45.2M
}
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.46M
{
5131
1.46M
    Py_ssize_t len = 0;
5132
5133
1.46M
    if (end - s >= SIZEOF_SIZE_T) {
5134
336k
        while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
5135
34.7k
            len += scalar_utf8_start_char(*s++);
5136
34.7k
        }
5137
5138
771k
        while (s + SIZEOF_SIZE_T <= end) {
5139
469k
            const unsigned char *e = end;
5140
469k
            if (e - s > SIZEOF_SIZE_T * 255) {
5141
169k
                e = s + SIZEOF_SIZE_T * 255;
5142
169k
            }
5143
469k
            Py_ssize_t vstart = 0;
5144
45.7M
            while (s + SIZEOF_SIZE_T <= e) {
5145
45.2M
                size_t v = *(size_t*)s;
5146
45.2M
                size_t vs = vector_utf8_start_chars(v);
5147
45.2M
                vstart += vs;
5148
45.2M
                s += SIZEOF_SIZE_T;
5149
45.2M
            }
5150
469k
            vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF);
5151
469k
            vstart += vstart >> 16;
5152
469k
#if SIZEOF_SIZE_T == 8
5153
469k
            vstart += vstart >> 32;
5154
469k
#endif
5155
469k
            len += vstart & 0x7ff;
5156
469k
        }
5157
301k
    }
5158
6.68M
    while (s < end) {
5159
5.22M
        len += scalar_utf8_start_char(*s++);
5160
5.22M
    }
5161
1.46M
    return len;
5162
1.46M
}
5163
5164
static Py_ssize_t
5165
ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
5166
15.4M
{
5167
15.4M
#if SIZEOF_SIZE_T <= SIZEOF_VOID_P
5168
15.4M
    if (_Py_IS_ALIGNED(start, ALIGNOF_SIZE_T)
5169
15.3M
        && _Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T))
5170
13.4M
    {
5171
        /* Fast path, see in STRINGLIB(utf8_decode) for
5172
           an explanation. */
5173
13.4M
        const char *p = start;
5174
13.4M
        Py_UCS1 *q = dest;
5175
22.6M
        while (p + SIZEOF_SIZE_T <= end) {
5176
11.8M
            size_t value = *(const size_t *) p;
5177
11.8M
            if (value & ASCII_CHAR_MASK)
5178
2.69M
                break;
5179
9.17M
            *((size_t *)q) = value;
5180
9.17M
            p += SIZEOF_SIZE_T;
5181
9.17M
            q += SIZEOF_SIZE_T;
5182
9.17M
        }
5183
62.5M
        while (p < end) {
5184
51.8M
            if ((unsigned char)*p & 0x80)
5185
2.72M
                break;
5186
49.1M
            *q++ = *p++;
5187
49.1M
        }
5188
13.4M
        return p - start;
5189
13.4M
    }
5190
2.02M
#endif
5191
2.02M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)start,
5192
2.02M
                                         (const unsigned char*)end);
5193
2.02M
    memcpy(dest, start, pos);
5194
2.02M
    return pos;
5195
15.4M
}
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.76M
{
5204
7.76M
    Py_ssize_t startinpos, endinpos;
5205
7.76M
    const char *errmsg = "";
5206
7.76M
    PyObject *error_handler_obj = NULL;
5207
7.76M
    PyObject *exc = NULL;
5208
5209
346M
    while (s < end) {
5210
344M
        Py_UCS4 ch;
5211
344M
        int kind = writer->kind;
5212
5213
344M
        if (kind == PyUnicode_1BYTE_KIND) {
5214
6.74M
            if (PyUnicode_IS_ASCII(writer->buffer))
5215
6.29M
                ch = asciilib_utf8_decode(&s, end, writer->data, &writer->pos);
5216
444k
            else
5217
444k
                ch = ucs1lib_utf8_decode(&s, end, writer->data, &writer->pos);
5218
337M
        } else if (kind == PyUnicode_2BYTE_KIND) {
5219
126M
            ch = ucs2lib_utf8_decode(&s, end, writer->data, &writer->pos);
5220
210M
        } else {
5221
210M
            assert(kind == PyUnicode_4BYTE_KIND);
5222
210M
            ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos);
5223
210M
        }
5224
5225
344M
        switch (ch) {
5226
5.39M
        case 0:
5227
5.39M
            if (s == end || consumed)
5228
5.36M
                goto End;
5229
26.6k
            errmsg = "unexpected end of data";
5230
26.6k
            startinpos = s - starts;
5231
26.6k
            endinpos = end - starts;
5232
26.6k
            break;
5233
209M
        case 1:
5234
209M
            errmsg = "invalid start byte";
5235
209M
            startinpos = s - starts;
5236
209M
            endinpos = startinpos + 1;
5237
209M
            break;
5238
121M
        case 2:
5239
121M
            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
121M
            _Py_FALLTHROUGH;
5246
122M
        case 3:
5247
122M
        case 4:
5248
122M
            errmsg = "invalid continuation byte";
5249
122M
            startinpos = s - starts;
5250
122M
            endinpos = startinpos + ch - 1;
5251
122M
            break;
5252
6.33M
        default:
5253
            // ch doesn't fit into kind, so change the buffer kind to write
5254
            // the character
5255
6.33M
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
5256
0
                goto onError;
5257
6.33M
            continue;
5258
344M
        }
5259
5260
332M
        if (error_handler == _Py_ERROR_UNKNOWN)
5261
167k
            error_handler = _Py_GetErrorHandler(errors);
5262
5263
332M
        switch (error_handler) {
5264
0
        case _Py_ERROR_IGNORE:
5265
0
            s += (endinpos - startinpos);
5266
0
            break;
5267
5268
329M
        case _Py_ERROR_REPLACE:
5269
329M
            if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0)
5270
0
                goto onError;
5271
329M
            s += (endinpos - startinpos);
5272
329M
            break;
5273
5274
3.30M
        case _Py_ERROR_SURROGATEESCAPE:
5275
3.30M
        {
5276
3.30M
            Py_ssize_t i;
5277
5278
3.30M
            if (_PyUnicodeWriter_PrepareKind(writer, PyUnicode_2BYTE_KIND) < 0)
5279
0
                goto onError;
5280
3.30M
            assert(_PyUnicodeWriter_CanWrite(writer));
5281
6.60M
            for (i=startinpos; i<endinpos; i++) {
5282
3.30M
                ch = (Py_UCS4)(unsigned char)(starts[i]);
5283
3.30M
                PyUnicode_WRITE(writer->kind, writer->data, writer->pos,
5284
3.30M
                                ch + 0xdc00);
5285
3.30M
                writer->pos++;
5286
3.30M
            }
5287
3.30M
            s += (endinpos - startinpos);
5288
3.30M
            break;
5289
3.30M
        }
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.24k
                goto onError;
5298
2.24k
            }
5299
5300
8
            if (_PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) {
5301
0
                goto onError;
5302
0
            }
5303
332M
        }
5304
332M
    }
5305
5306
7.76M
End:
5307
7.76M
    if (consumed)
5308
1.11k
        *consumed = s - starts;
5309
5310
7.76M
    Py_XDECREF(error_handler_obj);
5311
7.76M
    Py_XDECREF(exc);
5312
7.76M
    return 0;
5313
5314
2.24k
onError:
5315
2.24k
    Py_XDECREF(error_handler_obj);
5316
2.24k
    Py_XDECREF(exc);
5317
2.24k
    return -1;
5318
7.76M
}
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
122M
{
5326
122M
    if (size == 0) {
5327
5.59M
        if (consumed) {
5328
0
            *consumed = 0;
5329
0
        }
5330
5.59M
        _Py_RETURN_UNICODE_EMPTY();
5331
5.59M
    }
5332
5333
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5334
117M
    if (size == 1 && (unsigned char)s[0] < 128) {
5335
36.9M
        if (consumed) {
5336
0
            *consumed = 1;
5337
0
        }
5338
36.9M
        return get_latin1_char((unsigned char)s[0]);
5339
36.9M
    }
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
80.1M
    if (PY_SSIZE_T_MAX - sizeof(PyCompactUnicodeObject) < (size_t)size) {
5344
0
        PyErr_NoMemory();
5345
0
        return NULL;
5346
0
    }
5347
5348
80.1M
    const char *starts = s;
5349
80.1M
    const char *end = s + size;
5350
5351
80.1M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end);
5352
80.1M
    if (pos == size) {  // fast path: ASCII string.
5353
72.4M
        PyObject *u = PyUnicode_New(size, 127);
5354
72.4M
        if (u == NULL) {
5355
0
            return NULL;
5356
0
        }
5357
72.4M
        memcpy(PyUnicode_1BYTE_DATA(u), s, size);
5358
72.4M
        if (consumed) {
5359
116
            *consumed = size;
5360
116
        }
5361
72.4M
        return u;
5362
72.4M
    }
5363
5364
7.68M
    int maxchr = 127;
5365
7.68M
    Py_ssize_t maxsize = size;
5366
5367
7.68M
    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.68M
    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.46M
        maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end);
5380
1.46M
        if (ch < 0xc4) { // latin1
5381
264k
            maxchr = 0xff;
5382
264k
        }
5383
1.19M
        else if (ch < 0xf0) { // ucs2
5384
137k
            maxchr = 0xffff;
5385
137k
        }
5386
1.05M
        else { // ucs4
5387
1.05M
            maxchr = 0x10ffff;
5388
1.05M
        }
5389
1.46M
    }
5390
7.68M
    PyObject *u = PyUnicode_New(maxsize, maxchr);
5391
7.68M
    if (!u) {
5392
0
        return NULL;
5393
0
    }
5394
5395
    // Use _PyUnicodeWriter after fast path is failed.
5396
7.68M
    _PyUnicodeWriter writer;
5397
7.68M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
5398
7.68M
    if (maxchr <= 255) {
5399
6.49M
        memcpy(PyUnicode_1BYTE_DATA(u), s, pos);
5400
6.49M
        s += pos;
5401
6.49M
        writer.pos = pos;
5402
6.49M
    }
5403
5404
7.68M
    if (unicode_decode_utf8_impl(&writer, starts, s, end,
5405
7.68M
                                 error_handler, errors,
5406
7.68M
                                 consumed) < 0) {
5407
2.24k
        _PyUnicodeWriter_Dealloc(&writer);
5408
2.24k
        return NULL;
5409
2.24k
    }
5410
7.68M
    return _PyUnicodeWriter_Finish(&writer);
5411
7.68M
}
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.04M
{
5421
2.04M
    if (size == 0) {
5422
9.24k
        if (consumed) {
5423
0
            *consumed = 0;
5424
0
        }
5425
9.24k
        return 0;
5426
9.24k
    }
5427
5428
2.03M
    Py_ssize_t old_pos = writer->pos;
5429
2.03M
    Py_UCS4 old_maxchar = writer->maxchar;
5430
5431
    // fast path: try ASCII string.
5432
2.03M
    if (_PyUnicodeWriter_Prepare(writer, size, 127) < 0) {
5433
0
        goto error;
5434
0
    }
5435
2.03M
    assert(_PyUnicodeWriter_CanWrite(writer));
5436
5437
2.03M
    const char *starts = s;
5438
2.03M
    const char *end = s + size;
5439
2.03M
    if (writer->kind == PyUnicode_1BYTE_KIND) {
5440
2.02M
        Py_UCS1 *dest = (Py_UCS1*)writer->data + writer->pos * writer->kind;
5441
2.02M
        Py_ssize_t decoded = ascii_decode(s, end, dest);
5442
2.02M
        writer->pos += decoded;
5443
5444
2.02M
        if (decoded == size) {
5445
1.95M
            if (consumed) {
5446
1.06k
                *consumed = size;
5447
1.06k
            }
5448
1.95M
            return 0;
5449
1.95M
        }
5450
72.6k
        s += decoded;
5451
72.6k
    }
5452
5453
75.2k
    int res = unicode_decode_utf8_impl(writer, starts, s, end,
5454
75.2k
                                       error_handler, errors, consumed);
5455
75.2k
    if (res < 0) {
5456
0
        goto error;
5457
0
    }
5458
75.2k
    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
75.2k
}
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
122M
{
5480
122M
    return unicode_decode_utf8(s, size,
5481
122M
                               errors ? _Py_ERROR_UNKNOWN : _Py_ERROR_STRICT,
5482
122M
                               errors, consumed);
5483
122M
}
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
19.1M
{
5766
19.1M
    if (!PyUnicode_Check(unicode)) {
5767
0
        PyErr_BadArgument();
5768
0
        return NULL;
5769
0
    }
5770
5771
19.1M
    if (PyUnicode_UTF8(unicode))
5772
10.3M
        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5773
10.3M
                                         PyUnicode_UTF8_LENGTH(unicode));
5774
5775
8.71M
    int kind = PyUnicode_KIND(unicode);
5776
8.71M
    const void *data = PyUnicode_DATA(unicode);
5777
8.71M
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5778
5779
8.71M
    PyBytesWriter *writer;
5780
8.71M
    char *end;
5781
5782
8.71M
    switch (kind) {
5783
0
    default:
5784
0
        Py_UNREACHABLE();
5785
5.92M
    case PyUnicode_1BYTE_KIND:
5786
        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5787
5.92M
        assert(!PyUnicode_IS_ASCII(unicode));
5788
5.92M
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5789
5.92M
                                      error_handler, errors, &end);
5790
5.92M
        break;
5791
1.59M
    case PyUnicode_2BYTE_KIND:
5792
1.59M
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5793
1.59M
                                      error_handler, errors, &end);
5794
1.59M
        break;
5795
1.18M
    case PyUnicode_4BYTE_KIND:
5796
1.18M
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5797
1.18M
                                      error_handler, errors, &end);
5798
1.18M
        break;
5799
8.71M
    }
5800
5801
8.71M
    if (writer == NULL) {
5802
138k
        PyBytesWriter_Discard(writer);
5803
138k
        return NULL;
5804
138k
    }
5805
8.57M
    return PyBytesWriter_FinishWithPointer(writer, end);
5806
8.71M
}
5807
5808
static int
5809
unicode_fill_utf8(PyObject *unicode)
5810
181k
{
5811
181k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(unicode);
5812
    /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5813
181k
    assert(!PyUnicode_IS_ASCII(unicode));
5814
5815
181k
    int kind = PyUnicode_KIND(unicode);
5816
181k
    const void *data = PyUnicode_DATA(unicode);
5817
181k
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5818
5819
181k
    PyBytesWriter *writer;
5820
181k
    char *end;
5821
5822
181k
    switch (kind) {
5823
0
    default:
5824
0
        Py_UNREACHABLE();
5825
137k
    case PyUnicode_1BYTE_KIND:
5826
137k
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5827
137k
                                      _Py_ERROR_STRICT, NULL, &end);
5828
137k
        break;
5829
35.8k
    case PyUnicode_2BYTE_KIND:
5830
35.8k
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5831
35.8k
                                      _Py_ERROR_STRICT, NULL, &end);
5832
35.8k
        break;
5833
8.18k
    case PyUnicode_4BYTE_KIND:
5834
8.18k
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5835
8.18k
                                      _Py_ERROR_STRICT, NULL, &end);
5836
8.18k
        break;
5837
181k
    }
5838
181k
    if (writer == NULL) {
5839
270
        return -1;
5840
270
    }
5841
5842
181k
    const char *start = PyBytesWriter_GetData(writer);
5843
181k
    Py_ssize_t len = end - start;
5844
5845
181k
    char *cache = PyMem_Malloc(len + 1);
5846
181k
    if (cache == NULL) {
5847
0
        PyBytesWriter_Discard(writer);
5848
0
        PyErr_NoMemory();
5849
0
        return -1;
5850
0
    }
5851
181k
    memcpy(cache, start, len);
5852
181k
    cache[len] = '\0';
5853
181k
    PyUnicode_SET_UTF8_LENGTH(unicode, len);
5854
181k
    PyUnicode_SET_UTF8(unicode, cache);
5855
181k
    PyBytesWriter_Discard(writer);
5856
181k
    return 0;
5857
181k
}
5858
5859
PyObject *
5860
_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5861
18.4M
{
5862
18.4M
    return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5863
18.4M
}
5864
5865
5866
PyObject *
5867
PyUnicode_AsUTF8String(PyObject *unicode)
5868
402
{
5869
402
    return _PyUnicode_AsUTF8String(unicode, NULL);
5870
402
}
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
145
{
5880
145
    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5881
145
}
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.3k
        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
17.2k
        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5913
17.2k
        if (bom == 0x0000FEFF) {
5914
171
            bo = -1;
5915
171
            q += 4;
5916
171
        }
5917
17.1k
        else if (bom == 0xFFFE0000) {
5918
402
            bo = 1;
5919
402
            q += 4;
5920
402
        }
5921
17.2k
        if (byteorder)
5922
17.1k
            *byteorder = bo;
5923
17.2k
    }
5924
5925
19.4k
    if (q == e) {
5926
74
        if (consumed)
5927
0
            *consumed = size;
5928
74
        _Py_RETURN_UNICODE_EMPTY();
5929
74
    }
5930
5931
#ifdef WORDS_BIGENDIAN
5932
    le = bo < 0;
5933
#else
5934
19.4k
    le = bo <= 0;
5935
19.4k
#endif
5936
19.4k
    encoding = le ? "utf-32-le" : "utf-32-be";
5937
5938
19.4k
    _PyUnicodeWriter_Init(&writer);
5939
19.4k
    writer.min_length = (e - q + 3) / 4;
5940
19.4k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
5941
0
        goto onError;
5942
5943
84.2k
    while (1) {
5944
84.2k
        Py_UCS4 ch = 0;
5945
84.2k
        Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
5946
5947
84.2k
        if (e - q >= 4) {
5948
70.6k
            int kind = writer.kind;
5949
70.6k
            void *data = writer.data;
5950
70.6k
            const unsigned char *last = e - 4;
5951
70.6k
            Py_ssize_t pos = writer.pos;
5952
70.6k
            if (le) {
5953
2.39M
                do {
5954
2.39M
                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5955
2.39M
                    if (ch > maxch)
5956
65.1k
                        break;
5957
2.33M
                    if (kind != PyUnicode_1BYTE_KIND &&
5958
2.31M
                        Py_UNICODE_IS_SURROGATE(ch))
5959
218
                        break;
5960
2.33M
                    PyUnicode_WRITE(kind, data, pos++, ch);
5961
2.33M
                    q += 4;
5962
2.33M
                } while (q <= last);
5963
66.5k
            }
5964
4.06k
            else {
5965
9.39k
                do {
5966
9.39k
                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5967
9.39k
                    if (ch > maxch)
5968
3.66k
                        break;
5969
5.73k
                    if (kind != PyUnicode_1BYTE_KIND &&
5970
2.89k
                        Py_UNICODE_IS_SURROGATE(ch))
5971
115
                        break;
5972
5.62k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5973
5.62k
                    q += 4;
5974
5.62k
                } while (q <= last);
5975
4.06k
            }
5976
70.6k
            writer.pos = pos;
5977
70.6k
        }
5978
5979
84.2k
        if (Py_UNICODE_IS_SURROGATE(ch)) {
5980
337
            errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
5981
337
            startinpos = ((const char *)q) - starts;
5982
337
            endinpos = startinpos + 4;
5983
337
        }
5984
83.9k
        else if (ch <= maxch) {
5985
15.1k
            if (q == e || consumed)
5986
3.56k
                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
68.8k
        else {
5993
68.8k
            if (ch < 0x110000) {
5994
4.27k
                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
5995
0
                    goto onError;
5996
4.27k
                q += 4;
5997
4.27k
                continue;
5998
4.27k
            }
5999
64.5k
            errmsg = "code point not in range(0x110000)";
6000
64.5k
            startinpos = ((const char *)q) - starts;
6001
64.5k
            endinpos = startinpos + 4;
6002
64.5k
        }
6003
6004
        /* The remaining input chars are ignored if the callback
6005
           chooses to skip the input */
6006
76.4k
        if (unicode_decode_call_errorhandler_writer(
6007
76.4k
                errors, &errorHandler,
6008
76.4k
                encoding, errmsg,
6009
76.4k
                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
6010
76.4k
                &writer))
6011
15.8k
            goto onError;
6012
76.4k
    }
6013
6014
3.56k
    if (consumed)
6015
0
        *consumed = (const char *)q-starts;
6016
6017
3.56k
    Py_XDECREF(errorHandler);
6018
3.56k
    Py_XDECREF(exc);
6019
3.56k
    return _PyUnicodeWriter_Finish(&writer);
6020
6021
15.8k
  onError:
6022
15.8k
    _PyUnicodeWriter_Dealloc(&writer);
6023
15.8k
    Py_XDECREF(errorHandler);
6024
15.8k
    Py_XDECREF(exc);
6025
15.8k
    return NULL;
6026
19.4k
}
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
215
{
6196
215
    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
6197
215
}
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
34.7k
{
6206
34.7k
    const char *starts = s;
6207
34.7k
    Py_ssize_t startinpos;
6208
34.7k
    Py_ssize_t endinpos;
6209
34.7k
    _PyUnicodeWriter writer;
6210
34.7k
    const unsigned char *q, *e;
6211
34.7k
    int bo = 0;       /* assume native ordering by default */
6212
34.7k
    int native_ordering;
6213
34.7k
    const char *errmsg = "";
6214
34.7k
    PyObject *errorHandler = NULL;
6215
34.7k
    PyObject *exc = NULL;
6216
34.7k
    const char *encoding;
6217
6218
34.7k
    q = (const unsigned char *)s;
6219
34.7k
    e = q + size;
6220
6221
34.7k
    if (byteorder)
6222
34.5k
        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
34.7k
    if (bo == 0 && size >= 2) {
6229
13.6k
        const Py_UCS4 bom = (q[1] << 8) | q[0];
6230
13.6k
        if (bom == 0xFEFF) {
6231
300
            q += 2;
6232
300
            bo = -1;
6233
300
        }
6234
13.3k
        else if (bom == 0xFFFE) {
6235
2.66k
            q += 2;
6236
2.66k
            bo = 1;
6237
2.66k
        }
6238
13.6k
        if (byteorder)
6239
13.4k
            *byteorder = bo;
6240
13.6k
    }
6241
6242
34.7k
    if (q == e) {
6243
111
        if (consumed)
6244
0
            *consumed = size;
6245
111
        _Py_RETURN_UNICODE_EMPTY();
6246
111
    }
6247
6248
34.6k
#if PY_LITTLE_ENDIAN
6249
34.6k
    native_ordering = bo <= 0;
6250
34.6k
    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
34.6k
    _PyUnicodeWriter_Init(&writer);
6260
34.6k
    writer.min_length = (e - q + 1) / 2;
6261
34.6k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
6262
0
        goto onError;
6263
6264
85.7k
    while (1) {
6265
85.7k
        Py_UCS4 ch = 0;
6266
85.7k
        if (e - q >= 2) {
6267
68.4k
            int kind = writer.kind;
6268
68.4k
            if (kind == PyUnicode_1BYTE_KIND) {
6269
39.1k
                if (PyUnicode_IS_ASCII(writer.buffer))
6270
33.9k
                    ch = asciilib_utf16_decode(&q, e,
6271
33.9k
                            (Py_UCS1*)writer.data, &writer.pos,
6272
33.9k
                            native_ordering);
6273
5.14k
                else
6274
5.14k
                    ch = ucs1lib_utf16_decode(&q, e,
6275
5.14k
                            (Py_UCS1*)writer.data, &writer.pos,
6276
5.14k
                            native_ordering);
6277
39.1k
            } else if (kind == PyUnicode_2BYTE_KIND) {
6278
16.4k
                ch = ucs2lib_utf16_decode(&q, e,
6279
16.4k
                        (Py_UCS2*)writer.data, &writer.pos,
6280
16.4k
                        native_ordering);
6281
16.4k
            } else {
6282
12.9k
                assert(kind == PyUnicode_4BYTE_KIND);
6283
12.9k
                ch = ucs4lib_utf16_decode(&q, e,
6284
12.9k
                        (Py_UCS4*)writer.data, &writer.pos,
6285
12.9k
                        native_ordering);
6286
12.9k
            }
6287
68.4k
        }
6288
6289
85.7k
        switch (ch)
6290
85.7k
        {
6291
35.2k
        case 0:
6292
            /* remaining byte at the end? (size should be even) */
6293
35.2k
            if (q == e || consumed)
6294
28.6k
                goto End;
6295
6.60k
            errmsg = "truncated data";
6296
6.60k
            startinpos = ((const char *)q) - starts;
6297
6.60k
            endinpos = ((const char *)e) - starts;
6298
6.60k
            break;
6299
            /* The remaining input chars are ignored if the callback
6300
               chooses to skip the input */
6301
2.06k
        case 1:
6302
2.06k
            q -= 2;
6303
2.06k
            if (consumed)
6304
0
                goto End;
6305
2.06k
            errmsg = "unexpected end of data";
6306
2.06k
            startinpos = ((const char *)q) - starts;
6307
2.06k
            endinpos = ((const char *)e) - starts;
6308
2.06k
            break;
6309
10.1k
        case 2:
6310
10.1k
            errmsg = "illegal encoding";
6311
10.1k
            startinpos = ((const char *)q) - 2 - starts;
6312
10.1k
            endinpos = startinpos + 2;
6313
10.1k
            break;
6314
7.50k
        case 3:
6315
7.50k
            errmsg = "illegal UTF-16 surrogate";
6316
7.50k
            startinpos = ((const char *)q) - 4 - starts;
6317
7.50k
            endinpos = startinpos + 2;
6318
7.50k
            break;
6319
30.7k
        default:
6320
30.7k
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
6321
0
                goto onError;
6322
30.7k
            continue;
6323
85.7k
        }
6324
6325
26.3k
        if (unicode_decode_call_errorhandler_writer(
6326
26.3k
                errors,
6327
26.3k
                &errorHandler,
6328
26.3k
                encoding, errmsg,
6329
26.3k
                &starts,
6330
26.3k
                (const char **)&e,
6331
26.3k
                &startinpos,
6332
26.3k
                &endinpos,
6333
26.3k
                &exc,
6334
26.3k
                (const char **)&q,
6335
26.3k
                &writer))
6336
5.97k
            goto onError;
6337
26.3k
    }
6338
6339
28.6k
End:
6340
28.6k
    if (consumed)
6341
0
        *consumed = (const char *)q-starts;
6342
6343
28.6k
    Py_XDECREF(errorHandler);
6344
28.6k
    Py_XDECREF(exc);
6345
28.6k
    return _PyUnicodeWriter_Finish(&writer);
6346
6347
5.97k
  onError:
6348
5.97k
    _PyUnicodeWriter_Dealloc(&writer);
6349
5.97k
    Py_XDECREF(errorHandler);
6350
5.97k
    Py_XDECREF(exc);
6351
5.97k
    return NULL;
6352
34.6k
}
6353
6354
PyObject *
6355
_PyUnicode_EncodeUTF16(PyObject *str,
6356
                       const char *errors,
6357
                       int byteorder)
6358
9.14k
{
6359
9.14k
    if (!PyUnicode_Check(str)) {
6360
0
        PyErr_BadArgument();
6361
0
        return NULL;
6362
0
    }
6363
9.14k
    int kind = PyUnicode_KIND(str);
6364
9.14k
    const void *data = PyUnicode_DATA(str);
6365
9.14k
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6366
6367
9.14k
    Py_ssize_t pairs = 0;
6368
9.14k
    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
9.14k
    if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
6378
0
        return PyErr_NoMemory();
6379
0
    }
6380
9.14k
    Py_ssize_t nsize = len + pairs + (byteorder == 0);
6381
6382
#if PY_BIG_ENDIAN
6383
    int native_ordering = byteorder >= 0;
6384
#else
6385
9.14k
    int native_ordering = byteorder <= 0;
6386
9.14k
#endif
6387
6388
9.14k
    if (kind == PyUnicode_1BYTE_KIND) {
6389
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6390
        // on short strings
6391
9.05k
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 2);
6392
9.05k
        if (v == NULL) {
6393
0
            return NULL;
6394
0
        }
6395
6396
        /* output buffer is 2-bytes aligned */
6397
9.05k
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
6398
9.05k
        unsigned short *out = (unsigned short *)PyBytes_AS_STRING(v);
6399
9.05k
        if (byteorder == 0) {
6400
0
            *out++ = 0xFEFF;
6401
0
        }
6402
9.05k
        if (len > 0) {
6403
9.05k
            ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
6404
9.05k
        }
6405
9.05k
        return v;
6406
9.05k
    }
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
54.4k
{
6529
54.4k
    PyInterpreterState *interp = _PyInterpreterState_GET();
6530
54.4k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6531
6532
54.4k
    ucnhash_capi = _Py_atomic_load_ptr(&interp->unicode.ucnhash_capi);
6533
54.4k
    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
54.4k
    return ucnhash_capi;
6541
54.4k
}
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.6k
{
6553
31.6k
    const char *starts = s;
6554
31.6k
    const char *initial_starts = starts;
6555
31.6k
    _PyUnicodeWriter writer;
6556
31.6k
    const char *end;
6557
31.6k
    PyObject *errorHandler = NULL;
6558
31.6k
    PyObject *exc = NULL;
6559
31.6k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6560
6561
    // so we can remember if we've seen an invalid escape char or not
6562
31.6k
    *first_invalid_escape_char = -1;
6563
31.6k
    *first_invalid_escape_ptr = NULL;
6564
6565
31.6k
    if (size == 0) {
6566
3.27k
        if (consumed) {
6567
0
            *consumed = 0;
6568
0
        }
6569
3.27k
        _Py_RETURN_UNICODE_EMPTY();
6570
3.27k
    }
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.3k
    _PyUnicodeWriter_Init(&writer);
6577
28.3k
    writer.min_length = size;
6578
28.3k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6579
0
        goto onError;
6580
0
    }
6581
6582
28.3k
    end = s + size;
6583
11.3M
    while (s < end) {
6584
11.2M
        unsigned char c = (unsigned char) *s++;
6585
11.2M
        Py_UCS4 ch;
6586
11.2M
        int count;
6587
11.2M
        const char *message;
6588
6589
11.2M
#define WRITE_ASCII_CHAR(ch)                                                  \
6590
11.2M
            do {                                                              \
6591
136k
                assert(ch <= 127);                                            \
6592
136k
                assert(writer.pos < writer.size);                             \
6593
136k
                PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch);  \
6594
136k
            } while(0)
6595
6596
11.2M
#define WRITE_CHAR(ch)                                                        \
6597
11.2M
            do {                                                              \
6598
11.1M
                if (ch <= writer.maxchar) {                                   \
6599
11.1M
                    assert(writer.pos < writer.size);                         \
6600
11.1M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6601
11.1M
                }                                                             \
6602
11.1M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6603
0
                    goto onError;                                             \
6604
0
                }                                                             \
6605
11.1M
            } while(0)
6606
6607
        /* Non-escape characters are interpreted as Unicode ordinals */
6608
11.2M
        if (c != '\\') {
6609
11.0M
            WRITE_CHAR(c);
6610
11.0M
            continue;
6611
11.0M
        }
6612
6613
269k
        Py_ssize_t startinpos = s - starts - 1;
6614
        /* \ - Escapes */
6615
269k
        if (s >= end) {
6616
23
            message = "\\ at end of string";
6617
23
            goto incomplete;
6618
23
        }
6619
269k
        c = (unsigned char) *s++;
6620
6621
269k
        assert(writer.pos < writer.size);
6622
269k
        switch (c) {
6623
6624
            /* \x escapes */
6625
1.75k
        case '\n': continue;
6626
17.2k
        case '\\': WRITE_ASCII_CHAR('\\'); continue;
6627
2.53k
        case '\'': WRITE_ASCII_CHAR('\''); continue;
6628
1.81k
        case '\"': WRITE_ASCII_CHAR('\"'); continue;
6629
1.41k
        case 'b': WRITE_ASCII_CHAR('\b'); continue;
6630
        /* FF */
6631
1.48k
        case 'f': WRITE_ASCII_CHAR('\014'); continue;
6632
1.36k
        case 't': WRITE_ASCII_CHAR('\t'); continue;
6633
1.51k
        case 'n': WRITE_ASCII_CHAR('\n'); continue;
6634
22.4k
        case 'r': WRITE_ASCII_CHAR('\r'); continue;
6635
        /* VT */
6636
58.2k
        case 'v': WRITE_ASCII_CHAR('\013'); continue;
6637
        /* BEL, not classic C */
6638
2.19k
        case 'a': WRITE_ASCII_CHAR('\007'); continue;
6639
6640
            /* \OOO (octal) escapes */
6641
37.7k
        case '0': case '1': case '2': case '3':
6642
47.1k
        case '4': case '5': case '6': case '7':
6643
47.1k
            ch = c - '0';
6644
47.1k
            if (s < end && '0' <= *s && *s <= '7') {
6645
4.72k
                ch = (ch<<3) + *s++ - '0';
6646
4.72k
                if (s < end && '0' <= *s && *s <= '7') {
6647
2.39k
                    ch = (ch<<3) + *s++ - '0';
6648
2.39k
                }
6649
4.72k
            }
6650
47.1k
            if (ch > 0377) {
6651
1.96k
                if (*first_invalid_escape_char == -1) {
6652
999
                    *first_invalid_escape_char = ch;
6653
999
                    if (starts == initial_starts) {
6654
                        /* Back up 3 chars, since we've already incremented s. */
6655
999
                        *first_invalid_escape_ptr = s - 3;
6656
999
                    }
6657
999
                }
6658
1.96k
            }
6659
47.1k
            WRITE_CHAR(ch);
6660
47.1k
            continue;
6661
6662
            /* hex escapes */
6663
            /* \xXX */
6664
47.1k
        case 'x':
6665
6.46k
            count = 2;
6666
6.46k
            message = "truncated \\xXX escape";
6667
6.46k
            goto hexescape;
6668
6669
            /* \uXXXX */
6670
6.65k
        case 'u':
6671
6.65k
            count = 4;
6672
6.65k
            message = "truncated \\uXXXX escape";
6673
6.65k
            goto hexescape;
6674
6675
            /* \UXXXXXXXX */
6676
16.1k
        case 'U':
6677
16.1k
            count = 8;
6678
16.1k
            message = "truncated \\UXXXXXXXX escape";
6679
29.2k
        hexescape:
6680
197k
            for (ch = 0; count; ++s, --count) {
6681
168k
                if (s >= end) {
6682
32
                    goto incomplete;
6683
32
                }
6684
168k
                c = (unsigned char)*s;
6685
168k
                ch <<= 4;
6686
168k
                if (c >= '0' && c <= '9') {
6687
126k
                    ch += c - '0';
6688
126k
                }
6689
42.0k
                else if (c >= 'a' && c <= 'f') {
6690
40.9k
                    ch += c - ('a' - 10);
6691
40.9k
                }
6692
1.02k
                else if (c >= 'A' && c <= 'F') {
6693
1.01k
                    ch += c - ('A' - 10);
6694
1.01k
                }
6695
11
                else {
6696
11
                    goto error;
6697
11
                }
6698
168k
            }
6699
6700
            /* when we get here, ch is a 32-bit unicode character */
6701
29.1k
            if (ch > MAX_UNICODE) {
6702
3
                message = "illegal Unicode character";
6703
3
                goto error;
6704
3
            }
6705
6706
29.1k
            WRITE_CHAR(ch);
6707
29.1k
            continue;
6708
6709
            /* \N{name} */
6710
54.4k
        case 'N':
6711
54.4k
            ucnhash_capi = _PyUnicode_GetNameCAPI();
6712
54.4k
            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
54.4k
            message = "malformed \\N character escape";
6721
54.4k
            if (s >= end) {
6722
10
                goto incomplete;
6723
10
            }
6724
54.4k
            if (*s == '{') {
6725
54.4k
                const char *start = ++s;
6726
54.4k
                size_t namelen;
6727
                /* look for the closing brace */
6728
1.30M
                while (s < end && *s != '}')
6729
1.24M
                    s++;
6730
54.4k
                if (s >= end) {
6731
24
                    goto incomplete;
6732
24
                }
6733
54.4k
                namelen = s - start;
6734
54.4k
                if (namelen) {
6735
                    /* found a name.  look it up in the unicode database */
6736
54.4k
                    s++;
6737
54.4k
                    ch = 0xffffffff; /* in case 'getcode' messes up */
6738
54.4k
                    if (namelen <= INT_MAX &&
6739
54.4k
                        ucnhash_capi->getcode(start, (int)namelen,
6740
54.4k
                                              &ch, 0)) {
6741
54.2k
                        assert(ch <= MAX_UNICODE);
6742
54.2k
                        WRITE_CHAR(ch);
6743
54.2k
                        continue;
6744
54.2k
                    }
6745
144
                    message = "unknown Unicode character name";
6746
144
                }
6747
54.4k
            }
6748
159
            goto error;
6749
6750
26.1k
        default:
6751
26.1k
            if (*first_invalid_escape_char == -1) {
6752
5.66k
                *first_invalid_escape_char = c;
6753
5.66k
                if (starts == initial_starts) {
6754
                    /* Back up one char, since we've already incremented s. */
6755
5.66k
                    *first_invalid_escape_ptr = s - 1;
6756
5.66k
                }
6757
5.66k
            }
6758
26.1k
            WRITE_ASCII_CHAR('\\');
6759
26.1k
            WRITE_CHAR(c);
6760
26.1k
            continue;
6761
269k
        }
6762
6763
89
      incomplete:
6764
89
        if (consumed) {
6765
0
            *consumed = startinpos;
6766
0
            break;
6767
0
        }
6768
262
      error:;
6769
262
        Py_ssize_t endinpos = s-starts;
6770
262
        writer.min_length = end - s + writer.pos;
6771
262
        if (unicode_decode_call_errorhandler_writer(
6772
262
                errors, &errorHandler,
6773
262
                "unicodeescape", message,
6774
262
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6775
262
                &writer)) {
6776
262
            goto onError;
6777
262
        }
6778
262
        assert(end - s <= writer.size - writer.pos);
6779
6780
0
#undef WRITE_ASCII_CHAR
6781
0
#undef WRITE_CHAR
6782
0
    }
6783
6784
28.1k
    Py_XDECREF(errorHandler);
6785
28.1k
    Py_XDECREF(exc);
6786
28.1k
    return _PyUnicodeWriter_Finish(&writer);
6787
6788
262
  onError:
6789
262
    _PyUnicodeWriter_Dealloc(&writer);
6790
262
    Py_XDECREF(errorHandler);
6791
262
    Py_XDECREF(exc);
6792
262
    return NULL;
6793
28.3k
}
6794
6795
PyObject *
6796
_PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
6797
                              Py_ssize_t size,
6798
                              const char *errors,
6799
                              Py_ssize_t *consumed)
6800
617
{
6801
617
    int first_invalid_escape_char;
6802
617
    const char *first_invalid_escape_ptr;
6803
617
    PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal2(s, size, errors,
6804
617
                                                      consumed,
6805
617
                                                      &first_invalid_escape_char,
6806
617
                                                      &first_invalid_escape_ptr);
6807
617
    if (result == NULL)
6808
137
        return NULL;
6809
480
    if (first_invalid_escape_char != -1) {
6810
234
        if (first_invalid_escape_char > 0xff) {
6811
110
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6812
110
                                 "\"\\%o\" is an invalid octal escape sequence. "
6813
110
                                 "Such sequences will not work in the future. ",
6814
110
                                 first_invalid_escape_char) < 0)
6815
0
            {
6816
0
                Py_DECREF(result);
6817
0
                return NULL;
6818
0
            }
6819
110
        }
6820
124
        else {
6821
124
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6822
124
                                 "\"\\%c\" is an invalid escape sequence. "
6823
124
                                 "Such sequences will not work in the future. ",
6824
124
                                 first_invalid_escape_char) < 0)
6825
0
            {
6826
0
                Py_DECREF(result);
6827
0
                return NULL;
6828
0
            }
6829
124
        }
6830
234
    }
6831
480
    return result;
6832
480
}
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
408k
{
6847
408k
    if (!PyUnicode_Check(unicode)) {
6848
0
        PyErr_BadArgument();
6849
0
        return NULL;
6850
0
    }
6851
6852
408k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
6853
408k
    if (len == 0) {
6854
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
6855
0
    }
6856
408k
    int kind = PyUnicode_KIND(unicode);
6857
408k
    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
408k
    Py_ssize_t expandsize = kind * 2 + 2;
6866
408k
    if (len > PY_SSIZE_T_MAX / expandsize) {
6867
0
        return PyErr_NoMemory();
6868
0
    }
6869
6870
408k
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
6871
408k
    if (writer == NULL) {
6872
0
        return NULL;
6873
0
    }
6874
408k
    char *p = PyBytesWriter_GetData(writer);
6875
6876
816k
    for (Py_ssize_t i = 0; i < len; i++) {
6877
408k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6878
6879
        /* U+0000-U+00ff range */
6880
408k
        if (ch < 0x100) {
6881
398k
            if (ch >= ' ' && ch < 127) {
6882
13.1k
                if (ch != '\\') {
6883
                    /* Copy printable US ASCII as-is */
6884
0
                    *p++ = (char) ch;
6885
0
                }
6886
                /* Escape backslashes */
6887
13.1k
                else {
6888
13.1k
                    *p++ = '\\';
6889
13.1k
                    *p++ = '\\';
6890
13.1k
                }
6891
13.1k
            }
6892
6893
            /* Map special whitespace to '\t', \n', '\r' */
6894
385k
            else if (ch == '\t') {
6895
1.16k
                *p++ = '\\';
6896
1.16k
                *p++ = 't';
6897
1.16k
            }
6898
384k
            else if (ch == '\n') {
6899
1.18k
                *p++ = '\\';
6900
1.18k
                *p++ = 'n';
6901
1.18k
            }
6902
383k
            else if (ch == '\r') {
6903
480
                *p++ = '\\';
6904
480
                *p++ = 'r';
6905
480
            }
6906
6907
            /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6908
382k
            else {
6909
382k
                *p++ = '\\';
6910
382k
                *p++ = 'x';
6911
382k
                *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6912
382k
                *p++ = Py_hexdigits[ch & 0x000F];
6913
382k
            }
6914
398k
        }
6915
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
6916
9.44k
        else if (ch < 0x10000) {
6917
7.58k
            *p++ = '\\';
6918
7.58k
            *p++ = 'u';
6919
7.58k
            *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6920
7.58k
            *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6921
7.58k
            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6922
7.58k
            *p++ = Py_hexdigits[ch & 0x000F];
6923
7.58k
        }
6924
        /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6925
1.86k
        else {
6926
6927
            /* Make sure that the first two digits are zero */
6928
1.86k
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6929
1.86k
            *p++ = '\\';
6930
1.86k
            *p++ = 'U';
6931
1.86k
            *p++ = '0';
6932
1.86k
            *p++ = '0';
6933
1.86k
            *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6934
1.86k
            *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6935
1.86k
            *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6936
1.86k
            *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6937
1.86k
            *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6938
1.86k
            *p++ = Py_hexdigits[ch & 0x0000000F];
6939
1.86k
        }
6940
408k
    }
6941
6942
408k
    return PyBytesWriter_FinishWithPointer(writer, p);
6943
408k
}
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
120
{
6953
120
    const char *starts = s;
6954
120
    _PyUnicodeWriter writer;
6955
120
    const char *end;
6956
120
    PyObject *errorHandler = NULL;
6957
120
    PyObject *exc = NULL;
6958
6959
120
    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
120
    _PyUnicodeWriter_Init(&writer);
6971
120
    writer.min_length = size;
6972
120
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6973
0
        goto onError;
6974
0
    }
6975
6976
120
    end = s + size;
6977
411k
    while (s < end) {
6978
411k
        unsigned char c = (unsigned char) *s++;
6979
411k
        Py_UCS4 ch;
6980
411k
        int count;
6981
411k
        const char *message;
6982
6983
411k
#define WRITE_CHAR(ch)                                                        \
6984
411k
            do {                                                              \
6985
411k
                if (ch <= writer.maxchar) {                                   \
6986
411k
                    assert(writer.pos < writer.size);                         \
6987
411k
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6988
411k
                }                                                             \
6989
411k
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6990
0
                    goto onError;                                             \
6991
0
                }                                                             \
6992
411k
            } while(0)
6993
6994
        /* Non-escape characters are interpreted as Unicode ordinals */
6995
411k
        if (c != '\\' || (s >= end && !consumed)) {
6996
409k
            WRITE_CHAR(c);
6997
409k
            continue;
6998
409k
        }
6999
7000
1.58k
        Py_ssize_t startinpos = s - starts - 1;
7001
        /* \ - Escapes */
7002
1.58k
        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.58k
        c = (unsigned char) *s++;
7011
1.58k
        if (c == 'u') {
7012
536
            count = 4;
7013
536
            message = "truncated \\uXXXX escape";
7014
536
        }
7015
1.04k
        else if (c == 'U') {
7016
428
            count = 8;
7017
428
            message = "truncated \\UXXXXXXXX escape";
7018
428
        }
7019
621
        else {
7020
621
            assert(writer.pos < writer.size);
7021
621
            PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
7022
621
            WRITE_CHAR(c);
7023
621
            continue;
7024
621
        }
7025
7026
        /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
7027
6.40k
        for (ch = 0; count; ++s, --count) {
7028
5.46k
            if (s >= end) {
7029
19
                goto incomplete;
7030
19
            }
7031
5.44k
            c = (unsigned char)*s;
7032
5.44k
            ch <<= 4;
7033
5.44k
            if (c >= '0' && c <= '9') {
7034
3.50k
                ch += c - '0';
7035
3.50k
            }
7036
1.94k
            else if (c >= 'a' && c <= 'f') {
7037
523
                ch += c - ('a' - 10);
7038
523
            }
7039
1.42k
            else if (c >= 'A' && c <= 'F') {
7040
1.41k
                ch += c - ('A' - 10);
7041
1.41k
            }
7042
10
            else {
7043
10
                goto error;
7044
10
            }
7045
5.44k
        }
7046
935
        if (ch > MAX_UNICODE) {
7047
2
            message = "\\Uxxxxxxxx out of range";
7048
2
            goto error;
7049
2
        }
7050
933
        WRITE_CHAR(ch);
7051
933
        continue;
7052
7053
933
      incomplete:
7054
19
        if (consumed) {
7055
0
            *consumed = startinpos;
7056
0
            break;
7057
0
        }
7058
31
      error:;
7059
31
        Py_ssize_t endinpos = s-starts;
7060
31
        writer.min_length = end - s + writer.pos;
7061
31
        if (unicode_decode_call_errorhandler_writer(
7062
31
                errors, &errorHandler,
7063
31
                "rawunicodeescape", message,
7064
31
                &starts, &end, &startinpos, &endinpos, &exc, &s,
7065
31
                &writer)) {
7066
31
            goto onError;
7067
31
        }
7068
31
        assert(end - s <= writer.size - writer.pos);
7069
7070
0
#undef WRITE_CHAR
7071
0
    }
7072
89
    Py_XDECREF(errorHandler);
7073
89
    Py_XDECREF(exc);
7074
89
    return _PyUnicodeWriter_Finish(&writer);
7075
7076
31
  onError:
7077
31
    _PyUnicodeWriter_Dealloc(&writer);
7078
31
    Py_XDECREF(errorHandler);
7079
31
    Py_XDECREF(exc);
7080
31
    return NULL;
7081
120
}
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
274k
{
7095
274k
    if (!PyUnicode_Check(unicode)) {
7096
0
        PyErr_BadArgument();
7097
0
        return NULL;
7098
0
    }
7099
274k
    int kind = PyUnicode_KIND(unicode);
7100
274k
    const void *data = PyUnicode_DATA(unicode);
7101
274k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
7102
274k
    if (len == 0) {
7103
495
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7104
495
    }
7105
274k
    if (kind == PyUnicode_1BYTE_KIND) {
7106
274k
        return PyBytes_FromStringAndSize(data, len);
7107
274k
    }
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
287
    Py_ssize_t expandsize = kind * 2 + 2;
7112
287
    if (len > PY_SSIZE_T_MAX / expandsize) {
7113
0
        return PyErr_NoMemory();
7114
0
    }
7115
7116
287
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
7117
287
    if (writer == NULL) {
7118
0
        return NULL;
7119
0
    }
7120
287
    char *p = PyBytesWriter_GetData(writer);
7121
7122
4.63M
    for (Py_ssize_t pos = 0; pos < len; pos++) {
7123
4.63M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7124
7125
        /* U+0000-U+00ff range: Copy 8-bit characters as-is */
7126
4.63M
        if (ch < 0x100) {
7127
4.59M
            *p++ = (char) ch;
7128
4.59M
        }
7129
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
7130
47.5k
        else if (ch < 0x10000) {
7131
46.8k
            *p++ = '\\';
7132
46.8k
            *p++ = 'u';
7133
46.8k
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7134
46.8k
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7135
46.8k
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7136
46.8k
            *p++ = Py_hexdigits[ch & 15];
7137
46.8k
        }
7138
        /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
7139
680
        else {
7140
680
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
7141
680
            *p++ = '\\';
7142
680
            *p++ = 'U';
7143
680
            *p++ = '0';
7144
680
            *p++ = '0';
7145
680
            *p++ = Py_hexdigits[(ch >> 20) & 0xf];
7146
680
            *p++ = Py_hexdigits[(ch >> 16) & 0xf];
7147
680
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7148
680
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7149
680
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7150
680
            *p++ = Py_hexdigits[ch & 15];
7151
680
        }
7152
4.63M
    }
7153
7154
287
    return PyBytesWriter_FinishWithPointer(writer, p);
7155
287
}
7156
7157
/* --- Latin-1 Codec ------------------------------------------------------ */
7158
7159
PyObject *
7160
PyUnicode_DecodeLatin1(const char *s,
7161
                       Py_ssize_t size,
7162
                       const char *errors)
7163
3.46M
{
7164
    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
7165
3.46M
    return _PyUnicode_FromUCS1((const unsigned char*)s, size);
7166
3.46M
}
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.93M
{
7176
2.93M
    if (*exceptionObject == NULL) {
7177
2.93M
        *exceptionObject = PyObject_CallFunction(
7178
2.93M
            PyExc_UnicodeEncodeError, "sOnns",
7179
2.93M
            encoding, unicode, startpos, endpos, reason);
7180
2.93M
    }
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.93M
}
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.78M
{
7202
2.78M
    make_encode_exception(exceptionObject,
7203
2.78M
                          encoding, unicode, startpos, endpos, reason);
7204
2.78M
    if (*exceptionObject != NULL)
7205
2.78M
        PyCodec_StrictErrors(*exceptionObject);
7206
2.78M
}
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
150k
{
7220
150k
    static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
7221
150k
    Py_ssize_t len;
7222
150k
    PyObject *restuple;
7223
150k
    PyObject *resunicode;
7224
7225
150k
    if (*errorHandler == NULL) {
7226
150k
        *errorHandler = PyCodec_LookupError(errors);
7227
150k
        if (*errorHandler == NULL)
7228
0
            return NULL;
7229
150k
    }
7230
7231
150k
    len = PyUnicode_GET_LENGTH(unicode);
7232
7233
150k
    make_encode_exception(exceptionObject,
7234
150k
                          encoding, unicode, startpos, endpos, reason);
7235
150k
    if (*exceptionObject == NULL)
7236
0
        return NULL;
7237
7238
150k
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
7239
150k
    if (restuple == NULL)
7240
150k
        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.80M
{
7273
    /* input state */
7274
2.80M
    Py_ssize_t pos=0, size;
7275
2.80M
    int kind;
7276
2.80M
    const void *data;
7277
2.80M
    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
7278
2.80M
    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
7279
2.80M
    PyObject *error_handler_obj = NULL;
7280
2.80M
    PyObject *exc = NULL;
7281
2.80M
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7282
2.80M
    PyObject *rep = NULL;
7283
7284
2.80M
    size = PyUnicode_GET_LENGTH(unicode);
7285
2.80M
    kind = PyUnicode_KIND(unicode);
7286
2.80M
    data = PyUnicode_DATA(unicode);
7287
    /* allocate enough for a simple encoding without
7288
       replacements, if we need more, we'll resize */
7289
2.80M
    if (size == 0)
7290
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7291
7292
    /* output object */
7293
2.80M
    PyBytesWriter *writer = PyBytesWriter_Create(size);
7294
2.80M
    if (writer == NULL) {
7295
0
        return NULL;
7296
0
    }
7297
    /* pointer into the output */
7298
2.80M
    char *str = PyBytesWriter_GetData(writer);
7299
7300
10.8M
    while (pos < size) {
7301
10.8M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7302
7303
        /* can we encode this? */
7304
10.8M
        if (ch < limit) {
7305
            /* no overflow check, because we know that the space is enough */
7306
8.09M
            *str++ = (char)ch;
7307
8.09M
            ++pos;
7308
8.09M
        }
7309
2.80M
        else {
7310
2.80M
            Py_ssize_t newpos, i;
7311
            /* startpos for collecting unencodable chars */
7312
2.80M
            Py_ssize_t collstart = pos;
7313
2.80M
            Py_ssize_t collend = collstart + 1;
7314
            /* find all unecodable characters */
7315
7316
7.61M
            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
7317
4.81M
                ++collend;
7318
7319
            /* Only overallocate the buffer if it's not the last write */
7320
2.80M
            writer->overallocate = (collend < size);
7321
7322
            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
7323
2.80M
            if (error_handler == _Py_ERROR_UNKNOWN)
7324
2.80M
                error_handler = _Py_GetErrorHandler(errors);
7325
7326
2.80M
            switch (error_handler) {
7327
2.78M
            case _Py_ERROR_STRICT:
7328
2.78M
                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
7329
2.78M
                goto onError;
7330
7331
3.67k
            case _Py_ERROR_REPLACE:
7332
3.67k
                memset(str, '?', collend - collstart);
7333
3.67k
                str += (collend - collstart);
7334
3.67k
                _Py_FALLTHROUGH;
7335
3.67k
            case _Py_ERROR_IGNORE:
7336
3.67k
                pos = collend;
7337
3.67k
                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
11.7k
            case _Py_ERROR_SURROGATEESCAPE:
7356
11.7k
                for (i = collstart; i < collend; ++i) {
7357
11.7k
                    ch = PyUnicode_READ(kind, data, i);
7358
11.7k
                    if (ch < 0xdc80 || 0xdcff < ch) {
7359
                        /* Not a UTF-8b surrogate */
7360
11.7k
                        break;
7361
11.7k
                    }
7362
0
                    *str++ = (char)(ch - 0xdc00);
7363
0
                    ++pos;
7364
0
                }
7365
11.7k
                if (i >= collend)
7366
0
                    break;
7367
11.7k
                collstart = pos;
7368
11.7k
                assert(collstart != collend);
7369
11.7k
                _Py_FALLTHROUGH;
7370
7371
11.7k
            default:
7372
11.7k
                rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
7373
11.7k
                                                       encoding, reason, unicode, &exc,
7374
11.7k
                                                       collstart, collend, &newpos);
7375
11.7k
                if (rep == NULL)
7376
11.7k
                    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.80M
            }
7431
7432
            /* If overallocation was disabled, ensure that it was the last
7433
               write. Otherwise, we missed an optimization */
7434
2.80M
            assert(writer->overallocate || pos == size);
7435
3.67k
        }
7436
10.8M
    }
7437
7438
3.56k
    Py_XDECREF(error_handler_obj);
7439
3.56k
    Py_XDECREF(exc);
7440
3.56k
    return PyBytesWriter_FinishWithPointer(writer, str);
7441
7442
2.79M
  onError:
7443
2.79M
    Py_XDECREF(rep);
7444
2.79M
    PyBytesWriter_Discard(writer);
7445
2.79M
    Py_XDECREF(error_handler_obj);
7446
2.79M
    Py_XDECREF(exc);
7447
2.79M
    return NULL;
7448
2.80M
}
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.0M
{
7480
14.0M
    const char *starts = s;
7481
14.0M
    const char *e = s + size;
7482
14.0M
    PyObject *error_handler_obj = NULL;
7483
14.0M
    PyObject *exc = NULL;
7484
14.0M
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7485
7486
14.0M
    if (size == 0)
7487
0
        _Py_RETURN_UNICODE_EMPTY();
7488
7489
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
7490
14.0M
    if (size == 1 && (unsigned char)s[0] < 128) {
7491
644k
        return get_latin1_char((unsigned char)s[0]);
7492
644k
    }
7493
7494
    // Shortcut for simple case
7495
13.4M
    PyObject *u = PyUnicode_New(size, 127);
7496
13.4M
    if (u == NULL) {
7497
0
        return NULL;
7498
0
    }
7499
13.4M
    Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
7500
13.4M
    if (outpos == size) {
7501
10.7M
        return u;
7502
10.7M
    }
7503
7504
2.72M
    _PyUnicodeWriter writer;
7505
2.72M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
7506
2.72M
    writer.pos = outpos;
7507
7508
2.72M
    s += outpos;
7509
2.72M
    int kind = writer.kind;
7510
2.72M
    void *data = writer.data;
7511
2.72M
    Py_ssize_t startinpos, endinpos;
7512
7513
26.9M
    while (s < e) {
7514
26.8M
        unsigned char c = (unsigned char)*s;
7515
26.8M
        if (c < 128) {
7516
12.2M
            PyUnicode_WRITE(kind, data, writer.pos, c);
7517
12.2M
            writer.pos++;
7518
12.2M
            ++s;
7519
12.2M
            continue;
7520
12.2M
        }
7521
7522
        /* byte outsize range 0x00..0x7f: call the error handler */
7523
7524
14.5M
        if (error_handler == _Py_ERROR_UNKNOWN)
7525
2.72M
            error_handler = _Py_GetErrorHandler(errors);
7526
7527
14.5M
        switch (error_handler)
7528
14.5M
        {
7529
784k
        case _Py_ERROR_REPLACE:
7530
12.0M
        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
12.0M
            if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7534
0
                goto onError;
7535
12.0M
            assert(_PyUnicodeWriter_CanWrite(&writer));
7536
12.0M
            kind = writer.kind;
7537
12.0M
            data = writer.data;
7538
7539
12.0M
            if (error_handler == _Py_ERROR_REPLACE)
7540
784k
                PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7541
11.2M
            else
7542
11.2M
                PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7543
12.0M
            writer.pos++;
7544
12.0M
            ++s;
7545
12.0M
            break;
7546
7547
0
        case _Py_ERROR_IGNORE:
7548
0
            ++s;
7549
0
            break;
7550
7551
2.57M
        default:
7552
2.57M
            startinpos = s-starts;
7553
2.57M
            endinpos = startinpos + 1;
7554
2.57M
            if (unicode_decode_call_errorhandler_writer(
7555
2.57M
                    errors, &error_handler_obj,
7556
2.57M
                    "ascii", "ordinal not in range(128)",
7557
2.57M
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
7558
2.57M
                    &writer))
7559
2.57M
                goto onError;
7560
0
            kind = writer.kind;
7561
0
            data = writer.data;
7562
14.5M
        }
7563
14.5M
    }
7564
150k
    Py_XDECREF(error_handler_obj);
7565
150k
    Py_XDECREF(exc);
7566
150k
    return _PyUnicodeWriter_Finish(&writer);
7567
7568
2.57M
  onError:
7569
2.57M
    _PyUnicodeWriter_Dealloc(&writer);
7570
2.57M
    Py_XDECREF(error_handler_obj);
7571
2.57M
    Py_XDECREF(exc);
7572
2.57M
    return NULL;
7573
2.72M
}
7574
7575
PyObject *
7576
_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
7577
3.05M
{
7578
3.05M
    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
3.05M
    if (PyUnicode_IS_ASCII(unicode))
7585
255k
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7586
255k
                                         PyUnicode_GET_LENGTH(unicode));
7587
2.80M
    return unicode_encode_ucs1(unicode, errors, 128);
7588
3.05M
}
7589
7590
PyObject *
7591
PyUnicode_AsASCIIString(PyObject *unicode)
7592
98.8k
{
7593
98.8k
    return _PyUnicode_AsASCIIString(unicode, NULL);
7594
98.8k
}
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
11.9k
#  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
80.7k
{
8311
80.7k
    iconv_t cd = iconv_open(tocode, fromcode);
8312
80.7k
    if (cd == (iconv_t)-1) {
8313
68.5k
        if (errno == EINVAL) {
8314
68.5k
            PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding);
8315
68.5k
        }
8316
0
        else {
8317
0
            PyErr_SetFromErrno(PyExc_OSError);
8318
0
        }
8319
68.5k
    }
8320
80.7k
    return cd;
8321
80.7k
}
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
11.9k
{
8335
11.9k
    if (size < 0) {
8336
0
        PyErr_BadInternalCall();
8337
0
        return NULL;
8338
0
    }
8339
8340
11.9k
    iconv_t cd = iconv_open_or_set_error(ICONV_PIVOT, encoding, encoding);
8341
11.9k
    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
11.9k
    Py_UCS4 chunk[1024];
8347
11.9k
    const char *starts = s;
8348
11.9k
    const char *in = s;
8349
11.9k
    const char *inend = s + size;
8350
11.9k
    _PyUnicodeWriter writer;
8351
11.9k
    PyObject *errorHandler = NULL;
8352
11.9k
    PyObject *exc = NULL;
8353
8354
11.9k
    _PyUnicodeWriter_Init(&writer);
8355
11.9k
    writer.min_length = size;
8356
8357
223k
    while (in < inend) {
8358
220k
        char *inptr = (char *)in;
8359
220k
        size_t inleft = (size_t)(inend - in);
8360
220k
        char *outptr = (char *)chunk;
8361
220k
        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
220k
        size_t ret = iconv(cd, (void *)&inptr, &inleft, &outptr, &outleft);
8367
220k
        int err = errno;
8368
220k
        in = inptr;
8369
8370
        /* Append whatever code points this call produced. */
8371
220k
        Py_ssize_t nch = (Py_UCS4 *)outptr - chunk;
8372
220k
        if (nch > 0 && PyUnicodeWriter_WriteUCS4((PyUnicodeWriter *)&writer,
8373
28.4k
                                                 chunk, nch) < 0) {
8374
0
            goto error;
8375
0
        }
8376
8377
220k
        if (ret != (size_t)-1) {
8378
5.53k
            assert(in == inend);
8379
5.53k
            break;
8380
5.53k
        }
8381
8382
214k
        if (err == E2BIG) {
8383
            /* The scratch buffer filled up; drain it and continue. */
8384
580
            continue;
8385
580
        }
8386
8387
213k
        const char *reason;
8388
213k
        if (err == EINVAL) {
8389
            /* Incomplete multibyte sequence at the end of the input. */
8390
20
            if (consumed != NULL) {
8391
                /* Stateful decoding: stop and report the consumed bytes. */
8392
0
                break;
8393
0
            }
8394
20
            reason = "incomplete multibyte sequence";
8395
20
        }
8396
213k
        else if (err == EILSEQ) {
8397
213k
            reason = "invalid multibyte sequence";
8398
213k
        }
8399
0
        else {
8400
0
            errno = err;
8401
0
            PyErr_SetFromErrno(PyExc_OSError);
8402
0
            goto error;
8403
0
        }
8404
8405
213k
        Py_ssize_t startinpos = in - starts;
8406
213k
        Py_ssize_t endinpos = startinpos + 1;
8407
213k
        if (unicode_decode_call_errorhandler_writer(
8408
213k
                errors, &errorHandler, encoding, reason,
8409
213k
                &starts, &inend, &startinpos, &endinpos, &exc, &in,
8410
213k
                &writer)) {
8411
3.40k
            goto error;
8412
3.40k
        }
8413
        /* The error handler may have skipped bytes; reset the conversion
8414
           descriptor to the initial shift state before continuing. */
8415
210k
        iconv(cd, NULL, NULL, NULL, NULL);
8416
210k
    }
8417
8418
8.56k
    if (consumed != NULL) {
8419
0
        *consumed = in - starts;
8420
0
    }
8421
8.56k
    iconv_close(cd);
8422
8.56k
    Py_XDECREF(errorHandler);
8423
8.56k
    Py_XDECREF(exc);
8424
8.56k
    return _PyUnicodeWriter_Finish(&writer);
8425
8426
3.40k
error:
8427
3.40k
    iconv_close(cd);
8428
3.40k
    _PyUnicodeWriter_Dealloc(&writer);
8429
3.40k
    Py_XDECREF(errorHandler);
8430
3.40k
    Py_XDECREF(exc);
8431
3.40k
    return NULL;
8432
11.9k
}
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
68.7k
{
8465
68.7k
    if (!PyUnicode_Check(unicode)) {
8466
0
        PyErr_BadArgument();
8467
0
        return NULL;
8468
0
    }
8469
8470
68.7k
    Py_ssize_t ulen = PyUnicode_GET_LENGTH(unicode);
8471
68.7k
    const char *source;         /* iconv source encoding for this kind */
8472
68.7k
    const char *data;           /* the units to encode */
8473
68.7k
    Py_ssize_t unit;            /* bytes per code point in *data */
8474
68.7k
    Py_UCS4 *widened = NULL;    /* owned UTF-32 copy of a 2-byte string */
8475
68.7k
    int kind = PyUnicode_KIND(unicode);
8476
68.7k
    if (kind == PyUnicode_1BYTE_KIND) {
8477
68.7k
        source = "ISO-8859-1";
8478
68.7k
        data = (const char *)PyUnicode_1BYTE_DATA(unicode);
8479
68.7k
        unit = 1;
8480
68.7k
    }
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
68.7k
    iconv_t cd = iconv_open_or_set_error(encoding, source, encoding);
8505
68.7k
    if (cd == (iconv_t)-1) {
8506
68.5k
        PyMem_Free(widened);
8507
68.5k
        return NULL;
8508
68.5k
    }
8509
8510
260
    PyBytesWriter *writer = NULL;
8511
260
    PyObject *errorHandler = NULL;
8512
260
    PyObject *exc = NULL;
8513
260
    PyObject *result = NULL;
8514
260
    const char *ustart = data;
8515
260
    const char *up = data;
8516
260
    const char *uend = data + (size_t)ulen * unit;
8517
260
    int flushing = 0;
8518
260
    int careful = 0;            /* feed one code point per iconv() call */
8519
8520
    /* A generous initial estimate for the output size. */
8521
260
    writer = PyBytesWriter_Create(ulen + (ulen >> 1) + 16);
8522
260
    if (writer == NULL) {
8523
0
        goto done;
8524
0
    }
8525
260
    char *out = PyBytesWriter_GetData(writer);
8526
260
    char *outend = out + PyBytesWriter_GetSize(writer);
8527
8528
520
    for (;;) {
8529
520
        char *inptr = (char *)up;
8530
520
        size_t inleft = (size_t)(uend - up);
8531
        /* One code point at a time, to pin a substitution to its position. */
8532
520
        if (careful && inleft > (size_t)unit) {
8533
0
            inleft = (size_t)unit;
8534
0
        }
8535
520
        char *out_before = out;
8536
520
        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
520
        size_t ret = iconv(cd, flushing ? NULL : (void *)&inptr, &inleft, &out, &outleft);
8541
520
        if (!flushing) {
8542
260
            up = inptr;
8543
260
        }
8544
8545
520
        if (ret != (size_t)-1) {
8546
520
            if (flushing) {
8547
260
                break;
8548
260
            }
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
260
            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
260
            else if (careful && up < uend) {
8567
0
                continue;
8568
0
            }
8569
260
            else {
8570
                /* All input consumed; switch to flushing the shift state. */
8571
260
                flushing = 1;
8572
260
                continue;
8573
260
            }
8574
260
        }
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
260
    result = PyBytesWriter_FinishWithPointer(writer, out);
8648
260
    writer = NULL;
8649
8650
260
done:
8651
260
    if (writer != NULL) {
8652
0
        PyBytesWriter_Discard(writer);
8653
0
    }
8654
260
    iconv_close(cd);
8655
260
    PyMem_Free(widened);
8656
260
    Py_XDECREF(errorHandler);
8657
260
    Py_XDECREF(exc);
8658
260
    return result;
8659
260
}
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
522k
{
8672
522k
    const char *starts = s;
8673
522k
    const char *e;
8674
522k
    Py_ssize_t startinpos, endinpos;
8675
522k
    PyObject *errorHandler = NULL, *exc = NULL;
8676
522k
    Py_ssize_t maplen;
8677
522k
    int mapkind;
8678
522k
    const void *mapdata;
8679
522k
    Py_UCS4 x;
8680
522k
    unsigned char ch;
8681
8682
522k
    maplen = PyUnicode_GET_LENGTH(mapping);
8683
522k
    mapdata = PyUnicode_DATA(mapping);
8684
522k
    mapkind = PyUnicode_KIND(mapping);
8685
8686
522k
    e = s + size;
8687
8688
522k
    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
113
        const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
8693
113
        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8694
113
        Py_UCS4 maxchar = writer->maxchar;
8695
8696
113
        assert (writer->kind == PyUnicode_1BYTE_KIND);
8697
6.93k
        while (s < e) {
8698
6.82k
            ch = *s;
8699
6.82k
            x = mapdata_ucs1[ch];
8700
6.82k
            if (x > maxchar) {
8701
105
                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8702
0
                    goto onError;
8703
105
                maxchar = writer->maxchar;
8704
105
                outdata = (Py_UCS1 *)writer->data;
8705
105
            }
8706
6.82k
            outdata[writer->pos] = x;
8707
6.82k
            writer->pos++;
8708
6.82k
            ++s;
8709
6.82k
        }
8710
113
        return 0;
8711
113
    }
8712
8713
670k
    while (s < e) {
8714
647k
        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8715
647k
            int outkind = writer->kind;
8716
647k
            const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
8717
647k
            if (outkind == PyUnicode_1BYTE_KIND) {
8718
561k
                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8719
561k
                Py_UCS4 maxchar = writer->maxchar;
8720
8.60M
                while (s < e) {
8721
8.12M
                    ch = *s;
8722
8.12M
                    x = mapdata_ucs2[ch];
8723
8.12M
                    if (x > maxchar)
8724
86.9k
                        goto Error;
8725
8.03M
                    outdata[writer->pos] = x;
8726
8.03M
                    writer->pos++;
8727
8.03M
                    ++s;
8728
8.03M
                }
8729
474k
                break;
8730
561k
            }
8731
85.8k
            else if (outkind == PyUnicode_2BYTE_KIND) {
8732
85.8k
                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8733
24.1M
                while (s < e) {
8734
24.1M
                    ch = *s;
8735
24.1M
                    x = mapdata_ucs2[ch];
8736
24.1M
                    if (x == 0xFFFE)
8737
61.4k
                        goto Error;
8738
24.1M
                    outdata[writer->pos] = x;
8739
24.1M
                    writer->pos++;
8740
24.1M
                    ++s;
8741
24.1M
                }
8742
24.3k
                break;
8743
85.8k
            }
8744
647k
        }
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
148k
Error:
8752
148k
        if (x == 0xfffe)
8753
85.7k
        {
8754
            /* undefined mapping */
8755
85.7k
            startinpos = s-starts;
8756
85.7k
            endinpos = startinpos+1;
8757
85.7k
            if (unicode_decode_call_errorhandler_writer(
8758
85.7k
                    errors, &errorHandler,
8759
85.7k
                    "charmap", "character maps to <undefined>",
8760
85.7k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
8761
85.7k
                    writer)) {
8762
12
                goto onError;
8763
12
            }
8764
85.7k
            continue;
8765
85.7k
        }
8766
8767
62.6k
        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8768
0
            goto onError;
8769
62.6k
        ++s;
8770
62.6k
    }
8771
522k
    Py_XDECREF(errorHandler);
8772
522k
    Py_XDECREF(exc);
8773
522k
    return 0;
8774
8775
12
onError:
8776
12
    Py_XDECREF(errorHandler);
8777
12
    Py_XDECREF(exc);
8778
12
    return -1;
8779
522k
}
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
522k
{
8891
522k
    _PyUnicodeWriter writer;
8892
8893
    /* Default to Latin-1 */
8894
522k
    if (mapping == NULL)
8895
19
        return PyUnicode_DecodeLatin1(s, size, errors);
8896
8897
522k
    if (size == 0)
8898
0
        _Py_RETURN_UNICODE_EMPTY();
8899
522k
    _PyUnicodeWriter_Init(&writer);
8900
522k
    writer.min_length = size;
8901
522k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
8902
0
        goto onError;
8903
8904
522k
    if (PyUnicode_CheckExact(mapping)) {
8905
522k
        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8906
12
            goto onError;
8907
522k
    }
8908
0
    else {
8909
0
        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8910
0
            goto onError;
8911
0
    }
8912
522k
    return _PyUnicodeWriter_Finish(&writer);
8913
8914
12
  onError:
8915
12
    _PyUnicodeWriter_Dealloc(&writer);
8916
12
    return NULL;
8917
522k
}
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
138
{
8964
138
    PyObject *result;
8965
138
    struct encoding_map *mresult;
8966
138
    int i;
8967
138
    int need_dict = 0;
8968
138
    unsigned char level1[32];
8969
138
    unsigned char level2[512];
8970
138
    unsigned char *mlevel1, *mlevel2, *mlevel3;
8971
138
    int count2 = 0, count3 = 0;
8972
138
    int kind;
8973
138
    const void *data;
8974
138
    int length;
8975
138
    Py_UCS4 ch;
8976
8977
138
    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
8978
0
        PyErr_BadArgument();
8979
0
        return NULL;
8980
0
    }
8981
138
    kind = PyUnicode_KIND(string);
8982
138
    data = PyUnicode_DATA(string);
8983
138
    length = (int)Py_MIN(PyUnicode_GET_LENGTH(string), 256);
8984
138
    memset(level1, 0xFF, sizeof level1);
8985
138
    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
138
    if (PyUnicode_READ(kind, data, 0) != 0)
8991
0
        need_dict = 1;
8992
35.3k
    for (i = 1; i < length; i++) {
8993
35.1k
        int l1, l2;
8994
35.1k
        ch = PyUnicode_READ(kind, data, i);
8995
35.1k
        if (ch == 0 || ch > 0xFFFF) {
8996
0
            need_dict = 1;
8997
0
            break;
8998
0
        }
8999
35.1k
        if (ch == 0xFFFE)
9000
            /* unmapped character */
9001
930
            continue;
9002
34.2k
        l1 = ch >> 11;
9003
34.2k
        l2 = ch >> 7;
9004
34.2k
        if (level1[l1] == 0xFF)
9005
252
            level1[l1] = count2++;
9006
34.2k
        if (level2[l2] == 0xFF)
9007
750
            level2[l2] = count3++;
9008
34.2k
    }
9009
9010
138
    if (count2 >= 0xFF || count3 >= 0xFF)
9011
0
        need_dict = 1;
9012
9013
138
    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
138
    result = PyObject_Malloc(sizeof(struct encoding_map) +
9043
138
                             16*count2 + 128*count3 - 1);
9044
138
    if (!result) {
9045
0
        return PyErr_NoMemory();
9046
0
    }
9047
9048
138
    _PyObject_Init(result, &EncodingMapType);
9049
138
    mresult = (struct encoding_map*)result;
9050
138
    mresult->count2 = count2;
9051
138
    mresult->count3 = count3;
9052
138
    mlevel1 = mresult->level1;
9053
138
    mlevel2 = mresult->level23;
9054
138
    mlevel3 = mresult->level23 + 16*count2;
9055
138
    memcpy(mlevel1, level1, 32);
9056
138
    memset(mlevel2, 0xFF, 16*count2);
9057
138
    memset(mlevel3, 0, 128*count3);
9058
138
    count3 = 0;
9059
35.3k
    for (i = 1; i < length; i++) {
9060
35.1k
        int o1, o2, o3, i2, i3;
9061
35.1k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9062
35.1k
        if (ch == 0xFFFE)
9063
            /* unmapped character */
9064
930
            continue;
9065
34.2k
        o1 = ch>>11;
9066
34.2k
        o2 = (ch>>7) & 0xF;
9067
34.2k
        i2 = 16*mlevel1[o1] + o2;
9068
34.2k
        if (mlevel2[i2] == 0xFF)
9069
750
            mlevel2[i2] = count3++;
9070
34.2k
        o3 = ch & 0x7F;
9071
34.2k
        i3 = 128*mlevel2[i2] + o3;
9072
34.2k
        mlevel3[i3] = i;
9073
34.2k
    }
9074
138
    return result;
9075
138
}
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.19k
{
9649
6.19k
    PyObject *item;
9650
6.19k
    Py_UCS4 replace;
9651
9652
6.19k
    if (charmaptranslate_lookup(ch, mapping, &item, &replace))
9653
0
        return -1;
9654
9655
6.19k
    if (item == NULL) {
9656
        /* not found => default to 1:1 mapping */
9657
115
        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
9658
0
            return -1;
9659
0
        }
9660
115
        return 1;
9661
115
    }
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.19k
        int translate;
9848
6.19k
        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9849
6.19k
        Py_ssize_t newpos;
9850
        /* startpos for collecting untranslatable chars */
9851
6.19k
        Py_ssize_t collstart;
9852
6.19k
        Py_ssize_t collend;
9853
6.19k
        Py_UCS4 ch;
9854
9855
6.19k
        ch = PyUnicode_READ(kind, data, i);
9856
6.19k
        translate = charmaptranslate_output(ch, mapping, &writer);
9857
6.19k
        if (translate < 0)
9858
0
            goto onError;
9859
9860
6.19k
        if (translate != 0) {
9861
            /* it worked => adjust input pointer */
9862
6.19k
            ++i;
9863
6.19k
            continue;
9864
6.19k
        }
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
10.1M
{
9924
10.1M
    if (!PyUnicode_Check(unicode)) {
9925
0
        PyErr_BadInternalCall();
9926
0
        return NULL;
9927
0
    }
9928
10.1M
    if (PyUnicode_IS_ASCII(unicode)) {
9929
        /* If the string is already ASCII, just return the same string */
9930
10.1M
        return Py_NewRef(unicode);
9931
10.1M
    }
9932
9933
2.38k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9934
2.38k
    PyObject *result = PyUnicode_New(len, 127);
9935
2.38k
    if (result == NULL) {
9936
0
        return NULL;
9937
0
    }
9938
9939
2.38k
    Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9940
2.38k
    int kind = PyUnicode_KIND(unicode);
9941
2.38k
    const void *data = PyUnicode_DATA(unicode);
9942
2.38k
    Py_ssize_t i;
9943
51.9k
    for (i = 0; i < len; ++i) {
9944
49.9k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9945
49.9k
        if (ch < 127) {
9946
47.3k
            out[i] = ch;
9947
47.3k
        }
9948
2.66k
        else if (Py_UNICODE_ISSPACE(ch)) {
9949
760
            out[i] = ' ';
9950
760
        }
9951
1.90k
        else {
9952
1.90k
            int decimal = Py_UNICODE_TODECIMAL(ch);
9953
1.90k
            if (decimal < 0) {
9954
428
                out[i] = '?';
9955
428
                out[i+1] = '\0';
9956
428
                _PyUnicode_LENGTH(result) = i + 1;
9957
428
                break;
9958
428
            }
9959
1.47k
            out[i] = '0' + decimal;
9960
1.47k
        }
9961
49.9k
    }
9962
9963
2.38k
    assert(_PyUnicode_CheckConsistency(result, 1));
9964
2.38k
    return result;
9965
2.38k
}
9966
9967
/* --- Helpers ------------------------------------------------------------ */
9968
9969
/* helper macro to fixup start/end slice values */
9970
#define ADJUST_INDICES(start, end, len) \
9971
86.7M
    do {                                \
9972
86.7M
        if (end > len) {                \
9973
61.0M
            end = len;                  \
9974
61.0M
        }                               \
9975
86.7M
        else if (end < 0) {             \
9976
0
            end += len;                 \
9977
0
            if (end < 0) {              \
9978
0
                end = 0;                \
9979
0
            }                           \
9980
0
        }                               \
9981
86.7M
        if (start < 0) {                \
9982
22.5k
            start += len;               \
9983
22.5k
            if (start < 0) {            \
9984
0
                start = 0;              \
9985
0
            }                           \
9986
22.5k
        }                               \
9987
86.7M
    } 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
25.0M
{
9995
25.0M
    int kind1, kind2;
9996
25.0M
    const void *buf1, *buf2;
9997
25.0M
    Py_ssize_t len1, len2, result;
9998
9999
25.0M
    kind1 = PyUnicode_KIND(s1);
10000
25.0M
    kind2 = PyUnicode_KIND(s2);
10001
25.0M
    if (kind1 < kind2)
10002
0
        return -1;
10003
10004
25.0M
    len1 = PyUnicode_GET_LENGTH(s1);
10005
25.0M
    len2 = PyUnicode_GET_LENGTH(s2);
10006
25.0M
    ADJUST_INDICES(start, end, len1);
10007
25.0M
    if (end - start < len2)
10008
3.59M
        return -1;
10009
10010
21.4M
    buf1 = PyUnicode_DATA(s1);
10011
21.4M
    buf2 = PyUnicode_DATA(s2);
10012
21.4M
    if (len2 == 1) {
10013
21.4M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10014
21.4M
        result = findchar((const char *)buf1 + kind1*start,
10015
21.4M
                          kind1, end - start, ch, direction);
10016
21.4M
        if (result == -1)
10017
3.89M
            return -1;
10018
17.5M
        else
10019
17.5M
            return start + result;
10020
21.4M
    }
10021
10022
9.02k
    if (kind2 != kind1) {
10023
4.26k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10024
4.26k
        if (!buf2)
10025
0
            return -2;
10026
4.26k
    }
10027
10028
9.02k
    if (direction > 0) {
10029
9.02k
        switch (kind1) {
10030
4.76k
        case PyUnicode_1BYTE_KIND:
10031
4.76k
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
10032
484
                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
10033
4.27k
            else
10034
4.27k
                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
10035
4.76k
            break;
10036
3.39k
        case PyUnicode_2BYTE_KIND:
10037
3.39k
            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
10038
3.39k
            break;
10039
869
        case PyUnicode_4BYTE_KIND:
10040
869
            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
10041
869
            break;
10042
0
        default:
10043
0
            Py_UNREACHABLE();
10044
9.02k
        }
10045
9.02k
    }
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
9.02k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
10066
9.02k
    if (kind2 != kind1)
10067
4.26k
        PyMem_Free((void *)buf2);
10068
10069
9.02k
    return result;
10070
9.02k
}
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
2.78M
{
10103
2.78M
    int kind;
10104
2.78M
    Py_ssize_t len, result;
10105
2.78M
    len = PyUnicode_GET_LENGTH(str);
10106
2.78M
    ADJUST_INDICES(start, end, len);
10107
2.78M
    if (end - start < 1)
10108
0
        return -1;
10109
2.78M
    kind = PyUnicode_KIND(str);
10110
2.78M
    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
10111
2.78M
                      kind, end-start, ch, direction);
10112
2.78M
    if (result == -1)
10113
1.97M
        return -1;
10114
815k
    else
10115
815k
        return start + result;
10116
2.78M
}
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
34.7M
{
10125
34.7M
    int kind_self;
10126
34.7M
    int kind_sub;
10127
34.7M
    const void *data_self;
10128
34.7M
    const void *data_sub;
10129
34.7M
    Py_ssize_t offset;
10130
34.7M
    Py_ssize_t i;
10131
34.7M
    Py_ssize_t end_sub;
10132
10133
34.7M
    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
10134
34.7M
    end -= PyUnicode_GET_LENGTH(substring);
10135
34.7M
    if (end < start)
10136
9.84M
        return 0;
10137
10138
24.8M
    if (PyUnicode_GET_LENGTH(substring) == 0)
10139
0
        return 1;
10140
10141
24.8M
    kind_self = PyUnicode_KIND(self);
10142
24.8M
    data_self = PyUnicode_DATA(self);
10143
24.8M
    kind_sub = PyUnicode_KIND(substring);
10144
24.8M
    data_sub = PyUnicode_DATA(substring);
10145
24.8M
    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
10146
10147
24.8M
    if (direction > 0)
10148
7.61M
        offset = end;
10149
17.2M
    else
10150
17.2M
        offset = start;
10151
10152
24.8M
    if (PyUnicode_READ(kind_self, data_self, offset) ==
10153
24.8M
        PyUnicode_READ(kind_sub, data_sub, 0) &&
10154
9.70M
        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
10155
9.70M
        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
10156
        /* If both are of the same kind, memcmp is sufficient */
10157
4.83M
        if (kind_self == kind_sub) {
10158
4.50M
            return ! memcmp((char *)data_self +
10159
4.50M
                                (offset * PyUnicode_KIND(substring)),
10160
4.50M
                            data_sub,
10161
4.50M
                            PyUnicode_GET_LENGTH(substring) *
10162
4.50M
                                PyUnicode_KIND(substring));
10163
4.50M
        }
10164
        /* otherwise we have to compare each character by first accessing it */
10165
333k
        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
376k
            for (i = 1; i < end_sub; ++i) {
10170
147k
                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
10171
147k
                    PyUnicode_READ(kind_sub, data_sub, i))
10172
104k
                    return 0;
10173
147k
            }
10174
228k
            return 1;
10175
333k
        }
10176
4.83M
    }
10177
10178
20.0M
    return 0;
10179
24.8M
}
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
546
{
10188
546
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10189
0
        return -1;
10190
10191
546
    return tailmatch(str, substr, start, end, direction);
10192
546
}
10193
10194
static PyObject *
10195
ascii_upper_or_lower(PyObject *self, int lower)
10196
68.3M
{
10197
68.3M
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
10198
68.3M
    const char *data = PyUnicode_DATA(self);
10199
68.3M
    char *resdata;
10200
68.3M
    PyObject *res;
10201
10202
68.3M
    res = PyUnicode_New(len, 127);
10203
68.3M
    if (res == NULL)
10204
0
        return NULL;
10205
68.3M
    resdata = PyUnicode_DATA(res);
10206
68.3M
    if (lower)
10207
68.3M
        _Py_bytes_lower(resdata, data, len);
10208
306
    else
10209
306
        _Py_bytes_upper(resdata, data, len);
10210
68.3M
    return res;
10211
68.3M
}
10212
10213
static Py_UCS4
10214
handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
10215
9.25k
{
10216
9.25k
    Py_ssize_t j;
10217
9.25k
    int final_sigma;
10218
9.25k
    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
12.1k
    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.46k
            break;
10229
10.4k
    }
10230
9.25k
    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
10231
9.25k
    if (final_sigma) {
10232
7.57k
        for (j = i + 1; j < length; j++) {
10233
6.61k
            c = PyUnicode_READ(kind, data, j);
10234
6.61k
            if (!_PyUnicode_IsCaseIgnorable(c))
10235
4.86k
                break;
10236
6.61k
        }
10237
5.82k
        final_sigma = j == length || !_PyUnicode_IsCased(c);
10238
5.82k
    }
10239
9.25k
    return (final_sigma) ? 0x3C2 : 0x3C3;
10240
9.25k
}
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
155M
{
10246
    /* Obscure special case. */
10247
155M
    if (c == 0x3A3) {
10248
9.25k
        mapped[0] = handle_capital_sigma(kind, data, length, i);
10249
9.25k
        return 1;
10250
9.25k
    }
10251
155M
    return _PyUnicode_ToLowerFull(c, mapped);
10252
155M
}
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
11.2M
{
10307
11.2M
    Py_ssize_t i, k = 0;
10308
10309
166M
    for (i = 0; i < length; i++) {
10310
155M
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10311
155M
        int n_res, j;
10312
155M
        if (lower)
10313
155M
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10314
0
        else
10315
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10316
310M
        for (j = 0; j < n_res; j++) {
10317
155M
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10318
155M
            res[k++] = mapped[j];
10319
155M
        }
10320
155M
    }
10321
11.2M
    return k;
10322
11.2M
}
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
11.2M
{
10333
11.2M
    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
10334
11.2M
}
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
11.2M
{
10384
11.2M
    PyObject *res = NULL;
10385
11.2M
    Py_ssize_t length, newlength = 0;
10386
11.2M
    int kind, outkind;
10387
11.2M
    const void *data;
10388
11.2M
    void *outdata;
10389
11.2M
    Py_UCS4 maxchar = 0, *tmp, *tmpend;
10390
10391
11.2M
    kind = PyUnicode_KIND(self);
10392
11.2M
    data = PyUnicode_DATA(self);
10393
11.2M
    length = PyUnicode_GET_LENGTH(self);
10394
11.2M
    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
11.2M
    tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
10399
11.2M
    if (tmp == NULL)
10400
0
        return PyErr_NoMemory();
10401
11.2M
    newlength = perform(kind, data, length, tmp, &maxchar);
10402
11.2M
    res = PyUnicode_New(newlength, maxchar);
10403
11.2M
    if (res == NULL)
10404
0
        goto leave;
10405
11.2M
    tmpend = tmp + newlength;
10406
11.2M
    outdata = PyUnicode_DATA(res);
10407
11.2M
    outkind = PyUnicode_KIND(res);
10408
11.2M
    switch (outkind) {
10409
805k
    case PyUnicode_1BYTE_KIND:
10410
805k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10411
805k
        break;
10412
10.2M
    case PyUnicode_2BYTE_KIND:
10413
10.2M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10414
10.2M
        break;
10415
215k
    case PyUnicode_4BYTE_KIND:
10416
215k
        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10417
215k
        break;
10418
0
    default:
10419
0
        Py_UNREACHABLE();
10420
11.2M
    }
10421
11.2M
  leave:
10422
11.2M
    PyMem_Free(tmp);
10423
11.2M
    return res;
10424
11.2M
}
10425
10426
PyObject *
10427
PyUnicode_Join(PyObject *separator, PyObject *seq)
10428
33.2M
{
10429
33.2M
    PyObject *res;
10430
33.2M
    PyObject *fseq;
10431
33.2M
    Py_ssize_t seqlen;
10432
33.2M
    PyObject **items;
10433
10434
33.2M
    fseq = PySequence_Fast(seq, "can only join an iterable");
10435
33.2M
    if (fseq == NULL) {
10436
664
        return NULL;
10437
664
    }
10438
10439
33.2M
    Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(seq);
10440
10441
33.2M
    items = PySequence_Fast_ITEMS(fseq);
10442
33.2M
    seqlen = PySequence_Fast_GET_SIZE(fseq);
10443
33.2M
    res = _PyUnicode_JoinArray(separator, items, seqlen);
10444
10445
33.2M
    Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
10446
10447
33.2M
    Py_DECREF(fseq);
10448
33.2M
    return res;
10449
33.2M
}
10450
10451
PyObject *
10452
_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
10453
52.6M
{
10454
52.6M
    PyObject *res = NULL; /* the result */
10455
52.6M
    PyObject *sep = NULL;
10456
52.6M
    Py_ssize_t seplen;
10457
52.6M
    PyObject *item;
10458
52.6M
    Py_ssize_t sz, i, res_offset;
10459
52.6M
    Py_UCS4 maxchar;
10460
52.6M
    Py_UCS4 item_maxchar;
10461
52.6M
    int use_memcpy;
10462
52.6M
    unsigned char *res_data = NULL, *sep_data = NULL;
10463
52.6M
    PyObject *last_obj;
10464
52.6M
    int kind = 0;
10465
10466
    /* If empty sequence, return u"". */
10467
52.6M
    if (seqlen == 0) {
10468
7.02M
        _Py_RETURN_UNICODE_EMPTY();
10469
7.02M
    }
10470
10471
    /* If singleton sequence with an exact Unicode, return that. */
10472
45.6M
    last_obj = NULL;
10473
45.6M
    if (seqlen == 1) {
10474
17.7M
        if (PyUnicode_CheckExact(items[0])) {
10475
16.1M
            res = items[0];
10476
16.1M
            return Py_NewRef(res);
10477
16.1M
        }
10478
1.54M
        seplen = 0;
10479
1.54M
        maxchar = 0;
10480
1.54M
    }
10481
27.9M
    else {
10482
        /* Set up sep and seplen */
10483
27.9M
        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
27.9M
        else {
10492
27.9M
            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
27.9M
            sep = separator;
10500
27.9M
            seplen = PyUnicode_GET_LENGTH(separator);
10501
27.9M
            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
27.9M
            Py_INCREF(sep);
10505
27.9M
        }
10506
27.9M
        last_obj = sep;
10507
27.9M
    }
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
29.4M
    sz = 0;
10515
#ifdef Py_DEBUG
10516
    use_memcpy = 0;
10517
#else
10518
29.4M
    use_memcpy = 1;
10519
29.4M
#endif
10520
249M
    for (i = 0; i < seqlen; i++) {
10521
220M
        size_t add_sz;
10522
220M
        item = items[i];
10523
220M
        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
220M
        add_sz = PyUnicode_GET_LENGTH(item);
10531
220M
        item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
10532
220M
        maxchar = Py_MAX(maxchar, item_maxchar);
10533
220M
        if (i != 0) {
10534
190M
            add_sz += seplen;
10535
190M
        }
10536
220M
        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
220M
        sz += add_sz;
10542
220M
        if (use_memcpy && last_obj != NULL) {
10543
141M
            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10544
3.68M
                use_memcpy = 0;
10545
141M
        }
10546
220M
        last_obj = item;
10547
220M
    }
10548
10549
29.4M
    res = PyUnicode_New(sz, maxchar);
10550
29.4M
    if (res == NULL)
10551
0
        goto onError;
10552
10553
    /* Catenate everything. */
10554
#ifdef Py_DEBUG
10555
    use_memcpy = 0;
10556
#else
10557
29.4M
    if (use_memcpy) {
10558
25.7M
        res_data = PyUnicode_1BYTE_DATA(res);
10559
25.7M
        kind = PyUnicode_KIND(res);
10560
25.7M
        if (seplen != 0)
10561
232k
            sep_data = PyUnicode_1BYTE_DATA(sep);
10562
25.7M
    }
10563
29.4M
#endif
10564
29.4M
    if (use_memcpy) {
10565
146M
        for (i = 0; i < seqlen; ++i) {
10566
120M
            Py_ssize_t itemlen;
10567
120M
            item = items[i];
10568
10569
            /* Copy item, and maybe the separator. */
10570
120M
            if (i && seplen != 0) {
10571
1.07M
                memcpy(res_data,
10572
1.07M
                          sep_data,
10573
1.07M
                          kind * seplen);
10574
1.07M
                res_data += kind * seplen;
10575
1.07M
            }
10576
10577
120M
            itemlen = PyUnicode_GET_LENGTH(item);
10578
120M
            if (itemlen != 0) {
10579
110M
                memcpy(res_data,
10580
110M
                          PyUnicode_DATA(item),
10581
110M
                          kind * itemlen);
10582
110M
                res_data += kind * itemlen;
10583
110M
            }
10584
120M
        }
10585
25.7M
        assert(res_data == PyUnicode_1BYTE_DATA(res)
10586
25.7M
                           + kind * PyUnicode_GET_LENGTH(res));
10587
25.7M
    }
10588
3.68M
    else {
10589
102M
        for (i = 0, res_offset = 0; i < seqlen; ++i) {
10590
99.0M
            Py_ssize_t itemlen;
10591
99.0M
            item = items[i];
10592
10593
            /* Copy item, and maybe the separator. */
10594
99.0M
            if (i && seplen != 0) {
10595
4.07M
                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10596
4.07M
                res_offset += seplen;
10597
4.07M
            }
10598
10599
99.0M
            itemlen = PyUnicode_GET_LENGTH(item);
10600
99.0M
            if (itemlen != 0) {
10601
95.6M
                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
10602
95.6M
                res_offset += itemlen;
10603
95.6M
            }
10604
99.0M
        }
10605
3.68M
        assert(res_offset == PyUnicode_GET_LENGTH(res));
10606
3.68M
    }
10607
10608
29.4M
    Py_XDECREF(sep);
10609
29.4M
    assert(_PyUnicode_CheckConsistency(res, 1));
10610
29.4M
    return res;
10611
10612
0
  onError:
10613
0
    Py_XDECREF(sep);
10614
0
    Py_XDECREF(res);
10615
0
    return NULL;
10616
29.4M
}
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
606
{
10635
606
    Py_ssize_t maxlen;
10636
10637
606
    if (!PyUnicode_Check(unicode)) {
10638
0
        PyErr_BadInternalCall();
10639
0
        return -1;
10640
0
    }
10641
606
    if (unicode_check_modifiable(unicode))
10642
0
        return -1;
10643
10644
606
    if (start < 0) {
10645
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
10646
0
        return -1;
10647
0
    }
10648
606
    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
606
    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10656
606
    length = Py_MIN(maxlen, length);
10657
606
    if (length <= 0)
10658
0
        return 0;
10659
10660
606
    _PyUnicode_FastFill(unicode, start, length, fill_char);
10661
606
    return length;
10662
606
}
10663
10664
static PyObject *
10665
pad(PyObject *self,
10666
    Py_ssize_t left,
10667
    Py_ssize_t right,
10668
    Py_UCS4 fill)
10669
1.06k
{
10670
1.06k
    PyObject *u;
10671
1.06k
    Py_UCS4 maxchar;
10672
1.06k
    int kind;
10673
1.06k
    void *data;
10674
10675
1.06k
    if (left < 0)
10676
0
        left = 0;
10677
1.06k
    if (right < 0)
10678
0
        right = 0;
10679
10680
1.06k
    if (left == 0 && right == 0)
10681
0
        return unicode_result_unchanged(self);
10682
10683
1.06k
    if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10684
1.06k
        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
1.06k
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10689
1.06k
    maxchar = Py_MAX(maxchar, fill);
10690
1.06k
    u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
10691
1.06k
    if (!u)
10692
0
        return NULL;
10693
10694
1.06k
    kind = PyUnicode_KIND(u);
10695
1.06k
    data = PyUnicode_DATA(u);
10696
1.06k
    if (left)
10697
0
        _PyUnicode_Fill(kind, data, fill, 0, left);
10698
1.06k
    if (right)
10699
1.06k
        _PyUnicode_Fill(kind, data, fill,
10700
1.06k
                        left + _PyUnicode_LENGTH(self), right);
10701
1.06k
    _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
10702
1.06k
    assert(_PyUnicode_CheckConsistency(u, 1));
10703
1.06k
    return u;
10704
1.06k
}
10705
10706
PyObject *
10707
PyUnicode_Splitlines(PyObject *string, int keepends)
10708
16.6k
{
10709
16.6k
    PyObject *list;
10710
10711
16.6k
    if (ensure_unicode(string) < 0)
10712
0
        return NULL;
10713
10714
16.6k
    switch (PyUnicode_KIND(string)) {
10715
5.17k
    case PyUnicode_1BYTE_KIND:
10716
5.17k
        if (PyUnicode_IS_ASCII(string))
10717
4.16k
            list = asciilib_splitlines(
10718
4.16k
                string, PyUnicode_1BYTE_DATA(string),
10719
4.16k
                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.17k
        break;
10725
8.20k
    case PyUnicode_2BYTE_KIND:
10726
8.20k
        list = ucs2lib_splitlines(
10727
8.20k
            string, PyUnicode_2BYTE_DATA(string),
10728
8.20k
            PyUnicode_GET_LENGTH(string), keepends);
10729
8.20k
        break;
10730
3.23k
    case PyUnicode_4BYTE_KIND:
10731
3.23k
        list = ucs4lib_splitlines(
10732
3.23k
            string, PyUnicode_4BYTE_DATA(string),
10733
3.23k
            PyUnicode_GET_LENGTH(string), keepends);
10734
3.23k
        break;
10735
0
    default:
10736
0
        Py_UNREACHABLE();
10737
16.6k
    }
10738
16.6k
    return list;
10739
16.6k
}
10740
10741
static PyObject *
10742
split(PyObject *self,
10743
      PyObject *substring,
10744
      Py_ssize_t maxcount)
10745
23.1M
{
10746
23.1M
    int kind1, kind2;
10747
23.1M
    const void *buf1, *buf2;
10748
23.1M
    Py_ssize_t len1, len2;
10749
23.1M
    PyObject* out;
10750
23.1M
    len1 = PyUnicode_GET_LENGTH(self);
10751
23.1M
    kind1 = PyUnicode_KIND(self);
10752
10753
23.1M
    if (substring == NULL) {
10754
163k
        if (maxcount < 0) {
10755
143k
            maxcount = (len1 - 1) / 2 + 1;
10756
143k
        }
10757
163k
        switch (kind1) {
10758
93.6k
        case PyUnicode_1BYTE_KIND:
10759
93.6k
            if (PyUnicode_IS_ASCII(self))
10760
69.6k
                return asciilib_split_whitespace(
10761
69.6k
                    self,  PyUnicode_1BYTE_DATA(self),
10762
69.6k
                    len1, maxcount
10763
69.6k
                    );
10764
23.9k
            else
10765
23.9k
                return ucs1lib_split_whitespace(
10766
23.9k
                    self,  PyUnicode_1BYTE_DATA(self),
10767
23.9k
                    len1, maxcount
10768
23.9k
                    );
10769
55.4k
        case PyUnicode_2BYTE_KIND:
10770
55.4k
            return ucs2lib_split_whitespace(
10771
55.4k
                self,  PyUnicode_2BYTE_DATA(self),
10772
55.4k
                len1, maxcount
10773
55.4k
                );
10774
14.8k
        case PyUnicode_4BYTE_KIND:
10775
14.8k
            return ucs4lib_split_whitespace(
10776
14.8k
                self,  PyUnicode_4BYTE_DATA(self),
10777
14.8k
                len1, maxcount
10778
14.8k
                );
10779
0
        default:
10780
0
            Py_UNREACHABLE();
10781
163k
        }
10782
163k
    }
10783
10784
22.9M
    kind2 = PyUnicode_KIND(substring);
10785
22.9M
    len2 = PyUnicode_GET_LENGTH(substring);
10786
22.9M
    if (maxcount < 0) {
10787
        // if len2 == 0, it will raise ValueError.
10788
14.9M
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10789
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10790
14.9M
        maxcount = maxcount < 0 ? len1 : maxcount;
10791
14.9M
    }
10792
22.9M
    if (kind1 < kind2 || len1 < len2) {
10793
3.26M
        out = PyList_New(1);
10794
3.26M
        if (out == NULL)
10795
0
            return NULL;
10796
3.26M
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10797
3.26M
        return out;
10798
3.26M
    }
10799
19.7M
    buf1 = PyUnicode_DATA(self);
10800
19.7M
    buf2 = PyUnicode_DATA(substring);
10801
19.7M
    if (kind2 != kind1) {
10802
254k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10803
254k
        if (!buf2)
10804
0
            return NULL;
10805
254k
    }
10806
10807
19.7M
    switch (kind1) {
10808
19.4M
    case PyUnicode_1BYTE_KIND:
10809
19.4M
        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.31M
        else
10813
1.31M
            out = ucs1lib_split(
10814
1.31M
                self,  buf1, len1, buf2, len2, maxcount);
10815
19.4M
        break;
10816
210k
    case PyUnicode_2BYTE_KIND:
10817
210k
        out = ucs2lib_split(
10818
210k
            self,  buf1, len1, buf2, len2, maxcount);
10819
210k
        break;
10820
44.3k
    case PyUnicode_4BYTE_KIND:
10821
44.3k
        out = ucs4lib_split(
10822
44.3k
            self,  buf1, len1, buf2, len2, maxcount);
10823
44.3k
        break;
10824
0
    default:
10825
0
        out = NULL;
10826
19.7M
    }
10827
19.7M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10828
19.7M
    if (kind2 != kind1)
10829
254k
        PyMem_Free((void *)buf2);
10830
19.7M
    return out;
10831
19.7M
}
10832
10833
static PyObject *
10834
rsplit(PyObject *self,
10835
       PyObject *substring,
10836
       Py_ssize_t maxcount)
10837
42
{
10838
42
    int kind1, kind2;
10839
42
    const void *buf1, *buf2;
10840
42
    Py_ssize_t len1, len2;
10841
42
    PyObject* out;
10842
10843
42
    len1 = PyUnicode_GET_LENGTH(self);
10844
42
    kind1 = PyUnicode_KIND(self);
10845
10846
42
    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
42
    kind2 = PyUnicode_KIND(substring);
10877
42
    len2 = PyUnicode_GET_LENGTH(substring);
10878
42
    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
42
    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
42
    buf1 = PyUnicode_DATA(self);
10892
42
    buf2 = PyUnicode_DATA(substring);
10893
42
    if (kind2 != kind1) {
10894
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10895
0
        if (!buf2)
10896
0
            return NULL;
10897
0
    }
10898
10899
42
    switch (kind1) {
10900
42
    case PyUnicode_1BYTE_KIND:
10901
42
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10902
42
            out = asciilib_rsplit(
10903
42
                self,  buf1, len1, buf2, len2, maxcount);
10904
0
        else
10905
0
            out = ucs1lib_rsplit(
10906
0
                self,  buf1, len1, buf2, len2, maxcount);
10907
42
        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
42
    }
10919
42
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10920
42
    if (kind2 != kind1)
10921
0
        PyMem_Free((void *)buf2);
10922
42
    return out;
10923
42
}
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
25.8M
{
10929
25.8M
    switch (kind) {
10930
10.4M
    case PyUnicode_1BYTE_KIND:
10931
10.4M
        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10932
5.22M
            return asciilib_find(buf1, len1, buf2, len2, offset);
10933
5.22M
        else
10934
5.22M
            return ucs1lib_find(buf1, len1, buf2, len2, offset);
10935
6.56M
    case PyUnicode_2BYTE_KIND:
10936
6.56M
        return ucs2lib_find(buf1, len1, buf2, len2, offset);
10937
8.87M
    case PyUnicode_4BYTE_KIND:
10938
8.87M
        return ucs4lib_find(buf1, len1, buf2, len2, offset);
10939
25.8M
    }
10940
25.8M
    Py_UNREACHABLE();
10941
25.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.8M
{
10947
10.8M
    switch (kind) {
10948
10.0M
    case PyUnicode_1BYTE_KIND:
10949
10.0M
        return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10950
673k
    case PyUnicode_2BYTE_KIND:
10951
673k
        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10952
79.3k
    case PyUnicode_4BYTE_KIND:
10953
79.3k
        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10954
10.8M
    }
10955
10.8M
    Py_UNREACHABLE();
10956
10.8M
}
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
60.9k
{
10962
60.9k
    int kind = PyUnicode_KIND(u);
10963
60.9k
    void *data = PyUnicode_DATA(u);
10964
60.9k
    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10965
60.9k
    if (kind == PyUnicode_1BYTE_KIND) {
10966
37.6k
        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10967
37.6k
                                      (Py_UCS1 *)data + len,
10968
37.6k
                                      u1, u2, maxcount);
10969
37.6k
    }
10970
23.3k
    else if (kind == PyUnicode_2BYTE_KIND) {
10971
19.3k
        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10972
19.3k
                                      (Py_UCS2 *)data + len,
10973
19.3k
                                      u1, u2, maxcount);
10974
19.3k
    }
10975
3.94k
    else {
10976
3.94k
        assert(kind == PyUnicode_4BYTE_KIND);
10977
3.94k
        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10978
3.94k
                                      (Py_UCS4 *)data + len,
10979
3.94k
                                      u1, u2, maxcount);
10980
3.94k
    }
10981
60.9k
}
10982
10983
static PyObject *
10984
replace(PyObject *self, PyObject *str1,
10985
        PyObject *str2, Py_ssize_t maxcount)
10986
22.4M
{
10987
22.4M
    PyObject *u;
10988
22.4M
    const char *sbuf = PyUnicode_DATA(self);
10989
22.4M
    const void *buf1 = PyUnicode_DATA(str1);
10990
22.4M
    const void *buf2 = PyUnicode_DATA(str2);
10991
22.4M
    int srelease = 0, release1 = 0, release2 = 0;
10992
22.4M
    int skind = PyUnicode_KIND(self);
10993
22.4M
    int kind1 = PyUnicode_KIND(str1);
10994
22.4M
    int kind2 = PyUnicode_KIND(str2);
10995
22.4M
    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10996
22.4M
    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10997
22.4M
    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
10998
22.4M
    int mayshrink;
10999
22.4M
    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
11000
11001
22.4M
    if (slen < len1)
11002
11.2M
        goto nothing;
11003
11004
11.2M
    if (maxcount < 0)
11005
11.2M
        maxcount = PY_SSIZE_T_MAX;
11006
0
    else if (maxcount == 0)
11007
0
        goto nothing;
11008
11009
11.2M
    if (str1 == str2)
11010
0
        goto nothing;
11011
11012
11.2M
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
11013
11.2M
    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
11014
11.2M
    if (maxchar < maxchar_str1)
11015
        /* substring too wide to be present */
11016
0
        goto nothing;
11017
11.2M
    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
11018
    /* Replacing str1 with str2 may cause a maxchar reduction in the
11019
       result string. */
11020
11.2M
    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
11021
11.2M
    maxchar = Py_MAX(maxchar, maxchar_str2);
11022
11023
11.2M
    if (len1 == len2) {
11024
        /* same length */
11025
436k
        if (len1 == 0)
11026
0
            goto nothing;
11027
436k
        if (len1 == 1) {
11028
            /* replace characters */
11029
436k
            Py_UCS4 u1, u2;
11030
436k
            Py_ssize_t pos;
11031
11032
436k
            u1 = PyUnicode_READ(kind1, buf1, 0);
11033
436k
            pos = findchar(sbuf, skind, slen, u1, 1);
11034
436k
            if (pos < 0)
11035
375k
                goto nothing;
11036
60.9k
            u2 = PyUnicode_READ(kind2, buf2, 0);
11037
60.9k
            u = PyUnicode_New(slen, maxchar);
11038
60.9k
            if (!u)
11039
0
                goto error;
11040
11041
60.9k
            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
11042
60.9k
            replace_1char_inplace(u, pos, u1, u2, maxcount);
11043
60.9k
        }
11044
142
        else {
11045
142
            int rkind = skind;
11046
142
            char *res;
11047
142
            Py_ssize_t i;
11048
11049
142
            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
142
            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
11056
142
            if (i < 0)
11057
142
                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
436k
    }
11106
10.8M
    else {
11107
10.8M
        Py_ssize_t n, i, j, ires;
11108
10.8M
        Py_ssize_t new_size;
11109
10.8M
        int rkind = skind;
11110
10.8M
        char *res;
11111
11112
10.8M
        if (kind1 < rkind) {
11113
            /* widen substring */
11114
753k
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11115
753k
            if (!buf1) goto error;
11116
753k
            release1 = 1;
11117
753k
        }
11118
10.8M
        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
11119
10.8M
        if (n == 0)
11120
9.61M
            goto nothing;
11121
1.22M
        if (kind2 < rkind) {
11122
            /* widen replacement */
11123
39.5k
            buf2 = unicode_askind(kind2, buf2, len2, rkind);
11124
39.5k
            if (!buf2) goto error;
11125
39.5k
            release2 = 1;
11126
39.5k
        }
11127
1.18M
        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.22M
        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.22M
        new_size = slen + n * (len2 - len1);
11151
1.22M
        if (new_size == 0) {
11152
5
            u = _PyUnicode_GetEmpty();
11153
5
            goto done;
11154
5
        }
11155
1.22M
        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.22M
        u = PyUnicode_New(new_size, maxchar);
11161
1.22M
        if (!u)
11162
0
            goto error;
11163
1.22M
        assert(PyUnicode_KIND(u) == rkind);
11164
1.22M
        res = PyUnicode_DATA(u);
11165
1.22M
        ires = i = 0;
11166
1.22M
        if (len1 > 0) {
11167
27.1M
            while (n-- > 0) {
11168
                /* look for next match */
11169
25.8M
                j = anylib_find(rkind, self,
11170
25.8M
                                sbuf + rkind * i, slen-i,
11171
25.8M
                                str1, buf1, len1, i);
11172
25.8M
                if (j == -1)
11173
0
                    break;
11174
25.8M
                else if (j > i) {
11175
                    /* copy unchanged part [i:j] */
11176
4.29M
                    memcpy(res + rkind * ires,
11177
4.29M
                           sbuf + rkind * i,
11178
4.29M
                           rkind * (j-i));
11179
4.29M
                    ires += j - i;
11180
4.29M
                }
11181
                /* copy substitution string */
11182
25.8M
                if (len2 > 0) {
11183
25.7M
                    memcpy(res + rkind * ires,
11184
25.7M
                           buf2,
11185
25.7M
                           rkind * len2);
11186
25.7M
                    ires += len2;
11187
25.7M
                }
11188
25.8M
                i = j + len1;
11189
25.8M
            }
11190
1.22M
            if (i < slen)
11191
                /* copy tail [i:] */
11192
1.22M
                memcpy(res + rkind * ires,
11193
1.22M
                       sbuf + rkind * i,
11194
1.22M
                       rkind * (slen-i));
11195
1.22M
        }
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.22M
    }
11216
11217
1.29M
    if (mayshrink) {
11218
0
        unicode_adjust_maxchar(&u);
11219
0
        if (u == NULL)
11220
0
            goto error;
11221
0
    }
11222
11223
1.29M
  done:
11224
1.29M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11225
1.29M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11226
1.29M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11227
1.29M
    if (srelease)
11228
0
        PyMem_Free((void *)sbuf);
11229
1.29M
    if (release1)
11230
39.5k
        PyMem_Free((void *)buf1);
11231
1.29M
    if (release2)
11232
39.5k
        PyMem_Free((void *)buf2);
11233
1.29M
    assert(_PyUnicode_CheckConsistency(u, 1));
11234
1.29M
    return u;
11235
11236
21.2M
  nothing:
11237
    /* nothing to replace; return original string (when possible) */
11238
21.2M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11239
21.2M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11240
21.2M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11241
21.2M
    if (srelease)
11242
0
        PyMem_Free((void *)sbuf);
11243
21.2M
    if (release1)
11244
713k
        PyMem_Free((void *)buf1);
11245
21.2M
    if (release2)
11246
0
        PyMem_Free((void *)buf2);
11247
21.2M
    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.29M
}
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.62k
{
11319
1.62k
    Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
11320
11321
1.62k
    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.62k
    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.62k
    *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
11333
1.62k
    return 1;
11334
1.62k
}
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
31.0M
{
11369
31.0M
#define COMPARE(TYPE1, TYPE2) \
11370
31.0M
    do { \
11371
30.0M
        TYPE1* p1 = (TYPE1 *)data1; \
11372
30.0M
        TYPE2* p2 = (TYPE2 *)data2; \
11373
30.0M
        TYPE1* end = p1 + len; \
11374
30.0M
        Py_UCS4 c1, c2; \
11375
30.0M
        for (; p1 != end; p1++, p2++) { \
11376
30.0M
            c1 = *p1; \
11377
30.0M
            c2 = *p2; \
11378
30.0M
            if (c1 != c2) \
11379
30.0M
                return (c1 < c2) ? -1 : 1; \
11380
30.0M
        } \
11381
30.0M
    } \
11382
30.0M
    while (0)
11383
11384
31.0M
    int kind1, kind2;
11385
31.0M
    const void *data1, *data2;
11386
31.0M
    Py_ssize_t len1, len2, len;
11387
11388
31.0M
    kind1 = PyUnicode_KIND(str1);
11389
31.0M
    kind2 = PyUnicode_KIND(str2);
11390
31.0M
    data1 = PyUnicode_DATA(str1);
11391
31.0M
    data2 = PyUnicode_DATA(str2);
11392
31.0M
    len1 = PyUnicode_GET_LENGTH(str1);
11393
31.0M
    len2 = PyUnicode_GET_LENGTH(str2);
11394
31.0M
    len = Py_MIN(len1, len2);
11395
11396
31.0M
    switch(kind1) {
11397
5.59M
    case PyUnicode_1BYTE_KIND:
11398
5.59M
    {
11399
5.59M
        switch(kind2) {
11400
775k
        case PyUnicode_1BYTE_KIND:
11401
775k
        {
11402
775k
            int cmp = memcmp(data1, data2, len);
11403
            /* normalize result of memcmp() into the range [-1; 1] */
11404
775k
            if (cmp < 0)
11405
683k
                return -1;
11406
91.7k
            if (cmp > 0)
11407
86.4k
                return 1;
11408
5.27k
            break;
11409
91.7k
        }
11410
4.11M
        case PyUnicode_2BYTE_KIND:
11411
4.11M
            COMPARE(Py_UCS1, Py_UCS2);
11412
0
            break;
11413
700k
        case PyUnicode_4BYTE_KIND:
11414
700k
            COMPARE(Py_UCS1, Py_UCS4);
11415
0
            break;
11416
0
        default:
11417
0
            Py_UNREACHABLE();
11418
5.59M
        }
11419
5.27k
        break;
11420
5.59M
    }
11421
25.1M
    case PyUnicode_2BYTE_KIND:
11422
25.1M
    {
11423
25.1M
        switch(kind2) {
11424
9.80k
        case PyUnicode_1BYTE_KIND:
11425
9.80k
            COMPARE(Py_UCS2, Py_UCS1);
11426
0
            break;
11427
25.1M
        case PyUnicode_2BYTE_KIND:
11428
25.1M
        {
11429
25.1M
            COMPARE(Py_UCS2, Py_UCS2);
11430
0
            break;
11431
25.1M
        }
11432
3.97k
        case PyUnicode_4BYTE_KIND:
11433
3.97k
            COMPARE(Py_UCS2, Py_UCS4);
11434
0
            break;
11435
0
        default:
11436
0
            Py_UNREACHABLE();
11437
25.1M
        }
11438
0
        break;
11439
25.1M
    }
11440
307k
    case PyUnicode_4BYTE_KIND:
11441
307k
    {
11442
307k
        switch(kind2) {
11443
813
        case PyUnicode_1BYTE_KIND:
11444
813
            COMPARE(Py_UCS4, Py_UCS1);
11445
0
            break;
11446
3.60k
        case PyUnicode_2BYTE_KIND:
11447
3.60k
            COMPARE(Py_UCS4, Py_UCS2);
11448
0
            break;
11449
302k
        case PyUnicode_4BYTE_KIND:
11450
302k
        {
11451
302k
#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11452
302k
            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11453
            /* normalize result of wmemcmp() into the range [-1; 1] */
11454
302k
            if (cmp < 0)
11455
143k
                return -1;
11456
159k
            if (cmp > 0)
11457
159k
                return 1;
11458
#else
11459
            COMPARE(Py_UCS4, Py_UCS4);
11460
#endif
11461
0
            break;
11462
159k
        }
11463
0
        default:
11464
0
            Py_UNREACHABLE();
11465
307k
        }
11466
0
        break;
11467
307k
    }
11468
0
    default:
11469
0
        Py_UNREACHABLE();
11470
31.0M
    }
11471
11472
5.27k
    if (len1 == len2)
11473
5.24k
        return 0;
11474
38
    if (len1 < len2)
11475
13
        return -1;
11476
25
    else
11477
25
        return 1;
11478
11479
38
#undef COMPARE
11480
38
}
11481
11482
11483
int
11484
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
11485
634M
{
11486
634M
    assert(PyUnicode_Check(str1));
11487
634M
    assert(PyUnicode_Check(str2));
11488
634M
    if (str1 == str2) {
11489
88.6M
        return 1;
11490
88.6M
    }
11491
545M
    return unicode_eq(str1, str2);
11492
634M
}
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
162k
{
11516
162k
    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11517
        /* a string is equal to itself */
11518
162k
        if (left == right)
11519
0
            return 0;
11520
11521
162k
        return unicode_compare(left, right);
11522
162k
    }
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
162k
}
11529
11530
int
11531
PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11532
31.7M
{
11533
31.7M
    Py_ssize_t i;
11534
31.7M
    int kind;
11535
31.7M
    Py_UCS4 chr;
11536
11537
31.7M
    assert(_PyUnicode_CHECK(uni));
11538
31.7M
    kind = PyUnicode_KIND(uni);
11539
31.7M
    if (kind == PyUnicode_1BYTE_KIND) {
11540
31.7M
        const void *data = PyUnicode_1BYTE_DATA(uni);
11541
31.7M
        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
11542
31.7M
        size_t len, len2 = strlen(str);
11543
31.7M
        int cmp;
11544
11545
31.7M
        len = Py_MIN(len1, len2);
11546
31.7M
        cmp = memcmp(data, str, len);
11547
31.7M
        if (cmp != 0) {
11548
17.9M
            if (cmp < 0)
11549
39.1k
                return -1;
11550
17.9M
            else
11551
17.9M
                return 1;
11552
17.9M
        }
11553
13.7M
        if (len1 > len2)
11554
199
            return 1; /* uni is longer */
11555
13.7M
        if (len1 < len2)
11556
966
            return -1; /* str is longer */
11557
13.7M
        return 0;
11558
13.7M
    }
11559
2.18k
    else {
11560
2.18k
        const void *data = PyUnicode_DATA(uni);
11561
        /* Compare Unicode string and source character set string */
11562
3.67k
        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
11563
3.45k
            if (chr != (unsigned char)str[i])
11564
1.96k
                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
31.7M
}
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
1.97M
{
11654
1.97M
    size_t len;
11655
1.97M
    assert(_PyUnicode_CHECK(unicode));
11656
1.97M
    assert(str);
11657
#ifndef NDEBUG
11658
    for (const char *p = str; *p; p++) {
11659
        assert((unsigned char)*p < 128);
11660
    }
11661
#endif
11662
1.97M
    if (!PyUnicode_IS_ASCII(unicode))
11663
10.5k
        return 0;
11664
1.96M
    len = (size_t)PyUnicode_GET_LENGTH(unicode);
11665
1.96M
    return strlen(str) == len &&
11666
235k
           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11667
1.97M
}
11668
11669
PyObject *
11670
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
11671
60.9M
{
11672
60.9M
    int result;
11673
11674
60.9M
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11675
204k
        Py_RETURN_NOTIMPLEMENTED;
11676
11677
60.7M
    if (left == right) {
11678
2.91k
        switch (op) {
11679
2.68k
        case Py_EQ:
11680
2.68k
        case Py_LE:
11681
2.68k
        case Py_GE:
11682
            /* a string is equal to itself */
11683
2.68k
            Py_RETURN_TRUE;
11684
222
        case Py_NE:
11685
222
        case Py_LT:
11686
222
        case Py_GT:
11687
222
            Py_RETURN_FALSE;
11688
0
        default:
11689
0
            PyErr_BadArgument();
11690
0
            return NULL;
11691
2.91k
        }
11692
2.91k
    }
11693
60.6M
    else if (op == Py_EQ || op == Py_NE) {
11694
29.7M
        result = unicode_eq(left, right);
11695
29.7M
        result ^= (op == Py_NE);
11696
29.7M
        return PyBool_FromLong(result);
11697
29.7M
    }
11698
30.9M
    else {
11699
30.9M
        result = unicode_compare(left, right);
11700
30.9M
        Py_RETURN_RICHCOMPARE(result, 0, op);
11701
30.9M
    }
11702
60.7M
}
11703
11704
int
11705
PyUnicode_Contains(PyObject *str, PyObject *substr)
11706
201M
{
11707
201M
    int kind1, kind2;
11708
201M
    const void *buf1, *buf2;
11709
201M
    Py_ssize_t len1, len2;
11710
201M
    int result;
11711
11712
201M
    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
201M
    if (ensure_unicode(str) < 0)
11719
0
        return -1;
11720
11721
201M
    kind1 = PyUnicode_KIND(str);
11722
201M
    kind2 = PyUnicode_KIND(substr);
11723
201M
    if (kind1 < kind2)
11724
21.8M
        return 0;
11725
179M
    len1 = PyUnicode_GET_LENGTH(str);
11726
179M
    len2 = PyUnicode_GET_LENGTH(substr);
11727
179M
    if (len1 < len2)
11728
726k
        return 0;
11729
178M
    buf1 = PyUnicode_DATA(str);
11730
178M
    buf2 = PyUnicode_DATA(substr);
11731
178M
    if (len2 == 1) {
11732
165M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11733
165M
        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11734
165M
        return result;
11735
165M
    }
11736
13.3M
    if (kind2 != kind1) {
11737
18.0k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11738
18.0k
        if (!buf2)
11739
0
            return -1;
11740
18.0k
    }
11741
11742
13.3M
    switch (kind1) {
11743
13.3M
    case PyUnicode_1BYTE_KIND:
11744
13.3M
        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11745
13.3M
        break;
11746
13.1k
    case PyUnicode_2BYTE_KIND:
11747
13.1k
        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11748
13.1k
        break;
11749
4.86k
    case PyUnicode_4BYTE_KIND:
11750
4.86k
        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11751
4.86k
        break;
11752
0
    default:
11753
0
        Py_UNREACHABLE();
11754
13.3M
    }
11755
11756
13.3M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
11757
13.3M
    if (kind2 != kind1)
11758
18.0k
        PyMem_Free((void *)buf2);
11759
11760
13.3M
    return result;
11761
13.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
29.7M
{
11768
29.7M
    PyObject *result;
11769
29.7M
    Py_UCS4 maxchar, maxchar2;
11770
29.7M
    Py_ssize_t left_len, right_len, new_len;
11771
11772
29.7M
    if (ensure_unicode(left) < 0)
11773
0
        return NULL;
11774
11775
29.7M
    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
29.7M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11784
29.7M
    if (left == empty) {
11785
1.38M
        return PyUnicode_FromObject(right);
11786
1.38M
    }
11787
28.3M
    if (right == empty) {
11788
2.85M
        return PyUnicode_FromObject(left);
11789
2.85M
    }
11790
11791
25.4M
    left_len = PyUnicode_GET_LENGTH(left);
11792
25.4M
    right_len = PyUnicode_GET_LENGTH(right);
11793
25.4M
    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
25.4M
    new_len = left_len + right_len;
11799
11800
25.4M
    maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11801
25.4M
    maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11802
25.4M
    maxchar = Py_MAX(maxchar, maxchar2);
11803
11804
    /* Concat the two Unicode strings */
11805
25.4M
    result = PyUnicode_New(new_len, maxchar);
11806
25.4M
    if (result == NULL)
11807
0
        return NULL;
11808
25.4M
    _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11809
25.4M
    _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11810
25.4M
    assert(_PyUnicode_CheckConsistency(result, 1));
11811
25.4M
    return result;
11812
25.4M
}
11813
11814
void
11815
PyUnicode_Append(PyObject **p_left, PyObject *right)
11816
7.68M
{
11817
7.68M
    PyObject *left, *res;
11818
7.68M
    Py_UCS4 maxchar, maxchar2;
11819
7.68M
    Py_ssize_t left_len, right_len, new_len;
11820
11821
7.68M
    if (p_left == NULL) {
11822
0
        if (!PyErr_Occurred())
11823
0
            PyErr_BadInternalCall();
11824
0
        return;
11825
0
    }
11826
7.68M
    left = *p_left;
11827
7.68M
    if (right == NULL || left == NULL
11828
7.68M
        || !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
7.68M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11836
7.68M
    if (left == empty) {
11837
550k
        Py_DECREF(left);
11838
550k
        *p_left = Py_NewRef(right);
11839
550k
        return;
11840
550k
    }
11841
7.13M
    if (right == empty) {
11842
8.92k
        return;
11843
8.92k
    }
11844
11845
7.12M
    left_len = PyUnicode_GET_LENGTH(left);
11846
7.12M
    right_len = PyUnicode_GET_LENGTH(right);
11847
7.12M
    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.12M
    new_len = left_len + right_len;
11853
11854
7.12M
    if (_PyUnicode_IsModifiable(left)
11855
7.12M
        && PyUnicode_CheckExact(right)
11856
7.12M
        && 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.22M
        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11862
3.22M
    {
11863
        /* append inplace */
11864
3.22M
        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.22M
        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
11869
3.22M
    }
11870
3.89M
    else {
11871
3.89M
        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11872
3.89M
        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11873
3.89M
        maxchar = Py_MAX(maxchar, maxchar2);
11874
11875
        /* Concat the two Unicode strings */
11876
3.89M
        res = PyUnicode_New(new_len, maxchar);
11877
3.89M
        if (res == NULL)
11878
0
            goto error;
11879
3.89M
        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11880
3.89M
        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
11881
3.89M
        Py_DECREF(left);
11882
3.89M
        *p_left = res;
11883
3.89M
    }
11884
7.12M
    assert(_PyUnicode_CheckConsistency(*p_left, 1));
11885
7.12M
    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
24.2M
{
11920
24.2M
    assert(PyUnicode_Check(str));
11921
24.2M
    assert(PyUnicode_Check(substr));
11922
11923
24.2M
    Py_ssize_t result;
11924
24.2M
    int kind1, kind2;
11925
24.2M
    const void *buf1 = NULL, *buf2 = NULL;
11926
24.2M
    Py_ssize_t len1, len2;
11927
11928
24.2M
    kind1 = PyUnicode_KIND(str);
11929
24.2M
    kind2 = PyUnicode_KIND(substr);
11930
24.2M
    if (kind1 < kind2)
11931
0
        return 0;
11932
11933
24.2M
    len1 = PyUnicode_GET_LENGTH(str);
11934
24.2M
    len2 = PyUnicode_GET_LENGTH(substr);
11935
24.2M
    ADJUST_INDICES(start, end, len1);
11936
24.2M
    if (end - start < len2)
11937
7.87M
        return 0;
11938
11939
16.4M
    buf1 = PyUnicode_DATA(str);
11940
16.4M
    buf2 = PyUnicode_DATA(substr);
11941
16.4M
    if (kind2 != kind1) {
11942
179k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11943
179k
        if (!buf2)
11944
0
            goto onError;
11945
179k
    }
11946
11947
    // We don't reuse `anylib_count` here because of the explicit casts.
11948
16.4M
    switch (kind1) {
11949
16.2M
    case PyUnicode_1BYTE_KIND:
11950
16.2M
        result = ucs1lib_count(
11951
16.2M
            ((const Py_UCS1*)buf1) + start, end - start,
11952
16.2M
            buf2, len2, PY_SSIZE_T_MAX
11953
16.2M
            );
11954
16.2M
        break;
11955
134k
    case PyUnicode_2BYTE_KIND:
11956
134k
        result = ucs2lib_count(
11957
134k
            ((const Py_UCS2*)buf1) + start, end - start,
11958
134k
            buf2, len2, PY_SSIZE_T_MAX
11959
134k
            );
11960
134k
        break;
11961
45.0k
    case PyUnicode_4BYTE_KIND:
11962
45.0k
        result = ucs4lib_count(
11963
45.0k
            ((const Py_UCS4*)buf1) + start, end - start,
11964
45.0k
            buf2, len2, PY_SSIZE_T_MAX
11965
45.0k
            );
11966
45.0k
        break;
11967
0
    default:
11968
0
        Py_UNREACHABLE();
11969
16.4M
    }
11970
11971
16.4M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11972
16.4M
    if (kind2 != kind1)
11973
179k
        PyMem_Free((void *)buf2);
11974
11975
16.4M
    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
16.4M
}
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
23.1M
{
12002
23.1M
    return PyUnicode_AsEncodedString(self, encoding, errors);
12003
23.1M
}
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.13M
{
12019
1.13M
    Py_ssize_t i, j, line_pos, src_len, incr;
12020
1.13M
    Py_UCS4 ch;
12021
1.13M
    PyObject *u;
12022
1.13M
    const void *src_data;
12023
1.13M
    void *dest_data;
12024
1.13M
    int kind;
12025
1.13M
    int found;
12026
12027
    /* First pass: determine size of output string */
12028
1.13M
    src_len = PyUnicode_GET_LENGTH(self);
12029
1.13M
    i = j = line_pos = 0;
12030
1.13M
    kind = PyUnicode_KIND(self);
12031
1.13M
    src_data = PyUnicode_DATA(self);
12032
1.13M
    found = 0;
12033
2.43M
    for (; i < src_len; i++) {
12034
1.30M
        ch = PyUnicode_READ(kind, src_data, i);
12035
1.30M
        if (ch == '\t') {
12036
394k
            found = 1;
12037
394k
            if (tabsize > 0) {
12038
394k
                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
12039
394k
                if (j > PY_SSIZE_T_MAX - incr)
12040
0
                    goto overflow;
12041
394k
                line_pos += incr;
12042
394k
                j += incr;
12043
394k
            }
12044
394k
        }
12045
907k
        else {
12046
907k
            if (j > PY_SSIZE_T_MAX - 1)
12047
0
                goto overflow;
12048
907k
            line_pos++;
12049
907k
            j++;
12050
907k
            if (ch == '\n' || ch == '\r')
12051
2.23k
                line_pos = 0;
12052
907k
        }
12053
1.30M
    }
12054
1.13M
    if (!found)
12055
1.09M
        return unicode_result_unchanged(self);
12056
12057
    /* Second pass: create output string and fill it */
12058
37.8k
    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
12059
37.8k
    if (!u)
12060
0
        return NULL;
12061
37.8k
    dest_data = PyUnicode_DATA(u);
12062
12063
37.8k
    i = j = line_pos = 0;
12064
12065
751k
    for (; i < src_len; i++) {
12066
713k
        ch = PyUnicode_READ(kind, src_data, i);
12067
713k
        if (ch == '\t') {
12068
394k
            if (tabsize > 0) {
12069
394k
                incr = tabsize - (line_pos % tabsize);
12070
394k
                line_pos += incr;
12071
394k
                _PyUnicode_Fill(kind, dest_data, ' ', j, incr);
12072
394k
                j += incr;
12073
394k
            }
12074
394k
        }
12075
319k
        else {
12076
319k
            line_pos++;
12077
319k
            PyUnicode_WRITE(kind, dest_data, j, ch);
12078
319k
            j++;
12079
319k
            if (ch == '\n' || ch == '\r')
12080
0
                line_pos = 0;
12081
319k
        }
12082
713k
    }
12083
37.8k
    assert (j == PyUnicode_GET_LENGTH(u));
12084
37.8k
    return unicode_result(u);
12085
12086
0
  overflow:
12087
0
    PyErr_SetString(PyExc_OverflowError, "new string is too long");
12088
0
    return NULL;
12089
37.8k
}
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
24.7M
{
12106
24.7M
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12107
24.7M
    if (result < 0) {
12108
7.46M
        return -1;
12109
7.46M
    }
12110
17.2M
    return result;
12111
24.7M
}
12112
12113
static PyObject *
12114
unicode_getitem(PyObject *self, Py_ssize_t index)
12115
71.4M
{
12116
71.4M
    const void *data;
12117
71.4M
    int kind;
12118
71.4M
    Py_UCS4 ch;
12119
12120
71.4M
    if (!PyUnicode_Check(self)) {
12121
0
        PyErr_BadArgument();
12122
0
        return NULL;
12123
0
    }
12124
71.4M
    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
12125
13.9k
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12126
13.9k
        return NULL;
12127
13.9k
    }
12128
71.4M
    kind = PyUnicode_KIND(self);
12129
71.4M
    data = PyUnicode_DATA(self);
12130
71.4M
    ch = PyUnicode_READ(kind, data, index);
12131
71.4M
    return unicode_char(ch);
12132
71.4M
}
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
508M
{
12139
508M
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
12140
12141
#ifdef Py_DEBUG
12142
    assert(_Py_HashSecret_Initialized);
12143
#endif
12144
508M
    Py_hash_t hash = PyUnicode_HASH(self);
12145
508M
    if (hash != -1) {
12146
454M
        return hash;
12147
454M
    }
12148
53.5M
    x = Py_HashBuffer(PyUnicode_DATA(self),
12149
53.5M
                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
12150
12151
53.5M
    PyUnicode_SET_HASH(self, x);
12152
53.5M
    return x;
12153
508M
}
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
55.3k
{
12170
55.3k
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12171
55.3k
    if (result == -1) {
12172
542
        PyErr_SetString(PyExc_ValueError, "substring not found");
12173
542
    }
12174
54.8k
    else if (result < 0) {
12175
0
        return -1;
12176
0
    }
12177
55.3k
    return result;
12178
55.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
37.8k
{
12194
37.8k
    return PyBool_FromLong(PyUnicode_IS_ASCII(self));
12195
37.8k
}
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
3.79k
{
12253
3.79k
    Py_ssize_t i, length;
12254
3.79k
    int kind;
12255
3.79k
    const void *data;
12256
3.79k
    int cased;
12257
12258
3.79k
    length = PyUnicode_GET_LENGTH(self);
12259
3.79k
    kind = PyUnicode_KIND(self);
12260
3.79k
    data = PyUnicode_DATA(self);
12261
12262
    /* Shortcut for single character strings */
12263
3.79k
    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
3.79k
    if (length == 0)
12269
0
        Py_RETURN_FALSE;
12270
12271
3.79k
    cased = 0;
12272
46.3k
    for (i = 0; i < length; i++) {
12273
43.1k
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12274
12275
43.1k
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
12276
536
            Py_RETURN_FALSE;
12277
42.5k
        else if (!cased && Py_UNICODE_ISUPPER(ch))
12278
3.31k
            cased = 1;
12279
43.1k
    }
12280
3.26k
    return PyBool_FromLong(cased);
12281
3.79k
}
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.81M
{
12352
1.81M
    Py_ssize_t i, length;
12353
1.81M
    int kind;
12354
1.81M
    const void *data;
12355
12356
1.81M
    length = PyUnicode_GET_LENGTH(self);
12357
1.81M
    kind = PyUnicode_KIND(self);
12358
1.81M
    data = PyUnicode_DATA(self);
12359
12360
    /* Shortcut for single character strings */
12361
1.81M
    if (length == 1)
12362
1.81M
        return PyBool_FromLong(
12363
1.81M
            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.33k
{
12467
1.33k
    Py_ssize_t i, length;
12468
1.33k
    int kind;
12469
1.33k
    const void *data;
12470
12471
1.33k
    length = PyUnicode_GET_LENGTH(self);
12472
1.33k
    kind = PyUnicode_KIND(self);
12473
1.33k
    data = PyUnicode_DATA(self);
12474
12475
    /* Shortcut for single character strings */
12476
1.33k
    if (length == 1)
12477
263
        return PyBool_FromLong(
12478
263
            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
12479
12480
    /* Special case for empty strings */
12481
1.06k
    if (length == 0)
12482
0
        Py_RETURN_FALSE;
12483
12484
7.39k
    for (i = 0; i < length; i++) {
12485
6.83k
        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
12486
500
            Py_RETURN_FALSE;
12487
6.83k
    }
12488
1.06k
    Py_RETURN_TRUE;
12489
1.06k
}
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.39M
{
12504
1.39M
    Py_ssize_t i, length;
12505
1.39M
    int kind;
12506
1.39M
    const void *data;
12507
12508
1.39M
    length = PyUnicode_GET_LENGTH(self);
12509
1.39M
    kind = PyUnicode_KIND(self);
12510
1.39M
    data = PyUnicode_DATA(self);
12511
12512
    /* Shortcut for single character strings */
12513
1.39M
    if (length == 1) {
12514
1.39M
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12515
1.39M
        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12516
1.39M
    }
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
20.8k
{
12569
20.8k
    Py_ssize_t i;
12570
20.8k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12571
20.8k
    if (len == 0) {
12572
        /* an empty string is not a valid identifier */
12573
0
        return 0;
12574
0
    }
12575
12576
20.8k
    int kind = PyUnicode_KIND(self);
12577
20.8k
    const void *data = PyUnicode_DATA(self);
12578
20.8k
    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
20.8k
    if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12588
793
        return 0;
12589
793
    }
12590
12591
149k
    for (i = 1; i < len; i++) {
12592
130k
        ch = PyUnicode_READ(kind, data, i);
12593
130k
        if (!_PyUnicode_IsXidContinue(ch)) {
12594
294
            return i;
12595
294
        }
12596
130k
    }
12597
19.7k
    return i;
12598
20.0k
}
12599
12600
int
12601
PyUnicode_IsIdentifier(PyObject *self)
12602
7.86k
{
12603
7.86k
    Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12604
7.86k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12605
    /* an empty string is not a valid identifier */
12606
7.86k
    return len && i == len;
12607
7.86k
}
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
5.24k
{
12623
5.24k
    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12624
5.24k
}
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.22M
{
12639
1.22M
    Py_ssize_t i, length;
12640
1.22M
    int kind;
12641
1.22M
    const void *data;
12642
12643
1.22M
    length = PyUnicode_GET_LENGTH(self);
12644
1.22M
    kind = PyUnicode_KIND(self);
12645
1.22M
    data = PyUnicode_DATA(self);
12646
12647
    /* Shortcut for single character strings */
12648
1.22M
    if (length == 1)
12649
1.22M
        return PyBool_FromLong(
12650
1.22M
            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
25.3M
{
12678
25.3M
    return PyUnicode_Join(self, iterable);
12679
25.3M
}
12680
12681
static Py_ssize_t
12682
unicode_length(PyObject *self)
12683
44.4M
{
12684
44.4M
    return PyUnicode_GET_LENGTH(self);
12685
44.4M
}
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.62k
{
12704
1.62k
    if (PyUnicode_GET_LENGTH(self) >= width)
12705
565
        return unicode_result_unchanged(self);
12706
12707
1.06k
    return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
12708
1.62k
}
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
79.6M
{
12720
79.6M
    if (PyUnicode_IS_ASCII(self))
12721
68.3M
        return ascii_upper_or_lower(self, 1);
12722
11.2M
    return case_operation(self, do_lower);
12723
79.6M
}
12724
12725
70.9M
#define LEFTSTRIP 0
12726
86.3M
#define RIGHTSTRIP 1
12727
48.6M
#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.60M
{
12738
2.60M
    const void *data;
12739
2.60M
    int kind;
12740
2.60M
    Py_ssize_t i, j, len;
12741
2.60M
    BLOOM_MASK sepmask;
12742
2.60M
    Py_ssize_t seplen;
12743
12744
2.60M
    kind = PyUnicode_KIND(self);
12745
2.60M
    data = PyUnicode_DATA(self);
12746
2.60M
    len = PyUnicode_GET_LENGTH(self);
12747
2.60M
    seplen = PyUnicode_GET_LENGTH(sepobj);
12748
2.60M
    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12749
2.60M
                              PyUnicode_DATA(sepobj),
12750
2.60M
                              seplen);
12751
12752
2.60M
    i = 0;
12753
2.60M
    if (striptype != RIGHTSTRIP) {
12754
515k
        while (i < len) {
12755
511k
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12756
511k
            if (!BLOOM(sepmask, ch))
12757
468k
                break;
12758
43.3k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12759
3.36k
                break;
12760
39.9k
            i++;
12761
39.9k
        }
12762
475k
    }
12763
12764
2.60M
    j = len;
12765
2.60M
    if (striptype != LEFTSTRIP) {
12766
2.13M
        j--;
12767
2.76M
        while (j >= i) {
12768
1.76M
            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12769
1.76M
            if (!BLOOM(sepmask, ch))
12770
987k
                break;
12771
782k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12772
155k
                break;
12773
627k
            j--;
12774
627k
        }
12775
12776
2.13M
        j++;
12777
2.13M
    }
12778
12779
2.60M
    return PyUnicode_Substring(self, i, j);
12780
2.60M
}
12781
12782
PyObject*
12783
_PyUnicode_BinarySlice(PyObject *container, PyObject *start_o, PyObject *stop_o)
12784
29.4M
{
12785
29.4M
    assert(PyUnicode_CheckExact(container));
12786
29.4M
    Py_ssize_t len = PyUnicode_GET_LENGTH(container);
12787
29.4M
    Py_ssize_t istart, istop;
12788
29.4M
    if (!_PyEval_UnpackIndices(start_o, stop_o, len, &istart, &istop)) {
12789
0
        return NULL;
12790
0
    }
12791
29.4M
    return PyUnicode_Substring(container, istart, istop);
12792
29.4M
}
12793
12794
PyObject*
12795
PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12796
237M
{
12797
237M
    const unsigned char *data;
12798
237M
    int kind;
12799
237M
    Py_ssize_t length;
12800
12801
237M
    length = PyUnicode_GET_LENGTH(self);
12802
237M
    end = Py_MIN(end, length);
12803
12804
237M
    if (start == 0 && end == length)
12805
70.4M
        return unicode_result_unchanged(self);
12806
12807
167M
    if (start < 0 || end < 0) {
12808
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12809
0
        return NULL;
12810
0
    }
12811
167M
    if (start >= length || end < start)
12812
7.23M
        _Py_RETURN_UNICODE_EMPTY();
12813
12814
160M
    length = end - start;
12815
160M
    if (PyUnicode_IS_ASCII(self)) {
12816
55.8M
        data = PyUnicode_1BYTE_DATA(self);
12817
55.8M
        return _PyUnicode_FromASCII((const char*)(data + start), length);
12818
55.8M
    }
12819
104M
    else {
12820
104M
        kind = PyUnicode_KIND(self);
12821
104M
        data = PyUnicode_1BYTE_DATA(self);
12822
104M
        return PyUnicode_FromKindAndData(kind,
12823
104M
                                         data + kind * start,
12824
104M
                                         length);
12825
104M
    }
12826
160M
}
12827
12828
static PyObject *
12829
do_strip(PyObject *self, int striptype)
12830
66.0M
{
12831
66.0M
    Py_ssize_t len, i, j;
12832
12833
66.0M
    len = PyUnicode_GET_LENGTH(self);
12834
12835
66.0M
    if (PyUnicode_IS_ASCII(self)) {
12836
51.9M
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12837
12838
51.9M
        i = 0;
12839
51.9M
        if (striptype != RIGHTSTRIP) {
12840
45.9M
            while (i < len) {
12841
33.4M
                Py_UCS1 ch = data[i];
12842
33.4M
                if (!_Py_ascii_whitespace[ch])
12843
27.5M
                    break;
12844
5.90M
                i++;
12845
5.90M
            }
12846
40.0M
        }
12847
12848
51.9M
        j = len;
12849
51.9M
        if (striptype != LEFTSTRIP) {
12850
51.4M
            j--;
12851
57.4M
            while (j >= i) {
12852
38.7M
                Py_UCS1 ch = data[j];
12853
38.7M
                if (!_Py_ascii_whitespace[ch])
12854
32.7M
                    break;
12855
6.02M
                j--;
12856
6.02M
            }
12857
51.4M
            j++;
12858
51.4M
        }
12859
51.9M
    }
12860
14.1M
    else {
12861
14.1M
        int kind = PyUnicode_KIND(self);
12862
14.1M
        const void *data = PyUnicode_DATA(self);
12863
12864
14.1M
        i = 0;
12865
14.1M
        if (striptype != RIGHTSTRIP) {
12866
13.0M
            while (i < len) {
12867
13.0M
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12868
13.0M
                if (!Py_UNICODE_ISSPACE(ch))
12869
10.4M
                    break;
12870
2.54M
                i++;
12871
2.54M
            }
12872
10.4M
        }
12873
12874
14.1M
        j = len;
12875
14.1M
        if (striptype != LEFTSTRIP) {
12876
12.7M
            j--;
12877
15.5M
            while (j >= i) {
12878
15.5M
                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12879
15.5M
                if (!Py_UNICODE_ISSPACE(ch))
12880
12.7M
                    break;
12881
2.84M
                j--;
12882
2.84M
            }
12883
12.7M
            j++;
12884
12.7M
        }
12885
14.1M
    }
12886
12887
66.0M
    return PyUnicode_Substring(self, i, j);
12888
66.0M
}
12889
12890
12891
static PyObject *
12892
do_argstrip(PyObject *self, int striptype, PyObject *sep)
12893
68.6M
{
12894
68.6M
    if (sep != Py_None) {
12895
2.60M
        if (PyUnicode_Check(sep))
12896
2.60M
            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.60M
    }
12904
12905
66.0M
    return do_strip(self, striptype);
12906
68.6M
}
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
48.6M
{
12925
48.6M
    return do_argstrip(self, BOTHSTRIP, chars);
12926
48.6M
}
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.33M
{
12944
2.33M
    return do_argstrip(self, LEFTSTRIP, chars);
12945
2.33M
}
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.6M
{
12963
17.6M
    return do_argstrip(self, RIGHTSTRIP, chars);
12964
17.6M
}
12965
12966
12967
PyObject *
12968
_PyUnicode_Repeat(PyObject *str, Py_ssize_t len)
12969
281k
{
12970
281k
    PyObject *u;
12971
281k
    Py_ssize_t nchars, n;
12972
12973
281k
    if (len < 1)
12974
44.1k
        _Py_RETURN_UNICODE_EMPTY();
12975
12976
    /* no repeat, return original string */
12977
237k
    if (len == 1)
12978
31.5k
        return unicode_result_unchanged(str);
12979
12980
205k
    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
205k
    nchars = len * PyUnicode_GET_LENGTH(str);
12986
12987
205k
    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
12988
205k
    if (!u)
12989
0
        return NULL;
12990
205k
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
12991
12992
205k
    if (PyUnicode_GET_LENGTH(str) == 1) {
12993
203k
        int kind = PyUnicode_KIND(str);
12994
203k
        Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12995
203k
        if (kind == PyUnicode_1BYTE_KIND) {
12996
203k
            void *to = PyUnicode_DATA(u);
12997
203k
            memset(to, (unsigned char)fill_char, len);
12998
203k
        }
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
203k
    }
13010
2.28k
    else {
13011
2.28k
        Py_ssize_t char_size = PyUnicode_KIND(str);
13012
2.28k
        char *to = (char *) PyUnicode_DATA(u);
13013
2.28k
        _PyBytes_RepeatBuffer(to, nchars * char_size, PyUnicode_DATA(str),
13014
2.28k
            PyUnicode_GET_LENGTH(str) * char_size);
13015
2.28k
    }
13016
13017
205k
    assert(_PyUnicode_CheckConsistency(u, 1));
13018
205k
    return u;
13019
205k
}
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
22.4M
{
13054
22.4M
    return replace(self, old, new, count);
13055
22.4M
}
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.45k
{
13074
1.45k
    int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
13075
1.45k
    if (match == -1) {
13076
0
        return NULL;
13077
0
    }
13078
1.45k
    if (match) {
13079
7
        return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
13080
7
                                   PyUnicode_GET_LENGTH(self));
13081
7
    }
13082
1.44k
    return unicode_result_unchanged(self);
13083
1.45k
}
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
326M
    for (Py_ssize_t i = 0; i < isize; i++) {
13127
312M
        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
13128
312M
        Py_ssize_t incr = 1;
13129
312M
        switch (ch) {
13130
321k
        case '\'': squote++; break;
13131
747k
        case '"':  dquote++; break;
13132
6.57M
        case '\\': case '\t': case '\r': case '\n':
13133
6.57M
            incr = 2;
13134
6.57M
            break;
13135
304M
        default:
13136
            /* Fast-path ASCII */
13137
304M
            if (ch < ' ' || ch == 0x7f)
13138
160M
                incr = 4; /* \xHH */
13139
143M
            else if (ch < 0x7f)
13140
128M
                ;
13141
15.4M
            else if (Py_UNICODE_ISPRINTABLE(ch))
13142
13.6M
                maxch = (ch > maxch) ? ch : maxch;
13143
1.80M
            else if (ch < 0x100)
13144
151k
                incr = 4; /* \xHH */
13145
1.65M
            else if (ch < 0x10000)
13146
134k
                incr = 6; /* \uHHHH */
13147
1.52M
            else
13148
1.52M
                incr = 10; /* \uHHHHHHHH */
13149
312M
        }
13150
312M
        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
312M
        osize += incr;
13156
312M
    }
13157
13158
14.5M
    Py_UCS4 quote = '\'';
13159
14.5M
    int changed = (osize != isize);
13160
14.5M
    if (squote) {
13161
97.6k
        changed = 1;
13162
97.6k
        if (dquote)
13163
            /* Both squote and dquote present. Use squote,
13164
               and escape them */
13165
10.9k
            osize += squote;
13166
86.7k
        else
13167
86.7k
            quote = '"';
13168
97.6k
    }
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.51M
        PyUnicode_WRITE(okind, odata, 0, quote);
13179
13180
7.51M
        _PyUnicode_FastCopyCharacters(repr, 1,
13181
7.51M
                                      unicode, 0,
13182
7.51M
                                      isize);
13183
13184
7.51M
        PyUnicode_WRITE(okind, odata, osize-1, quote);
13185
7.51M
    }
13186
7.06M
    else {
13187
7.06M
        switch (okind) {
13188
6.74M
        case PyUnicode_1BYTE_KIND:
13189
6.74M
            ucs1lib_repr(unicode, quote, odata);
13190
6.74M
            break;
13191
311k
        case PyUnicode_2BYTE_KIND:
13192
311k
            ucs2lib_repr(unicode, quote, odata);
13193
311k
            break;
13194
9.18k
        default:
13195
9.18k
            assert(okind == PyUnicode_4BYTE_KIND);
13196
9.18k
            ucs4lib_repr(unicode, quote, odata);
13197
7.06M
        }
13198
7.06M
    }
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
188k
{
13219
188k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13220
188k
    if (result < 0) {
13221
16.1k
        return -1;
13222
16.1k
    }
13223
172k
    return result;
13224
188k
}
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.36k
{
13241
2.36k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13242
2.36k
    if (result == -1) {
13243
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
13244
0
    }
13245
2.36k
    else if (result < 0) {
13246
0
        return -1;
13247
0
    }
13248
2.36k
    return result;
13249
2.36k
}
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
23.1M
{
13311
23.1M
    if (sep == Py_None)
13312
163k
        return split(self, NULL, maxsplit);
13313
22.9M
    if (PyUnicode_Check(sep))
13314
22.9M
        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.9M
}
13321
13322
PyObject *
13323
PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
13324
8.41M
{
13325
8.41M
    PyObject* out;
13326
8.41M
    int kind1, kind2;
13327
8.41M
    const void *buf1, *buf2;
13328
8.41M
    Py_ssize_t len1, len2;
13329
13330
8.41M
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13331
0
        return NULL;
13332
13333
8.41M
    kind1 = PyUnicode_KIND(str_obj);
13334
8.41M
    kind2 = PyUnicode_KIND(sep_obj);
13335
8.41M
    len1 = PyUnicode_GET_LENGTH(str_obj);
13336
8.41M
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13337
8.41M
    if (kind1 < kind2 || len1 < len2) {
13338
1.36k
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13339
1.36k
        return PyTuple_Pack(3, str_obj, empty, empty);
13340
1.36k
    }
13341
8.41M
    buf1 = PyUnicode_DATA(str_obj);
13342
8.41M
    buf2 = PyUnicode_DATA(sep_obj);
13343
8.41M
    if (kind2 != kind1) {
13344
87.3k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13345
87.3k
        if (!buf2)
13346
0
            return NULL;
13347
87.3k
    }
13348
13349
8.41M
    switch (kind1) {
13350
8.32M
    case PyUnicode_1BYTE_KIND:
13351
8.32M
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13352
2.77M
            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13353
5.55M
        else
13354
5.55M
            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13355
8.32M
        break;
13356
75.0k
    case PyUnicode_2BYTE_KIND:
13357
75.0k
        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13358
75.0k
        break;
13359
12.3k
    case PyUnicode_4BYTE_KIND:
13360
12.3k
        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13361
12.3k
        break;
13362
0
    default:
13363
0
        Py_UNREACHABLE();
13364
8.41M
    }
13365
13366
8.41M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13367
8.41M
    if (kind2 != kind1)
13368
87.3k
        PyMem_Free((void *)buf2);
13369
13370
8.41M
    return out;
13371
8.41M
}
13372
13373
13374
PyObject *
13375
PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
13376
62.0k
{
13377
62.0k
    PyObject* out;
13378
62.0k
    int kind1, kind2;
13379
62.0k
    const void *buf1, *buf2;
13380
62.0k
    Py_ssize_t len1, len2;
13381
13382
62.0k
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13383
0
        return NULL;
13384
13385
62.0k
    kind1 = PyUnicode_KIND(str_obj);
13386
62.0k
    kind2 = PyUnicode_KIND(sep_obj);
13387
62.0k
    len1 = PyUnicode_GET_LENGTH(str_obj);
13388
62.0k
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13389
62.0k
    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
62.0k
    buf1 = PyUnicode_DATA(str_obj);
13394
62.0k
    buf2 = PyUnicode_DATA(sep_obj);
13395
62.0k
    if (kind2 != kind1) {
13396
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13397
0
        if (!buf2)
13398
0
            return NULL;
13399
0
    }
13400
13401
62.0k
    switch (kind1) {
13402
62.0k
    case PyUnicode_1BYTE_KIND:
13403
62.0k
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13404
62.0k
            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
62.0k
        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
62.0k
    }
13417
13418
62.0k
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13419
62.0k
    if (kind2 != kind1)
13420
0
        PyMem_Free((void *)buf2);
13421
13422
62.0k
    return out;
13423
62.0k
}
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.41M
{
13445
8.41M
    return PyUnicode_Partition(self, sep);
13446
8.41M
}
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
62.0k
{
13466
62.0k
    return PyUnicode_RPartition(self, sep);
13467
62.0k
}
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
42
{
13491
42
    if (sep == Py_None)
13492
0
        return rsplit(self, NULL, maxsplit);
13493
42
    if (PyUnicode_Check(sep))
13494
42
        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
42
}
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.6k
{
13518
16.6k
    return PyUnicode_Splitlines(self, keepends);
13519
16.6k
}
13520
13521
static
13522
PyObject *unicode_str(PyObject *self)
13523
3.53M
{
13524
3.53M
    return unicode_result_unchanged(self);
13525
3.53M
}
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
21.2M
{
13792
21.2M
    if (PyTuple_Check(subobj)) {
13793
1.50M
        Py_ssize_t i;
13794
5.48M
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13795
3.99M
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13796
3.99M
            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.99M
            int result = tailmatch(self, substring, start, end, -1);
13804
3.99M
            if (result < 0) {
13805
0
                return NULL;
13806
0
            }
13807
3.99M
            if (result) {
13808
18.4k
                Py_RETURN_TRUE;
13809
18.4k
            }
13810
3.99M
        }
13811
        /* nothing matched */
13812
1.50M
        Py_RETURN_FALSE;
13813
1.50M
    }
13814
19.7M
    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.7M
    int result = tailmatch(self, subobj, start, end, -1);
13821
19.7M
    if (result < 0) {
13822
0
        return NULL;
13823
0
    }
13824
19.7M
    return PyBool_FromLong(result);
13825
19.7M
}
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
10.8M
{
13849
10.8M
    if (PyTuple_Check(subobj)) {
13850
171k
        Py_ssize_t i;
13851
301k
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13852
284k
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13853
284k
            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
284k
            int result = tailmatch(self, substring, start, end, +1);
13861
284k
            if (result < 0) {
13862
0
                return NULL;
13863
0
            }
13864
284k
            if (result) {
13865
154k
                Py_RETURN_TRUE;
13866
154k
            }
13867
284k
        }
13868
171k
        Py_RETURN_FALSE;
13869
171k
    }
13870
10.7M
    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
10.7M
    int result = tailmatch(self, subobj, start, end, +1);
13877
10.7M
    if (result < 0) {
13878
0
        return NULL;
13879
0
    }
13880
10.7M
    return PyBool_FromLong(result);
13881
10.7M
}
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.3M
{
14187
12.3M
    if (!PyUnicode_Check(v))
14188
0
        Py_RETURN_NOTIMPLEMENTED;
14189
12.3M
    return PyUnicode_Format(v, w);
14190
12.3M
}
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
83.8M
{
14213
83.8M
    if (_PyIndex_Check(item)) {
14214
71.4M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
14215
71.4M
        if (i == -1 && PyErr_Occurred())
14216
0
            return NULL;
14217
71.4M
        if (i < 0)
14218
68.1k
            i += PyUnicode_GET_LENGTH(self);
14219
71.4M
        return unicode_getitem(self, i);
14220
71.4M
    } else if (PySlice_Check(item)) {
14221
12.3M
        Py_ssize_t start, stop, step, slicelength, i;
14222
12.3M
        size_t cur;
14223
12.3M
        PyObject *result;
14224
12.3M
        const void *src_data;
14225
12.3M
        void *dest_data;
14226
12.3M
        int src_kind, dest_kind;
14227
12.3M
        Py_UCS4 ch, max_char, kind_limit;
14228
14229
12.3M
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
14230
0
            return NULL;
14231
0
        }
14232
12.3M
        slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14233
12.3M
                                            &start, &stop, step);
14234
14235
12.3M
        if (slicelength <= 0) {
14236
1.11M
            _Py_RETURN_UNICODE_EMPTY();
14237
11.2M
        } else if (start == 0 && step == 1 &&
14238
299k
                   slicelength == PyUnicode_GET_LENGTH(self)) {
14239
2.66k
            return unicode_result_unchanged(self);
14240
11.2M
        } else if (step == 1) {
14241
11.2M
            return PyUnicode_Substring(self,
14242
11.2M
                                       start, start + slicelength);
14243
11.2M
        }
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
83.8M
}
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
18.7M
{
14305
18.7M
    PyObject *unicode;
14306
18.7M
    if (x == NULL) {
14307
0
        unicode = _PyUnicode_GetEmpty();
14308
0
    }
14309
18.7M
    else if (encoding == NULL && errors == NULL) {
14310
18.7M
        unicode = PyObject_Str(x);
14311
18.7M
    }
14312
0
    else {
14313
0
        unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
14314
0
    }
14315
14316
18.7M
    if (unicode != NULL && type != &PyUnicode_Type) {
14317
18.7M
        Py_SETREF(unicode, unicode_subtype_new(type, unicode));
14318
18.7M
    }
14319
18.7M
    return unicode;
14320
18.7M
}
14321
14322
static const char *
14323
arg_as_utf8(PyObject *obj, const char *name)
14324
12.4M
{
14325
12.4M
    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
12.4M
    return _PyUnicode_AsUTF8NoNUL(obj);
14332
12.4M
}
14333
14334
static PyObject *
14335
unicode_vectorcall(PyObject *type, PyObject *const *args,
14336
                   size_t nargsf, PyObject *kwnames)
14337
11.7M
{
14338
11.7M
    assert(Py_Is(_PyType_CAST(type), &PyUnicode_Type));
14339
14340
11.7M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
14341
11.7M
    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
11.7M
    if (!_PyArg_CheckPositional("str", nargs, 0, 3)) {
14358
0
        return NULL;
14359
0
    }
14360
11.7M
    if (nargs == 0) {
14361
4.10k
        return _PyUnicode_GetEmpty();
14362
4.10k
    }
14363
11.7M
    PyObject *object = args[0];
14364
11.7M
    if (nargs == 1) {
14365
1.05k
        return PyObject_Str(object);
14366
1.05k
    }
14367
11.7M
    const char *encoding = arg_as_utf8(args[1], "encoding");
14368
11.7M
    if (encoding == NULL) {
14369
0
        return NULL;
14370
0
    }
14371
11.7M
    const char *errors = NULL;
14372
11.7M
    if (nargs == 3) {
14373
691k
        errors = arg_as_utf8(args[2], "errors");
14374
691k
        if (errors == NULL) {
14375
0
            return NULL;
14376
0
        }
14377
691k
    }
14378
11.7M
    return PyUnicode_FromEncodedObject(object, encoding, errors);
14379
11.7M
}
14380
14381
static PyObject *
14382
unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
14383
18.7M
{
14384
18.7M
    PyObject *self;
14385
18.7M
    Py_ssize_t length, char_size;
14386
18.7M
    int share_utf8;
14387
18.7M
    int kind;
14388
18.7M
    void *data;
14389
14390
18.7M
    assert(PyType_IsSubtype(type, &PyUnicode_Type));
14391
18.7M
    assert(_PyUnicode_CHECK(unicode));
14392
14393
18.7M
    self = type->tp_alloc(type, 0);
14394
18.7M
    if (self == NULL) {
14395
0
        return NULL;
14396
0
    }
14397
18.7M
    kind = PyUnicode_KIND(unicode);
14398
18.7M
    length = PyUnicode_GET_LENGTH(unicode);
14399
14400
18.7M
    _PyUnicode_LENGTH(self) = length;
14401
#ifdef Py_DEBUG
14402
    _PyUnicode_HASH(self) = -1;
14403
#else
14404
18.7M
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14405
18.7M
#endif
14406
18.7M
    _PyUnicode_STATE(self).interned = 0;
14407
18.7M
    _PyUnicode_STATE(self).kind = kind;
14408
18.7M
    _PyUnicode_STATE(self).compact = 0;
14409
18.7M
    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
14410
18.7M
    _PyUnicode_STATE(self).statically_allocated = 0;
14411
18.7M
    PyUnicode_SET_UTF8_LENGTH(self, 0);
14412
18.7M
    PyUnicode_SET_UTF8(self, NULL);
14413
18.7M
    _PyUnicode_DATA_ANY(self) = NULL;
14414
14415
18.7M
    share_utf8 = 0;
14416
18.7M
    if (kind == PyUnicode_1BYTE_KIND) {
14417
15.9M
        char_size = 1;
14418
15.9M
        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14419
15.8M
            share_utf8 = 1;
14420
15.9M
    }
14421
2.82M
    else if (kind == PyUnicode_2BYTE_KIND) {
14422
2.76M
        char_size = 2;
14423
2.76M
    }
14424
63.6k
    else {
14425
63.6k
        assert(kind == PyUnicode_4BYTE_KIND);
14426
63.6k
        char_size = 4;
14427
63.6k
    }
14428
14429
    /* Ensure we won't overflow the length. */
14430
18.7M
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14431
0
        PyErr_NoMemory();
14432
0
        goto onError;
14433
0
    }
14434
18.7M
    data = PyMem_Malloc((length + 1) * char_size);
14435
18.7M
    if (data == NULL) {
14436
0
        PyErr_NoMemory();
14437
0
        goto onError;
14438
0
    }
14439
14440
18.7M
    _PyUnicode_DATA_ANY(self) = data;
14441
18.7M
    if (share_utf8) {
14442
15.8M
        PyUnicode_SET_UTF8_LENGTH(self, length);
14443
15.8M
        PyUnicode_SET_UTF8(self, data);
14444
15.8M
    }
14445
14446
18.7M
    memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
14447
18.7M
    assert(_PyUnicode_CheckConsistency(self, 1));
14448
#ifdef Py_DEBUG
14449
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14450
#endif
14451
18.7M
    return self;
14452
14453
0
onError:
14454
0
    Py_DECREF(self);
14455
0
    return NULL;
14456
18.7M
}
14457
14458
static _PyObjectIndexPair
14459
unicode_iteritem(PyObject *obj, Py_ssize_t index)
14460
72.1M
{
14461
72.1M
    if (index >= PyUnicode_GET_LENGTH(obj)) {
14462
14.1M
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
14463
14.1M
    }
14464
57.9M
    const void *data = PyUnicode_DATA(obj);
14465
57.9M
    int kind = PyUnicode_KIND(obj);
14466
57.9M
    Py_UCS4 ch = PyUnicode_READ(kind, data, index);
14467
57.9M
    PyObject *result = unicode_char(ch);
14468
57.9M
    index = (result == NULL) ? -1 : index + 1;
14469
57.9M
    return (_PyObjectIndexPair) { .object = result, .index = index };
14470
72.1M
}
14471
14472
void
14473
_PyUnicode_ExactDealloc(PyObject *op)
14474
101M
{
14475
101M
    assert(PyUnicode_CheckExact(op));
14476
101M
    unicode_dealloc(op);
14477
101M
}
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.6k
{
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.6k
    assert(s != NULL);
14623
42.6k
    assert(_PyUnicode_CHECK(s));
14624
42.6k
    assert(_PyUnicode_STATE(s).statically_allocated);
14625
42.6k
    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.6k
    PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14637
    /* We should only init each string once */
14638
42.6k
    assert(r == NULL);
14639
    /* but just in case (for the non-debug build), handle this */
14640
42.6k
    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.6k
    if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < 0) {
14648
0
        Py_FatalError("failed to intern static string");
14649
0
    }
14650
14651
42.6k
    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
14652
42.6k
    return s;
14653
42.6k
}
14654
14655
void
14656
_PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
14657
42.6k
{
14658
    // This should only be called as part of runtime initialization
14659
42.6k
    assert(!Py_IsInitialized());
14660
14661
42.6k
    *p = intern_static(interp, *p);
14662
42.6k
    assert(*p);
14663
42.6k
}
14664
14665
static void
14666
immortalize_interned(PyObject *s)
14667
276k
{
14668
276k
    assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
14669
276k
    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
276k
    _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
276k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_IMMORTAL);
14683
276k
}
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
94.7M
{
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
94.7M
    if (s == NULL || !PyUnicode_Check(s)) {
14709
0
        return s;
14710
0
    }
14711
94.7M
#endif
14712
14713
    /* If it's a subclass, we don't really know what putting
14714
       it in the interned dict might do. */
14715
94.7M
    if (!PyUnicode_CheckExact(s)) {
14716
0
        return s;
14717
0
    }
14718
14719
    /* Is it already interned? */
14720
94.7M
    switch (PyUnicode_CHECK_INTERNED(s)) {
14721
7.08M
        case SSTATE_NOT_INTERNED:
14722
            // no, go on
14723
7.08M
            break;
14724
23.6k
        case SSTATE_INTERNED_MORTAL:
14725
23.6k
#ifndef Py_GIL_DISABLED
14726
            // yes but we might need to make it immortal
14727
23.6k
            if (immortalize) {
14728
2.08k
                immortalize_interned(s);
14729
2.08k
            }
14730
23.6k
            return s;
14731
#else
14732
            // not fully interned yet; fall through to the locking path
14733
            break;
14734
#endif
14735
87.5M
        default:
14736
            // all done
14737
87.5M
            return s;
14738
94.7M
    }
14739
14740
    /* Statically allocated strings must be already interned. */
14741
94.7M
    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
7.08M
    if (_Py_IsImmortal(s)) {
14750
0
        immortalize = 1;
14751
0
    }
14752
14753
    /* if it's a short string, get the singleton */
14754
7.08M
    if (PyUnicode_GET_LENGTH(s) == 1 &&
14755
4.13k
                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
7.08M
    {
14767
7.08M
        PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14768
7.08M
        if (r != NULL) {
14769
357k
            assert(_PyUnicode_STATE(r).statically_allocated);
14770
357k
            assert(r != s);  // r must be statically_allocated; s is not
14771
357k
            Py_DECREF(s);
14772
357k
            return Py_NewRef(r);
14773
357k
        }
14774
7.08M
    }
14775
14776
    /* Do a setdefault on the per-interpreter cache. */
14777
6.72M
    PyObject *interned = get_interned_dict(interp);
14778
6.72M
    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.72M
    FT_MUTEX_LOCK_FLAGS(INTERN_MUTEX, _Py_LOCK_DONT_DETACH);
14826
6.72M
    PyObject *t;
14827
6.72M
    {
14828
6.72M
        int res = PyDict_SetDefaultRef(interned, s, s, &t);
14829
6.72M
        if (res < 0) {
14830
0
            PyErr_Clear();
14831
0
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14832
0
            return s;
14833
0
        }
14834
6.72M
        else if (res == 1) {
14835
            // value was already present (not inserted)
14836
5.96M
            Py_DECREF(s);
14837
5.96M
            if (immortalize &&
14838
550k
                    PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
14839
9.39k
                immortalize_interned(t);
14840
9.39k
            }
14841
5.96M
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14842
5.96M
            return t;
14843
5.96M
        }
14844
757k
        else {
14845
            // value was newly inserted
14846
757k
            assert (s == t);
14847
757k
            Py_DECREF(t);
14848
757k
        }
14849
6.72M
    }
14850
14851
    /* NOT_INTERNED -> INTERNED_MORTAL */
14852
14853
6.72M
    assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
14854
14855
757k
    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
757k
        Py_DECREF(s);
14859
757k
        Py_DECREF(s);
14860
757k
    }
14861
757k
    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
757k
    if (immortalize) {
14871
265k
        immortalize_interned(s);
14872
265k
    }
14873
14874
757k
    FT_MUTEX_UNLOCK(INTERN_MUTEX);
14875
757k
    return s;
14876
6.72M
}
14877
14878
void
14879
_PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
14880
2.83M
{
14881
2.83M
    *p = intern_common(interp, *p, 1);
14882
2.83M
    assert(*p);
14883
2.83M
}
14884
14885
void
14886
_PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
14887
91.8M
{
14888
91.8M
    *p = intern_common(interp, *p, 0);
14889
91.8M
    assert(*p);
14890
91.8M
}
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.07M
{
14919
1.07M
    PyObject *s = PyUnicode_FromString(cp);
14920
1.07M
    if (s == NULL) {
14921
0
        return NULL;
14922
0
    }
14923
1.07M
    PyInterpreterState *interp = _PyInterpreterState_GET();
14924
1.07M
    _PyUnicode_InternMortal(interp, &s);
14925
1.07M
    return s;
14926
1.07M
}
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
3.14M
{
15029
3.14M
    unicodeiterobject *it = (unicodeiterobject *)op;
15030
3.14M
    _PyObject_GC_UNTRACK(it);
15031
3.14M
    Py_XDECREF(it->it_seq);
15032
3.14M
    PyObject_GC_Del(it);
15033
3.14M
}
15034
15035
static int
15036
unicodeiter_traverse(PyObject *op, visitproc visit, void *arg)
15037
14
{
15038
14
    unicodeiterobject *it = (unicodeiterobject *)op;
15039
14
    Py_VISIT(it->it_seq);
15040
14
    return 0;
15041
14
}
15042
15043
static PyObject *
15044
unicodeiter_next(PyObject *op)
15045
214M
{
15046
214M
    unicodeiterobject *it = (unicodeiterobject *)op;
15047
214M
    PyObject *seq;
15048
15049
214M
    assert(it != NULL);
15050
214M
    seq = it->it_seq;
15051
214M
    if (seq == NULL)
15052
0
        return NULL;
15053
214M
    assert(_PyUnicode_CHECK(seq));
15054
15055
214M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15056
213M
        int kind = PyUnicode_KIND(seq);
15057
213M
        const void *data = PyUnicode_DATA(seq);
15058
213M
        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15059
213M
        it->it_index++;
15060
213M
        return unicode_char(chr);
15061
213M
    }
15062
15063
1.78M
    it->it_seq = NULL;
15064
1.78M
    Py_DECREF(seq);
15065
1.78M
    return NULL;
15066
214M
}
15067
15068
static PyObject *
15069
unicode_ascii_iter_next(PyObject *op)
15070
12.5M
{
15071
12.5M
    unicodeiterobject *it = (unicodeiterobject *)op;
15072
12.5M
    assert(it != NULL);
15073
12.5M
    PyObject *seq = it->it_seq;
15074
12.5M
    if (seq == NULL) {
15075
0
        return NULL;
15076
0
    }
15077
12.5M
    assert(_PyUnicode_CHECK(seq));
15078
12.5M
    assert(PyUnicode_IS_COMPACT_ASCII(seq));
15079
12.5M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15080
11.2M
        const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
15081
11.2M
        Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
15082
11.2M
                                              data, it->it_index);
15083
11.2M
        it->it_index++;
15084
11.2M
        return (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
15085
11.2M
    }
15086
1.34M
    it->it_seq = NULL;
15087
1.34M
    Py_DECREF(seq);
15088
1.34M
    return NULL;
15089
12.5M
}
15090
15091
static PyObject *
15092
unicodeiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
15093
1.55M
{
15094
1.55M
    unicodeiterobject *it = (unicodeiterobject *)op;
15095
1.55M
    Py_ssize_t len = 0;
15096
1.55M
    if (it->it_seq)
15097
1.55M
        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
15098
1.55M
    return PyLong_FromSsize_t(len);
15099
1.55M
}
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
3.14M
{
15202
3.14M
    unicodeiterobject *it;
15203
15204
3.14M
    if (!PyUnicode_Check(seq)) {
15205
0
        PyErr_BadInternalCall();
15206
0
        return NULL;
15207
0
    }
15208
3.14M
    if (PyUnicode_IS_COMPACT_ASCII(seq)) {
15209
1.35M
        it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
15210
1.35M
    }
15211
1.78M
    else {
15212
1.78M
        it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15213
1.78M
    }
15214
3.14M
    if (it == NULL)
15215
0
        return NULL;
15216
3.14M
    it->it_index = 0;
15217
3.14M
    it->it_seq = Py_NewRef(seq);
15218
3.14M
    _PyObject_GC_TRACK(it);
15219
3.14M
    return (PyObject *)it;
15220
3.14M
}
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
}