Coverage Report

Created: 2026-12-01 06:09

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
33.8M
#define MAX_UNICODE _Py_MAX_UNICODE
109
275M
#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
189M
{
119
189M
    assert(_PyUnicode_CHECK(op));
120
189M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
121
172M
        return ((char*)(_PyASCIIObject_CAST(op) + 1));
122
172M
    }
123
16.2M
    else {
124
16.2M
         return _PyUnicode_UTF8(op);
125
16.2M
    }
126
189M
}
127
128
static inline void PyUnicode_SET_UTF8(PyObject *op, char *utf8)
129
42.4M
{
130
42.4M
    FT_ATOMIC_STORE_PTR_RELEASE(_PyCompactUnicodeObject_CAST(op)->utf8, utf8);
131
42.4M
}
132
133
static inline Py_ssize_t PyUnicode_UTF8_LENGTH(PyObject *op)
134
89.5M
{
135
89.5M
    assert(_PyUnicode_CHECK(op));
136
89.5M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
137
86.2M
         return _PyASCIIObject_CAST(op)->length;
138
86.2M
    }
139
3.23M
    else {
140
3.23M
         return _PyCompactUnicodeObject_CAST(op)->utf8_length;
141
3.23M
    }
142
89.5M
}
143
144
static inline void PyUnicode_SET_UTF8_LENGTH(PyObject *op, Py_ssize_t length)
145
42.4M
{
146
42.4M
    _PyCompactUnicodeObject_CAST(op)->utf8_length = length;
147
42.4M
}
148
149
#define _PyUnicode_LENGTH(op)                           \
150
710M
    (_PyASCIIObject_CAST(op)->length)
151
#define _PyUnicode_STATE(op)                            \
152
4.58G
    (_PyASCIIObject_CAST(op)->state)
153
#define _PyUnicode_HASH(op)                             \
154
675M
    (_PyASCIIObject_CAST(op)->hash)
155
156
978M
#define PyUnicode_HASH PyUnstable_Unicode_GET_CACHED_HASH
157
158
static inline void PyUnicode_SET_HASH(PyObject *op, Py_hash_t hash)
159
57.4M
{
160
57.4M
    FT_ATOMIC_STORE_SSIZE_RELAXED(_PyASCIIObject_CAST(op)->hash, hash);
161
57.4M
}
162
163
#define _PyUnicode_DATA_ANY(op)                         \
164
91.2M
    (_PyUnicodeObject_CAST(op)->data.any)
165
166
static inline int _PyUnicode_SHARE_UTF8(PyObject *op)
167
0
{
168
0
    assert(_PyUnicode_CHECK(op));
169
0
    assert(!PyUnicode_IS_COMPACT_ASCII(op));
170
0
    return (_PyUnicode_UTF8(op) == PyUnicode_DATA(op));
171
0
}
172
173
174
370M
#define LATIN1 _Py_LATIN1_CHR
175
176
/* Forward declaration */
177
static PyObject *
178
unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
179
                    const char *errors);
180
static PyObject *
181
unicode_decode_utf8(const char *s, Py_ssize_t size,
182
                    _Py_error_handler error_handler, const char *errors,
183
                    Py_ssize_t *consumed);
184
#ifdef Py_DEBUG
185
static inline int unicode_is_finalizing(void);
186
static int unicode_is_singleton(PyObject *unicode);
187
#endif
188
189
190
// Return a reference to the immortal empty string singleton.
191
PyObject*
192
_PyUnicode_GetEmpty(void)
193
175M
{
194
175M
    _Py_DECLARE_STR(empty, "");
195
175M
    return &_Py_STR(empty);
196
175M
}
197
198
/* This dictionary holds per-interpreter interned strings.
199
 * See InternalDocs/string_interning.md for details.
200
 */
201
static inline PyObject *get_interned_dict(PyInterpreterState *interp)
202
7.18M
{
203
7.18M
    return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
204
7.18M
}
205
206
/* This hashtable holds statically allocated interned strings.
207
 * See InternalDocs/string_interning.md for details.
208
 */
209
7.35M
#define INTERNED_STRINGS _PyRuntime.cached_objects.interned_strings
210
211
/* Get number of all interned strings for the current interpreter. */
212
Py_ssize_t
213
_PyUnicode_InternedSize(void)
214
0
{
215
0
    PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
216
0
    return _Py_hashtable_len(INTERNED_STRINGS) + PyDict_GET_SIZE(dict);
217
0
}
218
219
/* Get number of immortal interned strings for the current interpreter. */
220
Py_ssize_t
221
_PyUnicode_InternedSize_Immortal(void)
222
0
{
223
0
    PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
224
0
    PyObject *key, *value;
225
0
    Py_ssize_t pos = 0;
226
0
    Py_ssize_t count = 0;
227
228
    // It's tempting to keep a count and avoid a loop here. But, this function
229
    // is intended for refleak tests. It spends extra work to report the true
230
    // value, to help detect bugs in optimizations.
231
232
0
    while (PyDict_Next(dict, &pos, &key, &value)) {
233
0
        assert(PyUnicode_CHECK_INTERNED(key) != SSTATE_INTERNED_IMMORTAL_STATIC);
234
0
        if (PyUnicode_CHECK_INTERNED(key) == SSTATE_INTERNED_IMMORTAL) {
235
0
           count++;
236
0
       }
237
0
    }
238
0
    return _Py_hashtable_len(INTERNED_STRINGS) + count;
239
0
}
240
241
static Py_hash_t unicode_hash(PyObject *);
242
243
static Py_uhash_t
244
hashtable_unicode_hash(const void *key)
245
7.35M
{
246
7.35M
    return unicode_hash((PyObject *)key);
247
7.35M
}
248
249
static int
250
hashtable_unicode_compare(const void *key1, const void *key2)
251
244k
{
252
244k
    PyObject *obj1 = (PyObject *)key1;
253
244k
    PyObject *obj2 = (PyObject *)key2;
254
244k
    if (obj1 != NULL && obj2 != NULL) {
255
244k
        return unicode_eq(obj1, obj2);
256
244k
    }
257
0
    else {
258
0
        return obj1 == obj2;
259
0
    }
260
244k
}
261
262
/* Return true if this interpreter should share the main interpreter's
263
   intern_dict.  That's important for interpreters which load basic
264
   single-phase init extension modules (m_size == -1).  There could be interned
265
   immortal strings that are shared between interpreters, due to the
266
   PyDict_Update(mdict, m_copy) call in import_find_extension().
267
268
   It's not safe to deallocate those strings until all interpreters that
269
   potentially use them are freed.  By storing them in the main interpreter, we
270
   ensure they get freed after all other interpreters are freed.
271
*/
272
static bool
273
has_shared_intern_dict(PyInterpreterState *interp)
274
37
{
275
37
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
276
37
    return interp != main_interp  && interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC;
277
37
}
278
279
static int
280
init_interned_dict(PyInterpreterState *interp)
281
37
{
282
37
    assert(get_interned_dict(interp) == NULL);
283
37
    PyObject *interned;
284
37
    if (has_shared_intern_dict(interp)) {
285
0
        interned = get_interned_dict(_PyInterpreterState_Main());
286
0
        Py_INCREF(interned);
287
0
    }
288
37
    else {
289
37
        interned = PyDict_New();
290
37
        if (interned == NULL) {
291
0
            return -1;
292
0
        }
293
37
    }
294
37
    _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
295
37
    return 0;
296
37
}
297
298
static void
299
clear_interned_dict(PyInterpreterState *interp)
300
0
{
301
0
    PyObject *interned = get_interned_dict(interp);
302
0
    if (interned != NULL) {
303
0
        if (!has_shared_intern_dict(interp)) {
304
            // only clear if the dict belongs to this interpreter
305
0
            PyDict_Clear(interned);
306
0
        }
307
0
        Py_DECREF(interned);
308
0
        _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = NULL;
309
0
    }
310
0
}
311
312
static PyStatus
313
init_global_interned_strings(PyInterpreterState *interp)
314
37
{
315
37
    assert(INTERNED_STRINGS == NULL);
316
37
    _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
317
318
37
    INTERNED_STRINGS = _Py_hashtable_new_full(
319
37
        hashtable_unicode_hash,
320
37
        hashtable_unicode_compare,
321
        // Objects stored here are immortal and statically allocated,
322
        // so we don't need key_destroy_func & value_destroy_func:
323
37
        NULL,
324
37
        NULL,
325
37
        &hashtable_alloc
326
37
    );
327
37
    if (INTERNED_STRINGS == NULL) {
328
0
        PyErr_Clear();
329
0
        return _PyStatus_ERR("failed to create global interned dict");
330
0
    }
331
332
    /* Intern statically allocated string identifiers, deepfreeze strings,
333
        * and one-byte latin-1 strings.
334
        * This must be done before any module initialization so that statically
335
        * allocated string identifiers are used instead of heap allocated strings.
336
        * Deepfreeze uses the interned identifiers if present to save space
337
        * else generates them and they are interned to speed up dict lookups.
338
    */
339
37
    _PyUnicode_InitStaticStrings(interp);
340
341
9.50k
    for (int i = 0; i < 256; i++) {
342
9.47k
        PyObject *s = LATIN1(i);
343
9.47k
        _PyUnicode_InternStatic(interp, &s);
344
9.47k
        assert(s == LATIN1(i));
345
9.47k
    }
346
#ifdef Py_DEBUG
347
    assert(_PyUnicode_CheckConsistency(&_Py_STR(empty), 1));
348
349
    for (int i = 0; i < 256; i++) {
350
        assert(_PyUnicode_CheckConsistency(LATIN1(i), 1));
351
    }
352
#endif
353
37
    return _PyStatus_OK();
354
37
}
355
356
static void clear_global_interned_strings(void)
357
0
{
358
0
    if (INTERNED_STRINGS != NULL) {
359
0
        _Py_hashtable_destroy(INTERNED_STRINGS);
360
0
        INTERNED_STRINGS = NULL;
361
0
    }
362
0
}
363
364
#define _Py_RETURN_UNICODE_EMPTY()   \
365
92.7M
    do {                             \
366
92.7M
        return _PyUnicode_GetEmpty();\
367
92.7M
    } while (0)
368
369
370
/* Fast detection of the most frequent whitespace characters */
371
const unsigned char _Py_ascii_whitespace[] = {
372
    0, 0, 0, 0, 0, 0, 0, 0,
373
/*     case 0x0009: * CHARACTER TABULATION */
374
/*     case 0x000A: * LINE FEED */
375
/*     case 0x000B: * LINE TABULATION */
376
/*     case 0x000C: * FORM FEED */
377
/*     case 0x000D: * CARRIAGE RETURN */
378
    0, 1, 1, 1, 1, 1, 0, 0,
379
    0, 0, 0, 0, 0, 0, 0, 0,
380
/*     case 0x001C: * FILE SEPARATOR */
381
/*     case 0x001D: * GROUP SEPARATOR */
382
/*     case 0x001E: * RECORD SEPARATOR */
383
/*     case 0x001F: * UNIT SEPARATOR */
384
    0, 0, 0, 0, 1, 1, 1, 1,
385
/*     case 0x0020: * SPACE */
386
    1, 0, 0, 0, 0, 0, 0, 0,
387
    0, 0, 0, 0, 0, 0, 0, 0,
388
    0, 0, 0, 0, 0, 0, 0, 0,
389
    0, 0, 0, 0, 0, 0, 0, 0,
390
391
    0, 0, 0, 0, 0, 0, 0, 0,
392
    0, 0, 0, 0, 0, 0, 0, 0,
393
    0, 0, 0, 0, 0, 0, 0, 0,
394
    0, 0, 0, 0, 0, 0, 0, 0,
395
    0, 0, 0, 0, 0, 0, 0, 0,
396
    0, 0, 0, 0, 0, 0, 0, 0,
397
    0, 0, 0, 0, 0, 0, 0, 0,
398
    0, 0, 0, 0, 0, 0, 0, 0
399
};
400
401
/* forward */
402
static PyObject* get_latin1_char(unsigned char ch);
403
404
405
static PyObject *
406
_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
407
static PyObject *
408
_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
409
static PyObject *
410
_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
411
412
static PyObject *
413
unicode_encode_call_errorhandler(const char *errors,
414
       PyObject **errorHandler,const char *encoding, const char *reason,
415
       PyObject *unicode, PyObject **exceptionObject,
416
       Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
417
418
static void
419
raise_encode_exception(PyObject **exceptionObject,
420
                       const char *encoding,
421
                       PyObject *unicode,
422
                       Py_ssize_t startpos, Py_ssize_t endpos,
423
                       const char *reason);
424
425
/* Same for linebreaks */
426
static const unsigned char ascii_linebreak[] = {
427
    0, 0, 0, 0, 0, 0, 0, 0,
428
/*         0x000A, * LINE FEED */
429
/*         0x000B, * LINE TABULATION */
430
/*         0x000C, * FORM FEED */
431
/*         0x000D, * CARRIAGE RETURN */
432
    0, 0, 1, 1, 1, 1, 0, 0,
433
    0, 0, 0, 0, 0, 0, 0, 0,
434
/*         0x001C, * FILE SEPARATOR */
435
/*         0x001D, * GROUP SEPARATOR */
436
/*         0x001E, * RECORD SEPARATOR */
437
    0, 0, 0, 0, 1, 1, 1, 0,
438
    0, 0, 0, 0, 0, 0, 0, 0,
439
    0, 0, 0, 0, 0, 0, 0, 0,
440
    0, 0, 0, 0, 0, 0, 0, 0,
441
    0, 0, 0, 0, 0, 0, 0, 0,
442
443
    0, 0, 0, 0, 0, 0, 0, 0,
444
    0, 0, 0, 0, 0, 0, 0, 0,
445
    0, 0, 0, 0, 0, 0, 0, 0,
446
    0, 0, 0, 0, 0, 0, 0, 0,
447
    0, 0, 0, 0, 0, 0, 0, 0,
448
    0, 0, 0, 0, 0, 0, 0, 0,
449
    0, 0, 0, 0, 0, 0, 0, 0,
450
    0, 0, 0, 0, 0, 0, 0, 0
451
};
452
453
static int convert_uc(PyObject *obj, void *addr);
454
455
struct encoding_map;
456
#include "clinic/unicodeobject.c.h"
457
458
_Py_error_handler
459
_Py_GetErrorHandler(const char *errors)
460
5.95M
{
461
5.95M
    if (errors == NULL || strcmp(errors, "strict") == 0) {
462
5.27M
        return _Py_ERROR_STRICT;
463
5.27M
    }
464
682k
    if (strcmp(errors, "surrogateescape") == 0) {
465
455k
        return _Py_ERROR_SURROGATEESCAPE;
466
455k
    }
467
227k
    if (strcmp(errors, "replace") == 0) {
468
227k
        return _Py_ERROR_REPLACE;
469
227k
    }
470
4
    if (strcmp(errors, "ignore") == 0) {
471
0
        return _Py_ERROR_IGNORE;
472
0
    }
473
4
    if (strcmp(errors, "backslashreplace") == 0) {
474
0
        return _Py_ERROR_BACKSLASHREPLACE;
475
0
    }
476
4
    if (strcmp(errors, "surrogatepass") == 0) {
477
4
        return _Py_ERROR_SURROGATEPASS;
478
4
    }
479
0
    if (strcmp(errors, "xmlcharrefreplace") == 0) {
480
0
        return _Py_ERROR_XMLCHARREFREPLACE;
481
0
    }
482
0
    return _Py_ERROR_OTHER;
483
0
}
484
485
486
static _Py_error_handler
487
get_error_handler_wide(const wchar_t *errors)
488
13.5k
{
489
13.5k
    if (errors == NULL || wcscmp(errors, L"strict") == 0) {
490
0
        return _Py_ERROR_STRICT;
491
0
    }
492
13.5k
    if (wcscmp(errors, L"surrogateescape") == 0) {
493
13.5k
        return _Py_ERROR_SURROGATEESCAPE;
494
13.5k
    }
495
0
    if (wcscmp(errors, L"replace") == 0) {
496
0
        return _Py_ERROR_REPLACE;
497
0
    }
498
0
    if (wcscmp(errors, L"ignore") == 0) {
499
0
        return _Py_ERROR_IGNORE;
500
0
    }
501
0
    if (wcscmp(errors, L"backslashreplace") == 0) {
502
0
        return _Py_ERROR_BACKSLASHREPLACE;
503
0
    }
504
0
    if (wcscmp(errors, L"surrogatepass") == 0) {
505
0
        return _Py_ERROR_SURROGATEPASS;
506
0
    }
507
0
    if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
508
0
        return _Py_ERROR_XMLCHARREFREPLACE;
509
0
    }
510
0
    return _Py_ERROR_OTHER;
511
0
}
512
513
514
static inline int
515
unicode_check_encoding_errors(const char *encoding, const char *errors)
516
63.7M
{
517
63.7M
    if (encoding == NULL && errors == NULL) {
518
13.6M
        return 0;
519
13.6M
    }
520
521
50.1M
    PyInterpreterState *interp = _PyInterpreterState_GET();
522
50.1M
#ifndef Py_DEBUG
523
    /* In release mode, only check in development mode (-X dev) */
524
50.1M
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
525
50.1M
        return 0;
526
50.1M
    }
527
#else
528
    /* Always check in debug mode */
529
#endif
530
531
    /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
532
       codec registry is ready: before_PyUnicode_InitEncodings() is called. */
533
0
    if (!interp->unicode.fs_codec.encoding) {
534
0
        return 0;
535
0
    }
536
537
    /* Disable checks during Python finalization. For example, it allows to
538
     * call PyObject_Dump() during finalization for debugging purpose.
539
     */
540
0
    if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
541
0
        return 0;
542
0
    }
543
544
0
    if (encoding != NULL
545
        // Fast path for the most common built-in encodings. Even if the codec
546
        // is cached, _PyCodec_Lookup() decodes the bytes string from UTF-8 to
547
        // create a temporary Unicode string (the key in the cache).
548
0
        && strcmp(encoding, "utf-8") != 0
549
0
        && strcmp(encoding, "utf8") != 0
550
0
        && strcmp(encoding, "ascii") != 0)
551
0
    {
552
0
        PyObject *handler = _PyCodec_Lookup(encoding);
553
0
        if (handler == NULL) {
554
0
            return -1;
555
0
        }
556
0
        Py_DECREF(handler);
557
0
    }
558
559
0
    if (errors != NULL
560
        // Fast path for the most common built-in error handlers.
561
0
        && strcmp(errors, "strict") != 0
562
0
        && strcmp(errors, "ignore") != 0
563
0
        && strcmp(errors, "replace") != 0
564
0
        && strcmp(errors, "surrogateescape") != 0
565
0
        && strcmp(errors, "surrogatepass") != 0)
566
0
    {
567
0
        PyObject *handler = PyCodec_LookupError(errors);
568
0
        if (handler == NULL) {
569
0
            return -1;
570
0
        }
571
0
        Py_DECREF(handler);
572
0
    }
573
0
    return 0;
574
0
}
575
576
577
int
578
_PyUnicode_CheckConsistency(PyObject *op, int check_content)
579
0
{
580
0
#define CHECK(expr) \
581
0
    do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
582
#ifdef Py_GIL_DISABLED
583
# define CHECK_IF_GIL(expr) (void)(expr)
584
# define CHECK_IF_FT(expr) CHECK(expr)
585
#else
586
0
# define CHECK_IF_GIL(expr) CHECK(expr)
587
0
# define CHECK_IF_FT(expr) (void)(expr)
588
0
#endif
589
590
0
    assert(op != NULL);
591
0
    CHECK(PyUnicode_Check(op));
592
593
0
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
594
0
    int kind = ascii->state.kind;
595
596
0
    if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
597
0
        CHECK(kind == PyUnicode_1BYTE_KIND);
598
0
    }
599
0
    else {
600
0
        PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
601
0
        void *data;
602
603
0
        if (ascii->state.compact == 1) {
604
0
            data = compact + 1;
605
0
            CHECK(kind == PyUnicode_1BYTE_KIND
606
0
                                 || kind == PyUnicode_2BYTE_KIND
607
0
                                 || kind == PyUnicode_4BYTE_KIND);
608
0
            CHECK(ascii->state.ascii == 0);
609
0
            CHECK(_PyUnicode_UTF8(op) != data);
610
0
        }
611
0
        else {
612
0
            PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
613
614
0
            data = unicode->data.any;
615
0
            CHECK(kind == PyUnicode_1BYTE_KIND
616
0
                     || kind == PyUnicode_2BYTE_KIND
617
0
                     || kind == PyUnicode_4BYTE_KIND);
618
0
            CHECK(ascii->state.compact == 0);
619
0
            CHECK(data != NULL);
620
0
            if (ascii->state.ascii) {
621
0
                CHECK(_PyUnicode_UTF8(op) == data);
622
0
                CHECK(compact->utf8_length == ascii->length);
623
0
            }
624
0
            else {
625
0
                CHECK(_PyUnicode_UTF8(op) != data);
626
0
            }
627
0
        }
628
0
#ifndef Py_GIL_DISABLED
629
0
        if (_PyUnicode_UTF8(op) == NULL)
630
0
            CHECK(compact->utf8_length == 0);
631
0
#endif
632
0
    }
633
634
    /* check that the best kind is used: O(n) operation */
635
0
    const void *data = PyUnicode_DATA(ascii);
636
0
    if (check_content) {
637
0
        Py_ssize_t i;
638
0
        Py_UCS4 maxchar = 0;
639
0
        Py_UCS4 ch;
640
641
0
        for (i=0; i < ascii->length; i++)
642
0
        {
643
0
            ch = PyUnicode_READ(kind, data, i);
644
0
            if (ch > maxchar)
645
0
                maxchar = ch;
646
0
        }
647
0
        if (kind == PyUnicode_1BYTE_KIND) {
648
0
            if (ascii->state.ascii == 0) {
649
0
                CHECK(maxchar >= 128);
650
0
                CHECK(maxchar <= 255);
651
0
            }
652
0
            else
653
0
                CHECK(maxchar < 128);
654
0
        }
655
0
        else if (kind == PyUnicode_2BYTE_KIND) {
656
0
            CHECK(maxchar >= 0x100);
657
0
            CHECK(maxchar <= 0xFFFF);
658
0
        }
659
0
        else {
660
0
            CHECK(maxchar >= 0x10000);
661
0
            CHECK(maxchar <= MAX_UNICODE);
662
0
        }
663
0
    }
664
665
    // Detect buffer overflow: check if the trailing null character
666
    // has been overridden
667
0
    CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
668
669
    /* Check interning state */
670
#ifdef Py_DEBUG
671
    // Note that we do not check `_Py_IsImmortal(op)` in the GIL-enabled build
672
    // since stable ABI extensions can make immortal strings mortal (but with a
673
    // high enough refcount).
674
    switch (PyUnicode_CHECK_INTERNED(op)) {
675
        case SSTATE_NOT_INTERNED:
676
            if (ascii->state.statically_allocated) {
677
                // This state is for two exceptions:
678
                // - strings are currently checked before they're interned
679
                // - the 256 one-latin1-character strings
680
                //   are static but use SSTATE_NOT_INTERNED
681
            }
682
            else {
683
                CHECK_IF_GIL(!_Py_IsImmortal(op));
684
            }
685
            break;
686
        case SSTATE_INTERNED_MORTAL:
687
            CHECK(!ascii->state.statically_allocated);
688
            CHECK_IF_GIL(!_Py_IsImmortal(op));
689
            break;
690
        case SSTATE_INTERNED_IMMORTAL:
691
            CHECK(!ascii->state.statically_allocated);
692
            CHECK_IF_FT(_Py_IsImmortal(op));
693
            break;
694
        case SSTATE_INTERNED_IMMORTAL_STATIC:
695
            CHECK(ascii->state.statically_allocated);
696
            CHECK_IF_FT(_Py_IsImmortal(op));
697
            break;
698
        default:
699
            Py_UNREACHABLE();
700
    }
701
#endif
702
703
0
    return 1;
704
705
0
#undef CHECK
706
0
}
707
708
PyObject*
709
_PyUnicode_Result(PyObject *unicode)
710
3.04M
{
711
3.04M
    assert(_PyUnicode_CHECK(unicode));
712
713
3.04M
    Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
714
3.04M
    if (length == 0) {
715
305
        PyObject *empty = _PyUnicode_GetEmpty();
716
305
        if (unicode != empty) {
717
0
            Py_DECREF(unicode);
718
0
        }
719
305
        return empty;
720
305
    }
721
722
3.04M
    if (length == 1) {
723
1.09M
        int kind = PyUnicode_KIND(unicode);
724
1.09M
        if (kind == PyUnicode_1BYTE_KIND) {
725
60.1k
            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
726
60.1k
            Py_UCS1 ch = data[0];
727
60.1k
            PyObject *latin1_char = LATIN1(ch);
728
60.1k
            if (unicode != latin1_char) {
729
0
                Py_DECREF(unicode);
730
0
            }
731
60.1k
            return latin1_char;
732
60.1k
        }
733
1.09M
    }
734
735
3.04M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
736
2.98M
    return unicode;
737
3.04M
}
738
3.04M
#define unicode_result _PyUnicode_Result
739
740
static PyObject*
741
unicode_result_unchanged(PyObject *unicode)
742
116M
{
743
116M
    if (PyUnicode_CheckExact(unicode)) {
744
112M
        return Py_NewRef(unicode);
745
112M
    }
746
3.30M
    else
747
        /* Subtype -- return genuine unicode string with the same value. */
748
3.30M
        return _PyUnicode_Copy(unicode);
749
116M
}
750
751
/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
752
   ASCII, Latin1, UTF-8, etc. */
753
static char*
754
backslashreplace(PyBytesWriter *writer, char *str,
755
                 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
756
0
{
757
0
    Py_ssize_t size, i;
758
0
    Py_UCS4 ch;
759
0
    int kind;
760
0
    const void *data;
761
762
0
    kind = PyUnicode_KIND(unicode);
763
0
    data = PyUnicode_DATA(unicode);
764
765
0
    size = 0;
766
    /* determine replacement size */
767
0
    for (i = collstart; i < collend; ++i) {
768
0
        Py_ssize_t incr;
769
770
0
        ch = PyUnicode_READ(kind, data, i);
771
0
        if (ch < 0x100)
772
0
            incr = 2+2;
773
0
        else if (ch < 0x10000)
774
0
            incr = 2+4;
775
0
        else {
776
0
            assert(ch <= MAX_UNICODE);
777
0
            incr = 2+8;
778
0
        }
779
0
        if (size > PY_SSIZE_T_MAX - incr) {
780
0
            PyErr_SetString(PyExc_OverflowError,
781
0
                            "encoded result is too long for a Python string");
782
0
            return NULL;
783
0
        }
784
0
        size += incr;
785
0
    }
786
    /* subtract preallocated bytes */
787
0
    size -= (collend - collstart);
788
789
0
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
790
0
    if (str == NULL) {
791
0
        return NULL;
792
0
    }
793
794
    /* generate replacement */
795
0
    for (i = collstart; i < collend; ++i) {
796
0
        ch = PyUnicode_READ(kind, data, i);
797
0
        *str++ = '\\';
798
0
        if (ch >= 0x00010000) {
799
0
            *str++ = 'U';
800
0
            *str++ = Py_hexdigits[(ch>>28)&0xf];
801
0
            *str++ = Py_hexdigits[(ch>>24)&0xf];
802
0
            *str++ = Py_hexdigits[(ch>>20)&0xf];
803
0
            *str++ = Py_hexdigits[(ch>>16)&0xf];
804
0
            *str++ = Py_hexdigits[(ch>>12)&0xf];
805
0
            *str++ = Py_hexdigits[(ch>>8)&0xf];
806
0
        }
807
0
        else if (ch >= 0x100) {
808
0
            *str++ = 'u';
809
0
            *str++ = Py_hexdigits[(ch>>12)&0xf];
810
0
            *str++ = Py_hexdigits[(ch>>8)&0xf];
811
0
        }
812
0
        else
813
0
            *str++ = 'x';
814
0
        *str++ = Py_hexdigits[(ch>>4)&0xf];
815
0
        *str++ = Py_hexdigits[ch&0xf];
816
0
    }
817
0
    return str;
818
0
}
819
820
/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
821
   ASCII, Latin1, UTF-8, etc. */
822
static char*
823
xmlcharrefreplace(PyBytesWriter *writer, char *str,
824
                  PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
825
0
{
826
0
    Py_ssize_t size, i;
827
0
    Py_UCS4 ch;
828
0
    int kind;
829
0
    const void *data;
830
831
0
    kind = PyUnicode_KIND(unicode);
832
0
    data = PyUnicode_DATA(unicode);
833
834
0
    size = 0;
835
    /* determine replacement size */
836
0
    for (i = collstart; i < collend; ++i) {
837
0
        Py_ssize_t incr;
838
839
0
        ch = PyUnicode_READ(kind, data, i);
840
0
        if (ch < 10)
841
0
            incr = 2+1+1;
842
0
        else if (ch < 100)
843
0
            incr = 2+2+1;
844
0
        else if (ch < 1000)
845
0
            incr = 2+3+1;
846
0
        else if (ch < 10000)
847
0
            incr = 2+4+1;
848
0
        else if (ch < 100000)
849
0
            incr = 2+5+1;
850
0
        else if (ch < 1000000)
851
0
            incr = 2+6+1;
852
0
        else {
853
0
            assert(ch <= MAX_UNICODE);
854
0
            incr = 2+7+1;
855
0
        }
856
0
        if (size > PY_SSIZE_T_MAX - incr) {
857
0
            PyErr_SetString(PyExc_OverflowError,
858
0
                            "encoded result is too long for a Python string");
859
0
            return NULL;
860
0
        }
861
0
        size += incr;
862
0
    }
863
    /* subtract preallocated bytes */
864
0
    size -= (collend - collstart);
865
866
0
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
867
0
    if (str == NULL) {
868
0
        return NULL;
869
0
    }
870
871
    /* generate replacement */
872
0
    for (i = collstart; i < collend; ++i) {
873
        // Use snprintf() with a temporary buffer to not write the trailing
874
        // NUL byte in the writer buffer.
875
0
        Py_BUILD_ASSERT(_Py_MAX_UNICODE <= 0x10ffff);
876
        // len('&#1114111;\0') is 11 bytes.
877
0
        char buffer[11];
878
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
879
0
        size = snprintf(buffer, sizeof(buffer), "&#%d;", ch);
880
0
        assert(4 <= size && (size_t)size <= (sizeof(buffer) - 1));
881
882
0
        memcpy(str, buffer, size);
883
0
        str += size;
884
0
    }
885
0
    return str;
886
0
}
887
888
/* --- Bloom Filters ----------------------------------------------------- */
889
890
/* stuff to implement simple "bloom filters" for Unicode characters.
891
   to keep things simple, we use a single bitmask, using the least 5
892
   bits from each unicode characters as the bit index. */
893
894
/* the linebreak mask is set up by _PyUnicode_Init() below */
895
896
#if LONG_BIT >= 128
897
#define BLOOM_WIDTH 128
898
#elif LONG_BIT >= 64
899
17.6M
#define BLOOM_WIDTH 64
900
#elif LONG_BIT >= 32
901
#define BLOOM_WIDTH 32
902
#else
903
#error "LONG_BIT is smaller than 32"
904
#endif
905
906
4.77M
#define BLOOM_MASK unsigned long
907
908
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
909
910
24.4M
#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
911
912
#define BLOOM_LINEBREAK(ch)                                             \
913
143M
    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
914
143M
     (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
915
916
static inline BLOOM_MASK
917
make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
918
2.38M
{
919
2.38M
#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
920
2.38M
    do {                                               \
921
2.38M
        TYPE *data = (TYPE *)PTR;                      \
922
2.38M
        TYPE *end = data + LEN;                        \
923
2.38M
        Py_UCS4 ch;                                    \
924
6.76M
        for (; data != end; data++) {                  \
925
4.37M
            ch = *data;                                \
926
4.37M
            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
927
4.37M
        }                                              \
928
2.38M
        break;                                         \
929
2.38M
    } while (0)
930
931
    /* calculate simple bloom-style bitmask for a given unicode string */
932
933
2.38M
    BLOOM_MASK mask;
934
935
2.38M
    mask = 0;
936
2.38M
    switch (kind) {
937
2.38M
    case PyUnicode_1BYTE_KIND:
938
2.38M
        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
939
2.38M
        break;
940
37
    case PyUnicode_2BYTE_KIND:
941
37
        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
942
37
        break;
943
0
    case PyUnicode_4BYTE_KIND:
944
0
        BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
945
0
        break;
946
0
    default:
947
0
        Py_UNREACHABLE();
948
2.38M
    }
949
2.38M
    return mask;
950
951
2.38M
#undef BLOOM_UPDATE
952
2.38M
}
953
954
/* Compilation of templated routines */
955
956
1.07M
#define STRINGLIB_GET_EMPTY() _PyUnicode_GetEmpty()
957
958
#include "stringlib/asciilib.h"
959
#include "stringlib/fastsearch.h"
960
#include "stringlib/partition.h"
961
#include "stringlib/split.h"
962
#include "stringlib/count.h"
963
#include "stringlib/find.h"
964
#include "stringlib/find_max_char.h"
965
#include "stringlib/undef.h"
966
967
#include "stringlib/ucs1lib.h"
968
#include "stringlib/fastsearch.h"
969
#include "stringlib/partition.h"
970
#include "stringlib/split.h"
971
#include "stringlib/count.h"
972
#include "stringlib/find.h"
973
#include "stringlib/replace.h"
974
#include "stringlib/repr.h"
975
#include "stringlib/find_max_char.h"
976
#include "stringlib/undef.h"
977
978
#include "stringlib/ucs2lib.h"
979
#include "stringlib/fastsearch.h"
980
#include "stringlib/partition.h"
981
#include "stringlib/split.h"
982
#include "stringlib/count.h"
983
#include "stringlib/find.h"
984
#include "stringlib/replace.h"
985
#include "stringlib/repr.h"
986
#include "stringlib/find_max_char.h"
987
#include "stringlib/undef.h"
988
989
#include "stringlib/ucs4lib.h"
990
#include "stringlib/fastsearch.h"
991
#include "stringlib/partition.h"
992
#include "stringlib/split.h"
993
#include "stringlib/count.h"
994
#include "stringlib/find.h"
995
#include "stringlib/replace.h"
996
#include "stringlib/repr.h"
997
#include "stringlib/find_max_char.h"
998
#include "stringlib/undef.h"
999
1000
#undef STRINGLIB_GET_EMPTY
1001
1002
/* --- Unicode Object ----------------------------------------------------- */
1003
1004
static inline Py_ssize_t
1005
findchar(const void *s, int kind,
1006
         Py_ssize_t size, Py_UCS4 ch,
1007
         int direction)
1008
205M
{
1009
205M
    switch (kind) {
1010
203M
    case PyUnicode_1BYTE_KIND:
1011
203M
        if ((Py_UCS1) ch != ch)
1012
5.28k
            return -1;
1013
203M
        if (direction > 0)
1014
203M
            return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1015
61.9k
        else
1016
61.9k
            return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1017
2.18M
    case PyUnicode_2BYTE_KIND:
1018
2.18M
        if ((Py_UCS2) ch != ch)
1019
0
            return -1;
1020
2.18M
        if (direction > 0)
1021
2.04M
            return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1022
141k
        else
1023
141k
            return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1024
582k
    case PyUnicode_4BYTE_KIND:
1025
582k
        if (direction > 0)
1026
569k
            return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
1027
12.6k
        else
1028
12.6k
            return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
1029
0
    default:
1030
0
        Py_UNREACHABLE();
1031
205M
    }
1032
205M
}
1033
1034
#ifdef Py_DEBUG
1035
/* Fill the data of a Unicode string with invalid characters to detect bugs
1036
   earlier.
1037
1038
   _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
1039
   ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
1040
   invalid character in Unicode 6.0. */
1041
static void
1042
unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
1043
{
1044
    int kind = PyUnicode_KIND(unicode);
1045
    Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
1046
    Py_ssize_t length = _PyUnicode_LENGTH(unicode);
1047
    if (length <= old_length)
1048
        return;
1049
    memset(data + old_length * kind, 0xff, (length - old_length) * kind);
1050
}
1051
#endif
1052
1053
static PyObject*
1054
resize_copy(PyObject *unicode, Py_ssize_t length)
1055
0
{
1056
0
    Py_ssize_t copy_length;
1057
0
    PyObject *copy;
1058
1059
0
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1060
0
    if (copy == NULL)
1061
0
        return NULL;
1062
1063
0
    copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
1064
0
    _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
1065
0
    return copy;
1066
0
}
1067
1068
PyObject*
1069
_PyUnicode_ResizeCompact(PyObject *unicode, Py_ssize_t length)
1070
57.4M
{
1071
57.4M
    Py_ssize_t char_size;
1072
57.4M
    Py_ssize_t struct_size;
1073
57.4M
    Py_ssize_t new_size;
1074
57.4M
    PyObject *new_unicode;
1075
#ifdef Py_DEBUG
1076
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1077
#endif
1078
1079
57.4M
    if (!_PyUnicode_IsModifiable(unicode)) {
1080
0
        PyObject *copy = resize_copy(unicode, length);
1081
0
        if (copy == NULL) {
1082
0
            return NULL;
1083
0
        }
1084
0
        Py_DECREF(unicode);
1085
0
        return copy;
1086
0
    }
1087
57.4M
    assert(PyUnicode_IS_COMPACT(unicode));
1088
1089
57.4M
    char_size = PyUnicode_KIND(unicode);
1090
57.4M
    if (PyUnicode_IS_ASCII(unicode))
1091
40.2M
        struct_size = sizeof(PyASCIIObject);
1092
17.2M
    else
1093
17.2M
        struct_size = sizeof(PyCompactUnicodeObject);
1094
1095
57.4M
    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1096
0
        PyErr_NoMemory();
1097
0
        return NULL;
1098
0
    }
1099
57.4M
    new_size = (struct_size + (length + 1) * char_size);
1100
1101
57.4M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1102
0
        PyMem_Free(_PyUnicode_UTF8(unicode));
1103
0
        PyUnicode_SET_UTF8_LENGTH(unicode, 0);
1104
0
        PyUnicode_SET_UTF8(unicode, NULL);
1105
0
    }
1106
#ifdef Py_TRACE_REFS
1107
    _Py_ForgetReference(unicode);
1108
#endif
1109
57.4M
    _PyReftracerTrack(unicode, PyRefTracer_DESTROY);
1110
1111
57.4M
    new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
1112
57.4M
    if (new_unicode == NULL) {
1113
0
        _Py_NewReferenceNoTotal(unicode);
1114
0
        PyErr_NoMemory();
1115
0
        return NULL;
1116
0
    }
1117
57.4M
    unicode = new_unicode;
1118
57.4M
    _Py_NewReferenceNoTotal(unicode);
1119
1120
57.4M
    _PyUnicode_LENGTH(unicode) = length;
1121
#ifdef Py_DEBUG
1122
    unicode_fill_invalid(unicode, old_length);
1123
#endif
1124
57.4M
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1125
57.4M
                    length, 0);
1126
57.4M
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1127
57.4M
    return unicode;
1128
57.4M
}
1129
1130
static int
1131
resize_inplace(PyObject *unicode, Py_ssize_t length)
1132
0
{
1133
0
    assert(!PyUnicode_IS_COMPACT(unicode));
1134
0
    assert(Py_REFCNT(unicode) == 1);
1135
1136
0
    Py_ssize_t new_size;
1137
0
    Py_ssize_t char_size;
1138
0
    int share_utf8;
1139
0
    void *data;
1140
#ifdef Py_DEBUG
1141
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1142
#endif
1143
1144
0
    data = _PyUnicode_DATA_ANY(unicode);
1145
0
    char_size = PyUnicode_KIND(unicode);
1146
0
    share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
1147
1148
0
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1149
0
        PyErr_NoMemory();
1150
0
        return -1;
1151
0
    }
1152
0
    new_size = (length + 1) * char_size;
1153
1154
0
    if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1155
0
    {
1156
0
        PyMem_Free(_PyUnicode_UTF8(unicode));
1157
0
        PyUnicode_SET_UTF8_LENGTH(unicode, 0);
1158
0
        PyUnicode_SET_UTF8(unicode, NULL);
1159
0
    }
1160
1161
0
    data = (PyObject *)PyObject_Realloc(data, new_size);
1162
0
    if (data == NULL) {
1163
0
        PyErr_NoMemory();
1164
0
        return -1;
1165
0
    }
1166
0
    _PyUnicode_DATA_ANY(unicode) = data;
1167
0
    if (share_utf8) {
1168
0
        PyUnicode_SET_UTF8_LENGTH(unicode, length);
1169
0
        PyUnicode_SET_UTF8(unicode, data);
1170
0
    }
1171
0
    _PyUnicode_LENGTH(unicode) = length;
1172
0
    PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
1173
#ifdef Py_DEBUG
1174
    unicode_fill_invalid(unicode, old_length);
1175
#endif
1176
1177
    /* check for integer overflow */
1178
0
    if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
1179
0
        PyErr_NoMemory();
1180
0
        return -1;
1181
0
    }
1182
0
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1183
0
    return 0;
1184
0
}
1185
1186
static const char*
1187
unicode_kind_name(PyObject *unicode)
1188
0
{
1189
    /* don't check consistency: unicode_kind_name() is called from
1190
       _PyUnicode_Dump() */
1191
0
    if (!PyUnicode_IS_COMPACT(unicode))
1192
0
    {
1193
0
        switch (PyUnicode_KIND(unicode))
1194
0
        {
1195
0
        case PyUnicode_1BYTE_KIND:
1196
0
            if (PyUnicode_IS_ASCII(unicode))
1197
0
                return "legacy ascii";
1198
0
            else
1199
0
                return "legacy latin1";
1200
0
        case PyUnicode_2BYTE_KIND:
1201
0
            return "legacy UCS2";
1202
0
        case PyUnicode_4BYTE_KIND:
1203
0
            return "legacy UCS4";
1204
0
        default:
1205
0
            return "<legacy invalid kind>";
1206
0
        }
1207
0
    }
1208
0
    switch (PyUnicode_KIND(unicode)) {
1209
0
    case PyUnicode_1BYTE_KIND:
1210
0
        if (PyUnicode_IS_ASCII(unicode))
1211
0
            return "ascii";
1212
0
        else
1213
0
            return "latin1";
1214
0
    case PyUnicode_2BYTE_KIND:
1215
0
        return "UCS2";
1216
0
    case PyUnicode_4BYTE_KIND:
1217
0
        return "UCS4";
1218
0
    default:
1219
0
        return "<invalid compact kind>";
1220
0
    }
1221
0
}
1222
1223
#ifdef Py_DEBUG
1224
/* Functions wrapping macros for use in debugger */
1225
const char *_PyUnicode_utf8(void *unicode_raw){
1226
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1227
    return PyUnicode_UTF8(unicode);
1228
}
1229
1230
const void *_PyUnicode_compact_data(void *unicode_raw) {
1231
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1232
    return _PyUnicode_COMPACT_DATA(unicode);
1233
}
1234
const void *_PyUnicode_data(void *unicode_raw) {
1235
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1236
    printf("obj %p\n", (void*)unicode);
1237
    printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1238
    printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1239
    printf("ascii op %p\n", (void*)(_PyASCIIObject_CAST(unicode) + 1));
1240
    if (!PyUnicode_IS_COMPACT_ASCII(unicode)) {
1241
        printf("compact op %p\n", (void*)(_PyCompactUnicodeObject_CAST(unicode) + 1));
1242
        printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1243
    }
1244
    return PyUnicode_DATA(unicode);
1245
}
1246
1247
void
1248
_PyUnicode_Dump(PyObject *op)
1249
{
1250
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
1251
1252
    printf("%s: len=%zu", unicode_kind_name(op), ascii->length);
1253
1254
    if (!ascii->state.ascii) {
1255
        PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
1256
        if (compact->utf8 == NULL) {
1257
            printf(", utf8=NULL");
1258
        }
1259
        else {
1260
            printf(", utf8=%p", (void *)compact->utf8);
1261
        }
1262
        printf(" (%zu)", compact->utf8_length);
1263
    }
1264
    printf(", data=%p\n", PyUnicode_DATA(op));
1265
    fflush(stdout);
1266
}
1267
#endif
1268
1269
1270
PyObject *
1271
PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1272
670M
{
1273
    /* Optimization for empty strings */
1274
670M
    if (size == 0) {
1275
40.4M
        return _PyUnicode_GetEmpty();
1276
40.4M
    }
1277
1278
629M
    PyObject *obj;
1279
629M
    PyCompactUnicodeObject *unicode;
1280
629M
    void *data;
1281
629M
    int kind;
1282
629M
    int is_ascii;
1283
629M
    Py_ssize_t char_size;
1284
629M
    Py_ssize_t struct_size;
1285
1286
629M
    is_ascii = 0;
1287
629M
    struct_size = sizeof(PyCompactUnicodeObject);
1288
629M
    if (maxchar < 128) {
1289
408M
        kind = PyUnicode_1BYTE_KIND;
1290
408M
        char_size = 1;
1291
408M
        is_ascii = 1;
1292
408M
        struct_size = sizeof(PyASCIIObject);
1293
408M
    }
1294
221M
    else if (maxchar < 256) {
1295
16.7M
        kind = PyUnicode_1BYTE_KIND;
1296
16.7M
        char_size = 1;
1297
16.7M
    }
1298
204M
    else if (maxchar < 65536) {
1299
192M
        kind = PyUnicode_2BYTE_KIND;
1300
192M
        char_size = 2;
1301
192M
    }
1302
11.5M
    else {
1303
11.5M
        if (maxchar > MAX_UNICODE) {
1304
0
            PyErr_SetString(PyExc_SystemError,
1305
0
                            "invalid maximum character passed to PyUnicode_New");
1306
0
            return NULL;
1307
0
        }
1308
11.5M
        kind = PyUnicode_4BYTE_KIND;
1309
11.5M
        char_size = 4;
1310
11.5M
    }
1311
1312
    /* Ensure we won't overflow the size. */
1313
629M
    if (size < 0) {
1314
0
        PyErr_SetString(PyExc_SystemError,
1315
0
                        "Negative size passed to PyUnicode_New");
1316
0
        return NULL;
1317
0
    }
1318
629M
    if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1319
0
        return PyErr_NoMemory();
1320
1321
    /* Duplicated allocation code from _PyObject_New() instead of a call to
1322
     * PyObject_New() so we are able to allocate space for the object and
1323
     * it's data buffer.
1324
     */
1325
629M
    obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
1326
629M
    if (obj == NULL) {
1327
0
        return PyErr_NoMemory();
1328
0
    }
1329
629M
    _PyObject_Init(obj, &PyUnicode_Type);
1330
1331
629M
    unicode = (PyCompactUnicodeObject *)obj;
1332
629M
    if (is_ascii)
1333
408M
        data = ((PyASCIIObject*)obj) + 1;
1334
221M
    else
1335
221M
        data = unicode + 1;
1336
629M
    _PyUnicode_LENGTH(unicode) = size;
1337
629M
    _PyUnicode_HASH(unicode) = -1;
1338
629M
    _PyUnicode_STATE(unicode).interned = 0;
1339
629M
    _PyUnicode_STATE(unicode).kind = kind;
1340
629M
    _PyUnicode_STATE(unicode).compact = 1;
1341
629M
    _PyUnicode_STATE(unicode).ascii = is_ascii;
1342
629M
    _PyUnicode_STATE(unicode).statically_allocated = 0;
1343
629M
    if (is_ascii) {
1344
408M
        ((char*)data)[size] = 0;
1345
408M
    }
1346
221M
    else if (kind == PyUnicode_1BYTE_KIND) {
1347
16.7M
        ((char*)data)[size] = 0;
1348
16.7M
        unicode->utf8 = NULL;
1349
16.7M
        unicode->utf8_length = 0;
1350
16.7M
    }
1351
204M
    else {
1352
204M
        unicode->utf8 = NULL;
1353
204M
        unicode->utf8_length = 0;
1354
204M
        if (kind == PyUnicode_2BYTE_KIND)
1355
192M
            ((Py_UCS2*)data)[size] = 0;
1356
11.5M
        else /* kind == PyUnicode_4BYTE_KIND */
1357
11.5M
            ((Py_UCS4*)data)[size] = 0;
1358
204M
    }
1359
#ifdef Py_DEBUG
1360
    unicode_fill_invalid((PyObject*)unicode, 0);
1361
#endif
1362
629M
    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
1363
629M
    return obj;
1364
629M
}
1365
1366
static int
1367
unicode_check_modifiable(PyObject *unicode)
1368
623
{
1369
623
    if (!_PyUnicode_IsModifiable(unicode)) {
1370
0
        PyErr_SetString(PyExc_SystemError,
1371
0
                        "Cannot modify a string currently used");
1372
0
        return -1;
1373
0
    }
1374
623
    return 0;
1375
623
}
1376
1377
static int
1378
_copy_characters(PyObject *to, Py_ssize_t to_start,
1379
                 PyObject *from, Py_ssize_t from_start,
1380
                 Py_ssize_t how_many, int check_maxchar)
1381
302M
{
1382
302M
    int from_kind, to_kind;
1383
302M
    const void *from_data;
1384
302M
    void *to_data;
1385
1386
302M
    assert(0 <= how_many);
1387
302M
    assert(0 <= from_start);
1388
302M
    assert(0 <= to_start);
1389
302M
    assert(PyUnicode_Check(from));
1390
302M
    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
1391
1392
302M
    assert(to == NULL || PyUnicode_Check(to));
1393
1394
302M
    if (how_many == 0) {
1395
2.57M
        return 0;
1396
2.57M
    }
1397
1398
302M
    assert(to != NULL);
1399
299M
    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1400
1401
299M
    from_kind = PyUnicode_KIND(from);
1402
299M
    from_data = PyUnicode_DATA(from);
1403
299M
    to_kind = PyUnicode_KIND(to);
1404
299M
    to_data = PyUnicode_DATA(to);
1405
1406
#ifdef Py_DEBUG
1407
    if (!check_maxchar
1408
        && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1409
    {
1410
        Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1411
        Py_UCS4 ch;
1412
        Py_ssize_t i;
1413
        for (i=0; i < how_many; i++) {
1414
            ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1415
            assert(ch <= to_maxchar);
1416
        }
1417
    }
1418
#endif
1419
1420
299M
    if (from_kind == to_kind) {
1421
189M
        if (check_maxchar
1422
0
            && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1423
0
        {
1424
            /* Writing Latin-1 characters into an ASCII string requires to
1425
               check that all written characters are pure ASCII */
1426
0
            Py_UCS4 max_char;
1427
0
            max_char = ucs1lib_find_max_char(from_data,
1428
0
                                             (const Py_UCS1*)from_data + how_many);
1429
0
            if (max_char >= 128)
1430
0
                return -1;
1431
0
        }
1432
189M
        memcpy((char*)to_data + to_kind * to_start,
1433
189M
                  (const char*)from_data + from_kind * from_start,
1434
189M
                  to_kind * how_many);
1435
189M
    }
1436
110M
    else if (from_kind == PyUnicode_1BYTE_KIND
1437
106M
             && to_kind == PyUnicode_2BYTE_KIND)
1438
95.2M
    {
1439
95.2M
        _PyUnicode_CONVERT_BYTES(
1440
95.2M
            Py_UCS1, Py_UCS2,
1441
95.2M
            PyUnicode_1BYTE_DATA(from) + from_start,
1442
95.2M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1443
95.2M
            PyUnicode_2BYTE_DATA(to) + to_start
1444
95.2M
            );
1445
95.2M
    }
1446
14.7M
    else if (from_kind == PyUnicode_1BYTE_KIND
1447
11.2M
             && to_kind == PyUnicode_4BYTE_KIND)
1448
11.2M
    {
1449
11.2M
        _PyUnicode_CONVERT_BYTES(
1450
11.2M
            Py_UCS1, Py_UCS4,
1451
11.2M
            PyUnicode_1BYTE_DATA(from) + from_start,
1452
11.2M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1453
11.2M
            PyUnicode_4BYTE_DATA(to) + to_start
1454
11.2M
            );
1455
11.2M
    }
1456
3.55M
    else if (from_kind == PyUnicode_2BYTE_KIND
1457
3.53M
             && to_kind == PyUnicode_4BYTE_KIND)
1458
3.52M
    {
1459
3.52M
        _PyUnicode_CONVERT_BYTES(
1460
3.52M
            Py_UCS2, Py_UCS4,
1461
3.52M
            PyUnicode_2BYTE_DATA(from) + from_start,
1462
3.52M
            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1463
3.52M
            PyUnicode_4BYTE_DATA(to) + to_start
1464
3.52M
            );
1465
3.52M
    }
1466
26.8k
    else {
1467
26.8k
        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1468
1469
26.8k
        if (!check_maxchar) {
1470
26.8k
            if (from_kind == PyUnicode_2BYTE_KIND
1471
8.94k
                && to_kind == PyUnicode_1BYTE_KIND)
1472
8.94k
            {
1473
8.94k
                _PyUnicode_CONVERT_BYTES(
1474
8.94k
                    Py_UCS2, Py_UCS1,
1475
8.94k
                    PyUnicode_2BYTE_DATA(from) + from_start,
1476
8.94k
                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1477
8.94k
                    PyUnicode_1BYTE_DATA(to) + to_start
1478
8.94k
                    );
1479
8.94k
            }
1480
17.9k
            else if (from_kind == PyUnicode_4BYTE_KIND
1481
17.9k
                     && to_kind == PyUnicode_1BYTE_KIND)
1482
12.4k
            {
1483
12.4k
                _PyUnicode_CONVERT_BYTES(
1484
12.4k
                    Py_UCS4, Py_UCS1,
1485
12.4k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1486
12.4k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1487
12.4k
                    PyUnicode_1BYTE_DATA(to) + to_start
1488
12.4k
                    );
1489
12.4k
            }
1490
5.49k
            else if (from_kind == PyUnicode_4BYTE_KIND
1491
5.49k
                     && to_kind == PyUnicode_2BYTE_KIND)
1492
5.49k
            {
1493
5.49k
                _PyUnicode_CONVERT_BYTES(
1494
5.49k
                    Py_UCS4, Py_UCS2,
1495
5.49k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1496
5.49k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1497
5.49k
                    PyUnicode_2BYTE_DATA(to) + to_start
1498
5.49k
                    );
1499
5.49k
            }
1500
0
            else {
1501
0
                Py_UNREACHABLE();
1502
0
            }
1503
26.8k
        }
1504
0
        else {
1505
0
            const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1506
0
            Py_UCS4 ch;
1507
0
            Py_ssize_t i;
1508
1509
0
            for (i=0; i < how_many; i++) {
1510
0
                ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1511
0
                if (ch > to_maxchar)
1512
0
                    return -1;
1513
0
                PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1514
0
            }
1515
0
        }
1516
26.8k
    }
1517
299M
    return 0;
1518
299M
}
1519
1520
void
1521
_PyUnicode_FastCopyCharacters(
1522
    PyObject *to, Py_ssize_t to_start,
1523
    PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
1524
302M
{
1525
302M
    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1526
302M
}
1527
1528
Py_ssize_t
1529
PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1530
                         PyObject *from, Py_ssize_t from_start,
1531
                         Py_ssize_t how_many)
1532
0
{
1533
0
    int err;
1534
1535
0
    if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1536
0
        PyErr_BadInternalCall();
1537
0
        return -1;
1538
0
    }
1539
1540
0
    if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
1541
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
1542
0
        return -1;
1543
0
    }
1544
0
    if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
1545
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
1546
0
        return -1;
1547
0
    }
1548
0
    if (how_many < 0) {
1549
0
        PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1550
0
        return -1;
1551
0
    }
1552
0
    how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
1553
0
    if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1554
0
        PyErr_Format(PyExc_SystemError,
1555
0
                     "Cannot write %zi characters at %zi "
1556
0
                     "in a string of %zi characters",
1557
0
                     how_many, to_start, PyUnicode_GET_LENGTH(to));
1558
0
        return -1;
1559
0
    }
1560
1561
0
    if (how_many == 0)
1562
0
        return 0;
1563
1564
0
    if (unicode_check_modifiable(to))
1565
0
        return -1;
1566
1567
0
    err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1568
0
    if (err) {
1569
0
        PyErr_Format(PyExc_SystemError,
1570
0
                     "Cannot copy %s characters "
1571
0
                     "into a string of %s characters",
1572
0
                     unicode_kind_name(from),
1573
0
                     unicode_kind_name(to));
1574
0
        return -1;
1575
0
    }
1576
0
    return how_many;
1577
0
}
1578
1579
1580
static void
1581
unicode_invalid_character(PyObject *exc, Py_UCS4 ch)
1582
0
{
1583
0
    PyErr_Format(exc,
1584
0
                 "character U+%x is not in range [U+0000; U+%x]",
1585
0
                 ch, MAX_UNICODE);
1586
0
}
1587
1588
1589
/* Find the maximum code point and count the number of surrogate pairs so a
1590
   correct string length can be computed before converting a string to UCS4.
1591
   This function counts single surrogates as a character and not as a pair.
1592
1593
   Return 0 on success, or -1 on error. */
1594
static int
1595
find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1596
                        Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
1597
378k
{
1598
378k
    const wchar_t *iter;
1599
378k
    Py_UCS4 ch;
1600
1601
378k
    assert(num_surrogates != NULL && maxchar != NULL);
1602
378k
    *num_surrogates = 0;
1603
378k
    *maxchar = 0;
1604
1605
11.4M
    for (iter = begin; iter < end; ) {
1606
#if SIZEOF_WCHAR_T == 2
1607
        if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1608
            && (iter+1) < end
1609
            && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1610
        {
1611
            ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1612
            ++(*num_surrogates);
1613
            iter += 2;
1614
        }
1615
        else
1616
#endif
1617
11.0M
        {
1618
11.0M
            ch = *iter;
1619
11.0M
            iter++;
1620
11.0M
        }
1621
11.0M
        if (ch > *maxchar) {
1622
1.52M
            *maxchar = ch;
1623
1.52M
            if (*maxchar > MAX_UNICODE) {
1624
0
                unicode_invalid_character(PyExc_ValueError, ch);
1625
0
                return -1;
1626
0
            }
1627
1.52M
        }
1628
11.0M
    }
1629
378k
    return 0;
1630
378k
}
1631
1632
static void
1633
unicode_dealloc(PyObject *unicode)
1634
651M
{
1635
#ifdef Py_DEBUG
1636
    if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
1637
        _Py_FatalRefcountError("deallocating an Unicode singleton");
1638
    }
1639
#endif
1640
651M
    if (_PyUnicode_STATE(unicode).statically_allocated) {
1641
        /* This should never get called, but we also don't want to SEGV if
1642
        * we accidentally decref an immortal string out of existence. Since
1643
        * the string is an immortal object, just re-set the reference count.
1644
        */
1645
#ifdef Py_DEBUG
1646
        Py_UNREACHABLE();
1647
#endif
1648
0
        _Py_SetImmortal(unicode);
1649
0
        return;
1650
0
    }
1651
651M
    switch (_PyUnicode_STATE(unicode).interned) {
1652
651M
        case SSTATE_NOT_INTERNED:
1653
651M
            break;
1654
155k
        case SSTATE_INTERNED_MORTAL:
1655
            /* Remove the object from the intern dict.
1656
             * Before doing so, we set the refcount to 2: the key and value
1657
             * in the interned_dict.
1658
             */
1659
155k
            assert(Py_REFCNT(unicode) == 0);
1660
155k
            Py_SET_REFCNT(unicode, 2);
1661
#ifdef Py_REF_DEBUG
1662
            /* let's be pedantic with the ref total */
1663
            _Py_IncRefTotal(_PyThreadState_GET());
1664
            _Py_IncRefTotal(_PyThreadState_GET());
1665
#endif
1666
155k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1667
155k
            PyObject *interned = get_interned_dict(interp);
1668
155k
            assert(interned != NULL);
1669
155k
            PyObject *popped;
1670
155k
            int r = PyDict_Pop(interned, unicode, &popped);
1671
155k
            if (r == -1) {
1672
0
                PyErr_FormatUnraisable("Exception ignored while "
1673
0
                                       "removing an interned string %R",
1674
0
                                       unicode);
1675
                // We don't know what happened to the string. It's probably
1676
                // best to leak it:
1677
                // - if it was popped, there are no more references to it
1678
                //   so it can't cause trouble (except wasted memory)
1679
                // - if it wasn't popped, it'll remain interned
1680
0
                _Py_SetImmortal(unicode);
1681
0
                _PyUnicode_STATE(unicode).interned = SSTATE_INTERNED_IMMORTAL;
1682
0
                return;
1683
0
            }
1684
155k
            if (r == 0) {
1685
                // The interned string was not found in the interned_dict.
1686
#ifdef Py_DEBUG
1687
                Py_UNREACHABLE();
1688
#endif
1689
0
                _Py_SetImmortal(unicode);
1690
0
                return;
1691
0
            }
1692
            // Successfully popped.
1693
155k
            assert(popped == unicode);
1694
            // Only our `popped` reference should be left; remove it too.
1695
155k
            assert(Py_REFCNT(unicode) == 1);
1696
155k
            Py_SET_REFCNT(unicode, 0);
1697
#ifdef Py_REF_DEBUG
1698
            /* let's be pedantic with the ref total */
1699
            _Py_DecRefTotal(_PyThreadState_GET());
1700
#endif
1701
155k
            break;
1702
0
        default:
1703
            // As with `statically_allocated` above.
1704
#ifdef Py_REF_DEBUG
1705
            Py_UNREACHABLE();
1706
#endif
1707
0
            _Py_SetImmortal(unicode);
1708
0
            return;
1709
651M
    }
1710
651M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1711
197k
        PyMem_Free(_PyUnicode_UTF8(unicode));
1712
197k
    }
1713
651M
    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
1714
22.8M
        PyMem_Free(_PyUnicode_DATA_ANY(unicode));
1715
22.8M
    }
1716
1717
651M
    Py_TYPE(unicode)->tp_free(unicode);
1718
651M
}
1719
1720
#ifdef Py_DEBUG
1721
static int
1722
unicode_is_singleton(PyObject *unicode)
1723
{
1724
    if (unicode == &_Py_STR(empty)) {
1725
        return 1;
1726
    }
1727
1728
    PyASCIIObject *ascii = _PyASCIIObject_CAST(unicode);
1729
    if (ascii->length == 1) {
1730
        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1731
        if (ch < 256 && LATIN1(ch) == unicode) {
1732
            return 1;
1733
        }
1734
    }
1735
    return 0;
1736
}
1737
#endif
1738
1739
// If this function is updated, update also _PyUnicodeWriter_CanWrite().
1740
int
1741
_PyUnicode_IsModifiable(PyObject *unicode)
1742
69.8M
{
1743
69.8M
    assert(_PyUnicode_CHECK(unicode));
1744
69.8M
    if (!PyUnicode_CheckExact(unicode))
1745
0
        return 0;
1746
    // On Free Threading, this test fails if called from a thread other
1747
    // than the one which created the str object.
1748
69.8M
    if (!_PyObject_IsUniquelyReferenced(unicode))
1749
3.70M
        return 0;
1750
66.1M
    if (PyUnicode_HASH(unicode) != -1)
1751
0
        return 0;
1752
66.1M
    if (PyUnicode_CHECK_INTERNED(unicode))
1753
0
        return 0;
1754
66.1M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1755
0
        return 0;
1756
0
    }
1757
#ifdef Py_DEBUG
1758
    /* singleton refcount is greater than 1 */
1759
    assert(!unicode_is_singleton(unicode));
1760
#endif
1761
66.1M
    return 1;
1762
66.1M
}
1763
1764
static int
1765
unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1766
4.36M
{
1767
4.36M
    PyObject *unicode;
1768
4.36M
    Py_ssize_t old_length;
1769
1770
4.36M
    assert(p_unicode != NULL);
1771
4.36M
    unicode = *p_unicode;
1772
1773
4.36M
    assert(unicode != NULL);
1774
4.36M
    assert(PyUnicode_Check(unicode));
1775
4.36M
    assert(0 <= length);
1776
1777
4.36M
    old_length = PyUnicode_GET_LENGTH(unicode);
1778
4.36M
    if (old_length == length)
1779
0
        return 0;
1780
1781
4.36M
    if (length == 0) {
1782
0
        PyObject *empty = _PyUnicode_GetEmpty();
1783
0
        Py_SETREF(*p_unicode, empty);
1784
0
        return 0;
1785
0
    }
1786
1787
4.36M
    if (!_PyUnicode_IsModifiable(unicode)) {
1788
0
        PyObject *copy = resize_copy(unicode, length);
1789
0
        if (copy == NULL)
1790
0
            return -1;
1791
0
        Py_SETREF(*p_unicode, copy);
1792
0
        return 0;
1793
0
    }
1794
1795
4.36M
    if (PyUnicode_IS_COMPACT(unicode)) {
1796
4.36M
        PyObject *new_unicode = _PyUnicode_ResizeCompact(unicode, length);
1797
4.36M
        if (new_unicode == NULL)
1798
0
            return -1;
1799
4.36M
        *p_unicode = new_unicode;
1800
4.36M
        return 0;
1801
4.36M
    }
1802
0
    return resize_inplace(unicode, length);
1803
4.36M
}
1804
1805
int
1806
PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
1807
0
{
1808
0
    PyObject *unicode;
1809
0
    if (p_unicode == NULL) {
1810
0
        PyErr_BadInternalCall();
1811
0
        return -1;
1812
0
    }
1813
0
    unicode = *p_unicode;
1814
0
    if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
1815
0
    {
1816
0
        PyErr_BadInternalCall();
1817
0
        return -1;
1818
0
    }
1819
0
    return unicode_resize(p_unicode, length);
1820
0
}
1821
1822
static PyObject*
1823
get_latin1_char(Py_UCS1 ch)
1824
370M
{
1825
370M
    PyObject *o = LATIN1(ch);
1826
370M
    return o;
1827
370M
}
1828
1829
static PyObject*
1830
unicode_char(Py_UCS4 ch)
1831
401M
{
1832
401M
    if (ch < 256) {
1833
255M
        return get_latin1_char(ch);
1834
255M
    }
1835
1836
    // Raise SystemError if the character is not in range [U+0000; MAX_UNICODE]
1837
146M
    PyObject *unicode = PyUnicode_New(1, ch);
1838
146M
    if (unicode == NULL) {
1839
0
        return NULL;
1840
0
    }
1841
1842
146M
    assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1843
146M
    if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
1844
138M
        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1845
138M
    } else {
1846
7.63M
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1847
7.63M
        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1848
7.63M
    }
1849
146M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
1850
146M
    return unicode;
1851
146M
}
1852
1853
1854
static inline void
1855
unicode_write_widechar(int kind, void *data,
1856
                       const wchar_t *u, Py_ssize_t size,
1857
                       Py_ssize_t num_surrogates)
1858
378k
{
1859
378k
    switch (kind) {
1860
349k
    case PyUnicode_1BYTE_KIND:
1861
349k
        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, u, u + size, data);
1862
349k
        break;
1863
1864
26.9k
    case PyUnicode_2BYTE_KIND:
1865
#if SIZEOF_WCHAR_T == 2
1866
        memcpy(data, u, size * 2);
1867
#else
1868
26.9k
        _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2, u, u + size, data);
1869
26.9k
#endif
1870
26.9k
        break;
1871
1872
1.76k
    case PyUnicode_4BYTE_KIND:
1873
1.76k
    {
1874
#if SIZEOF_WCHAR_T == 2
1875
        // Convert a 16-bits wchar_t representation to UCS4, this will decode
1876
        // surrogate pairs.
1877
        const wchar_t *end = u + size;
1878
        Py_UCS4 *ucs4_out = (Py_UCS4*)data;
1879
#  ifndef NDEBUG
1880
        Py_UCS4 *ucs4_end = (Py_UCS4*)data + (size - num_surrogates);
1881
#  endif
1882
        for (const wchar_t *iter = u; iter < end; ) {
1883
            assert(ucs4_out < ucs4_end);
1884
            if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1885
                && (iter+1) < end
1886
                && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1887
            {
1888
                *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1889
                iter += 2;
1890
            }
1891
            else {
1892
                *ucs4_out++ = *iter;
1893
                iter++;
1894
            }
1895
        }
1896
        assert(ucs4_out == ucs4_end);
1897
#else
1898
1.76k
        assert(num_surrogates == 0);
1899
1.76k
        memcpy(data, u, size * 4);
1900
1.76k
#endif
1901
1.76k
        break;
1902
0
    }
1903
0
    default:
1904
0
        Py_UNREACHABLE();
1905
378k
    }
1906
378k
}
1907
1908
1909
PyObject *
1910
PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
1911
715k
{
1912
715k
    PyObject *unicode;
1913
715k
    Py_UCS4 maxchar = 0;
1914
715k
    Py_ssize_t num_surrogates;
1915
1916
715k
    if (u == NULL && size != 0) {
1917
0
        PyErr_BadInternalCall();
1918
0
        return NULL;
1919
0
    }
1920
1921
715k
    if (size == -1) {
1922
1.29k
        size = wcslen(u);
1923
1.29k
    }
1924
1925
    /* If the Unicode data is known at construction time, we can apply
1926
       some optimizations which share commonly used objects. */
1927
1928
    /* Optimization for empty strings */
1929
715k
    if (size == 0)
1930
267k
        _Py_RETURN_UNICODE_EMPTY();
1931
1932
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
1933
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
1934
       non-Unicode locales and hence needs conversion to UCS-4 first. */
1935
    if (_Py_LocaleUsesNonUnicodeWchar()) {
1936
        wchar_t* converted = _Py_DecodeNonUnicodeWchar(u, size);
1937
        if (!converted) {
1938
            return NULL;
1939
        }
1940
        PyObject *unicode = _PyUnicode_FromUCS4(converted, size);
1941
        PyMem_Free(converted);
1942
        return unicode;
1943
    }
1944
#endif
1945
1946
    /* Single character Unicode objects in the Latin-1 range are
1947
       shared when using this constructor */
1948
447k
    if (size == 1 && (Py_UCS4)*u < 256)
1949
68.9k
        return get_latin1_char((unsigned char)*u);
1950
1951
    /* If not empty and not single character, copy the Unicode data
1952
       into the new object */
1953
378k
    if (find_maxchar_surrogates(u, u + size,
1954
378k
                                &maxchar, &num_surrogates) == -1)
1955
0
        return NULL;
1956
1957
378k
    unicode = PyUnicode_New(size - num_surrogates, maxchar);
1958
378k
    if (!unicode)
1959
0
        return NULL;
1960
1961
378k
    unicode_write_widechar(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1962
378k
                           u, size, num_surrogates);
1963
1964
378k
    return unicode_result(unicode);
1965
378k
}
1966
1967
1968
int
1969
PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *pub_writer,
1970
                              const wchar_t *str,
1971
                              Py_ssize_t size)
1972
0
{
1973
0
    _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer;
1974
1975
0
    if (size < 0) {
1976
0
        size = wcslen(str);
1977
0
    }
1978
1979
0
    if (size == 0) {
1980
0
        return 0;
1981
0
    }
1982
1983
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
1984
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
1985
       non-Unicode locales and hence needs conversion to UCS-4 first. */
1986
    if (_Py_LocaleUsesNonUnicodeWchar()) {
1987
        wchar_t* converted = _Py_DecodeNonUnicodeWchar(str, size);
1988
        if (!converted) {
1989
            return -1;
1990
        }
1991
1992
        int res = PyUnicodeWriter_WriteUCS4(pub_writer, converted, size);
1993
        PyMem_Free(converted);
1994
        return res;
1995
    }
1996
#endif
1997
1998
0
    Py_UCS4 maxchar = 0;
1999
0
    Py_ssize_t num_surrogates;
2000
0
    if (find_maxchar_surrogates(str, str + size,
2001
0
                                &maxchar, &num_surrogates) == -1) {
2002
0
        return -1;
2003
0
    }
2004
2005
0
    if (_PyUnicodeWriter_Prepare(writer, size - num_surrogates, maxchar) < 0) {
2006
0
        return -1;
2007
0
    }
2008
0
    assert(_PyUnicodeWriter_CanWrite(writer));
2009
2010
0
    int kind = writer->kind;
2011
0
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2012
0
    unicode_write_widechar(kind, data, str, size, num_surrogates);
2013
2014
0
    writer->pos += size - num_surrogates;
2015
0
    return 0;
2016
0
}
2017
2018
2019
PyObject *
2020
PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
2021
11.6M
{
2022
11.6M
    if (size < 0) {
2023
0
        PyErr_SetString(PyExc_SystemError,
2024
0
                        "Negative size passed to PyUnicode_FromStringAndSize");
2025
0
        return NULL;
2026
0
    }
2027
11.6M
    if (u != NULL) {
2028
11.6M
        return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2029
11.6M
    }
2030
0
    if (size > 0) {
2031
0
        PyErr_SetString(PyExc_SystemError,
2032
0
            "NULL string with positive size with NULL passed to PyUnicode_FromStringAndSize");
2033
0
        return NULL;
2034
0
    }
2035
0
    return _PyUnicode_GetEmpty();
2036
0
}
2037
2038
PyObject *
2039
PyUnicode_FromString(const char *u)
2040
41.9M
{
2041
41.9M
    size_t size = strlen(u);
2042
41.9M
    if (size > PY_SSIZE_T_MAX) {
2043
0
        PyErr_SetString(PyExc_OverflowError, "input too long");
2044
0
        return NULL;
2045
0
    }
2046
41.9M
    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
2047
41.9M
}
2048
2049
2050
PyObject *
2051
_PyUnicode_FromId(_Py_Identifier *id)
2052
0
{
2053
0
    PyMutex_Lock((PyMutex *)&id->mutex);
2054
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2055
0
    struct _Py_unicode_ids *ids = &interp->unicode.ids;
2056
2057
0
    Py_ssize_t index = _Py_atomic_load_ssize(&id->index);
2058
0
    if (index < 0) {
2059
0
        struct _Py_unicode_runtime_ids *rt_ids = &interp->runtime->unicode_state.ids;
2060
2061
0
        PyMutex_Lock(&rt_ids->mutex);
2062
        // Check again to detect concurrent access. Another thread can have
2063
        // initialized the index while this thread waited for the lock.
2064
0
        index = _Py_atomic_load_ssize(&id->index);
2065
0
        if (index < 0) {
2066
0
            assert(rt_ids->next_index < PY_SSIZE_T_MAX);
2067
0
            index = rt_ids->next_index;
2068
0
            rt_ids->next_index++;
2069
0
            _Py_atomic_store_ssize(&id->index, index);
2070
0
        }
2071
0
        PyMutex_Unlock(&rt_ids->mutex);
2072
0
    }
2073
0
    assert(index >= 0);
2074
2075
0
    PyObject *obj;
2076
0
    if (index < ids->size) {
2077
0
        obj = ids->array[index];
2078
0
        if (obj) {
2079
            // Return a borrowed reference
2080
0
            goto end;
2081
0
        }
2082
0
    }
2083
2084
0
    obj = PyUnicode_DecodeUTF8Stateful(id->string, strlen(id->string),
2085
0
                                       NULL, NULL);
2086
0
    if (!obj) {
2087
0
        goto end;
2088
0
    }
2089
0
    _PyUnicode_InternImmortal(interp, &obj);
2090
2091
0
    if (index >= ids->size) {
2092
        // Overallocate to reduce the number of realloc
2093
0
        Py_ssize_t new_size = Py_MAX(index * 2, 16);
2094
0
        Py_ssize_t item_size = sizeof(ids->array[0]);
2095
0
        PyObject **new_array = PyMem_Realloc(ids->array, new_size * item_size);
2096
0
        if (new_array == NULL) {
2097
0
            PyErr_NoMemory();
2098
0
            obj = NULL;
2099
0
            goto end;
2100
0
        }
2101
0
        memset(&new_array[ids->size], 0, (new_size - ids->size) * item_size);
2102
0
        ids->array = new_array;
2103
0
        ids->size = new_size;
2104
0
    }
2105
2106
    // The array stores a strong reference
2107
0
    ids->array[index] = obj;
2108
2109
0
end:
2110
0
    PyMutex_Unlock((PyMutex *)&id->mutex);
2111
    // Return a borrowed reference
2112
0
    return obj;
2113
0
}
2114
2115
2116
static void
2117
unicode_clear_identifiers(struct _Py_unicode_state *state)
2118
0
{
2119
0
    struct _Py_unicode_ids *ids = &state->ids;
2120
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
2121
0
        Py_XDECREF(ids->array[i]);
2122
0
    }
2123
0
    ids->size = 0;
2124
0
    PyMem_Free(ids->array);
2125
0
    ids->array = NULL;
2126
    // Don't reset _PyRuntime next_index: _Py_Identifier.id remains valid
2127
    // after Py_Finalize().
2128
0
}
2129
2130
2131
/* Internal function, doesn't check maximum character */
2132
2133
PyObject*
2134
_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
2135
135M
{
2136
135M
    const unsigned char *s = (const unsigned char *)buffer;
2137
135M
    PyObject *unicode;
2138
135M
    if (size == 1) {
2139
#ifdef Py_DEBUG
2140
        assert((unsigned char)s[0] < 128);
2141
#endif
2142
51.8M
        return get_latin1_char(s[0]);
2143
51.8M
    }
2144
83.9M
    unicode = PyUnicode_New(size, 127);
2145
83.9M
    if (!unicode)
2146
0
        return NULL;
2147
83.9M
    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2148
83.9M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
2149
83.9M
    return unicode;
2150
83.9M
}
2151
2152
static Py_UCS4
2153
kind_maxchar_limit(int kind)
2154
0
{
2155
0
    switch (kind) {
2156
0
    case PyUnicode_1BYTE_KIND:
2157
0
        return 0x80;
2158
0
    case PyUnicode_2BYTE_KIND:
2159
0
        return 0x100;
2160
0
    case PyUnicode_4BYTE_KIND:
2161
0
        return 0x10000;
2162
0
    default:
2163
0
        Py_UNREACHABLE();
2164
0
    }
2165
0
}
2166
2167
static PyObject*
2168
_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
2169
56.1M
{
2170
56.1M
    PyObject *res;
2171
56.1M
    unsigned char max_char;
2172
2173
56.1M
    if (size == 0) {
2174
14.7M
        _Py_RETURN_UNICODE_EMPTY();
2175
14.7M
    }
2176
56.1M
    assert(size > 0);
2177
41.3M
    if (size == 1) {
2178
11.9M
        return get_latin1_char(u[0]);
2179
11.9M
    }
2180
2181
29.4M
    max_char = ucs1lib_find_max_char(u, u + size);
2182
29.4M
    res = PyUnicode_New(size, max_char);
2183
29.4M
    if (!res)
2184
0
        return NULL;
2185
29.4M
    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
2186
29.4M
    assert(_PyUnicode_CheckConsistency(res, 1));
2187
29.4M
    return res;
2188
29.4M
}
2189
2190
static PyObject*
2191
_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
2192
87.1M
{
2193
87.1M
    PyObject *res;
2194
87.1M
    Py_UCS2 max_char;
2195
2196
87.1M
    if (size == 0)
2197
17.1M
        _Py_RETURN_UNICODE_EMPTY();
2198
87.1M
    assert(size > 0);
2199
70.0M
    if (size == 1)
2200
48.3M
        return unicode_char(u[0]);
2201
2202
21.7M
    max_char = ucs2lib_find_max_char(u, u + size);
2203
21.7M
    res = PyUnicode_New(size, max_char);
2204
21.7M
    if (!res)
2205
0
        return NULL;
2206
21.7M
    if (max_char >= 256)
2207
15.9M
        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
2208
5.80M
    else {
2209
5.80M
        _PyUnicode_CONVERT_BYTES(
2210
5.80M
            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2211
5.80M
    }
2212
21.7M
    assert(_PyUnicode_CheckConsistency(res, 1));
2213
21.7M
    return res;
2214
21.7M
}
2215
2216
static PyObject*
2217
_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
2218
79.3M
{
2219
79.3M
    PyObject *res;
2220
2221
79.3M
    if (size == 0)
2222
18.3M
        _Py_RETURN_UNICODE_EMPTY();
2223
79.3M
    assert(size > 0);
2224
2225
60.9M
    if (size == 1) {
2226
        // Raise SystemError if the character is invalid
2227
40.6M
        return unicode_char(u[0]);
2228
40.6M
    }
2229
2230
#ifdef Py_DEBUG
2231
    // Check for invalid characters in debug mode
2232
    Py_UCS4 max_char = 127;
2233
    for (Py_ssize_t i = 0; i < size; i++) {
2234
        Py_UCS4 ch = u[i];
2235
        if (ch > max_char) {
2236
            if (ch > MAX_UNICODE) {
2237
                unicode_invalid_character(PyExc_SystemError, ch);
2238
                return NULL;
2239
            }
2240
            max_char = ch;
2241
        }
2242
    }
2243
#else
2244
    // gh-158445: Return MAX_UNICODE even if the string contains invalid
2245
    // characters. Checking for invalid characters would make the function
2246
    // slower whereas it's unlikely in practice.
2247
20.2M
    Py_UCS4 max_char = ucs4lib_find_max_char(u, u + size);
2248
20.2M
#endif
2249
2250
20.2M
    res = PyUnicode_New(size, max_char);
2251
20.2M
    if (!res)
2252
0
        return NULL;
2253
20.2M
    if (max_char < 256)
2254
13.0M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2255
20.2M
                                 PyUnicode_1BYTE_DATA(res));
2256
7.17M
    else if (max_char < 0x10000)
2257
5.44M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2258
7.17M
                                 PyUnicode_2BYTE_DATA(res));
2259
1.73M
    else
2260
1.73M
        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
2261
20.2M
    assert(_PyUnicode_CheckConsistency(res, 1));
2262
20.2M
    return res;
2263
20.2M
}
2264
2265
2266
int
2267
PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *pub_writer,
2268
                          const Py_UCS4 *str,
2269
                          Py_ssize_t size)
2270
45.3k
{
2271
45.3k
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
2272
2273
45.3k
    if (size < 0) {
2274
0
        PyErr_SetString(PyExc_ValueError,
2275
0
                        "size must be positive");
2276
0
        return -1;
2277
0
    }
2278
2279
45.3k
    if (size == 0) {
2280
0
        return 0;
2281
0
    }
2282
2283
#ifdef Py_DEBUG
2284
    // Check for invalid characters in debug mode
2285
    Py_UCS4 maxchar = 127;
2286
    for (Py_ssize_t i = 0; i < size; i++) {
2287
        Py_UCS4 ch = str[i];
2288
        if (ch > maxchar) {
2289
            if (ch > MAX_UNICODE) {
2290
                unicode_invalid_character(PyExc_SystemError, ch);
2291
                return -1;
2292
            }
2293
            maxchar = ch;
2294
        }
2295
    }
2296
#else
2297
    // gh-158445: Return MAX_UNICODE even if the string contains invalid
2298
    // characters. Checking for invalid characters would make the function
2299
    // slower whereas it's unlikely in practice.
2300
45.3k
    Py_UCS4 maxchar = ucs4lib_find_max_char(str, str + size);
2301
45.3k
#endif
2302
2303
45.3k
    if (_PyUnicodeWriter_Prepare(writer, size, maxchar) < 0) {
2304
0
        return -1;
2305
0
    }
2306
45.3k
    assert(_PyUnicodeWriter_CanWrite(writer));
2307
2308
45.3k
    int kind = writer->kind;
2309
45.3k
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2310
45.3k
    if (kind == PyUnicode_1BYTE_KIND) {
2311
9.69k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1,
2312
9.69k
                                 str, str + size,
2313
9.69k
                                 data);
2314
9.69k
    }
2315
35.6k
    else if (kind == PyUnicode_2BYTE_KIND) {
2316
35.6k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2,
2317
35.6k
                                 str, str + size,
2318
35.6k
                                 data);
2319
35.6k
    }
2320
6
    else {
2321
6
        memcpy(data, str, size * sizeof(Py_UCS4));
2322
6
    }
2323
45.3k
    writer->pos += size;
2324
2325
45.3k
    return 0;
2326
45.3k
}
2327
2328
2329
PyObject*
2330
PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2331
158M
{
2332
158M
    if (size < 0) {
2333
0
        PyErr_SetString(PyExc_ValueError, "size must be positive");
2334
0
        return NULL;
2335
0
    }
2336
158M
    switch (kind) {
2337
24.9M
    case PyUnicode_1BYTE_KIND:
2338
24.9M
        return _PyUnicode_FromUCS1(buffer, size);
2339
69.9M
    case PyUnicode_2BYTE_KIND:
2340
69.9M
        return _PyUnicode_FromUCS2(buffer, size);
2341
63.7M
    case PyUnicode_4BYTE_KIND:
2342
63.7M
        return _PyUnicode_FromUCS4(buffer, size);
2343
0
    default:
2344
0
        PyErr_SetString(PyExc_SystemError, "invalid kind");
2345
0
        return NULL;
2346
158M
    }
2347
158M
}
2348
2349
Py_UCS4
2350
_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2351
12.9M
{
2352
12.9M
    int kind;
2353
12.9M
    const void *startptr, *endptr;
2354
2355
12.9M
    assert(0 <= start);
2356
12.9M
    assert(end <= PyUnicode_GET_LENGTH(unicode));
2357
12.9M
    assert(start <= end);
2358
2359
12.9M
    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2360
57.4k
        return PyUnicode_MAX_CHAR_VALUE(unicode);
2361
2362
12.9M
    if (start == end)
2363
0
        return 127;
2364
2365
12.9M
    if (PyUnicode_IS_ASCII(unicode))
2366
12.8M
        return 127;
2367
2368
40.5k
    kind = PyUnicode_KIND(unicode);
2369
40.5k
    startptr = PyUnicode_DATA(unicode);
2370
40.5k
    endptr = (char *)startptr + end * kind;
2371
40.5k
    startptr = (char *)startptr + start * kind;
2372
40.5k
    switch(kind) {
2373
4.04k
    case PyUnicode_1BYTE_KIND:
2374
4.04k
        return ucs1lib_find_max_char(startptr, endptr);
2375
11.0k
    case PyUnicode_2BYTE_KIND:
2376
11.0k
        return ucs2lib_find_max_char(startptr, endptr);
2377
25.4k
    case PyUnicode_4BYTE_KIND:
2378
25.4k
        return ucs4lib_find_max_char(startptr, endptr);
2379
0
    default:
2380
0
        Py_UNREACHABLE();
2381
40.5k
    }
2382
40.5k
}
2383
2384
/* Ensure that a string uses the most efficient storage, if it is not the
2385
   case: create a new string with of the right kind. Write NULL into *p_unicode
2386
   on error. */
2387
static void
2388
unicode_adjust_maxchar(PyObject **p_unicode)
2389
0
{
2390
0
    PyObject *unicode, *copy;
2391
0
    Py_UCS4 max_char;
2392
0
    Py_ssize_t len;
2393
0
    int kind;
2394
2395
0
    assert(p_unicode != NULL);
2396
0
    unicode = *p_unicode;
2397
0
    if (PyUnicode_IS_ASCII(unicode))
2398
0
        return;
2399
2400
0
    len = PyUnicode_GET_LENGTH(unicode);
2401
0
    kind = PyUnicode_KIND(unicode);
2402
0
    if (kind == PyUnicode_1BYTE_KIND) {
2403
0
        const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
2404
0
        max_char = ucs1lib_find_max_char(u, u + len);
2405
0
        if (max_char >= 128)
2406
0
            return;
2407
0
    }
2408
0
    else if (kind == PyUnicode_2BYTE_KIND) {
2409
0
        const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
2410
0
        max_char = ucs2lib_find_max_char(u, u + len);
2411
0
        if (max_char >= 256)
2412
0
            return;
2413
0
    }
2414
0
    else if (kind == PyUnicode_4BYTE_KIND) {
2415
0
        const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
2416
0
        max_char = ucs4lib_find_max_char(u, u + len);
2417
0
        if (max_char >= 0x10000)
2418
0
            return;
2419
0
    }
2420
0
    else
2421
0
        Py_UNREACHABLE();
2422
2423
0
    copy = PyUnicode_New(len, max_char);
2424
0
    if (copy != NULL)
2425
0
        _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
2426
0
    Py_DECREF(unicode);
2427
0
    *p_unicode = copy;
2428
0
}
2429
2430
PyObject*
2431
_PyUnicode_Copy(PyObject *unicode)
2432
3.30M
{
2433
3.30M
    Py_ssize_t length;
2434
3.30M
    PyObject *copy;
2435
2436
3.30M
    if (!PyUnicode_Check(unicode)) {
2437
0
        PyErr_BadInternalCall();
2438
0
        return NULL;
2439
0
    }
2440
2441
3.30M
    length = PyUnicode_GET_LENGTH(unicode);
2442
3.30M
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
2443
3.30M
    if (!copy)
2444
0
        return NULL;
2445
3.30M
    assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2446
2447
3.30M
    memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2448
3.30M
              length * PyUnicode_KIND(unicode));
2449
3.30M
    assert(_PyUnicode_CheckConsistency(copy, 1));
2450
3.30M
    return copy;
2451
3.30M
}
2452
2453
2454
/* Widen Unicode objects to larger buffers. Don't write terminating null
2455
   character. Return NULL on error. */
2456
2457
static void*
2458
unicode_askind(int skind, void const *data, Py_ssize_t len, int kind)
2459
1.49M
{
2460
1.49M
    void *result;
2461
2462
1.49M
    assert(skind < kind);
2463
1.49M
    switch (kind) {
2464
1.27M
    case PyUnicode_2BYTE_KIND:
2465
1.27M
        result = PyMem_New(Py_UCS2, len);
2466
1.27M
        if (!result)
2467
0
            return PyErr_NoMemory();
2468
1.27M
        assert(skind == PyUnicode_1BYTE_KIND);
2469
1.27M
        _PyUnicode_CONVERT_BYTES(
2470
1.27M
            Py_UCS1, Py_UCS2,
2471
1.27M
            (const Py_UCS1 *)data,
2472
1.27M
            ((const Py_UCS1 *)data) + len,
2473
1.27M
            result);
2474
1.27M
        return result;
2475
228k
    case PyUnicode_4BYTE_KIND:
2476
228k
        result = PyMem_New(Py_UCS4, len);
2477
228k
        if (!result)
2478
0
            return PyErr_NoMemory();
2479
228k
        if (skind == PyUnicode_2BYTE_KIND) {
2480
0
            _PyUnicode_CONVERT_BYTES(
2481
0
                Py_UCS2, Py_UCS4,
2482
0
                (const Py_UCS2 *)data,
2483
0
                ((const Py_UCS2 *)data) + len,
2484
0
                result);
2485
0
        }
2486
228k
        else {
2487
228k
            assert(skind == PyUnicode_1BYTE_KIND);
2488
228k
            _PyUnicode_CONVERT_BYTES(
2489
228k
                Py_UCS1, Py_UCS4,
2490
228k
                (const Py_UCS1 *)data,
2491
228k
                ((const Py_UCS1 *)data) + len,
2492
228k
                result);
2493
228k
        }
2494
228k
        return result;
2495
0
    default:
2496
0
        Py_UNREACHABLE();
2497
0
        return NULL;
2498
1.49M
    }
2499
1.49M
}
2500
2501
static Py_UCS4*
2502
as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2503
        int copy_null)
2504
83.3k
{
2505
83.3k
    int kind;
2506
83.3k
    const void *data;
2507
83.3k
    Py_ssize_t len, targetlen;
2508
83.3k
    kind = PyUnicode_KIND(string);
2509
83.3k
    data = PyUnicode_DATA(string);
2510
83.3k
    len = PyUnicode_GET_LENGTH(string);
2511
83.3k
    targetlen = len;
2512
83.3k
    if (copy_null)
2513
0
        targetlen++;
2514
83.3k
    if (!target) {
2515
0
        target = PyMem_New(Py_UCS4, targetlen);
2516
0
        if (!target) {
2517
0
            PyErr_NoMemory();
2518
0
            return NULL;
2519
0
        }
2520
0
    }
2521
83.3k
    else {
2522
83.3k
        if (targetsize < targetlen) {
2523
0
            PyErr_Format(PyExc_SystemError,
2524
0
                         "string is longer than the buffer");
2525
0
            if (copy_null && 0 < targetsize)
2526
0
                target[0] = 0;
2527
0
            return NULL;
2528
0
        }
2529
83.3k
    }
2530
83.3k
    if (kind == PyUnicode_1BYTE_KIND) {
2531
59.6k
        const Py_UCS1 *start = (const Py_UCS1 *) data;
2532
59.6k
        _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
2533
59.6k
    }
2534
23.6k
    else if (kind == PyUnicode_2BYTE_KIND) {
2535
16.8k
        const Py_UCS2 *start = (const Py_UCS2 *) data;
2536
16.8k
        _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2537
16.8k
    }
2538
6.82k
    else if (kind == PyUnicode_4BYTE_KIND) {
2539
6.82k
        memcpy(target, data, len * sizeof(Py_UCS4));
2540
6.82k
    }
2541
0
    else {
2542
0
        Py_UNREACHABLE();
2543
0
    }
2544
83.3k
    if (copy_null)
2545
0
        target[len] = 0;
2546
83.3k
    return target;
2547
83.3k
}
2548
2549
Py_UCS4*
2550
PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2551
                 int copy_null)
2552
83.3k
{
2553
83.3k
    if (target == NULL || targetsize < 0) {
2554
0
        PyErr_BadInternalCall();
2555
0
        return NULL;
2556
0
    }
2557
83.3k
    return as_ucs4(string, target, targetsize, copy_null);
2558
83.3k
}
2559
2560
Py_UCS4*
2561
PyUnicode_AsUCS4Copy(PyObject *string)
2562
0
{
2563
0
    return as_ucs4(string, NULL, 0, 1);
2564
0
}
2565
2566
/* maximum number of characters required for output of %jo or %jd or %p.
2567
   We need at most ceil(log8(256)*sizeof(intmax_t)) digits,
2568
   plus 1 for the sign, plus 2 for the 0x prefix (for %p),
2569
   plus 1 for the terminal NUL. */
2570
#define MAX_INTMAX_CHARS (5 + (sizeof(intmax_t)*8-1) / 3)
2571
2572
static int
2573
unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2574
                             Py_ssize_t width, Py_ssize_t precision, int flags)
2575
4.77M
{
2576
4.77M
    Py_ssize_t length, fill, arglen;
2577
4.77M
    Py_UCS4 maxchar;
2578
2579
4.77M
    length = PyUnicode_GET_LENGTH(str);
2580
4.77M
    if ((precision == -1 || precision >= length) && width <= length) {
2581
4.77M
        return _PyUnicodeWriter_WriteStr(writer, str);
2582
4.77M
    }
2583
2584
69
    if (precision != -1)
2585
69
        length = Py_MIN(precision, length);
2586
2587
69
    arglen = Py_MAX(length, width);
2588
69
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2589
38
        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2590
31
    else
2591
31
        maxchar = writer->maxchar;
2592
2593
69
    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1) {
2594
0
        return -1;
2595
0
    }
2596
69
    assert(_PyUnicodeWriter_CanWrite(writer));
2597
2598
69
    fill = Py_MAX(width - length, 0);
2599
69
    if (fill && !(flags & F_LJUST)) {
2600
0
        if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2601
0
            return -1;
2602
0
        writer->pos += fill;
2603
0
    }
2604
2605
69
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2606
69
                                  str, 0, length);
2607
69
    writer->pos += length;
2608
2609
69
    if (fill && (flags & F_LJUST)) {
2610
0
        if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2611
0
            return -1;
2612
0
        writer->pos += fill;
2613
0
    }
2614
2615
69
    return 0;
2616
69
}
2617
2618
static int
2619
unicode_fromformat_write_utf8(_PyUnicodeWriter *writer, const char *str,
2620
                              Py_ssize_t width, Py_ssize_t precision, int flags)
2621
1.67M
{
2622
    /* UTF-8 */
2623
1.67M
    Py_ssize_t *pconsumed = NULL;
2624
1.67M
    Py_ssize_t length;
2625
1.67M
    if (precision == -1) {
2626
812k
        length = strlen(str);
2627
812k
    }
2628
865k
    else {
2629
865k
        length = 0;
2630
14.9M
        while (length < precision && str[length]) {
2631
14.0M
            length++;
2632
14.0M
        }
2633
865k
        if (length == precision) {
2634
            /* The input string is not NUL-terminated.  If it ends with an
2635
             * incomplete UTF-8 sequence, truncate the string just before it.
2636
             * Incomplete sequences in the middle and sequences which cannot
2637
             * be valid prefixes are still treated as errors and replaced
2638
             * with \xfffd. */
2639
2.36k
            pconsumed = &length;
2640
2.36k
        }
2641
865k
    }
2642
2643
1.67M
    if (width < 0) {
2644
1.67M
        return _PyUnicode_DecodeUTF8Writer(writer, str, length,
2645
1.67M
                                           _Py_ERROR_REPLACE, "replace", pconsumed);
2646
1.67M
    }
2647
2648
0
    PyObject *unicode = PyUnicode_DecodeUTF8Stateful(str, length,
2649
0
                                                     "replace", pconsumed);
2650
0
    if (unicode == NULL)
2651
0
        return -1;
2652
2653
0
    int res = unicode_fromformat_write_str(writer, unicode,
2654
0
                                           width, -1, flags);
2655
0
    Py_DECREF(unicode);
2656
0
    return res;
2657
0
}
2658
2659
static int
2660
unicode_fromformat_write_wcstr(_PyUnicodeWriter *writer, const wchar_t *str,
2661
                              Py_ssize_t width, Py_ssize_t precision, int flags)
2662
0
{
2663
0
    Py_ssize_t length;
2664
0
    if (precision == -1) {
2665
0
        length = wcslen(str);
2666
0
    }
2667
0
    else {
2668
0
        length = 0;
2669
0
        while (length < precision && str[length]) {
2670
0
            length++;
2671
0
        }
2672
0
    }
2673
2674
0
    if (width < 0) {
2675
0
        return PyUnicodeWriter_WriteWideChar((PyUnicodeWriter*)writer,
2676
0
                                             str, length);
2677
0
    }
2678
2679
0
    PyObject *unicode = PyUnicode_FromWideChar(str, length);
2680
0
    if (unicode == NULL)
2681
0
        return -1;
2682
2683
0
    int res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
2684
0
    Py_DECREF(unicode);
2685
0
    return res;
2686
0
}
2687
2688
0
#define F_LONG 1
2689
54.5k
#define F_LONGLONG 2
2690
210k
#define F_SIZE 3
2691
0
#define F_PTRDIFF 4
2692
0
#define F_INTMAX 5
2693
2694
static const char*
2695
unicode_fromformat_arg(_PyUnicodeWriter *writer,
2696
                       const char *f, va_list *vargs)
2697
24.7M
{
2698
24.7M
    const char *p;
2699
24.7M
    Py_ssize_t len;
2700
24.7M
    int flags = 0;
2701
24.7M
    Py_ssize_t width;
2702
24.7M
    Py_ssize_t precision;
2703
2704
24.7M
    p = f;
2705
24.7M
    f++;
2706
24.7M
    if (*f == '%') {
2707
853k
        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
2708
0
            return NULL;
2709
853k
        f++;
2710
853k
        return f;
2711
853k
    }
2712
2713
    /* Parse flags. Example: "%-i" => flags=F_LJUST. */
2714
    /* Flags '+', ' ' and '#' are not particularly useful.
2715
     * They are not worth the implementation and maintenance costs.
2716
     * In addition, '#' should add "0" for "o" conversions for compatibility
2717
     * with printf, but it would confuse Python users. */
2718
23.8M
    while (1) {
2719
23.8M
        switch (*f++) {
2720
0
        case '-': flags |= F_LJUST; continue;
2721
2.08k
        case '0': flags |= F_ZERO; continue;
2722
0
        case '#': flags |= F_ALT; continue;
2723
23.8M
        }
2724
23.8M
        f--;
2725
23.8M
        break;
2726
23.8M
    }
2727
2728
    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2729
23.8M
    width = -1;
2730
23.8M
    if (*f == '*') {
2731
0
        width = va_arg(*vargs, int);
2732
0
        if (width < 0) {
2733
0
            flags |= F_LJUST;
2734
0
            width = -width;
2735
0
        }
2736
0
        f++;
2737
0
    }
2738
23.8M
    else if (Py_ISDIGIT((unsigned)*f)) {
2739
2.08k
        width = *f - '0';
2740
2.08k
        f++;
2741
2.08k
        while (Py_ISDIGIT((unsigned)*f)) {
2742
0
            if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2743
0
                PyErr_SetString(PyExc_ValueError,
2744
0
                                "width too big");
2745
0
                return NULL;
2746
0
            }
2747
0
            width = (width * 10) + (*f - '0');
2748
0
            f++;
2749
0
        }
2750
2.08k
    }
2751
23.8M
    precision = -1;
2752
23.8M
    if (*f == '.') {
2753
2.40M
        f++;
2754
2.40M
        if (*f == '*') {
2755
0
            precision = va_arg(*vargs, int);
2756
0
            if (precision < 0) {
2757
0
                precision = -2;
2758
0
            }
2759
0
            f++;
2760
0
        }
2761
2.40M
        else if (Py_ISDIGIT((unsigned)*f)) {
2762
2.40M
            precision = (*f - '0');
2763
2.40M
            f++;
2764
7.20M
            while (Py_ISDIGIT((unsigned)*f)) {
2765
4.80M
                if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2766
0
                    PyErr_SetString(PyExc_ValueError,
2767
0
                                    "precision too big");
2768
0
                    return NULL;
2769
0
                }
2770
4.80M
                precision = (precision * 10) + (*f - '0');
2771
4.80M
                f++;
2772
4.80M
            }
2773
2.40M
        }
2774
2.40M
    }
2775
2776
23.8M
    int sizemod = 0;
2777
23.8M
    if (*f == 'l') {
2778
27.2k
        if (f[1] == 'l') {
2779
27.2k
            sizemod = F_LONGLONG;
2780
27.2k
            f += 2;
2781
27.2k
        }
2782
0
        else {
2783
0
            sizemod = F_LONG;
2784
0
            ++f;
2785
0
        }
2786
27.2k
    }
2787
23.8M
    else if (*f == 'z') {
2788
105k
        sizemod = F_SIZE;
2789
105k
        ++f;
2790
105k
    }
2791
23.7M
    else if (*f == 't') {
2792
0
        sizemod = F_PTRDIFF;
2793
0
        ++f;
2794
0
    }
2795
23.7M
    else if (*f == 'j') {
2796
0
        sizemod = F_INTMAX;
2797
0
        ++f;
2798
0
    }
2799
23.8M
    if (f[0] != '\0' && f[1] == '\0')
2800
3.08M
        writer->overallocate = 0;
2801
2802
23.8M
    switch (*f) {
2803
16.0M
    case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
2804
16.0M
        break;
2805
1.36M
    case 'c': case 'p':
2806
1.36M
        if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
2807
1.36M
        break;
2808
1.67M
    case 's':
2809
1.67M
    case 'V':
2810
1.67M
        if (sizemod && sizemod != F_LONG) goto invalid_format;
2811
1.67M
        break;
2812
4.77M
    default:
2813
4.77M
        if (sizemod) goto invalid_format;
2814
4.77M
        break;
2815
23.8M
    }
2816
2817
23.8M
    switch (*f) {
2818
1.35M
    case 'c':
2819
1.35M
    {
2820
1.35M
        int ordinal = va_arg(*vargs, int);
2821
1.35M
        if (ordinal < 0 || ordinal > MAX_UNICODE) {
2822
0
            PyErr_SetString(PyExc_OverflowError,
2823
0
                            "character argument not in range(0x110000)");
2824
0
            return NULL;
2825
0
        }
2826
1.35M
        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
2827
0
            return NULL;
2828
1.35M
        break;
2829
1.35M
    }
2830
2831
16.0M
    case 'd': case 'i':
2832
16.0M
    case 'o': case 'u': case 'x': case 'X':
2833
16.0M
    {
2834
16.0M
        char buffer[MAX_INTMAX_CHARS];
2835
2836
        // Fill buffer using sprinf, with one of many possible format
2837
        // strings, like "%llX" for `long long` in hexadecimal.
2838
        // The type/size is in `sizemod`; the format is in `*f`.
2839
2840
        // Use macros with nested switches to keep the sprintf format strings
2841
        // as compile-time literals, avoiding warnings and maybe allowing
2842
        // optimizations.
2843
2844
        // `SPRINT` macro does one sprintf
2845
        // Example usage: SPRINT("l", "X", unsigned long) expands to
2846
        // sprintf(buffer, "%" "l" "X", va_arg(*vargs, unsigned long))
2847
16.0M
        #define SPRINT(SIZE_SPEC, FMT_CHAR, TYPE) \
2848
16.0M
            sprintf(buffer, "%" SIZE_SPEC FMT_CHAR, va_arg(*vargs, TYPE))
2849
2850
        // One inner switch to handle all format variants
2851
16.0M
        #define DO_SPRINTS(SIZE_SPEC, SIGNED_TYPE, UNSIGNED_TYPE)             \
2852
16.0M
            switch (*f) {                                                     \
2853
110
                case 'o': len = SPRINT(SIZE_SPEC, "o", UNSIGNED_TYPE); break; \
2854
27.2k
                case 'u': len = SPRINT(SIZE_SPEC, "u", UNSIGNED_TYPE); break; \
2855
1.65k
                case 'x': len = SPRINT(SIZE_SPEC, "x", UNSIGNED_TYPE); break; \
2856
997
                case 'X': len = SPRINT(SIZE_SPEC, "X", UNSIGNED_TYPE); break; \
2857
16.0M
                default:  len = SPRINT(SIZE_SPEC, "d", SIGNED_TYPE); break;   \
2858
16.0M
            }
2859
2860
        // Outer switch to handle all the sizes/types
2861
16.0M
        switch (sizemod) {
2862
0
            case F_LONG:     DO_SPRINTS("l", long, unsigned long); break;
2863
27.2k
            case F_LONGLONG: DO_SPRINTS("ll", long long, unsigned long long); break;
2864
105k
            case F_SIZE:     DO_SPRINTS("z", Py_ssize_t, size_t); break;
2865
0
            case F_PTRDIFF:  DO_SPRINTS("t", ptrdiff_t, ptrdiff_t); break;
2866
0
            case F_INTMAX:   DO_SPRINTS("j", intmax_t, uintmax_t); break;
2867
15.9M
            default:         DO_SPRINTS("", int, unsigned int); break;
2868
16.0M
        }
2869
16.0M
        #undef SPRINT
2870
16.0M
        #undef DO_SPRINTS
2871
2872
16.0M
        assert(len >= 1);
2873
2874
16.0M
        int sign = (buffer[0] == '-');
2875
16.0M
        len -= sign;
2876
2877
16.0M
        precision = Py_MAX(precision, len);
2878
16.0M
        width = Py_MAX(width, precision + sign);
2879
16.0M
        if ((flags & F_ZERO) && !(flags & F_LJUST)) {
2880
2.08k
            precision = width - sign;
2881
2.08k
        }
2882
2883
16.0M
        Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
2884
16.0M
        Py_ssize_t zeropad = Py_MAX(precision - len, 0);
2885
2886
16.0M
        if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1) {
2887
0
            return NULL;
2888
0
        }
2889
16.0M
        assert(_PyUnicodeWriter_CanWrite(writer));
2890
2891
16.0M
        if (spacepad && !(flags & F_LJUST)) {
2892
0
            if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
2893
0
                return NULL;
2894
0
            writer->pos += spacepad;
2895
0
        }
2896
2897
16.0M
        if (sign) {
2898
825
            if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
2899
0
                return NULL;
2900
825
        }
2901
2902
16.0M
        if (zeropad) {
2903
623
            if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
2904
0
                return NULL;
2905
623
            writer->pos += zeropad;
2906
623
        }
2907
2908
16.0M
        if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
2909
0
            return NULL;
2910
2911
16.0M
        if (spacepad && (flags & F_LJUST)) {
2912
0
            if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
2913
0
                return NULL;
2914
0
            writer->pos += spacepad;
2915
0
        }
2916
16.0M
        break;
2917
16.0M
    }
2918
2919
16.0M
    case 'p':
2920
4.80k
    {
2921
4.80k
        char number[MAX_INTMAX_CHARS];
2922
2923
4.80k
        len = sprintf(number, "%p", va_arg(*vargs, void*));
2924
4.80k
        assert(len >= 0);
2925
2926
        /* %p is ill-defined:  ensure leading 0x. */
2927
4.80k
        if (number[1] == 'X')
2928
0
            number[1] = 'x';
2929
4.80k
        else if (number[1] != 'x') {
2930
0
            memmove(number + 2, number,
2931
0
                    strlen(number) + 1);
2932
0
            number[0] = '0';
2933
0
            number[1] = 'x';
2934
0
            len += 2;
2935
0
        }
2936
2937
4.80k
        if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
2938
0
            return NULL;
2939
4.80k
        break;
2940
4.80k
    }
2941
2942
1.67M
    case 's':
2943
1.67M
    {
2944
1.67M
        if (sizemod) {
2945
0
            const wchar_t *s = va_arg(*vargs, const wchar_t*);
2946
0
            if (unicode_fromformat_write_wcstr(writer, s, width, precision, flags) < 0)
2947
0
                return NULL;
2948
0
        }
2949
1.67M
        else {
2950
            /* UTF-8 */
2951
1.67M
            const char *s = va_arg(*vargs, const char*);
2952
1.67M
            if (unicode_fromformat_write_utf8(writer, s, width, precision, flags) < 0)
2953
0
                return NULL;
2954
1.67M
        }
2955
1.67M
        break;
2956
1.67M
    }
2957
2958
1.88M
    case 'U':
2959
1.88M
    {
2960
1.88M
        PyObject *obj = va_arg(*vargs, PyObject *);
2961
1.88M
        assert(obj && _PyUnicode_CHECK(obj));
2962
2963
1.88M
        if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2964
0
            return NULL;
2965
1.88M
        break;
2966
1.88M
    }
2967
2968
1.88M
    case 'V':
2969
565
    {
2970
565
        PyObject *obj = va_arg(*vargs, PyObject *);
2971
565
        const char *str;
2972
565
        const wchar_t *wstr;
2973
565
        if (sizemod) {
2974
0
            wstr = va_arg(*vargs, const wchar_t*);
2975
0
        }
2976
565
        else {
2977
565
            str = va_arg(*vargs, const char *);
2978
565
        }
2979
565
        if (obj) {
2980
0
            assert(_PyUnicode_CHECK(obj));
2981
0
            if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2982
0
                return NULL;
2983
0
        }
2984
565
        else if (sizemod) {
2985
0
            assert(wstr != NULL);
2986
0
            if (unicode_fromformat_write_wcstr(writer, wstr, width, precision, flags) < 0)
2987
0
                return NULL;
2988
0
        }
2989
565
        else {
2990
565
            assert(str != NULL);
2991
565
            if (unicode_fromformat_write_utf8(writer, str, width, precision, flags) < 0)
2992
0
                return NULL;
2993
565
        }
2994
565
        break;
2995
565
    }
2996
2997
1.78k
    case 'S':
2998
1.78k
    {
2999
1.78k
        PyObject *obj = va_arg(*vargs, PyObject *);
3000
1.78k
        PyObject *str;
3001
1.78k
        assert(obj);
3002
1.78k
        str = PyObject_Str(obj);
3003
1.78k
        if (!str)
3004
0
            return NULL;
3005
1.78k
        if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
3006
0
            Py_DECREF(str);
3007
0
            return NULL;
3008
0
        }
3009
1.78k
        Py_DECREF(str);
3010
1.78k
        break;
3011
1.78k
    }
3012
3013
1.54M
    case 'R':
3014
1.54M
    {
3015
1.54M
        PyObject *obj = va_arg(*vargs, PyObject *);
3016
1.54M
        PyObject *repr;
3017
1.54M
        assert(obj);
3018
1.54M
        repr = PyObject_Repr(obj);
3019
1.54M
        if (!repr)
3020
0
            return NULL;
3021
1.54M
        if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
3022
0
            Py_DECREF(repr);
3023
0
            return NULL;
3024
0
        }
3025
1.54M
        Py_DECREF(repr);
3026
1.54M
        break;
3027
1.54M
    }
3028
3029
0
    case 'A':
3030
0
    {
3031
0
        PyObject *obj = va_arg(*vargs, PyObject *);
3032
0
        PyObject *ascii;
3033
0
        assert(obj);
3034
0
        ascii = PyObject_ASCII(obj);
3035
0
        if (!ascii)
3036
0
            return NULL;
3037
0
        if (unicode_fromformat_write_str(writer, ascii, width, precision, flags) == -1) {
3038
0
            Py_DECREF(ascii);
3039
0
            return NULL;
3040
0
        }
3041
0
        Py_DECREF(ascii);
3042
0
        break;
3043
0
    }
3044
3045
1.34M
    case 'T':
3046
1.34M
    {
3047
1.34M
        PyObject *obj = va_arg(*vargs, PyObject *);
3048
1.34M
        PyTypeObject *type = (PyTypeObject *)Py_NewRef(Py_TYPE(obj));
3049
3050
1.34M
        PyObject *type_name;
3051
1.34M
        if (flags & F_ALT) {
3052
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3053
0
        }
3054
1.34M
        else {
3055
1.34M
            type_name = PyType_GetFullyQualifiedName(type);
3056
1.34M
        }
3057
1.34M
        Py_DECREF(type);
3058
1.34M
        if (!type_name) {
3059
0
            return NULL;
3060
0
        }
3061
3062
1.34M
        if (unicode_fromformat_write_str(writer, type_name,
3063
1.34M
                                         width, precision, flags) == -1) {
3064
0
            Py_DECREF(type_name);
3065
0
            return NULL;
3066
0
        }
3067
1.34M
        Py_DECREF(type_name);
3068
1.34M
        break;
3069
1.34M
    }
3070
3071
0
    case 'N':
3072
0
    {
3073
0
        PyObject *type_raw = va_arg(*vargs, PyObject *);
3074
0
        assert(type_raw != NULL);
3075
3076
0
        if (!PyType_Check(type_raw)) {
3077
0
            PyErr_SetString(PyExc_TypeError, "%N argument must be a type");
3078
0
            return NULL;
3079
0
        }
3080
0
        PyTypeObject *type = (PyTypeObject*)type_raw;
3081
3082
0
        PyObject *type_name;
3083
0
        if (flags & F_ALT) {
3084
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3085
0
        }
3086
0
        else {
3087
0
            type_name = PyType_GetFullyQualifiedName(type);
3088
0
        }
3089
0
        if (!type_name) {
3090
0
            return NULL;
3091
0
        }
3092
0
        if (unicode_fromformat_write_str(writer, type_name,
3093
0
                                         width, precision, flags) == -1) {
3094
0
            Py_DECREF(type_name);
3095
0
            return NULL;
3096
0
        }
3097
0
        Py_DECREF(type_name);
3098
0
        break;
3099
0
    }
3100
3101
0
    default:
3102
0
    invalid_format:
3103
0
        PyErr_Format(PyExc_SystemError, "invalid format string: %s", p);
3104
0
        return NULL;
3105
23.8M
    }
3106
3107
23.8M
    f++;
3108
23.8M
    return f;
3109
23.8M
}
3110
3111
static int
3112
unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
3113
11.8M
{
3114
11.8M
    Py_ssize_t len = strlen(format);
3115
11.8M
    writer->min_length += len + 100;
3116
11.8M
    writer->overallocate = 1;
3117
3118
    // Copy varags to be able to pass a reference to a subfunction.
3119
11.8M
    va_list vargs2;
3120
11.8M
    va_copy(vargs2, vargs);
3121
3122
    // _PyUnicodeWriter_WriteASCIIString() below requires the format string
3123
    // to be encoded to ASCII.
3124
11.8M
    int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)format, (Py_UCS1*)format + len) < 128);
3125
11.8M
    if (!is_ascii) {
3126
0
        Py_ssize_t i;
3127
0
        for (i=0; i < len && (unsigned char)format[i] <= 127; i++);
3128
0
        PyErr_Format(PyExc_ValueError,
3129
0
            "PyUnicode_FromFormatV() expects an ASCII-encoded format "
3130
0
            "string, got a non-ASCII byte: 0x%02x",
3131
0
            (unsigned char)format[i]);
3132
0
        goto fail;
3133
0
    }
3134
3135
67.6M
    for (const char *f = format; *f; ) {
3136
55.7M
        if (*f == '%') {
3137
24.7M
            f = unicode_fromformat_arg(writer, f, &vargs2);
3138
24.7M
            if (f == NULL)
3139
0
                goto fail;
3140
24.7M
        }
3141
31.0M
        else {
3142
31.0M
            const char *p = strchr(f, '%');
3143
31.0M
            if (p != NULL) {
3144
22.3M
                len = p - f;
3145
22.3M
            }
3146
8.73M
            else {
3147
8.73M
                len = strlen(f);
3148
8.73M
                writer->overallocate = 0;
3149
8.73M
            }
3150
3151
31.0M
            if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
3152
0
                goto fail;
3153
0
            }
3154
31.0M
            f += len;
3155
31.0M
        }
3156
55.7M
    }
3157
11.8M
    va_end(vargs2);
3158
11.8M
    return 0;
3159
3160
0
  fail:
3161
0
    va_end(vargs2);
3162
0
    return -1;
3163
11.8M
}
3164
3165
PyObject *
3166
PyUnicode_FromFormatV(const char *format, va_list vargs)
3167
11.8M
{
3168
11.8M
    _PyUnicodeWriter writer;
3169
11.8M
    _PyUnicodeWriter_Init(&writer);
3170
3171
11.8M
    if (unicode_from_format(&writer, format, vargs) < 0) {
3172
0
        _PyUnicodeWriter_Dealloc(&writer);
3173
0
        return NULL;
3174
0
    }
3175
11.8M
    return _PyUnicodeWriter_Finish(&writer);
3176
11.8M
}
3177
3178
PyObject *
3179
PyUnicode_FromFormat(const char *format, ...)
3180
560k
{
3181
560k
    PyObject* ret;
3182
560k
    va_list vargs;
3183
3184
560k
    va_start(vargs, format);
3185
560k
    ret = PyUnicode_FromFormatV(format, vargs);
3186
560k
    va_end(vargs);
3187
560k
    return ret;
3188
560k
}
3189
3190
int
3191
PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...)
3192
0
{
3193
0
    va_list vargs;
3194
0
    va_start(vargs, format);
3195
0
    int res = _PyUnicodeWriter_FormatV(writer, format, vargs);
3196
0
    va_end(vargs);
3197
0
    return res;
3198
0
}
3199
3200
int
3201
_PyUnicodeWriter_FormatV(PyUnicodeWriter *pub_writer, const char *format,
3202
                         va_list vargs)
3203
0
{
3204
0
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
3205
0
    Py_ssize_t old_pos = writer->pos;
3206
0
    Py_UCS4 old_maxchar = writer->maxchar;
3207
3208
0
    int res = unicode_from_format(writer, format, vargs);
3209
3210
0
    if (res < 0) {
3211
0
        writer->pos = old_pos;
3212
0
        if (writer->maxchar > old_maxchar) {
3213
            // _PyUnicodeWriter_Finish() will check maxchar
3214
0
            writer->recheck_maxchar = 1;
3215
0
        }
3216
0
    }
3217
0
    return res;
3218
0
}
3219
3220
static Py_ssize_t
3221
unicode_get_widechar_size(PyObject *unicode)
3222
180k
{
3223
180k
    Py_ssize_t res;
3224
3225
180k
    assert(unicode != NULL);
3226
180k
    assert(_PyUnicode_CHECK(unicode));
3227
3228
180k
    res = _PyUnicode_LENGTH(unicode);
3229
#if SIZEOF_WCHAR_T == 2
3230
    if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
3231
        const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3232
        const Py_UCS4 *end = s + res;
3233
        for (; s < end; ++s) {
3234
            if (*s > 0xFFFF) {
3235
                ++res;
3236
            }
3237
        }
3238
    }
3239
#endif
3240
180k
    return res;
3241
180k
}
3242
3243
static void
3244
unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3245
180k
{
3246
180k
    assert(unicode != NULL);
3247
180k
    assert(_PyUnicode_CHECK(unicode));
3248
3249
180k
    if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
3250
1.76k
        memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
3251
1.76k
        return;
3252
1.76k
    }
3253
3254
178k
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3255
151k
        const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3256
4.27M
        for (; size--; ++s, ++w) {
3257
4.12M
            *w = *s;
3258
4.12M
        }
3259
151k
    }
3260
26.9k
    else {
3261
26.9k
#if SIZEOF_WCHAR_T == 4
3262
26.9k
        assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3263
26.9k
        const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3264
1.57M
        for (; size--; ++s, ++w) {
3265
1.54M
            *w = *s;
3266
1.54M
        }
3267
#else
3268
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3269
        const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3270
        for (; size--; ++s, ++w) {
3271
            Py_UCS4 ch = *s;
3272
            if (ch > 0xFFFF) {
3273
                assert(ch <= MAX_UNICODE);
3274
                /* encode surrogate pair in this case */
3275
                *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3276
                if (!size--)
3277
                    break;
3278
                *w = Py_UNICODE_LOW_SURROGATE(ch);
3279
            }
3280
            else {
3281
                *w = ch;
3282
            }
3283
        }
3284
#endif
3285
26.9k
    }
3286
178k
}
3287
3288
#ifdef HAVE_WCHAR_H
3289
3290
/* Convert a Unicode object to a wide character string.
3291
3292
   - If w is NULL: return the number of wide characters (including the null
3293
     character) required to convert the unicode object. Ignore size argument.
3294
3295
   - Otherwise: return the number of wide characters (excluding the null
3296
     character) written into w. Write at most size wide characters (including
3297
     the null character). */
3298
Py_ssize_t
3299
PyUnicode_AsWideChar(PyObject *unicode,
3300
                     wchar_t *w,
3301
                     Py_ssize_t size)
3302
0
{
3303
0
    Py_ssize_t res;
3304
3305
0
    if (unicode == NULL) {
3306
0
        PyErr_BadInternalCall();
3307
0
        return -1;
3308
0
    }
3309
0
    if (!PyUnicode_Check(unicode)) {
3310
0
        PyErr_BadArgument();
3311
0
        return -1;
3312
0
    }
3313
3314
0
    res = unicode_get_widechar_size(unicode);
3315
0
    if (w == NULL) {
3316
0
        return res + 1;
3317
0
    }
3318
3319
0
    if (size > res) {
3320
0
        size = res + 1;
3321
0
    }
3322
0
    else {
3323
0
        res = size;
3324
0
    }
3325
0
    unicode_copy_as_widechar(unicode, w, size);
3326
3327
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
3328
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
3329
       non-Unicode locales and hence needs conversion first. */
3330
    if (_Py_LocaleUsesNonUnicodeWchar()) {
3331
        if (_Py_EncodeNonUnicodeWchar_InPlace(w, size) < 0) {
3332
            return -1;
3333
        }
3334
    }
3335
#endif
3336
3337
0
    return res;
3338
0
}
3339
3340
wchar_t*
3341
PyUnicode_AsWideCharString(PyObject *unicode,
3342
                           Py_ssize_t *size)
3343
180k
{
3344
180k
    wchar_t *buffer;
3345
180k
    Py_ssize_t buflen;
3346
3347
180k
    if (unicode == NULL) {
3348
0
        PyErr_BadInternalCall();
3349
0
        return NULL;
3350
0
    }
3351
180k
    if (!PyUnicode_Check(unicode)) {
3352
0
        PyErr_BadArgument();
3353
0
        return NULL;
3354
0
    }
3355
3356
180k
    buflen = unicode_get_widechar_size(unicode);
3357
180k
    buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
3358
180k
    if (buffer == NULL) {
3359
0
        PyErr_NoMemory();
3360
0
        return NULL;
3361
0
    }
3362
180k
    unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3363
3364
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
3365
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
3366
       non-Unicode locales and hence needs conversion first. */
3367
    if (_Py_LocaleUsesNonUnicodeWchar()) {
3368
        if (_Py_EncodeNonUnicodeWchar_InPlace(buffer, (buflen + 1)) < 0) {
3369
            return NULL;
3370
        }
3371
    }
3372
#endif
3373
3374
180k
    if (size != NULL) {
3375
177k
        *size = buflen;
3376
177k
    }
3377
3.19k
    else if (wcslen(buffer) != (size_t)buflen) {
3378
0
        PyMem_Free(buffer);
3379
0
        PyErr_SetString(PyExc_ValueError,
3380
0
                        "embedded null character");
3381
0
        return NULL;
3382
0
    }
3383
180k
    return buffer;
3384
180k
}
3385
3386
#endif /* HAVE_WCHAR_H */
3387
3388
int
3389
_PyUnicode_WideCharString_Converter(PyObject *obj, void *ptr)
3390
0
{
3391
0
    wchar_t **p = (wchar_t **)ptr;
3392
0
    if (obj == NULL) {
3393
0
        PyMem_Free(*p);
3394
0
        *p = NULL;
3395
0
        return 1;
3396
0
    }
3397
0
    if (PyUnicode_Check(obj)) {
3398
0
        *p = PyUnicode_AsWideCharString(obj, NULL);
3399
0
        if (*p == NULL) {
3400
0
            return 0;
3401
0
        }
3402
0
        return Py_CLEANUP_SUPPORTED;
3403
0
    }
3404
0
    PyErr_Format(PyExc_TypeError,
3405
0
                 "argument must be str, not %.50s",
3406
0
                 Py_TYPE(obj)->tp_name);
3407
0
    return 0;
3408
0
}
3409
3410
int
3411
_PyUnicode_WideCharString_Opt_Converter(PyObject *obj, void *ptr)
3412
0
{
3413
0
    wchar_t **p = (wchar_t **)ptr;
3414
0
    if (obj == NULL) {
3415
0
        PyMem_Free(*p);
3416
0
        *p = NULL;
3417
0
        return 1;
3418
0
    }
3419
0
    if (obj == Py_None) {
3420
0
        *p = NULL;
3421
0
        return 1;
3422
0
    }
3423
0
    if (PyUnicode_Check(obj)) {
3424
0
        *p = PyUnicode_AsWideCharString(obj, NULL);
3425
0
        if (*p == NULL) {
3426
0
            return 0;
3427
0
        }
3428
0
        return Py_CLEANUP_SUPPORTED;
3429
0
    }
3430
0
    PyErr_Format(PyExc_TypeError,
3431
0
                 "argument must be str or None, not %.50s",
3432
0
                 Py_TYPE(obj)->tp_name);
3433
0
    return 0;
3434
0
}
3435
3436
PyObject *
3437
PyUnicode_FromOrdinal(int ordinal)
3438
19.1M
{
3439
19.1M
    if (ordinal < 0 || ordinal > MAX_UNICODE) {
3440
26
        PyErr_SetString(PyExc_ValueError,
3441
26
                        "chr() arg not in range(0x110000)");
3442
26
        return NULL;
3443
26
    }
3444
3445
19.1M
    return unicode_char((Py_UCS4)ordinal);
3446
19.1M
}
3447
3448
PyObject *
3449
PyUnicode_FromObject(PyObject *obj)
3450
3.85M
{
3451
    /* XXX Perhaps we should make this API an alias of
3452
       PyObject_Str() instead ?! */
3453
3.85M
    if (PyUnicode_CheckExact(obj)) {
3454
3.85M
        return Py_NewRef(obj);
3455
3.85M
    }
3456
0
    if (PyUnicode_Check(obj)) {
3457
        /* For a Unicode subtype that's not a Unicode object,
3458
           return a true Unicode object with the same data. */
3459
0
        return _PyUnicode_Copy(obj);
3460
0
    }
3461
0
    PyErr_Format(PyExc_TypeError,
3462
0
                 "Can't convert '%.100s' object to str implicitly",
3463
0
                 Py_TYPE(obj)->tp_name);
3464
0
    return NULL;
3465
0
}
3466
3467
PyObject *
3468
PyUnicode_FromEncodedObject(PyObject *obj,
3469
                            const char *encoding,
3470
                            const char *errors)
3471
38.2M
{
3472
38.2M
    Py_buffer buffer;
3473
38.2M
    PyObject *v;
3474
3475
38.2M
    if (obj == NULL) {
3476
0
        PyErr_BadInternalCall();
3477
0
        return NULL;
3478
0
    }
3479
3480
    /* Decoding bytes objects is the most common case and should be fast */
3481
38.2M
    if (PyBytes_Check(obj)) {
3482
38.2M
        if (PyBytes_GET_SIZE(obj) == 0) {
3483
14.8M
            if (unicode_check_encoding_errors(encoding, errors) < 0) {
3484
0
                return NULL;
3485
0
            }
3486
14.8M
            _Py_RETURN_UNICODE_EMPTY();
3487
14.8M
        }
3488
23.3M
        return PyUnicode_Decode(
3489
23.3M
                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3490
23.3M
                encoding, errors);
3491
38.2M
    }
3492
3493
0
    if (PyUnicode_Check(obj)) {
3494
0
        PyErr_SetString(PyExc_TypeError,
3495
0
                        "decoding str is not supported");
3496
0
        return NULL;
3497
0
    }
3498
3499
    /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3500
0
    if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3501
0
        PyErr_Format(PyExc_TypeError,
3502
0
                     "decoding to str: need a bytes-like object, %.80s found",
3503
0
                     Py_TYPE(obj)->tp_name);
3504
0
        return NULL;
3505
0
    }
3506
3507
0
    if (buffer.len == 0) {
3508
0
        PyBuffer_Release(&buffer);
3509
0
        if (unicode_check_encoding_errors(encoding, errors) < 0) {
3510
0
            return NULL;
3511
0
        }
3512
0
        _Py_RETURN_UNICODE_EMPTY();
3513
0
    }
3514
3515
0
    v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
3516
0
    PyBuffer_Release(&buffer);
3517
0
    return v;
3518
0
}
3519
3520
/* Normalize an encoding name like encodings.normalize_encoding()
3521
   but allow to convert to lowercase if *to_lower* is true.
3522
   Return 1 on success, or 0 on error (encoding is longer than lower_len-1). */
3523
int
3524
_Py_normalize_encoding(const char *encoding,
3525
                       char *lower,
3526
                       size_t lower_len,
3527
                       int to_lower)
3528
35.3M
{
3529
35.3M
    const char *e;
3530
35.3M
    char *l;
3531
35.3M
    char *l_end;
3532
35.3M
    int punct;
3533
3534
35.3M
    assert(encoding != NULL);
3535
3536
35.3M
    e = encoding;
3537
35.3M
    l = lower;
3538
35.3M
    l_end = &lower[lower_len - 1];
3539
35.3M
    punct = 0;
3540
239M
    while (1) {
3541
239M
        char c = *e;
3542
239M
        if (c == 0) {
3543
34.3M
            break;
3544
34.3M
        }
3545
3546
204M
        if (Py_ISALNUM(c) || c == '.') {
3547
184M
            if (punct && l != lower) {
3548
14.6M
                if (l == l_end) {
3549
1.99k
                    return 0;
3550
1.99k
                }
3551
14.6M
                *l++ = '_';
3552
14.6M
            }
3553
184M
            punct = 0;
3554
3555
184M
            if (l == l_end) {
3556
1.02M
                return 0;
3557
1.02M
            }
3558
183M
            *l++ = to_lower ? Py_TOLOWER(c) : c;
3559
183M
        }
3560
20.1M
        else {
3561
20.1M
            punct = 1;
3562
20.1M
        }
3563
3564
203M
        e++;
3565
203M
    }
3566
34.3M
    *l = '\0';
3567
34.3M
    return 1;
3568
35.3M
}
3569
3570
PyObject *
3571
PyUnicode_Decode(const char *s,
3572
                 Py_ssize_t size,
3573
                 const char *encoding,
3574
                 const char *errors)
3575
24.5M
{
3576
24.5M
    PyObject *buffer = NULL, *unicode;
3577
24.5M
    Py_buffer info;
3578
24.5M
    char buflower[11];   /* strlen("iso-8859-1\0") == 11, longest shortcut */
3579
3580
24.5M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3581
0
        return NULL;
3582
0
    }
3583
3584
24.5M
    if (size == 0) {
3585
0
        _Py_RETURN_UNICODE_EMPTY();
3586
0
    }
3587
3588
24.5M
    if (encoding == NULL) {
3589
63.2k
        return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3590
63.2k
    }
3591
3592
    /* Shortcuts for common default encodings */
3593
24.4M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3594
24.4M
        char *lower = buflower;
3595
3596
        /* Fast paths */
3597
24.4M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3598
4.02M
            lower += 3;
3599
4.02M
            if (*lower == '_') {
3600
                /* Match "utf8" and "utf_8" */
3601
4.02M
                lower++;
3602
4.02M
            }
3603
3604
4.02M
            if (lower[0] == '8' && lower[1] == 0) {
3605
3.98M
                return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3606
3.98M
            }
3607
38.1k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3608
221
                return PyUnicode_DecodeUTF16(s, size, errors, 0);
3609
221
            }
3610
37.9k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3611
122
                return PyUnicode_DecodeUTF32(s, size, errors, 0);
3612
122
            }
3613
4.02M
        }
3614
20.4M
        else {
3615
20.4M
            if (strcmp(lower, "ascii") == 0
3616
14.2M
                || strcmp(lower, "us_ascii") == 0) {
3617
14.2M
                return PyUnicode_DecodeASCII(s, size, errors);
3618
14.2M
            }
3619
    #ifdef MS_WINDOWS
3620
            else if (strcmp(lower, "mbcs") == 0) {
3621
                return PyUnicode_DecodeMBCS(s, size, errors);
3622
            }
3623
    #endif
3624
6.20M
            else if (strcmp(lower, "latin1") == 0
3625
6.20M
                     || strcmp(lower, "latin_1") == 0
3626
2.67M
                     || strcmp(lower, "iso_8859_1") == 0
3627
3.55M
                     || strcmp(lower, "iso8859_1") == 0) {
3628
3.55M
                return PyUnicode_DecodeLatin1(s, size, errors);
3629
3.55M
            }
3630
20.4M
        }
3631
24.4M
    }
3632
3633
    /* Decode via the codec registry */
3634
2.69M
    buffer = NULL;
3635
2.69M
    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
3636
0
        goto onError;
3637
2.69M
    buffer = PyMemoryView_FromBuffer(&info);
3638
2.69M
    if (buffer == NULL)
3639
0
        goto onError;
3640
2.69M
    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
3641
2.69M
    if (unicode == NULL)
3642
69.9k
        goto onError;
3643
2.62M
    if (!PyUnicode_Check(unicode)) {
3644
0
        PyErr_Format(PyExc_TypeError,
3645
0
                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
3646
0
                     "use codecs.decode() to decode to arbitrary types",
3647
0
                     encoding,
3648
0
                     Py_TYPE(unicode)->tp_name);
3649
0
        Py_DECREF(unicode);
3650
0
        goto onError;
3651
0
    }
3652
2.62M
    Py_DECREF(buffer);
3653
2.62M
    return unicode_result(unicode);
3654
3655
69.9k
  onError:
3656
69.9k
    Py_XDECREF(buffer);
3657
69.9k
    return NULL;
3658
2.62M
}
3659
3660
PyAPI_FUNC(PyObject *)
3661
PyUnicode_AsDecodedObject(PyObject *unicode,
3662
                          const char *encoding,
3663
                          const char *errors)
3664
0
{
3665
0
    if (!PyUnicode_Check(unicode)) {
3666
0
        PyErr_BadArgument();
3667
0
        return NULL;
3668
0
    }
3669
3670
0
    if (encoding == NULL)
3671
0
        encoding = PyUnicode_GetDefaultEncoding();
3672
3673
    /* Decode via the codec registry */
3674
0
    return PyCodec_Decode(unicode, encoding, errors);
3675
0
}
3676
3677
PyAPI_FUNC(PyObject *)
3678
PyUnicode_AsDecodedUnicode(PyObject *unicode,
3679
                           const char *encoding,
3680
                           const char *errors)
3681
0
{
3682
0
    PyObject *v;
3683
3684
0
    if (!PyUnicode_Check(unicode)) {
3685
0
        PyErr_BadArgument();
3686
0
        goto onError;
3687
0
    }
3688
3689
0
    if (encoding == NULL)
3690
0
        encoding = PyUnicode_GetDefaultEncoding();
3691
3692
    /* Decode via the codec registry */
3693
0
    v = PyCodec_Decode(unicode, encoding, errors);
3694
0
    if (v == NULL)
3695
0
        goto onError;
3696
0
    if (!PyUnicode_Check(v)) {
3697
0
        PyErr_Format(PyExc_TypeError,
3698
0
                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
3699
0
                     "use codecs.decode() to decode to arbitrary types",
3700
0
                     encoding,
3701
0
                     Py_TYPE(unicode)->tp_name);
3702
0
        Py_DECREF(v);
3703
0
        goto onError;
3704
0
    }
3705
0
    return unicode_result(v);
3706
3707
0
  onError:
3708
0
    return NULL;
3709
0
}
3710
3711
PyAPI_FUNC(PyObject *)
3712
PyUnicode_AsEncodedObject(PyObject *unicode,
3713
                          const char *encoding,
3714
                          const char *errors)
3715
0
{
3716
0
    PyObject *v;
3717
3718
0
    if (!PyUnicode_Check(unicode)) {
3719
0
        PyErr_BadArgument();
3720
0
        goto onError;
3721
0
    }
3722
3723
0
    if (encoding == NULL)
3724
0
        encoding = PyUnicode_GetDefaultEncoding();
3725
3726
    /* Encode via the codec registry */
3727
0
    v = PyCodec_Encode(unicode, encoding, errors);
3728
0
    if (v == NULL)
3729
0
        goto onError;
3730
0
    return v;
3731
3732
0
  onError:
3733
0
    return NULL;
3734
0
}
3735
3736
3737
static PyObject *
3738
unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
3739
                      int current_locale)
3740
1.44k
{
3741
1.44k
    Py_ssize_t wlen;
3742
1.44k
    wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3743
1.44k
    if (wstr == NULL) {
3744
0
        return NULL;
3745
0
    }
3746
3747
1.44k
    if ((size_t)wlen != wcslen(wstr)) {
3748
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
3749
0
        PyMem_Free(wstr);
3750
0
        return NULL;
3751
0
    }
3752
3753
1.44k
    char *str;
3754
1.44k
    size_t str_len;
3755
1.44k
    size_t error_pos;
3756
1.44k
    int res = _Py_EncodeLocale(wstr, &str, &str_len, &error_pos,
3757
1.44k
                               current_locale, error_handler);
3758
1.44k
    PyMem_Free(wstr);
3759
3760
1.44k
    if (res != 0) {
3761
0
        if (res == _Py_CODEC_ENCODE_ERROR) {
3762
0
            PyObject *exc;
3763
0
            assert(error_pos <= (size_t)(PY_SSIZE_T_MAX - 1));
3764
0
            exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3765
0
                    "locale", unicode,
3766
0
                    (Py_ssize_t)error_pos,
3767
0
                    (Py_ssize_t)(error_pos+1),
3768
0
                    "encode error");
3769
0
            if (exc != NULL) {
3770
0
                PyCodec_StrictErrors(exc);
3771
0
                Py_DECREF(exc);
3772
0
            }
3773
0
        }
3774
0
        else if (res == _Py_CODEC_UNSUPPORTED_ERROR_HANDLER) {
3775
0
            PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3776
0
        }
3777
0
        else {
3778
0
            assert(res == _Py_CODEC_MEMORY_ERROR);
3779
0
            PyErr_NoMemory();
3780
0
        }
3781
0
        return NULL;
3782
0
    }
3783
3784
1.44k
    PyObject *bytes = PyBytes_FromStringAndSize(str, str_len);
3785
1.44k
    PyMem_RawFree(str);
3786
1.44k
    return bytes;
3787
1.44k
}
3788
3789
PyObject *
3790
PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3791
0
{
3792
0
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3793
0
    return unicode_encode_locale(unicode, error_handler, 1);
3794
0
}
3795
3796
PyObject *
3797
PyUnicode_EncodeFSDefault(PyObject *unicode)
3798
718k
{
3799
718k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3800
718k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3801
718k
    if (fs_codec->utf8) {
3802
717k
        return unicode_encode_utf8(unicode,
3803
717k
                                   fs_codec->error_handler,
3804
717k
                                   fs_codec->errors);
3805
717k
    }
3806
1.44k
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3807
1.44k
    else if (fs_codec->encoding) {
3808
0
        return PyUnicode_AsEncodedString(unicode,
3809
0
                                         fs_codec->encoding,
3810
0
                                         fs_codec->errors);
3811
0
    }
3812
1.44k
#endif
3813
1.44k
    else {
3814
        /* Before _PyUnicode_InitEncodings() is called, the Python codec
3815
           machinery is not ready and so cannot be used:
3816
           use wcstombs() in this case. */
3817
1.44k
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3818
1.44k
        const wchar_t *filesystem_errors = config->filesystem_errors;
3819
1.44k
        assert(filesystem_errors != NULL);
3820
1.44k
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3821
1.44k
        assert(errors != _Py_ERROR_UNKNOWN);
3822
#ifdef _Py_FORCE_UTF8_FS_ENCODING
3823
        return unicode_encode_utf8(unicode, errors, NULL);
3824
#else
3825
1.44k
        return unicode_encode_locale(unicode, errors, 0);
3826
1.44k
#endif
3827
1.44k
    }
3828
718k
}
3829
3830
PyObject *
3831
PyUnicode_AsEncodedString(PyObject *unicode,
3832
                          const char *encoding,
3833
                          const char *errors)
3834
24.4M
{
3835
24.4M
    PyObject *v;
3836
24.4M
    char buflower[11];   /* strlen("iso_8859_1\0") == 11, longest shortcut */
3837
3838
24.4M
    if (!PyUnicode_Check(unicode)) {
3839
0
        PyErr_BadArgument();
3840
0
        return NULL;
3841
0
    }
3842
3843
24.4M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3844
0
        return NULL;
3845
0
    }
3846
3847
24.4M
    if (encoding == NULL) {
3848
13.5M
        return _PyUnicode_AsUTF8String(unicode, errors);
3849
13.5M
    }
3850
3851
    /* Shortcuts for common default encodings */
3852
10.9M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3853
9.88M
        char *lower = buflower;
3854
3855
        /* Fast paths */
3856
9.88M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3857
5.73M
            lower += 3;
3858
5.73M
            if (*lower == '_') {
3859
                /* Match "utf8" and "utf_8" */
3860
5.73M
                lower++;
3861
5.73M
            }
3862
3863
5.73M
            if (lower[0] == '8' && lower[1] == 0) {
3864
5.72M
                return _PyUnicode_AsUTF8String(unicode, errors);
3865
5.72M
            }
3866
12.3k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3867
0
                return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3868
0
            }
3869
12.3k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3870
0
                return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3871
0
            }
3872
5.73M
        }
3873
4.14M
        else {
3874
4.14M
            if (strcmp(lower, "ascii") == 0
3875
2.83M
                || strcmp(lower, "us_ascii") == 0) {
3876
2.83M
                return _PyUnicode_AsASCIIString(unicode, errors);
3877
2.83M
            }
3878
#ifdef MS_WINDOWS
3879
            else if (strcmp(lower, "mbcs") == 0) {
3880
                return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3881
            }
3882
#endif
3883
1.30M
            else if (strcmp(lower, "latin1") == 0 ||
3884
1.30M
                     strcmp(lower, "latin_1") == 0 ||
3885
1.30M
                     strcmp(lower, "iso_8859_1") == 0 ||
3886
1.30M
                     strcmp(lower, "iso8859_1") == 0) {
3887
10
                return _PyUnicode_AsLatin1String(unicode, errors);
3888
10
            }
3889
4.14M
        }
3890
9.88M
    }
3891
3892
    /* Encode via the codec registry */
3893
2.34M
    v = _PyCodec_EncodeText(unicode, encoding, errors);
3894
2.34M
    if (v == NULL)
3895
0
        return NULL;
3896
3897
    /* The normal path */
3898
2.34M
    if (PyBytes_Check(v))
3899
2.34M
        return v;
3900
3901
    /* If the codec returns a buffer, raise a warning and convert to bytes */
3902
0
    if (PyByteArray_Check(v)) {
3903
0
        int error;
3904
0
        PyObject *b;
3905
3906
0
        error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3907
0
            "encoder %s returned bytearray instead of bytes; "
3908
0
            "use codecs.encode() to encode to arbitrary types",
3909
0
            encoding);
3910
0
        if (error) {
3911
0
            Py_DECREF(v);
3912
0
            return NULL;
3913
0
        }
3914
3915
0
        b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3916
0
                                      PyByteArray_GET_SIZE(v));
3917
0
        Py_DECREF(v);
3918
0
        return b;
3919
0
    }
3920
3921
0
    PyErr_Format(PyExc_TypeError,
3922
0
                 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3923
0
                 "use codecs.encode() to encode to arbitrary types",
3924
0
                 encoding,
3925
0
                 Py_TYPE(v)->tp_name);
3926
0
    Py_DECREF(v);
3927
0
    return NULL;
3928
0
}
3929
3930
PyAPI_FUNC(PyObject *)
3931
PyUnicode_AsEncodedUnicode(PyObject *unicode,
3932
                           const char *encoding,
3933
                           const char *errors)
3934
0
{
3935
0
    PyObject *v;
3936
3937
0
    if (!PyUnicode_Check(unicode)) {
3938
0
        PyErr_BadArgument();
3939
0
        goto onError;
3940
0
    }
3941
3942
0
    if (encoding == NULL)
3943
0
        encoding = PyUnicode_GetDefaultEncoding();
3944
3945
    /* Encode via the codec registry */
3946
0
    v = PyCodec_Encode(unicode, encoding, errors);
3947
0
    if (v == NULL)
3948
0
        goto onError;
3949
0
    if (!PyUnicode_Check(v)) {
3950
0
        PyErr_Format(PyExc_TypeError,
3951
0
                     "'%.400s' encoder returned '%.400s' instead of 'str'; "
3952
0
                     "use codecs.encode() to encode to arbitrary types",
3953
0
                     encoding,
3954
0
                     Py_TYPE(v)->tp_name);
3955
0
        Py_DECREF(v);
3956
0
        goto onError;
3957
0
    }
3958
0
    return v;
3959
3960
0
  onError:
3961
0
    return NULL;
3962
0
}
3963
3964
static PyObject*
3965
unicode_decode_locale(const char *str, Py_ssize_t len,
3966
                      _Py_error_handler errors, int current_locale)
3967
244k
{
3968
244k
    if (str[len] != '\0' || (size_t)len != strlen(str))  {
3969
0
        PyErr_SetString(PyExc_ValueError, "embedded null byte");
3970
0
        return NULL;
3971
0
    }
3972
3973
244k
    wchar_t *wstr;
3974
244k
    size_t wlen;
3975
244k
    int res = _Py_DecodeLocale(str, &wstr, &wlen, current_locale, errors);
3976
244k
    if (res != 0) {
3977
0
        if (res == _Py_CODEC_DECODE_ERROR) {
3978
0
            PyObject *exc;
3979
0
            assert(wlen <= (size_t)(PY_SSIZE_T_MAX - 1));
3980
0
            exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3981
0
                                        "locale", str, len,
3982
0
                                        (Py_ssize_t)wlen,
3983
0
                                        (Py_ssize_t)(wlen + 1),
3984
0
                                        "decode error");
3985
0
            if (exc != NULL) {
3986
0
                PyCodec_StrictErrors(exc);
3987
0
                Py_DECREF(exc);
3988
0
            }
3989
0
        }
3990
0
        else if (res == _Py_CODEC_UNSUPPORTED_ERROR_HANDLER) {
3991
0
            PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3992
0
        }
3993
0
        else {
3994
0
            assert(res == _Py_CODEC_MEMORY_ERROR);
3995
0
            PyErr_NoMemory();
3996
0
        }
3997
0
        return NULL;
3998
0
    }
3999
4000
244k
    PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
4001
244k
    PyMem_RawFree(wstr);
4002
244k
    return unicode;
4003
244k
}
4004
4005
PyObject*
4006
PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
4007
                              const char *errors)
4008
0
{
4009
0
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
4010
0
    return unicode_decode_locale(str, len, error_handler, 1);
4011
0
}
4012
4013
PyObject*
4014
PyUnicode_DecodeLocale(const char *str, const char *errors)
4015
232k
{
4016
232k
    Py_ssize_t size = (Py_ssize_t)strlen(str);
4017
232k
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
4018
232k
    return unicode_decode_locale(str, size, error_handler, 1);
4019
232k
}
4020
4021
4022
PyObject*
4023
1.16k
PyUnicode_DecodeFSDefault(const char *s) {
4024
1.16k
    Py_ssize_t size = (Py_ssize_t)strlen(s);
4025
1.16k
    return PyUnicode_DecodeFSDefaultAndSize(s, size);
4026
1.16k
}
4027
4028
PyObject*
4029
PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
4030
138k
{
4031
138k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4032
138k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
4033
138k
    if (fs_codec->utf8) {
4034
126k
        return unicode_decode_utf8(s, size,
4035
126k
                                   fs_codec->error_handler,
4036
126k
                                   fs_codec->errors,
4037
126k
                                   NULL);
4038
126k
    }
4039
12.0k
#ifndef _Py_FORCE_UTF8_FS_ENCODING
4040
12.0k
    else if (fs_codec->encoding) {
4041
0
        return PyUnicode_Decode(s, size,
4042
0
                                fs_codec->encoding,
4043
0
                                fs_codec->errors);
4044
0
    }
4045
12.0k
#endif
4046
12.0k
    else {
4047
        /* Before _PyUnicode_InitEncodings() is called, the Python codec
4048
           machinery is not ready and so cannot be used:
4049
           use mbstowcs() in this case. */
4050
12.0k
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
4051
12.0k
        const wchar_t *filesystem_errors = config->filesystem_errors;
4052
12.0k
        assert(filesystem_errors != NULL);
4053
12.0k
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
4054
12.0k
        assert(errors != _Py_ERROR_UNKNOWN);
4055
#ifdef _Py_FORCE_UTF8_FS_ENCODING
4056
        return unicode_decode_utf8(s, size, errors, NULL, NULL);
4057
#else
4058
12.0k
        return unicode_decode_locale(s, size, errors, 0);
4059
12.0k
#endif
4060
12.0k
    }
4061
138k
}
4062
4063
4064
int
4065
PyUnicode_FSConverter(PyObject* arg, void* addr)
4066
173k
{
4067
173k
    PyObject *path = NULL;
4068
173k
    PyObject *output = NULL;
4069
173k
    Py_ssize_t size;
4070
173k
    const char *data;
4071
173k
    if (arg == NULL) {
4072
0
        Py_DECREF(*(PyObject**)addr);
4073
0
        *(PyObject**)addr = NULL;
4074
0
        return 1;
4075
0
    }
4076
173k
    path = PyOS_FSPath(arg);
4077
173k
    if (path == NULL) {
4078
0
        return 0;
4079
0
    }
4080
173k
    if (PyBytes_Check(path)) {
4081
0
        output = path;
4082
0
    }
4083
173k
    else {  // PyOS_FSPath() guarantees its returned value is bytes or str.
4084
173k
        output = PyUnicode_EncodeFSDefault(path);
4085
173k
        Py_DECREF(path);
4086
173k
        if (!output) {
4087
0
            return 0;
4088
0
        }
4089
173k
        assert(PyBytes_Check(output));
4090
173k
    }
4091
4092
173k
    size = PyBytes_GET_SIZE(output);
4093
173k
    data = PyBytes_AS_STRING(output);
4094
173k
    if ((size_t)size != strlen(data)) {
4095
0
        PyErr_SetString(PyExc_ValueError, "embedded null byte");
4096
0
        Py_DECREF(output);
4097
0
        return 0;
4098
0
    }
4099
173k
    *(PyObject**)addr = output;
4100
173k
    return Py_CLEANUP_SUPPORTED;
4101
173k
}
4102
4103
4104
int
4105
PyUnicode_FSDecoder(PyObject* arg, void* addr)
4106
67.1k
{
4107
67.1k
    if (arg == NULL) {
4108
0
        Py_DECREF(*(PyObject**)addr);
4109
0
        *(PyObject**)addr = NULL;
4110
0
        return 1;
4111
0
    }
4112
4113
67.1k
    PyObject *path = PyOS_FSPath(arg);
4114
67.1k
    if (path == NULL) {
4115
0
        return 0;
4116
0
    }
4117
4118
67.1k
    PyObject *output = NULL;
4119
67.1k
    if (PyUnicode_Check(path)) {
4120
67.1k
        output = path;
4121
67.1k
    }
4122
0
    else if (PyBytes_Check(path)) {
4123
0
        output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path),
4124
0
                                                  PyBytes_GET_SIZE(path));
4125
0
        Py_DECREF(path);
4126
0
        if (!output) {
4127
0
            return 0;
4128
0
        }
4129
0
    }
4130
0
    else {
4131
0
        PyErr_Format(PyExc_TypeError,
4132
0
                     "path should be string, bytes, or os.PathLike, not %.200s",
4133
0
                     Py_TYPE(arg)->tp_name);
4134
0
        Py_DECREF(path);
4135
0
        return 0;
4136
0
    }
4137
4138
67.1k
    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
4139
67.1k
                 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
4140
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4141
0
        Py_DECREF(output);
4142
0
        return 0;
4143
0
    }
4144
67.1k
    *(PyObject**)addr = output;
4145
67.1k
    return Py_CLEANUP_SUPPORTED;
4146
67.1k
}
4147
4148
4149
static int unicode_fill_utf8(PyObject *unicode);
4150
4151
4152
static int
4153
unicode_ensure_utf8(PyObject *unicode)
4154
79.2M
{
4155
79.2M
    int err = 0;
4156
79.2M
    if (PyUnicode_UTF8(unicode) == NULL) {
4157
199k
        Py_BEGIN_CRITICAL_SECTION(unicode);
4158
199k
        if (PyUnicode_UTF8(unicode) == NULL) {
4159
199k
            err = unicode_fill_utf8(unicode);
4160
199k
        }
4161
199k
        Py_END_CRITICAL_SECTION();
4162
199k
    }
4163
79.2M
    return err;
4164
79.2M
}
4165
4166
const char *
4167
PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
4168
79.2M
{
4169
79.2M
    if (!PyUnicode_Check(unicode)) {
4170
0
        PyErr_BadArgument();
4171
0
        if (psize) {
4172
0
            *psize = -1;
4173
0
        }
4174
0
        return NULL;
4175
0
    }
4176
4177
79.2M
    if (unicode_ensure_utf8(unicode) == -1) {
4178
312
        if (psize) {
4179
312
            *psize = -1;
4180
312
        }
4181
312
        return NULL;
4182
312
    }
4183
4184
79.2M
    if (psize) {
4185
79.1M
        *psize = PyUnicode_UTF8_LENGTH(unicode);
4186
79.1M
    }
4187
79.2M
    return PyUnicode_UTF8(unicode);
4188
79.2M
}
4189
4190
const char *
4191
PyUnicode_AsUTF8(PyObject *unicode)
4192
166k
{
4193
166k
    return PyUnicode_AsUTF8AndSize(unicode, NULL);
4194
166k
}
4195
4196
const char *
4197
_PyUnicode_AsUTF8NoNUL(PyObject *unicode)
4198
68.8M
{
4199
68.8M
    Py_ssize_t size;
4200
68.8M
    const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
4201
68.8M
    if (s && strlen(s) != (size_t)size) {
4202
1.66k
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4203
1.66k
        return NULL;
4204
1.66k
    }
4205
68.8M
    return s;
4206
68.8M
}
4207
4208
/*
4209
PyUnicode_GetSize() has been deprecated since Python 3.3
4210
because it returned length of Py_UNICODE.
4211
4212
But this function is part of stable abi, because it doesn't
4213
include Py_UNICODE in signature and it was not excluded from
4214
stable ABI in PEP 384.
4215
*/
4216
PyAPI_FUNC(Py_ssize_t)
4217
PyUnicode_GetSize(PyObject *unicode)
4218
0
{
4219
0
    PyErr_SetString(PyExc_RuntimeError,
4220
0
                    "PyUnicode_GetSize has been removed.");
4221
0
    return -1;
4222
0
}
4223
4224
Py_ssize_t
4225
PyUnicode_GetLength(PyObject *unicode)
4226
28.4k
{
4227
28.4k
    if (!PyUnicode_Check(unicode)) {
4228
0
        PyErr_BadArgument();
4229
0
        return -1;
4230
0
    }
4231
28.4k
    return PyUnicode_GET_LENGTH(unicode);
4232
28.4k
}
4233
4234
Py_UCS4
4235
PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4236
531k
{
4237
531k
    const void *data;
4238
531k
    int kind;
4239
4240
531k
    if (!PyUnicode_Check(unicode)) {
4241
0
        PyErr_BadArgument();
4242
0
        return (Py_UCS4)-1;
4243
0
    }
4244
531k
    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
4245
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
4246
0
        return (Py_UCS4)-1;
4247
0
    }
4248
531k
    data = PyUnicode_DATA(unicode);
4249
531k
    kind = PyUnicode_KIND(unicode);
4250
531k
    return PyUnicode_READ(kind, data, index);
4251
531k
}
4252
4253
int
4254
PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4255
0
{
4256
0
    if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
4257
0
        PyErr_BadArgument();
4258
0
        return -1;
4259
0
    }
4260
0
    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
4261
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
4262
0
        return -1;
4263
0
    }
4264
0
    if (unicode_check_modifiable(unicode))
4265
0
        return -1;
4266
0
    if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4267
0
        PyErr_SetString(PyExc_ValueError, "character out of range");
4268
0
        return -1;
4269
0
    }
4270
0
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4271
0
                    index, ch);
4272
0
    return 0;
4273
0
}
4274
4275
const char *
4276
PyUnicode_GetDefaultEncoding(void)
4277
0
{
4278
0
    return "utf-8";
4279
0
}
4280
4281
/* create or adjust a UnicodeDecodeError */
4282
static void
4283
make_decode_exception(PyObject **exceptionObject,
4284
                      const char *encoding,
4285
                      const char *input, Py_ssize_t length,
4286
                      Py_ssize_t startpos, Py_ssize_t endpos,
4287
                      const char *reason)
4288
3.16M
{
4289
3.16M
    if (*exceptionObject == NULL) {
4290
2.57M
        *exceptionObject = PyUnicodeDecodeError_Create(
4291
2.57M
            encoding, input, length, startpos, endpos, reason);
4292
2.57M
    }
4293
590k
    else {
4294
590k
        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4295
0
            goto onError;
4296
590k
        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4297
0
            goto onError;
4298
590k
        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4299
0
            goto onError;
4300
590k
    }
4301
3.16M
    return;
4302
4303
3.16M
onError:
4304
0
    Py_CLEAR(*exceptionObject);
4305
0
}
4306
4307
#ifdef MS_WINDOWS
4308
static int
4309
widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
4310
{
4311
    if (newsize > *size) {
4312
        wchar_t *newbuf = *buf;
4313
        if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
4314
            PyErr_NoMemory();
4315
            return -1;
4316
        }
4317
        *buf = newbuf;
4318
    }
4319
    *size = newsize;
4320
    return 0;
4321
}
4322
4323
/* error handling callback helper:
4324
   build arguments, call the callback and check the arguments,
4325
   if no exception occurred, copy the replacement to the output
4326
   and adjust various state variables.
4327
   return 0 on success, -1 on error
4328
*/
4329
4330
static int
4331
unicode_decode_call_errorhandler_wchar(
4332
    const char *errors, PyObject **errorHandler,
4333
    const char *encoding, const char *reason,
4334
    const char **input, const char **inend, Py_ssize_t *startinpos,
4335
    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4336
    wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
4337
{
4338
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4339
4340
    PyObject *restuple = NULL;
4341
    PyObject *repunicode = NULL;
4342
    Py_ssize_t outsize;
4343
    Py_ssize_t insize;
4344
    Py_ssize_t requiredsize;
4345
    Py_ssize_t newpos;
4346
    PyObject *inputobj = NULL;
4347
    Py_ssize_t repwlen;
4348
4349
    if (*errorHandler == NULL) {
4350
        *errorHandler = PyCodec_LookupError(errors);
4351
        if (*errorHandler == NULL)
4352
            goto onError;
4353
    }
4354
4355
    make_decode_exception(exceptionObject,
4356
        encoding,
4357
        *input, *inend - *input,
4358
        *startinpos, *endinpos,
4359
        reason);
4360
    if (*exceptionObject == NULL)
4361
        goto onError;
4362
4363
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4364
    if (restuple == NULL)
4365
        goto onError;
4366
    if (!PyTuple_Check(restuple)) {
4367
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4368
        goto onError;
4369
    }
4370
    if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
4371
        goto onError;
4372
4373
    /* Copy back the bytes variables, which might have been modified by the
4374
       callback */
4375
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4376
    if (!inputobj)
4377
        goto onError;
4378
    *input = PyBytes_AS_STRING(inputobj);
4379
    insize = PyBytes_GET_SIZE(inputobj);
4380
    *inend = *input + insize;
4381
    /* we can DECREF safely, as the exception has another reference,
4382
       so the object won't go away. */
4383
    Py_DECREF(inputobj);
4384
4385
    if (newpos<0)
4386
        newpos = insize+newpos;
4387
    if (newpos<0 || newpos>insize) {
4388
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4389
        goto onError;
4390
    }
4391
4392
    repwlen = PyUnicode_AsWideChar(repunicode, NULL, 0);
4393
    if (repwlen < 0)
4394
        goto onError;
4395
    repwlen--;
4396
    /* need more space? (at least enough for what we
4397
       have+the replacement+the rest of the string (starting
4398
       at the new input position), so we won't have to check space
4399
       when there are no errors in the rest of the string) */
4400
    requiredsize = *outpos;
4401
    if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4402
        goto overflow;
4403
    requiredsize += repwlen;
4404
    if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4405
        goto overflow;
4406
    requiredsize += insize - newpos;
4407
    outsize = *bufsize;
4408
    if (requiredsize > outsize) {
4409
        if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
4410
            requiredsize = 2*outsize;
4411
        if (widechar_resize(buf, bufsize, requiredsize) < 0) {
4412
            goto onError;
4413
        }
4414
    }
4415
    PyUnicode_AsWideChar(repunicode, *buf + *outpos, repwlen);
4416
    *outpos += repwlen;
4417
    *endinpos = newpos;
4418
    *inptr = *input + newpos;
4419
4420
    /* we made it! */
4421
    Py_DECREF(restuple);
4422
    return 0;
4423
4424
  overflow:
4425
    PyErr_SetString(PyExc_OverflowError,
4426
                    "decoded result is too long for a Python string");
4427
4428
  onError:
4429
    Py_XDECREF(restuple);
4430
    return -1;
4431
}
4432
#endif   /* MS_WINDOWS */
4433
4434
static int
4435
unicode_decode_call_errorhandler_writer(
4436
    const char *errors, PyObject **errorHandler,
4437
    const char *encoding, const char *reason,
4438
    const char **input, const char **inend, Py_ssize_t *startinpos,
4439
    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4440
    _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4441
3.16M
{
4442
3.16M
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4443
4444
3.16M
    PyObject *restuple = NULL;
4445
3.16M
    PyObject *repunicode = NULL;
4446
3.16M
    Py_ssize_t insize;
4447
3.16M
    Py_ssize_t newpos;
4448
3.16M
    Py_ssize_t replen;
4449
3.16M
    Py_ssize_t remain;
4450
3.16M
    PyObject *inputobj = NULL;
4451
3.16M
    int need_to_grow = 0;
4452
3.16M
    const char *new_inptr;
4453
4454
3.16M
    if (*errorHandler == NULL) {
4455
2.57M
        *errorHandler = PyCodec_LookupError(errors);
4456
2.57M
        if (*errorHandler == NULL)
4457
0
            goto onError;
4458
2.57M
    }
4459
4460
3.16M
    make_decode_exception(exceptionObject,
4461
3.16M
        encoding,
4462
3.16M
        *input, *inend - *input,
4463
3.16M
        *startinpos, *endinpos,
4464
3.16M
        reason);
4465
3.16M
    if (*exceptionObject == NULL)
4466
0
        goto onError;
4467
4468
3.16M
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4469
3.16M
    if (restuple == NULL)
4470
2.52M
        goto onError;
4471
637k
    if (!PyTuple_Check(restuple)) {
4472
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4473
0
        goto onError;
4474
0
    }
4475
637k
    if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
4476
0
        goto onError;
4477
4478
    /* Copy back the bytes variables, which might have been modified by the
4479
       callback */
4480
637k
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4481
637k
    if (!inputobj)
4482
0
        goto onError;
4483
637k
    remain = *inend - *input - *endinpos;
4484
637k
    *input = PyBytes_AS_STRING(inputobj);
4485
637k
    insize = PyBytes_GET_SIZE(inputobj);
4486
637k
    *inend = *input + insize;
4487
    /* we can DECREF safely, as the exception has another reference,
4488
       so the object won't go away. */
4489
637k
    Py_DECREF(inputobj);
4490
4491
637k
    if (newpos<0)
4492
0
        newpos = insize+newpos;
4493
637k
    if (newpos<0 || newpos>insize) {
4494
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4495
0
        goto onError;
4496
0
    }
4497
4498
637k
    replen = PyUnicode_GET_LENGTH(repunicode);
4499
637k
    if (replen > 1) {
4500
11.9k
        writer->min_length += replen - 1;
4501
11.9k
        need_to_grow = 1;
4502
11.9k
    }
4503
637k
    new_inptr = *input + newpos;
4504
637k
    if (*inend - new_inptr > remain) {
4505
        /* We don't know the decoding algorithm here so we make the worst
4506
           assumption that one byte decodes to one unicode character.
4507
           If unfortunately one byte could decode to more unicode characters,
4508
           the decoder may write out-of-bound then.  Is it possible for the
4509
           algorithms using this function? */
4510
2.84k
        writer->min_length += *inend - new_inptr - remain;
4511
2.84k
        need_to_grow = 1;
4512
2.84k
    }
4513
637k
    if (need_to_grow) {
4514
12.0k
        writer->overallocate = 1;
4515
12.0k
        if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
4516
12.0k
                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4517
0
            goto onError;
4518
12.0k
    }
4519
637k
    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4520
0
        goto onError;
4521
4522
637k
    *endinpos = newpos;
4523
637k
    *inptr = new_inptr;
4524
4525
    /* we made it! */
4526
637k
    Py_DECREF(restuple);
4527
637k
    return 0;
4528
4529
2.52M
  onError:
4530
2.52M
    Py_XDECREF(restuple);
4531
2.52M
    return -1;
4532
637k
}
4533
4534
/* --- UTF-7 Codec -------------------------------------------------------- */
4535
4536
/* See RFC2152 for details.  We encode conservatively and decode liberally. */
4537
4538
/* Three simple macros defining base-64. */
4539
4540
/* Is c a base-64 character? */
4541
4542
#define IS_BASE64(c) \
4543
356k
    (((c) >= 'A' && (c) <= 'Z') ||     \
4544
356k
     ((c) >= 'a' && (c) <= 'z') ||     \
4545
356k
     ((c) >= '0' && (c) <= '9') ||     \
4546
356k
     (c) == '+' || (c) == '/')
4547
4548
/* given that c is a base-64 character, what is its base-64 value? */
4549
4550
#define FROM_BASE64(c)                                                  \
4551
318k
    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
4552
318k
     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
4553
192k
     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
4554
109k
     (c) == '+' ? 62 : 63)
4555
4556
/* What is the base-64 character of the bottom 6 bits of n? */
4557
4558
#define TO_BASE64(n)  \
4559
0
    ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4560
4561
/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4562
 * decoded as itself.  We are permissive on decoding; the only ASCII
4563
 * byte not decoding to itself is the + which begins a base64
4564
 * string. */
4565
4566
#define DECODE_DIRECT(c)                                \
4567
9.08M
    ((c) <= 127 && (c) != '+')
4568
4569
/* The UTF-7 encoder treats ASCII characters differently according to
4570
 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4571
 * the above).  See RFC2152.  This array identifies these different
4572
 * sets:
4573
 * 0 : "Set D"
4574
 *     alphanumeric and '(),-./:?
4575
 * 1 : "Set O"
4576
 *     !"#$%&*;<=>@[]^_`{|}
4577
 * 2 : "whitespace"
4578
 *     ht nl cr sp
4579
 * 3 : special (must be base64 encoded)
4580
 *     everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4581
 */
4582
4583
static
4584
char utf7_category[128] = {
4585
/* nul soh stx etx eot enq ack bel bs  ht  nl  vt  np  cr  so  si  */
4586
    3,  3,  3,  3,  3,  3,  3,  3,  3,  2,  2,  3,  3,  2,  3,  3,
4587
/* dle dc1 dc2 dc3 dc4 nak syn etb can em  sub esc fs  gs  rs  us  */
4588
    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
4589
/* sp   !   "   #   $   %   &   '   (   )   *   +   ,   -   .   /  */
4590
    2,  1,  1,  1,  1,  1,  1,  0,  0,  0,  1,  3,  0,  0,  0,  0,
4591
/*  0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?  */
4592
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0,
4593
/*  @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O  */
4594
    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
4595
/*  P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _  */
4596
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  3,  1,  1,  1,
4597
/*  `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o  */
4598
    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
4599
/*  p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~  del */
4600
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  3,  3,
4601
};
4602
4603
/* ENCODE_DIRECT: this character should be encoded as itself.  The
4604
 * answer depends on whether we are encoding set O as itself, and also
4605
 * on whether we are encoding whitespace as itself.  RFC 2152 makes it
4606
 * clear that the answers to these questions vary between
4607
 * applications, so this code needs to be flexible.  */
4608
4609
#define ENCODE_DIRECT(c) \
4610
0
    ((c) < 128 && (c) > 0 && ((utf7_category[(c)] != 3)))
4611
4612
PyObject *
4613
PyUnicode_DecodeUTF7(const char *s,
4614
                     Py_ssize_t size,
4615
                     const char *errors)
4616
0
{
4617
0
    return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4618
0
}
4619
4620
/* The decoder.  The only state we preserve is our read position,
4621
 * i.e. how many characters we have consumed.  So if we end in the
4622
 * middle of a shift sequence we have to back off the read position
4623
 * and the output to the beginning of the sequence, otherwise we lose
4624
 * all the shift state (seen bits, number of bits seen, high
4625
 * surrogate). */
4626
4627
PyObject *
4628
PyUnicode_DecodeUTF7Stateful(const char *s,
4629
                             Py_ssize_t size,
4630
                             const char *errors,
4631
                             Py_ssize_t *consumed)
4632
28.3k
{
4633
28.3k
    const char *starts = s;
4634
28.3k
    Py_ssize_t startinpos;
4635
28.3k
    Py_ssize_t endinpos;
4636
28.3k
    const char *e;
4637
28.3k
    _PyUnicodeWriter writer;
4638
28.3k
    const char *errmsg = "";
4639
28.3k
    int inShift = 0;
4640
28.3k
    Py_ssize_t shiftOutStart;
4641
28.3k
    unsigned int base64bits = 0;
4642
28.3k
    unsigned long base64buffer = 0;
4643
28.3k
    Py_UCS4 surrogate = 0;
4644
28.3k
    PyObject *errorHandler = NULL;
4645
28.3k
    PyObject *exc = NULL;
4646
4647
28.3k
    if (size == 0) {
4648
0
        if (consumed)
4649
0
            *consumed = 0;
4650
0
        _Py_RETURN_UNICODE_EMPTY();
4651
0
    }
4652
4653
    /* Start off assuming it's all ASCII. Widen later as necessary. */
4654
28.3k
    _PyUnicodeWriter_Init(&writer);
4655
28.3k
    writer.min_length = size;
4656
4657
28.3k
    shiftOutStart = 0;
4658
28.3k
    e = s + size;
4659
4660
9.45M
    while (s < e) {
4661
9.43M
        Py_UCS4 ch;
4662
9.43M
      restart:
4663
9.43M
        ch = (unsigned char) *s;
4664
4665
9.43M
        if (inShift) { /* in a base-64 section */
4666
334k
            if (IS_BASE64(ch)) { /* consume a base-64 character */
4667
318k
                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4668
318k
                base64bits += 6;
4669
318k
                s++;
4670
318k
                if (base64bits >= 16) {
4671
                    /* we have enough bits for a UTF-16 value */
4672
113k
                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
4673
113k
                    base64bits -= 16;
4674
113k
                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4675
113k
                    assert(outCh <= 0xffff);
4676
113k
                    if (surrogate) {
4677
                        /* expecting a second surrogate */
4678
10.0k
                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4679
3.54k
                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
4680
3.54k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
4681
0
                                goto onError;
4682
3.54k
                            surrogate = 0;
4683
3.54k
                            continue;
4684
3.54k
                        }
4685
6.48k
                        else {
4686
6.48k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4687
0
                                goto onError;
4688
6.48k
                            surrogate = 0;
4689
6.48k
                        }
4690
10.0k
                    }
4691
109k
                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
4692
                        /* first surrogate */
4693
13.5k
                        surrogate = outCh;
4694
13.5k
                    }
4695
96.1k
                    else {
4696
96.1k
                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
4697
0
                            goto onError;
4698
96.1k
                    }
4699
109k
                }
4700
318k
            }
4701
15.8k
            else { /* now leaving a base-64 section */
4702
15.8k
                inShift = 0;
4703
15.8k
                if (base64bits > 0) { /* left-over bits */
4704
13.2k
                    if (base64bits >= 6) {
4705
                        /* We've seen at least one base-64 character */
4706
6.11k
                        s++;
4707
6.11k
                        errmsg = "partial character in shift sequence";
4708
6.11k
                        goto utf7Error;
4709
6.11k
                    }
4710
7.11k
                    else {
4711
                        /* Some bits remain; they should be zero */
4712
7.11k
                        if (base64buffer != 0) {
4713
1.51k
                            s++;
4714
1.51k
                            errmsg = "non-zero padding bits in shift sequence";
4715
1.51k
                            goto utf7Error;
4716
1.51k
                        }
4717
7.11k
                    }
4718
13.2k
                }
4719
8.18k
                if (surrogate && DECODE_DIRECT(ch)) {
4720
2.80k
                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4721
0
                        goto onError;
4722
2.80k
                }
4723
8.18k
                surrogate = 0;
4724
8.18k
                if (ch == '-') {
4725
                    /* '-' is absorbed; other terminating
4726
                       characters are preserved */
4727
1.64k
                    s++;
4728
1.64k
                }
4729
8.18k
            }
4730
334k
        }
4731
9.10M
        else if ( ch == '+' ) {
4732
25.6k
            startinpos = s-starts;
4733
25.6k
            s++; /* consume '+' */
4734
25.6k
            if (s < e && *s == '-') { /* '+-' encodes '+' */
4735
2.67k
                s++;
4736
2.67k
                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
4737
0
                    goto onError;
4738
2.67k
            }
4739
22.9k
            else if (s < e && !IS_BASE64(*s)) {
4740
2.91k
                s++;
4741
2.91k
                errmsg = "ill-formed sequence";
4742
2.91k
                goto utf7Error;
4743
2.91k
            }
4744
20.0k
            else { /* begin base64-encoded section */
4745
20.0k
                inShift = 1;
4746
20.0k
                surrogate = 0;
4747
20.0k
                shiftOutStart = writer.pos;
4748
20.0k
                base64bits = 0;
4749
20.0k
                base64buffer = 0;
4750
20.0k
            }
4751
25.6k
        }
4752
9.07M
        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
4753
8.98M
            s++;
4754
8.98M
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
4755
0
                goto onError;
4756
8.98M
        }
4757
93.6k
        else {
4758
93.6k
            startinpos = s-starts;
4759
93.6k
            s++;
4760
93.6k
            errmsg = "unexpected special character";
4761
93.6k
            goto utf7Error;
4762
93.6k
        }
4763
9.32M
        continue;
4764
9.32M
utf7Error:
4765
104k
        endinpos = s-starts;
4766
104k
        if (unicode_decode_call_errorhandler_writer(
4767
104k
                errors, &errorHandler,
4768
104k
                "utf7", errmsg,
4769
104k
                &starts, &e, &startinpos, &endinpos, &exc, &s,
4770
104k
                &writer))
4771
12.1k
            goto onError;
4772
104k
    }
4773
4774
    /* end of string */
4775
4776
16.2k
    if (inShift && !consumed) { /* in shift sequence, no more to follow */
4777
        /* if we're in an inconsistent state, that's an error */
4778
4.26k
        inShift = 0;
4779
4.26k
        if (surrogate ||
4780
4.04k
                (base64bits >= 6) ||
4781
2.77k
                (base64bits > 0 && base64buffer != 0)) {
4782
2.77k
            endinpos = size;
4783
2.77k
            if (unicode_decode_call_errorhandler_writer(
4784
2.77k
                    errors, &errorHandler,
4785
2.77k
                    "utf7", "unterminated shift sequence",
4786
2.77k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
4787
2.77k
                    &writer))
4788
2.39k
                goto onError;
4789
378
            if (s < e)
4790
0
                goto restart;
4791
378
        }
4792
4.26k
    }
4793
4794
    /* return state */
4795
13.8k
    if (consumed) {
4796
0
        if (inShift) {
4797
0
            *consumed = startinpos;
4798
4799
0
            Py_XDECREF(errorHandler);
4800
0
            Py_XDECREF(exc);
4801
0
            return _PyUnicodeWriter_FinishWithSize(&writer, shiftOutStart);
4802
0
        }
4803
0
        else {
4804
0
            *consumed = s-starts;
4805
0
        }
4806
0
    }
4807
4808
13.8k
    Py_XDECREF(errorHandler);
4809
13.8k
    Py_XDECREF(exc);
4810
13.8k
    return _PyUnicodeWriter_Finish(&writer);
4811
4812
14.5k
  onError:
4813
14.5k
    Py_XDECREF(errorHandler);
4814
14.5k
    Py_XDECREF(exc);
4815
14.5k
    _PyUnicodeWriter_Dealloc(&writer);
4816
14.5k
    return NULL;
4817
13.8k
}
4818
4819
4820
PyObject *
4821
_PyUnicode_EncodeUTF7(PyObject *str,
4822
                      const char *errors)
4823
0
{
4824
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
4825
0
    if (len == 0) {
4826
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
4827
0
    }
4828
0
    int kind = PyUnicode_KIND(str);
4829
0
    const void *data = PyUnicode_DATA(str);
4830
4831
    /* It might be possible to tighten this worst case */
4832
0
    if (len > PY_SSIZE_T_MAX / 8) {
4833
0
        return PyErr_NoMemory();
4834
0
    }
4835
0
    PyBytesWriter *writer = PyBytesWriter_Create(len * 8);
4836
0
    if (writer == NULL) {
4837
0
        return NULL;
4838
0
    }
4839
4840
0
    int inShift = 0;
4841
0
    unsigned int base64bits = 0;
4842
0
    unsigned long base64buffer = 0;
4843
0
    char *out = PyBytesWriter_GetData(writer);
4844
0
    for (Py_ssize_t i = 0; i < len; ++i) {
4845
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
4846
4847
0
        if (inShift) {
4848
0
            if (ENCODE_DIRECT(ch)) {
4849
                /* shifting out */
4850
0
                if (base64bits) { /* output remaining bits */
4851
0
                    *out++ = TO_BASE64(base64buffer << (6-base64bits));
4852
0
                    base64buffer = 0;
4853
0
                    base64bits = 0;
4854
0
                }
4855
0
                inShift = 0;
4856
                /* Characters not in the BASE64 set implicitly unshift the sequence
4857
                   so no '-' is required, except if the character is itself a '-' */
4858
0
                if (IS_BASE64(ch) || ch == '-') {
4859
0
                    *out++ = '-';
4860
0
                }
4861
0
                *out++ = (char) ch;
4862
0
            }
4863
0
            else {
4864
0
                goto encode_char;
4865
0
            }
4866
0
        }
4867
0
        else { /* not in a shift sequence */
4868
0
            if (ch == '+') {
4869
0
                *out++ = '+';
4870
0
                *out++ = '-';
4871
0
            }
4872
0
            else if (ENCODE_DIRECT(ch)) {
4873
0
                *out++ = (char) ch;
4874
0
            }
4875
0
            else {
4876
0
                *out++ = '+';
4877
0
                inShift = 1;
4878
0
                goto encode_char;
4879
0
            }
4880
0
        }
4881
0
        continue;
4882
0
encode_char:
4883
0
        if (ch >= 0x10000) {
4884
0
            assert(ch <= MAX_UNICODE);
4885
4886
            /* code first surrogate */
4887
0
            base64bits += 16;
4888
0
            base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
4889
0
            while (base64bits >= 6) {
4890
0
                *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4891
0
                base64bits -= 6;
4892
0
            }
4893
            /* prepare second surrogate */
4894
0
            ch = Py_UNICODE_LOW_SURROGATE(ch);
4895
0
        }
4896
0
        base64bits += 16;
4897
0
        base64buffer = (base64buffer << 16) | ch;
4898
0
        while (base64bits >= 6) {
4899
0
            *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4900
0
            base64bits -= 6;
4901
0
        }
4902
0
    }
4903
0
    if (base64bits)
4904
0
        *out++= TO_BASE64(base64buffer << (6-base64bits) );
4905
0
    if (inShift)
4906
0
        *out++ = '-';
4907
0
    return PyBytesWriter_FinishWithPointer(writer, out);
4908
0
}
4909
4910
#undef IS_BASE64
4911
#undef FROM_BASE64
4912
#undef TO_BASE64
4913
#undef DECODE_DIRECT
4914
#undef ENCODE_DIRECT
4915
4916
/* --- UTF-8 Codec -------------------------------------------------------- */
4917
4918
PyObject *
4919
PyUnicode_DecodeUTF8(const char *s,
4920
                     Py_ssize_t size,
4921
                     const char *errors)
4922
86.3M
{
4923
86.3M
    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4924
86.3M
}
4925
4926
#include "stringlib/asciilib.h"
4927
#include "stringlib/codecs.h"
4928
#include "stringlib/undef.h"
4929
4930
#include "stringlib/ucs1lib.h"
4931
#include "stringlib/codecs.h"
4932
#include "stringlib/undef.h"
4933
4934
#include "stringlib/ucs2lib.h"
4935
#include "stringlib/codecs.h"
4936
#include "stringlib/undef.h"
4937
4938
#include "stringlib/ucs4lib.h"
4939
#include "stringlib/codecs.h"
4940
#include "stringlib/undef.h"
4941
4942
#if (SIZEOF_SIZE_T == 8)
4943
/* Mask to quickly check whether a C 'size_t' contains a
4944
   non-ASCII, UTF8-encoded char. */
4945
151M
# define ASCII_CHAR_MASK 0x8080808080808080ULL
4946
// used to count codepoints in UTF-8 string.
4947
36.6M
# define VECTOR_0101     0x0101010101010101ULL
4948
930k
# define VECTOR_00FF     0x00ff00ff00ff00ffULL
4949
#elif (SIZEOF_SIZE_T == 4)
4950
# define ASCII_CHAR_MASK 0x80808080U
4951
# define VECTOR_0101     0x01010101U
4952
# define VECTOR_00FF     0x00ff00ffU
4953
#else
4954
# error C 'size_t' size should be either 4 or 8!
4955
#endif
4956
4957
#if (defined(__clang__) || defined(__GNUC__))
4958
#define HAVE_CTZ 1
4959
static inline unsigned int
4960
ctz(size_t v)
4961
8.25M
{
4962
8.25M
    return __builtin_ctzll((unsigned long long)v);
4963
8.25M
}
4964
#elif defined(_MSC_VER)
4965
#define HAVE_CTZ 1
4966
static inline unsigned int
4967
ctz(size_t v)
4968
{
4969
    unsigned long pos;
4970
#if SIZEOF_SIZE_T == 4
4971
    _BitScanForward(&pos, v);
4972
#else
4973
    _BitScanForward64(&pos, v);
4974
#endif /* SIZEOF_SIZE_T */
4975
    return pos;
4976
}
4977
#else
4978
#define HAVE_CTZ 0
4979
#endif
4980
4981
#if HAVE_CTZ && PY_LITTLE_ENDIAN
4982
// load p[0]..p[size-1] as a size_t without unaligned access nor read ahead.
4983
static size_t
4984
load_unaligned(const unsigned char *p, size_t size)
4985
84.6M
{
4986
84.6M
    union {
4987
84.6M
        size_t s;
4988
84.6M
        unsigned char b[SIZEOF_SIZE_T];
4989
84.6M
    } u;
4990
84.6M
    u.s = 0;
4991
    // This switch statement assumes little endian because:
4992
    // * union is faster than bitwise or and shift.
4993
    // * big endian machine is rare and hard to maintain.
4994
84.6M
    switch (size) {
4995
0
    default:
4996
0
#if SIZEOF_SIZE_T == 8
4997
0
    case 8:
4998
0
        u.b[7] = p[7];
4999
0
        _Py_FALLTHROUGH;
5000
2.59M
    case 7:
5001
2.59M
        u.b[6] = p[6];
5002
2.59M
        _Py_FALLTHROUGH;
5003
11.1M
    case 6:
5004
11.1M
        u.b[5] = p[5];
5005
11.1M
        _Py_FALLTHROUGH;
5006
22.9M
    case 5:
5007
22.9M
        u.b[4] = p[4];
5008
22.9M
        _Py_FALLTHROUGH;
5009
22.9M
#endif
5010
32.4M
    case 4:
5011
32.4M
        u.b[3] = p[3];
5012
32.4M
        _Py_FALLTHROUGH;
5013
47.9M
    case 3:
5014
47.9M
        u.b[2] = p[2];
5015
47.9M
        _Py_FALLTHROUGH;
5016
79.4M
    case 2:
5017
79.4M
        u.b[1] = p[1];
5018
79.4M
        _Py_FALLTHROUGH;
5019
80.2M
    case 1:
5020
80.2M
        u.b[0] = p[0];
5021
80.2M
        break;
5022
4.39M
    case 0:
5023
4.39M
        break;
5024
84.6M
    }
5025
84.6M
    return u.s;
5026
84.6M
}
5027
#endif
5028
5029
/*
5030
 * Find the first non-ASCII character in a byte sequence.
5031
 *
5032
 * This function scans a range of bytes from `start` to `end` and returns the
5033
 * index of the first byte that is not an ASCII character (i.e., has the most
5034
 * significant bit set). If all characters in the range are ASCII, it returns
5035
 * `end - start`.
5036
 */
5037
static Py_ssize_t
5038
find_first_nonascii(const unsigned char *start, const unsigned char *end)
5039
88.4M
{
5040
    // The search is done in `size_t` chunks.
5041
    // The start and end might not be aligned at `size_t` boundaries,
5042
    // so they're handled specially.
5043
5044
88.4M
    const unsigned char *p = start;
5045
5046
88.4M
    if (end - start >= SIZEOF_SIZE_T) {
5047
        // Avoid unaligned read.
5048
22.9M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5049
22.9M
        size_t u;
5050
22.9M
        memcpy(&u, p, sizeof(size_t));
5051
22.9M
        u &= ASCII_CHAR_MASK;
5052
22.9M
        if (u) {
5053
2.77M
            return (ctz(u) - 7) / 8;
5054
2.77M
        }
5055
20.1M
        p = _Py_ALIGN_DOWN(p + SIZEOF_SIZE_T, SIZEOF_SIZE_T);
5056
#else /* PY_LITTLE_ENDIAN && HAVE_CTZ */
5057
        const unsigned char *p2 = _Py_ALIGN_UP(p, SIZEOF_SIZE_T);
5058
        while (p < p2) {
5059
            if (*p & 0x80) {
5060
                return p - start;
5061
            }
5062
            p++;
5063
        }
5064
#endif
5065
5066
        // Long ASCII runs: test eight words per branch.
5067
27.8M
        for (; end - p >= 8 * SIZEOF_SIZE_T; p += 8 * SIZEOF_SIZE_T) {
5068
8.01M
            const size_t *w = (const size_t *)p;
5069
8.01M
            if ((w[0] | w[1] | w[2] | w[3] |
5070
8.01M
                 w[4] | w[5] | w[6] | w[7]) & ASCII_CHAR_MASK)
5071
285k
            {
5072
285k
                break;
5073
285k
            }
5074
8.01M
        }
5075
5076
20.1M
        const unsigned char *e = end - SIZEOF_SIZE_T;
5077
41.3M
        while (p <= e) {
5078
22.2M
            size_t u = (*(const size_t *)p) & ASCII_CHAR_MASK;
5079
22.2M
            if (u) {
5080
1.02M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5081
1.02M
                return p - start + (ctz(u) - 7) / 8;
5082
#else
5083
                // big endian and minor compilers are difficult to test.
5084
                // fallback to per byte check.
5085
                break;
5086
#endif
5087
1.02M
            }
5088
21.2M
            p += SIZEOF_SIZE_T;
5089
21.2M
        }
5090
20.1M
    }
5091
84.6M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5092
88.4M
    assert((end - p) < SIZEOF_SIZE_T);
5093
    // we can not use *(const size_t*)p to avoid buffer overrun.
5094
84.6M
    size_t u = load_unaligned(p, end - p) & ASCII_CHAR_MASK;
5095
84.6M
    if (u) {
5096
4.45M
        return p - start + (ctz(u) - 7) / 8;
5097
4.45M
    }
5098
80.1M
    return end - start;
5099
#else
5100
    while (p < end) {
5101
        if (*p & 0x80) {
5102
            break;
5103
        }
5104
        p++;
5105
    }
5106
    return p - start;
5107
#endif
5108
84.6M
}
5109
5110
static inline int
5111
scalar_utf8_start_char(unsigned int ch)
5112
5.36M
{
5113
    // 0xxxxxxx or 11xxxxxx are first byte.
5114
5.36M
    return (~ch >> 7 | ch >> 6) & 1;
5115
5.36M
}
5116
5117
static inline size_t
5118
vector_utf8_start_chars(size_t v)
5119
36.6M
{
5120
36.6M
    return ((~v >> 7) | (v >> 6)) & VECTOR_0101;
5121
36.6M
}
5122
5123
5124
// Count the number of UTF-8 code points in a given byte sequence.
5125
static Py_ssize_t
5126
utf8_count_codepoints(const unsigned char *s, const unsigned char *end)
5127
1.49M
{
5128
1.49M
    Py_ssize_t len = 0;
5129
5130
1.49M
    if (end - s >= SIZEOF_SIZE_T) {
5131
368k
        while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
5132
36.1k
            len += scalar_utf8_start_char(*s++);
5133
36.1k
        }
5134
5135
797k
        while (s + SIZEOF_SIZE_T <= end) {
5136
465k
            const unsigned char *e = end;
5137
465k
            if (e - s > SIZEOF_SIZE_T * 255) {
5138
134k
                e = s + SIZEOF_SIZE_T * 255;
5139
134k
            }
5140
465k
            Py_ssize_t vstart = 0;
5141
37.1M
            while (s + SIZEOF_SIZE_T <= e) {
5142
36.6M
                size_t v = *(size_t*)s;
5143
36.6M
                size_t vs = vector_utf8_start_chars(v);
5144
36.6M
                vstart += vs;
5145
36.6M
                s += SIZEOF_SIZE_T;
5146
36.6M
            }
5147
465k
            vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF);
5148
465k
            vstart += vstart >> 16;
5149
465k
#if SIZEOF_SIZE_T == 8
5150
465k
            vstart += vstart >> 32;
5151
465k
#endif
5152
465k
            len += vstart & 0x7ff;
5153
465k
        }
5154
332k
    }
5155
6.82M
    while (s < end) {
5156
5.33M
        len += scalar_utf8_start_char(*s++);
5157
5.33M
    }
5158
1.49M
    return len;
5159
1.49M
}
5160
5161
static Py_ssize_t
5162
ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
5163
15.2M
{
5164
15.2M
#if SIZEOF_SIZE_T <= SIZEOF_VOID_P
5165
15.2M
    if (_Py_IS_ALIGNED(start, ALIGNOF_SIZE_T)
5166
15.1M
        && _Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T))
5167
13.5M
    {
5168
        /* Fast path, see in STRINGLIB(utf8_decode) for
5169
           an explanation. */
5170
13.5M
        const char *p = start;
5171
13.5M
        Py_UCS1 *q = dest;
5172
24.4M
        while (p + SIZEOF_SIZE_T <= end) {
5173
13.4M
            size_t value = *(const size_t *) p;
5174
13.4M
            if (value & ASCII_CHAR_MASK)
5175
2.63M
                break;
5176
10.8M
            *((size_t *)q) = value;
5177
10.8M
            p += SIZEOF_SIZE_T;
5178
10.8M
            q += SIZEOF_SIZE_T;
5179
10.8M
        }
5180
62.5M
        while (p < end) {
5181
51.6M
            if ((unsigned char)*p & 0x80)
5182
2.66M
                break;
5183
49.0M
            *q++ = *p++;
5184
49.0M
        }
5185
13.5M
        return p - start;
5186
13.5M
    }
5187
1.65M
#endif
5188
1.65M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)start,
5189
1.65M
                                         (const unsigned char*)end);
5190
1.65M
    memcpy(dest, start, pos);
5191
1.65M
    return pos;
5192
15.2M
}
5193
5194
static int
5195
unicode_decode_utf8_impl(_PyUnicodeWriter *writer,
5196
                         const char *starts, const char *s, const char *end,
5197
                         _Py_error_handler error_handler,
5198
                         const char *errors,
5199
                         Py_ssize_t *consumed)
5200
8.25M
{
5201
8.25M
    Py_ssize_t startinpos, endinpos;
5202
8.25M
    const char *errmsg = "";
5203
8.25M
    PyObject *error_handler_obj = NULL;
5204
8.25M
    PyObject *exc = NULL;
5205
5206
378M
    while (s < end) {
5207
375M
        Py_UCS4 ch;
5208
375M
        int kind = writer->kind;
5209
5210
375M
        if (kind == PyUnicode_1BYTE_KIND) {
5211
7.22M
            if (PyUnicode_IS_ASCII(writer->buffer))
5212
6.75M
                ch = asciilib_utf8_decode(&s, end, writer->data, &writer->pos);
5213
471k
            else
5214
471k
                ch = ucs1lib_utf8_decode(&s, end, writer->data, &writer->pos);
5215
368M
        } else if (kind == PyUnicode_2BYTE_KIND) {
5216
148M
            ch = ucs2lib_utf8_decode(&s, end, writer->data, &writer->pos);
5217
219M
        } else {
5218
219M
            assert(kind == PyUnicode_4BYTE_KIND);
5219
219M
            ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos);
5220
219M
        }
5221
5222
375M
        switch (ch) {
5223
5.82M
        case 0:
5224
5.82M
            if (s == end || consumed)
5225
5.79M
                goto End;
5226
27.9k
            errmsg = "unexpected end of data";
5227
27.9k
            startinpos = s - starts;
5228
27.9k
            endinpos = end - starts;
5229
27.9k
            break;
5230
177M
        case 1:
5231
177M
            errmsg = "invalid start byte";
5232
177M
            startinpos = s - starts;
5233
177M
            endinpos = startinpos + 1;
5234
177M
            break;
5235
184M
        case 2:
5236
184M
            if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5237
0
                && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
5238
0
            {
5239
                /* Truncated surrogate code in range D800-DFFF */
5240
0
                goto End;
5241
0
            }
5242
184M
            _Py_FALLTHROUGH;
5243
185M
        case 3:
5244
186M
        case 4:
5245
186M
            errmsg = "invalid continuation byte";
5246
186M
            startinpos = s - starts;
5247
186M
            endinpos = startinpos + ch - 1;
5248
186M
            break;
5249
6.78M
        default:
5250
            // ch doesn't fit into kind, so change the buffer kind to write
5251
            // the character
5252
6.78M
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
5253
0
                goto onError;
5254
6.78M
            continue;
5255
375M
        }
5256
5257
363M
        if (error_handler == _Py_ERROR_UNKNOWN)
5258
193k
            error_handler = _Py_GetErrorHandler(errors);
5259
5260
363M
        switch (error_handler) {
5261
0
        case _Py_ERROR_IGNORE:
5262
0
            s += (endinpos - startinpos);
5263
0
            break;
5264
5265
358M
        case _Py_ERROR_REPLACE:
5266
358M
            if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0)
5267
0
                goto onError;
5268
358M
            s += (endinpos - startinpos);
5269
358M
            break;
5270
5271
4.30M
        case _Py_ERROR_SURROGATEESCAPE:
5272
4.30M
        {
5273
4.30M
            Py_ssize_t i;
5274
5275
4.30M
            if (_PyUnicodeWriter_PrepareKind(writer, PyUnicode_2BYTE_KIND) < 0)
5276
0
                goto onError;
5277
4.30M
            assert(_PyUnicodeWriter_CanWrite(writer));
5278
8.60M
            for (i=startinpos; i<endinpos; i++) {
5279
4.30M
                ch = (Py_UCS4)(unsigned char)(starts[i]);
5280
4.30M
                PyUnicode_WRITE(writer->kind, writer->data, writer->pos,
5281
4.30M
                                ch + 0xdc00);
5282
4.30M
                writer->pos++;
5283
4.30M
            }
5284
4.30M
            s += (endinpos - startinpos);
5285
4.30M
            break;
5286
4.30M
        }
5287
5288
2.54k
        default:
5289
2.54k
            if (unicode_decode_call_errorhandler_writer(
5290
2.54k
                    errors, &error_handler_obj,
5291
2.54k
                    "utf-8", errmsg,
5292
2.54k
                    &starts, &end, &startinpos, &endinpos, &exc, &s,
5293
2.54k
                    writer)) {
5294
2.53k
                goto onError;
5295
2.53k
            }
5296
5297
8
            if (_PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) {
5298
0
                goto onError;
5299
0
            }
5300
363M
        }
5301
363M
    }
5302
5303
8.25M
End:
5304
8.25M
    if (consumed)
5305
1.06k
        *consumed = s - starts;
5306
5307
8.25M
    Py_XDECREF(error_handler_obj);
5308
8.25M
    Py_XDECREF(exc);
5309
8.25M
    return 0;
5310
5311
2.53k
onError:
5312
2.53k
    Py_XDECREF(error_handler_obj);
5313
2.53k
    Py_XDECREF(exc);
5314
2.53k
    return -1;
5315
8.25M
}
5316
5317
5318
static PyObject *
5319
unicode_decode_utf8(const char *s, Py_ssize_t size,
5320
                    _Py_error_handler error_handler, const char *errors,
5321
                    Py_ssize_t *consumed)
5322
144M
{
5323
144M
    if (size == 0) {
5324
7.19M
        if (consumed) {
5325
0
            *consumed = 0;
5326
0
        }
5327
7.19M
        _Py_RETURN_UNICODE_EMPTY();
5328
7.19M
    }
5329
5330
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5331
137M
    if (size == 1 && (unsigned char)s[0] < 128) {
5332
50.2M
        if (consumed) {
5333
0
            *consumed = 1;
5334
0
        }
5335
50.2M
        return get_latin1_char((unsigned char)s[0]);
5336
50.2M
    }
5337
5338
    // I don't know this check is necessary or not. But there is a test
5339
    // case that requires size=PY_SSIZE_T_MAX cause MemoryError.
5340
86.7M
    if (PY_SSIZE_T_MAX - sizeof(PyCompactUnicodeObject) < (size_t)size) {
5341
0
        PyErr_NoMemory();
5342
0
        return NULL;
5343
0
    }
5344
5345
86.7M
    const char *starts = s;
5346
86.7M
    const char *end = s + size;
5347
5348
86.7M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end);
5349
86.7M
    if (pos == size) {  // fast path: ASCII string.
5350
78.6M
        PyObject *u = PyUnicode_New(size, 127);
5351
78.6M
        if (u == NULL) {
5352
0
            return NULL;
5353
0
        }
5354
78.6M
        memcpy(PyUnicode_1BYTE_DATA(u), s, size);
5355
78.6M
        if (consumed) {
5356
116
            *consumed = size;
5357
116
        }
5358
78.6M
        return u;
5359
78.6M
    }
5360
5361
8.17M
    int maxchr = 127;
5362
8.17M
    Py_ssize_t maxsize = size;
5363
5364
8.17M
    unsigned char ch = (unsigned char)(s[pos]);
5365
    // error handler other than strict may remove/replace the invalid byte.
5366
    // consumed != NULL allows 1~3 bytes remainings.
5367
    // 0x80 <= ch < 0xc2 is invalid start byte that cause UnicodeDecodeError.
5368
    // otherwise: check the input and decide the maxchr and maxsize to reduce
5369
    // reallocation and copy.
5370
8.17M
    if (error_handler == _Py_ERROR_STRICT && !consumed && ch >= 0xc2) {
5371
        // we only calculate the number of codepoints and don't determine the exact maxchr.
5372
        // This is because writing fast and portable SIMD code to find maxchr is difficult.
5373
        // If reallocation occurs for a larger maxchar, knowing the exact number of codepoints
5374
        // means that it is no longer necessary to allocate several times the required amount
5375
        // of memory.
5376
1.49M
        maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end);
5377
1.49M
        if (ch < 0xc4) { // latin1
5378
288k
            maxchr = 0xff;
5379
288k
        }
5380
1.20M
        else if (ch < 0xf0) { // ucs2
5381
146k
            maxchr = 0xffff;
5382
146k
        }
5383
1.06M
        else { // ucs4
5384
1.06M
            maxchr = 0x10ffff;
5385
1.06M
        }
5386
1.49M
    }
5387
8.17M
    PyObject *u = PyUnicode_New(maxsize, maxchr);
5388
8.17M
    if (!u) {
5389
0
        return NULL;
5390
0
    }
5391
5392
    // Use _PyUnicodeWriter after fast path is failed.
5393
8.17M
    _PyUnicodeWriter writer;
5394
8.17M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
5395
8.17M
    if (maxchr <= 255) {
5396
6.96M
        memcpy(PyUnicode_1BYTE_DATA(u), s, pos);
5397
6.96M
        s += pos;
5398
6.96M
        writer.pos = pos;
5399
6.96M
    }
5400
5401
8.17M
    if (unicode_decode_utf8_impl(&writer, starts, s, end,
5402
8.17M
                                 error_handler, errors,
5403
8.17M
                                 consumed) < 0) {
5404
2.53k
        _PyUnicodeWriter_Dealloc(&writer);
5405
2.53k
        return NULL;
5406
2.53k
    }
5407
8.16M
    return _PyUnicodeWriter_Finish(&writer);
5408
8.17M
}
5409
5410
5411
// Used by PyUnicodeWriter_WriteUTF8() and PyUnicodeWriter_DecodeUTF8Stateful()
5412
int
5413
_PyUnicode_DecodeUTF8Writer(_PyUnicodeWriter *writer,
5414
                            const char *s, Py_ssize_t size,
5415
                            _Py_error_handler error_handler, const char *errors,
5416
                            Py_ssize_t *consumed)
5417
1.67M
{
5418
1.67M
    if (size == 0) {
5419
8.85k
        if (consumed) {
5420
0
            *consumed = 0;
5421
0
        }
5422
8.85k
        return 0;
5423
8.85k
    }
5424
5425
1.66M
    Py_ssize_t old_pos = writer->pos;
5426
1.66M
    Py_UCS4 old_maxchar = writer->maxchar;
5427
5428
    // fast path: try ASCII string.
5429
1.66M
    if (_PyUnicodeWriter_Prepare(writer, size, 127) < 0) {
5430
0
        goto error;
5431
0
    }
5432
1.66M
    assert(_PyUnicodeWriter_CanWrite(writer));
5433
5434
1.66M
    const char *starts = s;
5435
1.66M
    const char *end = s + size;
5436
1.66M
    if (writer->kind == PyUnicode_1BYTE_KIND) {
5437
1.66M
        Py_UCS1 *dest = (Py_UCS1*)writer->data + writer->pos * writer->kind;
5438
1.66M
        Py_ssize_t decoded = ascii_decode(s, end, dest);
5439
1.66M
        writer->pos += decoded;
5440
5441
1.66M
        if (decoded == size) {
5442
1.58M
            if (consumed) {
5443
1.30k
                *consumed = size;
5444
1.30k
            }
5445
1.58M
            return 0;
5446
1.58M
        }
5447
80.6k
        s += decoded;
5448
80.6k
    }
5449
5450
83.3k
    int res = unicode_decode_utf8_impl(writer, starts, s, end,
5451
83.3k
                                       error_handler, errors, consumed);
5452
83.3k
    if (res < 0) {
5453
0
        goto error;
5454
0
    }
5455
83.3k
    return 0;
5456
5457
0
error:
5458
    // Restore the writer to its previous state
5459
0
    writer->pos = old_pos;
5460
0
    if (writer->maxchar > old_maxchar) {
5461
        // _PyUnicodeWriter_Finish() will check maxchar
5462
0
        writer->recheck_maxchar = 1;
5463
0
    }
5464
0
    if (consumed) {
5465
0
        *consumed = 0;
5466
0
    }
5467
0
    return -1;
5468
83.3k
}
5469
5470
5471
PyObject *
5472
PyUnicode_DecodeUTF8Stateful(const char *s,
5473
                             Py_ssize_t size,
5474
                             const char *errors,
5475
                             Py_ssize_t *consumed)
5476
144M
{
5477
144M
    return unicode_decode_utf8(s, size,
5478
144M
                               errors ? _Py_ERROR_UNKNOWN : _Py_ERROR_STRICT,
5479
144M
                               errors, consumed);
5480
144M
}
5481
5482
5483
// UTF-8 decoder.
5484
//
5485
// Supported error handlers: "strict", "surrogateescape" and "surrogatepass".
5486
//
5487
// On success, write a pointer to a newly allocated wide character string into
5488
// *wstr (use PyMem_RawFree() to free the memory), write the output length
5489
// (in number of wchar_t units) into *wlen (if wlen is set), and return 0.
5490
//
5491
// On error, return a negative number.
5492
//
5493
// On memory allocation failure, return _Py_CODEC_MEMORY_ERROR.
5494
//
5495
// On decoding error (if errors is "strict"), return _Py_CODEC_DECODE_ERROR.
5496
// If wlen is non-NULL, write the start of the illegal byte sequence into
5497
// *wlen.
5498
//
5499
// Return _Py_CODEC_UNSUPPORTED_ERROR_HANDLER if errors error handler is not
5500
// supported.
5501
int
5502
_Py_DecodeUTF8(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
5503
               _Py_error_handler errors)
5504
12.2k
{
5505
12.2k
    assert(0 <= size);
5506
12.2k
    assert(s != NULL);
5507
12.2k
    assert(wstr != NULL);
5508
5509
12.2k
    int surrogateescape = 0;
5510
12.2k
    int surrogatepass = 0;
5511
12.2k
    switch (errors)
5512
12.2k
    {
5513
0
    case _Py_ERROR_STRICT:
5514
0
        break;
5515
12.2k
    case _Py_ERROR_SURROGATEESCAPE:
5516
12.2k
        surrogateescape = 1;
5517
12.2k
        break;
5518
0
    case _Py_ERROR_SURROGATEPASS:
5519
0
        surrogatepass = 1;
5520
0
        break;
5521
0
    default:
5522
0
        return _Py_CODEC_UNSUPPORTED_ERROR_HANDLER;
5523
12.2k
    }
5524
5525
    /* Note: size will always be longer than the resulting Unicode
5526
       character count */
5527
12.2k
    if ((size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1 < (size_t)size) {
5528
0
        return _Py_CODEC_MEMORY_ERROR;
5529
0
    }
5530
12.2k
    wchar_t *unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
5531
12.2k
    if (!unicode) {
5532
0
        return _Py_CODEC_MEMORY_ERROR;
5533
0
    }
5534
5535
    /* Unpack UTF-8 encoded data */
5536
12.2k
    const char *orig_s = s;
5537
12.2k
    const char *e = s + size;
5538
12.2k
    Py_ssize_t outpos = 0;
5539
12.2k
    while (s < e) {
5540
12.2k
        Py_UCS4 ch;
5541
12.2k
#if SIZEOF_WCHAR_T == 4
5542
12.2k
        ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
5543
#else
5544
        ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
5545
#endif
5546
12.2k
        if (ch > 0xFF) {
5547
0
#if SIZEOF_WCHAR_T == 4
5548
0
            Py_UNREACHABLE();
5549
#else
5550
            assert(ch > 0xFFFF && ch <= MAX_UNICODE);
5551
            /* write a surrogate pair */
5552
            unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5553
            unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5554
#endif
5555
0
        }
5556
12.2k
        else {
5557
12.2k
            if (!ch && s == e) {
5558
12.2k
                break;
5559
12.2k
            }
5560
5561
0
            if (surrogateescape) {
5562
0
                unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5563
0
            }
5564
0
            else {
5565
                /* Is it a valid three-byte code? */
5566
0
                if (surrogatepass
5567
0
                    && (e - s) >= 3
5568
0
                    && (s[0] & 0xf0) == 0xe0
5569
0
                    && (s[1] & 0xc0) == 0x80
5570
0
                    && (s[2] & 0xc0) == 0x80)
5571
0
                {
5572
0
                    ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5573
0
                    s += 3;
5574
0
                    unicode[outpos++] = ch;
5575
0
                }
5576
0
                else {
5577
0
                    PyMem_RawFree(unicode );
5578
0
                    if (wlen != NULL) {
5579
0
                        *wlen = s - orig_s;
5580
0
                    }
5581
0
                    return _Py_CODEC_DECODE_ERROR;
5582
0
                }
5583
0
            }
5584
0
        }
5585
12.2k
    }
5586
12.2k
    unicode[outpos] = L'\0';
5587
12.2k
    if (wlen) {
5588
12.2k
        *wlen = outpos;
5589
12.2k
    }
5590
12.2k
    *wstr = unicode;
5591
12.2k
    return 0;
5592
12.2k
}
5593
5594
5595
// Decode from UTF-8 with the "surrogateescape" error handler.
5596
// On success, set *wlen and return a newly allocated string.
5597
// On error, set *wlen to the error (_Py_CODEC_MEMORY_ERROR or
5598
// _Py_CODEC_DECODE_ERROR) and the return NULL
5599
wchar_t*
5600
_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
5601
                               size_t *wlen)
5602
0
{
5603
0
    wchar_t *wstr;
5604
0
    int res = _Py_DecodeUTF8(arg, arglen, &wstr, wlen,
5605
0
                             _Py_ERROR_SURROGATEESCAPE);
5606
0
    if (res != 0) {
5607
        /* _Py_DecodeUTF8() must support _Py_ERROR_SURROGATEESCAPE */
5608
0
        assert(res != _Py_CODEC_UNSUPPORTED_ERROR_HANDLER);
5609
0
        if (wlen) {
5610
0
            *wlen = (size_t)res;
5611
0
        }
5612
0
        return NULL;
5613
0
    }
5614
0
    return wstr;
5615
0
}
5616
5617
5618
/* UTF-8 encoder.
5619
5620
   On success, return 0 and write the newly allocated character string (use
5621
   PyMem_Free() to free the memory) into *str.
5622
5623
   On encoding failure, return _Py_CODEC_ENCODE_ERROR (-2) and write the
5624
   position of the invalid surrogate character into *error_pos (if error_pos is
5625
   set).
5626
5627
   On memory allocation failure, return _Py_CODEC_MEMORY_ERROR (-1).
5628
5629
   str and output_length must not be NULL
5630
*/
5631
int
5632
_Py_EncodeUTF8(const wchar_t *text, char **str, size_t *output_length,
5633
               size_t *error_pos, int raw_malloc, _Py_error_handler errors)
5634
1.73k
{
5635
1.73k
    assert(str != NULL);
5636
1.73k
    assert(output_length != NULL);
5637
5638
    // U+10ffff encoded to UTF-8 takes 4 bytes
5639
1.73k
    const size_t max_char_size = 4;
5640
1.73k
    size_t len = wcslen(text);
5641
5642
1.73k
    int surrogateescape = 0;
5643
1.73k
    int surrogatepass = 0;
5644
1.73k
    switch (errors)
5645
1.73k
    {
5646
148
    case _Py_ERROR_STRICT:
5647
148
        break;
5648
1.59k
    case _Py_ERROR_SURROGATEESCAPE:
5649
1.59k
        surrogateescape = 1;
5650
1.59k
        break;
5651
0
    case _Py_ERROR_SURROGATEPASS:
5652
0
        surrogatepass = 1;
5653
0
        break;
5654
0
    default:
5655
0
        return _Py_CODEC_UNSUPPORTED_ERROR_HANDLER;
5656
1.73k
    }
5657
5658
1.73k
    if (len > (size_t)PY_SSIZE_T_MAX / max_char_size - 1) {
5659
0
        return _Py_CODEC_MEMORY_ERROR;
5660
0
    }
5661
1.73k
    char *bytes;
5662
1.73k
    if (raw_malloc) {
5663
1.73k
        bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5664
1.73k
    }
5665
0
    else {
5666
0
        bytes = PyMem_Malloc((len + 1) * max_char_size);
5667
0
    }
5668
1.73k
    if (bytes == NULL) {
5669
0
        return _Py_CODEC_MEMORY_ERROR;
5670
0
    }
5671
5672
1.73k
    char *p = bytes;
5673
124k
    for (size_t i = 0; i < len; ) {
5674
122k
        Py_ssize_t ch_pos = i;
5675
122k
        Py_UCS4 ch = text[i];
5676
122k
        i++;
5677
122k
        if (sizeof(wchar_t) == 2
5678
0
            && Py_UNICODE_IS_HIGH_SURROGATE(ch)
5679
0
            && i < len
5680
0
            && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5681
0
        {
5682
0
            ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5683
0
            i++;
5684
0
        }
5685
5686
122k
        if (ch < 0x80) {
5687
            /* Encode ASCII */
5688
122k
            *p++ = (char) ch;
5689
122k
        }
5690
0
        else if (ch < 0x0800) {
5691
            /* Encode Latin-1 */
5692
0
            *p++ = (char)(0xc0 | (ch >> 6));
5693
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5694
0
        }
5695
0
        else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
5696
            /* surrogateescape error handler */
5697
0
            if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
5698
0
                if (error_pos != NULL) {
5699
0
                    *error_pos = (size_t)ch_pos;
5700
0
                }
5701
0
                if (raw_malloc) {
5702
0
                    PyMem_RawFree(bytes);
5703
0
                }
5704
0
                else {
5705
0
                    PyMem_Free(bytes);
5706
0
                }
5707
0
                return _Py_CODEC_ENCODE_ERROR;
5708
0
            }
5709
0
            *p++ = (char)(ch & 0xff);
5710
0
        }
5711
0
        else if (ch < 0x10000) {
5712
0
            *p++ = (char)(0xe0 | (ch >> 12));
5713
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5714
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5715
0
        }
5716
0
        else {  /* ch >= 0x10000 */
5717
0
            assert(ch <= MAX_UNICODE);
5718
            /* Encode UCS4 Unicode ordinals */
5719
0
            *p++ = (char)(0xf0 | (ch >> 18));
5720
0
            *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5721
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5722
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5723
0
        }
5724
122k
    }
5725
5726
1.73k
    *p++ = '\0';  // trailing NUL byte
5727
1.73k
    size_t final_size = (p - bytes);
5728
1.73k
    assert(final_size >= 1);
5729
1.73k
    *output_length = final_size - 1;  // -1 for the trailing NUL byte
5730
5731
1.73k
    char *result;
5732
1.73k
    if (raw_malloc) {
5733
1.73k
        result = PyMem_RawRealloc(bytes, final_size);
5734
1.73k
    }
5735
0
    else {
5736
0
        result = PyMem_Realloc(bytes, final_size);
5737
0
    }
5738
1.73k
    if (result == NULL) {
5739
0
        if (raw_malloc) {
5740
0
            PyMem_RawFree(bytes);
5741
0
        }
5742
0
        else {
5743
0
            PyMem_Free(bytes);
5744
0
        }
5745
0
        return _Py_CODEC_MEMORY_ERROR;
5746
0
    }
5747
1.73k
    *str = result;
5748
1.73k
    return 0;
5749
1.73k
}
5750
5751
5752
/* Primary internal function which creates utf8 encoded bytes objects.
5753
5754
   Allocation strategy:  if the string is short, convert into a stack buffer
5755
   and allocate exactly as much space needed at the end.  Else allocate the
5756
   maximum possible needed (4 result bytes per Unicode character), and return
5757
   the excess memory at the end.
5758
*/
5759
static PyObject *
5760
unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
5761
                    const char *errors)
5762
19.9M
{
5763
19.9M
    if (!PyUnicode_Check(unicode)) {
5764
0
        PyErr_BadArgument();
5765
0
        return NULL;
5766
0
    }
5767
5768
19.9M
    if (PyUnicode_UTF8(unicode))
5769
10.3M
        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5770
10.3M
                                         PyUnicode_UTF8_LENGTH(unicode));
5771
5772
9.60M
    int kind = PyUnicode_KIND(unicode);
5773
9.60M
    const void *data = PyUnicode_DATA(unicode);
5774
9.60M
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5775
5776
9.60M
    PyBytesWriter *writer;
5777
9.60M
    char *end;
5778
5779
9.60M
    switch (kind) {
5780
0
    default:
5781
0
        Py_UNREACHABLE();
5782
6.75M
    case PyUnicode_1BYTE_KIND:
5783
        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5784
6.75M
        assert(!PyUnicode_IS_ASCII(unicode));
5785
6.75M
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5786
6.75M
                                      error_handler, errors, &end);
5787
6.75M
        break;
5788
1.66M
    case PyUnicode_2BYTE_KIND:
5789
1.66M
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5790
1.66M
                                      error_handler, errors, &end);
5791
1.66M
        break;
5792
1.17M
    case PyUnicode_4BYTE_KIND:
5793
1.17M
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5794
1.17M
                                      error_handler, errors, &end);
5795
1.17M
        break;
5796
9.60M
    }
5797
5798
9.60M
    if (writer == NULL) {
5799
165k
        PyBytesWriter_Discard(writer);
5800
165k
        return NULL;
5801
165k
    }
5802
9.43M
    return PyBytesWriter_FinishWithPointer(writer, end);
5803
9.60M
}
5804
5805
static int
5806
unicode_fill_utf8(PyObject *unicode)
5807
199k
{
5808
199k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(unicode);
5809
    /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5810
199k
    assert(!PyUnicode_IS_ASCII(unicode));
5811
5812
199k
    int kind = PyUnicode_KIND(unicode);
5813
199k
    const void *data = PyUnicode_DATA(unicode);
5814
199k
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5815
5816
199k
    PyBytesWriter *writer;
5817
199k
    char *end;
5818
5819
199k
    switch (kind) {
5820
0
    default:
5821
0
        Py_UNREACHABLE();
5822
149k
    case PyUnicode_1BYTE_KIND:
5823
149k
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5824
149k
                                      _Py_ERROR_STRICT, NULL, &end);
5825
149k
        break;
5826
40.4k
    case PyUnicode_2BYTE_KIND:
5827
40.4k
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5828
40.4k
                                      _Py_ERROR_STRICT, NULL, &end);
5829
40.4k
        break;
5830
9.43k
    case PyUnicode_4BYTE_KIND:
5831
9.43k
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5832
9.43k
                                      _Py_ERROR_STRICT, NULL, &end);
5833
9.43k
        break;
5834
199k
    }
5835
199k
    if (writer == NULL) {
5836
312
        return -1;
5837
312
    }
5838
5839
199k
    const char *start = PyBytesWriter_GetData(writer);
5840
199k
    Py_ssize_t len = end - start;
5841
5842
199k
    char *cache = PyMem_Malloc(len + 1);
5843
199k
    if (cache == NULL) {
5844
0
        PyBytesWriter_Discard(writer);
5845
0
        PyErr_NoMemory();
5846
0
        return -1;
5847
0
    }
5848
199k
    memcpy(cache, start, len);
5849
199k
    cache[len] = '\0';
5850
199k
    PyUnicode_SET_UTF8_LENGTH(unicode, len);
5851
199k
    PyUnicode_SET_UTF8(unicode, cache);
5852
199k
    PyBytesWriter_Discard(writer);
5853
199k
    return 0;
5854
199k
}
5855
5856
PyObject *
5857
_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5858
19.2M
{
5859
19.2M
    return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5860
19.2M
}
5861
5862
5863
PyObject *
5864
PyUnicode_AsUTF8String(PyObject *unicode)
5865
397
{
5866
397
    return _PyUnicode_AsUTF8String(unicode, NULL);
5867
397
}
5868
5869
/* --- UTF-32 Codec ------------------------------------------------------- */
5870
5871
PyObject *
5872
PyUnicode_DecodeUTF32(const char *s,
5873
                      Py_ssize_t size,
5874
                      const char *errors,
5875
                      int *byteorder)
5876
122
{
5877
122
    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5878
122
}
5879
5880
PyObject *
5881
PyUnicode_DecodeUTF32Stateful(const char *s,
5882
                              Py_ssize_t size,
5883
                              const char *errors,
5884
                              int *byteorder,
5885
                              Py_ssize_t *consumed)
5886
11.5k
{
5887
11.5k
    const char *starts = s;
5888
11.5k
    Py_ssize_t startinpos;
5889
11.5k
    Py_ssize_t endinpos;
5890
11.5k
    _PyUnicodeWriter writer;
5891
11.5k
    const unsigned char *q, *e;
5892
11.5k
    int le, bo = 0;       /* assume native ordering by default */
5893
11.5k
    const char *encoding;
5894
11.5k
    const char *errmsg = "";
5895
11.5k
    PyObject *errorHandler = NULL;
5896
11.5k
    PyObject *exc = NULL;
5897
5898
11.5k
    q = (const unsigned char *)s;
5899
11.5k
    e = q + size;
5900
5901
11.5k
    if (byteorder)
5902
11.4k
        bo = *byteorder;
5903
5904
    /* Check for BOM marks (U+FEFF) in the input and adjust current
5905
       byte order setting accordingly. In native mode, the leading BOM
5906
       mark is skipped, in all other modes, it is copied to the output
5907
       stream as-is (giving a ZWNBSP character). */
5908
11.5k
    if (bo == 0 && size >= 4) {
5909
8.98k
        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5910
8.98k
        if (bom == 0x0000FEFF) {
5911
152
            bo = -1;
5912
152
            q += 4;
5913
152
        }
5914
8.83k
        else if (bom == 0xFFFE0000) {
5915
298
            bo = 1;
5916
298
            q += 4;
5917
298
        }
5918
8.98k
        if (byteorder)
5919
8.86k
            *byteorder = bo;
5920
8.98k
    }
5921
5922
11.5k
    if (q == e) {
5923
107
        if (consumed)
5924
0
            *consumed = size;
5925
107
        _Py_RETURN_UNICODE_EMPTY();
5926
107
    }
5927
5928
#ifdef WORDS_BIGENDIAN
5929
    le = bo < 0;
5930
#else
5931
11.4k
    le = bo <= 0;
5932
11.4k
#endif
5933
11.4k
    encoding = le ? "utf-32-le" : "utf-32-be";
5934
5935
11.4k
    _PyUnicodeWriter_Init(&writer);
5936
11.4k
    writer.min_length = (e - q + 3) / 4;
5937
11.4k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
5938
0
        goto onError;
5939
5940
76.0k
    while (1) {
5941
76.0k
        Py_UCS4 ch = 0;
5942
76.0k
        Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
5943
5944
76.0k
        if (e - q >= 4) {
5945
66.1k
            int kind = writer.kind;
5946
66.1k
            void *data = writer.data;
5947
66.1k
            const unsigned char *last = e - 4;
5948
66.1k
            Py_ssize_t pos = writer.pos;
5949
66.1k
            if (le) {
5950
2.79M
                do {
5951
2.79M
                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5952
2.79M
                    if (ch > maxch)
5953
45.3k
                        break;
5954
2.75M
                    if (kind != PyUnicode_1BYTE_KIND &&
5955
2.73M
                        Py_UNICODE_IS_SURROGATE(ch))
5956
179
                        break;
5957
2.75M
                    PyUnicode_WRITE(kind, data, pos++, ch);
5958
2.75M
                    q += 4;
5959
2.75M
                } while (q <= last);
5960
46.8k
            }
5961
19.2k
            else {
5962
24.0k
                do {
5963
24.0k
                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5964
24.0k
                    if (ch > maxch)
5965
18.8k
                        break;
5966
5.25k
                    if (kind != PyUnicode_1BYTE_KIND &&
5967
4.75k
                        Py_UNICODE_IS_SURROGATE(ch))
5968
300
                        break;
5969
4.95k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5970
4.95k
                    q += 4;
5971
4.95k
                } while (q <= last);
5972
19.2k
            }
5973
66.1k
            writer.pos = pos;
5974
66.1k
        }
5975
5976
76.0k
        if (Py_UNICODE_IS_SURROGATE(ch)) {
5977
482
            errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
5978
482
            startinpos = ((const char *)q) - starts;
5979
482
            endinpos = startinpos + 4;
5980
482
        }
5981
75.5k
        else if (ch <= maxch) {
5982
11.4k
            if (q == e || consumed)
5983
3.62k
                break;
5984
            /* remaining bytes at the end? (size should be divisible by 4) */
5985
7.80k
            errmsg = "truncated data";
5986
7.80k
            startinpos = ((const char *)q) - starts;
5987
7.80k
            endinpos = ((const char *)e) - starts;
5988
7.80k
        }
5989
64.1k
        else {
5990
64.1k
            if (ch < 0x110000) {
5991
4.24k
                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
5992
0
                    goto onError;
5993
4.24k
                q += 4;
5994
4.24k
                continue;
5995
4.24k
            }
5996
59.8k
            errmsg = "code point not in range(0x110000)";
5997
59.8k
            startinpos = ((const char *)q) - starts;
5998
59.8k
            endinpos = startinpos + 4;
5999
59.8k
        }
6000
6001
        /* The remaining input chars are ignored if the callback
6002
           chooses to skip the input */
6003
68.1k
        if (unicode_decode_call_errorhandler_writer(
6004
68.1k
                errors, &errorHandler,
6005
68.1k
                encoding, errmsg,
6006
68.1k
                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
6007
68.1k
                &writer))
6008
7.83k
            goto onError;
6009
68.1k
    }
6010
6011
3.62k
    if (consumed)
6012
0
        *consumed = (const char *)q-starts;
6013
6014
3.62k
    Py_XDECREF(errorHandler);
6015
3.62k
    Py_XDECREF(exc);
6016
3.62k
    return _PyUnicodeWriter_Finish(&writer);
6017
6018
7.83k
  onError:
6019
7.83k
    _PyUnicodeWriter_Dealloc(&writer);
6020
7.83k
    Py_XDECREF(errorHandler);
6021
7.83k
    Py_XDECREF(exc);
6022
7.83k
    return NULL;
6023
11.4k
}
6024
6025
PyObject *
6026
_PyUnicode_EncodeUTF32(PyObject *str,
6027
                       const char *errors,
6028
                       int byteorder)
6029
0
{
6030
0
    if (!PyUnicode_Check(str)) {
6031
0
        PyErr_BadArgument();
6032
0
        return NULL;
6033
0
    }
6034
0
    int kind = PyUnicode_KIND(str);
6035
0
    const void *data = PyUnicode_DATA(str);
6036
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6037
6038
0
    if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
6039
0
        return PyErr_NoMemory();
6040
0
    Py_ssize_t nsize = len + (byteorder == 0);
6041
6042
0
#if PY_LITTLE_ENDIAN
6043
0
    int native_ordering = byteorder <= 0;
6044
#else
6045
    int native_ordering = byteorder >= 0;
6046
#endif
6047
6048
0
    if (kind == PyUnicode_1BYTE_KIND) {
6049
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6050
        // on short strings
6051
0
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 4);
6052
0
        if (v == NULL) {
6053
0
            return NULL;
6054
0
        }
6055
6056
        /* output buffer is 4-bytes aligned */
6057
0
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
6058
0
        uint32_t *out = (uint32_t *)PyBytes_AS_STRING(v);
6059
0
        if (byteorder == 0) {
6060
0
            *out++ = 0xFEFF;
6061
0
        }
6062
0
        if (len > 0) {
6063
0
            ucs1lib_utf32_encode((const Py_UCS1 *)data, len,
6064
0
                                 &out, native_ordering);
6065
0
        }
6066
0
        return v;
6067
0
    }
6068
6069
0
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 4);
6070
0
    if (writer == NULL) {
6071
0
        return NULL;
6072
0
    }
6073
6074
    /* output buffer is 4-bytes aligned */
6075
0
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 4));
6076
0
    uint32_t *out = (uint32_t *)PyBytesWriter_GetData(writer);
6077
0
    if (byteorder == 0) {
6078
0
        *out++ = 0xFEFF;
6079
0
    }
6080
0
    if (len == 0) {
6081
0
        return PyBytesWriter_Finish(writer);
6082
0
    }
6083
6084
0
    const char *encoding;
6085
0
    if (byteorder == -1)
6086
0
        encoding = "utf-32-le";
6087
0
    else if (byteorder == 1)
6088
0
        encoding = "utf-32-be";
6089
0
    else
6090
0
        encoding = "utf-32";
6091
6092
0
    PyObject *errorHandler = NULL;
6093
0
    PyObject *exc = NULL;
6094
0
    PyObject *rep = NULL;
6095
6096
0
    for (Py_ssize_t pos = 0; pos < len; ) {
6097
0
        if (kind == PyUnicode_2BYTE_KIND) {
6098
0
            pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
6099
0
                                        &out, native_ordering);
6100
0
        }
6101
0
        else {
6102
0
            assert(kind == PyUnicode_4BYTE_KIND);
6103
0
            pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
6104
0
                                        &out, native_ordering);
6105
0
        }
6106
0
        if (pos == len)
6107
0
            break;
6108
6109
0
        Py_ssize_t newpos;
6110
0
        rep = unicode_encode_call_errorhandler(
6111
0
                errors, &errorHandler,
6112
0
                encoding, "surrogates not allowed",
6113
0
                str, &exc, pos, pos + 1, &newpos);
6114
0
        if (!rep)
6115
0
            goto error;
6116
6117
0
        Py_ssize_t repsize, moreunits;
6118
0
        if (PyBytes_Check(rep)) {
6119
0
            repsize = PyBytes_GET_SIZE(rep);
6120
0
            if (repsize & 3) {
6121
0
                raise_encode_exception(&exc, encoding,
6122
0
                                       str, pos, pos + 1,
6123
0
                                       "surrogates not allowed");
6124
0
                goto error;
6125
0
            }
6126
0
            moreunits = repsize / 4;
6127
0
        }
6128
0
        else {
6129
0
            assert(PyUnicode_Check(rep));
6130
0
            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6131
0
            if (!PyUnicode_IS_ASCII(rep)) {
6132
0
                raise_encode_exception(&exc, encoding,
6133
0
                                       str, pos, pos + 1,
6134
0
                                       "surrogates not allowed");
6135
0
                goto error;
6136
0
            }
6137
0
        }
6138
0
        moreunits += pos - newpos;
6139
0
        pos = newpos;
6140
6141
        /* four bytes are reserved for each surrogate */
6142
0
        if (moreunits > 0) {
6143
0
            out = PyBytesWriter_GrowAndUpdatePointer(writer, 4 * moreunits, out);
6144
0
            if (out == NULL) {
6145
0
                goto error;
6146
0
            }
6147
0
        }
6148
6149
0
        if (PyBytes_Check(rep)) {
6150
0
            memcpy(out, PyBytes_AS_STRING(rep), repsize);
6151
0
            out += repsize / 4;
6152
0
        }
6153
0
        else {
6154
            /* rep is unicode */
6155
0
            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6156
0
            ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6157
0
                                 &out, native_ordering);
6158
0
        }
6159
6160
0
        Py_CLEAR(rep);
6161
0
    }
6162
6163
0
    Py_XDECREF(errorHandler);
6164
0
    Py_XDECREF(exc);
6165
6166
    /* Cut back to size actually needed. This is necessary for, for example,
6167
       encoding of a string containing isolated surrogates and the 'ignore'
6168
       handler is used. */
6169
0
    return PyBytesWriter_FinishWithPointer(writer, out);
6170
6171
0
  error:
6172
0
    Py_XDECREF(rep);
6173
0
    Py_XDECREF(errorHandler);
6174
0
    Py_XDECREF(exc);
6175
0
    PyBytesWriter_Discard(writer);
6176
0
    return NULL;
6177
0
}
6178
6179
PyObject *
6180
PyUnicode_AsUTF32String(PyObject *unicode)
6181
0
{
6182
0
    return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
6183
0
}
6184
6185
/* --- UTF-16 Codec ------------------------------------------------------- */
6186
6187
PyObject *
6188
PyUnicode_DecodeUTF16(const char *s,
6189
                      Py_ssize_t size,
6190
                      const char *errors,
6191
                      int *byteorder)
6192
221
{
6193
221
    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
6194
221
}
6195
6196
PyObject *
6197
PyUnicode_DecodeUTF16Stateful(const char *s,
6198
                              Py_ssize_t size,
6199
                              const char *errors,
6200
                              int *byteorder,
6201
                              Py_ssize_t *consumed)
6202
55.7k
{
6203
55.7k
    const char *starts = s;
6204
55.7k
    Py_ssize_t startinpos;
6205
55.7k
    Py_ssize_t endinpos;
6206
55.7k
    _PyUnicodeWriter writer;
6207
55.7k
    const unsigned char *q, *e;
6208
55.7k
    int bo = 0;       /* assume native ordering by default */
6209
55.7k
    int native_ordering;
6210
55.7k
    const char *errmsg = "";
6211
55.7k
    PyObject *errorHandler = NULL;
6212
55.7k
    PyObject *exc = NULL;
6213
55.7k
    const char *encoding;
6214
6215
55.7k
    q = (const unsigned char *)s;
6216
55.7k
    e = q + size;
6217
6218
55.7k
    if (byteorder)
6219
55.5k
        bo = *byteorder;
6220
6221
    /* Check for BOM marks (U+FEFF) in the input and adjust current
6222
       byte order setting accordingly. In native mode, the leading BOM
6223
       mark is skipped, in all other modes, it is copied to the output
6224
       stream as-is (giving a ZWNBSP character). */
6225
55.7k
    if (bo == 0 && size >= 2) {
6226
20.5k
        const Py_UCS4 bom = (q[1] << 8) | q[0];
6227
20.5k
        if (bom == 0xFEFF) {
6228
320
            q += 2;
6229
320
            bo = -1;
6230
320
        }
6231
20.1k
        else if (bom == 0xFFFE) {
6232
2.78k
            q += 2;
6233
2.78k
            bo = 1;
6234
2.78k
        }
6235
20.5k
        if (byteorder)
6236
20.2k
            *byteorder = bo;
6237
20.5k
    }
6238
6239
55.7k
    if (q == e) {
6240
93
        if (consumed)
6241
0
            *consumed = size;
6242
93
        _Py_RETURN_UNICODE_EMPTY();
6243
93
    }
6244
6245
55.6k
#if PY_LITTLE_ENDIAN
6246
55.6k
    native_ordering = bo <= 0;
6247
55.6k
    encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
6248
#else
6249
    native_ordering = bo >= 0;
6250
    encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
6251
#endif
6252
6253
    /* Note: size will always be longer than the resulting Unicode
6254
       character count normally.  Error handler will take care of
6255
       resizing when needed. */
6256
55.6k
    _PyUnicodeWriter_Init(&writer);
6257
55.6k
    writer.min_length = (e - q + 1) / 2;
6258
55.6k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
6259
0
        goto onError;
6260
6261
133k
    while (1) {
6262
133k
        Py_UCS4 ch = 0;
6263
133k
        if (e - q >= 2) {
6264
116k
            int kind = writer.kind;
6265
116k
            if (kind == PyUnicode_1BYTE_KIND) {
6266
68.2k
                if (PyUnicode_IS_ASCII(writer.buffer))
6267
54.9k
                    ch = asciilib_utf16_decode(&q, e,
6268
54.9k
                            (Py_UCS1*)writer.data, &writer.pos,
6269
54.9k
                            native_ordering);
6270
13.2k
                else
6271
13.2k
                    ch = ucs1lib_utf16_decode(&q, e,
6272
13.2k
                            (Py_UCS1*)writer.data, &writer.pos,
6273
13.2k
                            native_ordering);
6274
68.2k
            } else if (kind == PyUnicode_2BYTE_KIND) {
6275
34.7k
                ch = ucs2lib_utf16_decode(&q, e,
6276
34.7k
                        (Py_UCS2*)writer.data, &writer.pos,
6277
34.7k
                        native_ordering);
6278
34.7k
            } else {
6279
13.9k
                assert(kind == PyUnicode_4BYTE_KIND);
6280
13.9k
                ch = ucs4lib_utf16_decode(&q, e,
6281
13.9k
                        (Py_UCS4*)writer.data, &writer.pos,
6282
13.9k
                        native_ordering);
6283
13.9k
            }
6284
116k
        }
6285
6286
133k
        switch (ch)
6287
133k
        {
6288
55.8k
        case 0:
6289
            /* remaining byte at the end? (size should be even) */
6290
55.8k
            if (q == e || consumed)
6291
43.7k
                goto End;
6292
12.1k
            errmsg = "truncated data";
6293
12.1k
            startinpos = ((const char *)q) - starts;
6294
12.1k
            endinpos = ((const char *)e) - starts;
6295
12.1k
            break;
6296
            /* The remaining input chars are ignored if the callback
6297
               chooses to skip the input */
6298
2.07k
        case 1:
6299
2.07k
            q -= 2;
6300
2.07k
            if (consumed)
6301
0
                goto End;
6302
2.07k
            errmsg = "unexpected end of data";
6303
2.07k
            startinpos = ((const char *)q) - starts;
6304
2.07k
            endinpos = ((const char *)e) - starts;
6305
2.07k
            break;
6306
11.2k
        case 2:
6307
11.2k
            errmsg = "illegal encoding";
6308
11.2k
            startinpos = ((const char *)q) - 2 - starts;
6309
11.2k
            endinpos = startinpos + 2;
6310
11.2k
            break;
6311
7.58k
        case 3:
6312
7.58k
            errmsg = "illegal UTF-16 surrogate";
6313
7.58k
            startinpos = ((const char *)q) - 4 - starts;
6314
7.58k
            endinpos = startinpos + 2;
6315
7.58k
            break;
6316
56.6k
        default:
6317
56.6k
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
6318
0
                goto onError;
6319
56.6k
            continue;
6320
133k
        }
6321
6322
33.0k
        if (unicode_decode_call_errorhandler_writer(
6323
33.0k
                errors,
6324
33.0k
                &errorHandler,
6325
33.0k
                encoding, errmsg,
6326
33.0k
                &starts,
6327
33.0k
                (const char **)&e,
6328
33.0k
                &startinpos,
6329
33.0k
                &endinpos,
6330
33.0k
                &exc,
6331
33.0k
                (const char **)&q,
6332
33.0k
                &writer))
6333
11.9k
            goto onError;
6334
33.0k
    }
6335
6336
43.7k
End:
6337
43.7k
    if (consumed)
6338
0
        *consumed = (const char *)q-starts;
6339
6340
43.7k
    Py_XDECREF(errorHandler);
6341
43.7k
    Py_XDECREF(exc);
6342
43.7k
    return _PyUnicodeWriter_Finish(&writer);
6343
6344
11.9k
  onError:
6345
11.9k
    _PyUnicodeWriter_Dealloc(&writer);
6346
11.9k
    Py_XDECREF(errorHandler);
6347
11.9k
    Py_XDECREF(exc);
6348
11.9k
    return NULL;
6349
55.6k
}
6350
6351
PyObject *
6352
_PyUnicode_EncodeUTF16(PyObject *str,
6353
                       const char *errors,
6354
                       int byteorder)
6355
12.3k
{
6356
12.3k
    if (!PyUnicode_Check(str)) {
6357
0
        PyErr_BadArgument();
6358
0
        return NULL;
6359
0
    }
6360
12.3k
    int kind = PyUnicode_KIND(str);
6361
12.3k
    const void *data = PyUnicode_DATA(str);
6362
12.3k
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6363
6364
12.3k
    Py_ssize_t pairs = 0;
6365
12.3k
    if (kind == PyUnicode_4BYTE_KIND) {
6366
3
        const Py_UCS4 *in = (const Py_UCS4 *)data;
6367
3
        const Py_UCS4 *end = in + len;
6368
30
        while (in < end) {
6369
27
            if (*in++ >= 0x10000) {
6370
3
                pairs++;
6371
3
            }
6372
27
        }
6373
3
    }
6374
12.3k
    if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
6375
0
        return PyErr_NoMemory();
6376
0
    }
6377
12.3k
    Py_ssize_t nsize = len + pairs + (byteorder == 0);
6378
6379
#if PY_BIG_ENDIAN
6380
    int native_ordering = byteorder >= 0;
6381
#else
6382
12.3k
    int native_ordering = byteorder <= 0;
6383
12.3k
#endif
6384
6385
12.3k
    if (kind == PyUnicode_1BYTE_KIND) {
6386
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6387
        // on short strings
6388
12.2k
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 2);
6389
12.2k
        if (v == NULL) {
6390
0
            return NULL;
6391
0
        }
6392
6393
        /* output buffer is 2-bytes aligned */
6394
12.2k
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
6395
12.2k
        unsigned short *out = (unsigned short *)PyBytes_AS_STRING(v);
6396
12.2k
        if (byteorder == 0) {
6397
0
            *out++ = 0xFEFF;
6398
0
        }
6399
12.2k
        if (len > 0) {
6400
12.2k
            ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
6401
12.2k
        }
6402
12.2k
        return v;
6403
12.2k
    }
6404
6405
99
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 2);
6406
99
    if (writer == NULL) {
6407
0
        return NULL;
6408
0
    }
6409
6410
    /* output buffer is 2-bytes aligned */
6411
99
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 2));
6412
99
    unsigned short *out = PyBytesWriter_GetData(writer);
6413
99
    if (byteorder == 0) {
6414
0
        *out++ = 0xFEFF;
6415
0
    }
6416
99
    if (len == 0) {
6417
0
        return PyBytesWriter_Finish(writer);
6418
0
    }
6419
6420
99
    const char *encoding;
6421
99
    if (byteorder < 0) {
6422
0
        encoding = "utf-16-le";
6423
0
    }
6424
99
    else if (byteorder > 0) {
6425
99
        encoding = "utf-16-be";
6426
99
    }
6427
0
    else {
6428
0
        encoding = "utf-16";
6429
0
    }
6430
6431
99
    PyObject *errorHandler = NULL;
6432
99
    PyObject *exc = NULL;
6433
99
    PyObject *rep = NULL;
6434
6435
99
    for (Py_ssize_t pos = 0; pos < len; ) {
6436
99
        if (kind == PyUnicode_2BYTE_KIND) {
6437
96
            pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
6438
96
                                        &out, native_ordering);
6439
96
        }
6440
3
        else {
6441
3
            assert(kind == PyUnicode_4BYTE_KIND);
6442
3
            pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
6443
3
                                        &out, native_ordering);
6444
3
        }
6445
99
        if (pos == len)
6446
99
            break;
6447
6448
0
        Py_ssize_t newpos;
6449
0
        rep = unicode_encode_call_errorhandler(
6450
0
                errors, &errorHandler,
6451
0
                encoding, "surrogates not allowed",
6452
0
                str, &exc, pos, pos + 1, &newpos);
6453
0
        if (!rep)
6454
0
            goto error;
6455
6456
0
        Py_ssize_t repsize, moreunits;
6457
0
        if (PyBytes_Check(rep)) {
6458
0
            repsize = PyBytes_GET_SIZE(rep);
6459
0
            if (repsize & 1) {
6460
0
                raise_encode_exception(&exc, encoding,
6461
0
                                       str, pos, pos + 1,
6462
0
                                       "surrogates not allowed");
6463
0
                goto error;
6464
0
            }
6465
0
            moreunits = repsize / 2;
6466
0
        }
6467
0
        else {
6468
0
            assert(PyUnicode_Check(rep));
6469
0
            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6470
0
            if (!PyUnicode_IS_ASCII(rep)) {
6471
0
                raise_encode_exception(&exc, encoding,
6472
0
                                       str, pos, pos + 1,
6473
0
                                       "surrogates not allowed");
6474
0
                goto error;
6475
0
            }
6476
0
        }
6477
0
        moreunits += pos - newpos;
6478
0
        pos = newpos;
6479
6480
        /* two bytes are reserved for each surrogate */
6481
0
        if (moreunits > 0) {
6482
0
            out = PyBytesWriter_GrowAndUpdatePointer(writer, 2 * moreunits, out);
6483
0
            if (out == NULL) {
6484
0
                goto error;
6485
0
            }
6486
0
        }
6487
6488
0
        if (PyBytes_Check(rep)) {
6489
0
            memcpy(out, PyBytes_AS_STRING(rep), repsize);
6490
0
            out += repsize / 2;
6491
0
        } else {
6492
            /* rep is unicode */
6493
0
            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6494
0
            ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6495
0
                                 &out, native_ordering);
6496
0
        }
6497
6498
0
        Py_CLEAR(rep);
6499
0
    }
6500
6501
99
    Py_XDECREF(errorHandler);
6502
99
    Py_XDECREF(exc);
6503
6504
    /* Cut back to size actually needed. This is necessary for, for example,
6505
    encoding of a string containing isolated surrogates and the 'ignore' handler
6506
    is used. */
6507
99
    return PyBytesWriter_FinishWithPointer(writer, out);
6508
6509
0
  error:
6510
0
    Py_XDECREF(rep);
6511
0
    Py_XDECREF(errorHandler);
6512
0
    Py_XDECREF(exc);
6513
0
    PyBytesWriter_Discard(writer);
6514
0
    return NULL;
6515
99
}
6516
6517
PyObject *
6518
PyUnicode_AsUTF16String(PyObject *unicode)
6519
0
{
6520
0
    return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
6521
0
}
6522
6523
_PyUnicode_Name_CAPI *
6524
_PyUnicode_GetNameCAPI(void)
6525
52.0k
{
6526
52.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
6527
52.0k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6528
6529
52.0k
    ucnhash_capi = _Py_atomic_load_ptr(&interp->unicode.ucnhash_capi);
6530
52.0k
    if (ucnhash_capi == NULL) {
6531
2
        ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6532
2
                PyUnicodeData_CAPSULE_NAME, 1);
6533
6534
        // It's fine if we overwrite the value here. It's always the same value.
6535
2
        _Py_atomic_store_ptr(&interp->unicode.ucnhash_capi, ucnhash_capi);
6536
2
    }
6537
52.0k
    return ucnhash_capi;
6538
52.0k
}
6539
6540
/* --- Unicode Escape Codec ----------------------------------------------- */
6541
6542
PyObject *
6543
_PyUnicode_DecodeUnicodeEscapeInternal2(const char *s,
6544
                               Py_ssize_t size,
6545
                               const char *errors,
6546
                               Py_ssize_t *consumed,
6547
                               int *first_invalid_escape_char,
6548
                               const char **first_invalid_escape_ptr)
6549
32.6k
{
6550
32.6k
    const char *starts = s;
6551
32.6k
    const char *initial_starts = starts;
6552
32.6k
    _PyUnicodeWriter writer;
6553
32.6k
    const char *end;
6554
32.6k
    PyObject *errorHandler = NULL;
6555
32.6k
    PyObject *exc = NULL;
6556
32.6k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6557
6558
    // so we can remember if we've seen an invalid escape char or not
6559
32.6k
    *first_invalid_escape_char = -1;
6560
32.6k
    *first_invalid_escape_ptr = NULL;
6561
6562
32.6k
    if (size == 0) {
6563
3.33k
        if (consumed) {
6564
0
            *consumed = 0;
6565
0
        }
6566
3.33k
        _Py_RETURN_UNICODE_EMPTY();
6567
3.33k
    }
6568
    /* Escaped strings will always be longer than the resulting
6569
       Unicode string, so we start with size here and then reduce the
6570
       length after conversion to the true value.
6571
       (but if the error callback returns a long replacement string
6572
       we'll have to allocate more space) */
6573
29.3k
    _PyUnicodeWriter_Init(&writer);
6574
29.3k
    writer.min_length = size;
6575
29.3k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6576
0
        goto onError;
6577
0
    }
6578
6579
29.3k
    end = s + size;
6580
14.7M
    while (s < end) {
6581
14.7M
        unsigned char c = (unsigned char) *s++;
6582
14.7M
        Py_UCS4 ch;
6583
14.7M
        int count;
6584
14.7M
        const char *message;
6585
6586
14.7M
#define WRITE_ASCII_CHAR(ch)                                                  \
6587
14.7M
            do {                                                              \
6588
153k
                assert(ch <= 127);                                            \
6589
153k
                assert(writer.pos < writer.size);                             \
6590
153k
                PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch);  \
6591
153k
            } while(0)
6592
6593
14.7M
#define WRITE_CHAR(ch)                                                        \
6594
14.7M
            do {                                                              \
6595
14.5M
                if (ch <= writer.maxchar) {                                   \
6596
14.5M
                    assert(writer.pos < writer.size);                         \
6597
14.5M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6598
14.5M
                }                                                             \
6599
14.5M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6600
0
                    goto onError;                                             \
6601
0
                }                                                             \
6602
14.5M
            } while(0)
6603
6604
        /* Non-escape characters are interpreted as Unicode ordinals */
6605
14.7M
        if (c != '\\') {
6606
14.4M
            WRITE_CHAR(c);
6607
14.4M
            continue;
6608
14.4M
        }
6609
6610
280k
        Py_ssize_t startinpos = s - starts - 1;
6611
        /* \ - Escapes */
6612
280k
        if (s >= end) {
6613
19
            message = "\\ at end of string";
6614
19
            goto incomplete;
6615
19
        }
6616
280k
        c = (unsigned char) *s++;
6617
6618
280k
        assert(writer.pos < writer.size);
6619
280k
        switch (c) {
6620
6621
            /* \x escapes */
6622
1.73k
        case '\n': continue;
6623
16.4k
        case '\\': WRITE_ASCII_CHAR('\\'); continue;
6624
4.62k
        case '\'': WRITE_ASCII_CHAR('\''); continue;
6625
3.80k
        case '\"': WRITE_ASCII_CHAR('\"'); continue;
6626
1.72k
        case 'b': WRITE_ASCII_CHAR('\b'); continue;
6627
        /* FF */
6628
1.86k
        case 'f': WRITE_ASCII_CHAR('\014'); continue;
6629
1.45k
        case 't': WRITE_ASCII_CHAR('\t'); continue;
6630
1.52k
        case 'n': WRITE_ASCII_CHAR('\n'); continue;
6631
18.1k
        case 'r': WRITE_ASCII_CHAR('\r'); continue;
6632
        /* VT */
6633
50.8k
        case 'v': WRITE_ASCII_CHAR('\013'); continue;
6634
        /* BEL, not classic C */
6635
22.4k
        case 'a': WRITE_ASCII_CHAR('\007'); continue;
6636
6637
            /* \OOO (octal) escapes */
6638
34.8k
        case '0': case '1': case '2': case '3':
6639
44.8k
        case '4': case '5': case '6': case '7':
6640
44.8k
            ch = c - '0';
6641
44.8k
            if (s < end && '0' <= *s && *s <= '7') {
6642
4.91k
                ch = (ch<<3) + *s++ - '0';
6643
4.91k
                if (s < end && '0' <= *s && *s <= '7') {
6644
2.74k
                    ch = (ch<<3) + *s++ - '0';
6645
2.74k
                }
6646
4.91k
            }
6647
44.8k
            if (ch > 0377) {
6648
2.40k
                if (*first_invalid_escape_char == -1) {
6649
1.23k
                    *first_invalid_escape_char = ch;
6650
1.23k
                    if (starts == initial_starts) {
6651
                        /* Back up 3 chars, since we've already incremented s. */
6652
1.23k
                        *first_invalid_escape_ptr = s - 3;
6653
1.23k
                    }
6654
1.23k
                }
6655
2.40k
            }
6656
44.8k
            WRITE_CHAR(ch);
6657
44.8k
            continue;
6658
6659
            /* hex escapes */
6660
            /* \xXX */
6661
44.8k
        case 'x':
6662
6.32k
            count = 2;
6663
6.32k
            message = "truncated \\xXX escape";
6664
6.32k
            goto hexescape;
6665
6666
            /* \uXXXX */
6667
6.70k
        case 'u':
6668
6.70k
            count = 4;
6669
6.70k
            message = "truncated \\uXXXX escape";
6670
6.70k
            goto hexescape;
6671
6672
            /* \UXXXXXXXX */
6673
15.3k
        case 'U':
6674
15.3k
            count = 8;
6675
15.3k
            message = "truncated \\UXXXXXXXX escape";
6676
28.3k
        hexescape:
6677
190k
            for (ch = 0; count; ++s, --count) {
6678
162k
                if (s >= end) {
6679
33
                    goto incomplete;
6680
33
                }
6681
162k
                c = (unsigned char)*s;
6682
162k
                ch <<= 4;
6683
162k
                if (c >= '0' && c <= '9') {
6684
121k
                    ch += c - '0';
6685
121k
                }
6686
40.4k
                else if (c >= 'a' && c <= 'f') {
6687
39.6k
                    ch += c - ('a' - 10);
6688
39.6k
                }
6689
771
                else if (c >= 'A' && c <= 'F') {
6690
759
                    ch += c - ('A' - 10);
6691
759
                }
6692
12
                else {
6693
12
                    goto error;
6694
12
                }
6695
162k
            }
6696
6697
            /* when we get here, ch is a 32-bit unicode character */
6698
28.3k
            if (ch > MAX_UNICODE) {
6699
3
                message = "illegal Unicode character";
6700
3
                goto error;
6701
3
            }
6702
6703
28.3k
            WRITE_CHAR(ch);
6704
28.3k
            continue;
6705
6706
            /* \N{name} */
6707
52.0k
        case 'N':
6708
52.0k
            ucnhash_capi = _PyUnicode_GetNameCAPI();
6709
52.0k
            if (ucnhash_capi == NULL) {
6710
0
                PyErr_SetString(
6711
0
                        PyExc_UnicodeError,
6712
0
                        "\\N escapes not supported (can't load unicodedata module)"
6713
0
                );
6714
0
                goto onError;
6715
0
            }
6716
6717
52.0k
            message = "malformed \\N character escape";
6718
52.0k
            if (s >= end) {
6719
8
                goto incomplete;
6720
8
            }
6721
52.0k
            if (*s == '{') {
6722
52.0k
                const char *start = ++s;
6723
52.0k
                size_t namelen;
6724
                /* look for the closing brace */
6725
1.48M
                while (s < end && *s != '}')
6726
1.43M
                    s++;
6727
52.0k
                if (s >= end) {
6728
26
                    goto incomplete;
6729
26
                }
6730
52.0k
                namelen = s - start;
6731
52.0k
                if (namelen) {
6732
                    /* found a name.  look it up in the unicode database */
6733
52.0k
                    s++;
6734
52.0k
                    ch = 0xffffffff; /* in case 'getcode' messes up */
6735
52.0k
                    if (namelen <= INT_MAX &&
6736
52.0k
                        ucnhash_capi->getcode(start, (int)namelen,
6737
52.0k
                                              &ch, 0)) {
6738
51.8k
                        assert(ch <= MAX_UNICODE);
6739
51.8k
                        WRITE_CHAR(ch);
6740
51.8k
                        continue;
6741
51.8k
                    }
6742
138
                    message = "unknown Unicode character name";
6743
138
                }
6744
52.0k
            }
6745
150
            goto error;
6746
6747
30.4k
        default:
6748
30.4k
            if (*first_invalid_escape_char == -1) {
6749
5.55k
                *first_invalid_escape_char = c;
6750
5.55k
                if (starts == initial_starts) {
6751
                    /* Back up one char, since we've already incremented s. */
6752
5.55k
                    *first_invalid_escape_ptr = s - 1;
6753
5.55k
                }
6754
5.55k
            }
6755
30.4k
            WRITE_ASCII_CHAR('\\');
6756
30.4k
            WRITE_CHAR(c);
6757
30.4k
            continue;
6758
280k
        }
6759
6760
86
      incomplete:
6761
86
        if (consumed) {
6762
0
            *consumed = startinpos;
6763
0
            break;
6764
0
        }
6765
251
      error:;
6766
251
        Py_ssize_t endinpos = s-starts;
6767
251
        writer.min_length = end - s + writer.pos;
6768
251
        if (unicode_decode_call_errorhandler_writer(
6769
251
                errors, &errorHandler,
6770
251
                "unicodeescape", message,
6771
251
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6772
251
                &writer)) {
6773
251
            goto onError;
6774
251
        }
6775
251
        assert(end - s <= writer.size - writer.pos);
6776
6777
0
#undef WRITE_ASCII_CHAR
6778
0
#undef WRITE_CHAR
6779
0
    }
6780
6781
29.0k
    Py_XDECREF(errorHandler);
6782
29.0k
    Py_XDECREF(exc);
6783
29.0k
    return _PyUnicodeWriter_Finish(&writer);
6784
6785
251
  onError:
6786
251
    _PyUnicodeWriter_Dealloc(&writer);
6787
251
    Py_XDECREF(errorHandler);
6788
251
    Py_XDECREF(exc);
6789
251
    return NULL;
6790
29.3k
}
6791
6792
PyObject *
6793
_PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
6794
                              Py_ssize_t size,
6795
                              const char *errors,
6796
                              Py_ssize_t *consumed)
6797
626
{
6798
626
    int first_invalid_escape_char;
6799
626
    const char *first_invalid_escape_ptr;
6800
626
    PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal2(s, size, errors,
6801
626
                                                      consumed,
6802
626
                                                      &first_invalid_escape_char,
6803
626
                                                      &first_invalid_escape_ptr);
6804
626
    if (result == NULL)
6805
140
        return NULL;
6806
486
    if (first_invalid_escape_char != -1) {
6807
222
        if (first_invalid_escape_char > 0xff) {
6808
110
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6809
110
                                 "\"\\%o\" is an invalid octal escape sequence. "
6810
110
                                 "Such sequences will not work in the future. ",
6811
110
                                 first_invalid_escape_char) < 0)
6812
0
            {
6813
0
                Py_DECREF(result);
6814
0
                return NULL;
6815
0
            }
6816
110
        }
6817
112
        else {
6818
112
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6819
112
                                 "\"\\%c\" is an invalid escape sequence. "
6820
112
                                 "Such sequences will not work in the future. ",
6821
112
                                 first_invalid_escape_char) < 0)
6822
0
            {
6823
0
                Py_DECREF(result);
6824
0
                return NULL;
6825
0
            }
6826
112
        }
6827
222
    }
6828
486
    return result;
6829
486
}
6830
6831
PyObject *
6832
PyUnicode_DecodeUnicodeEscape(const char *s,
6833
                              Py_ssize_t size,
6834
                              const char *errors)
6835
0
{
6836
0
    return _PyUnicode_DecodeUnicodeEscapeStateful(s, size, errors, NULL);
6837
0
}
6838
6839
/* Return a Unicode-Escape string version of the Unicode object. */
6840
6841
PyObject *
6842
PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
6843
737k
{
6844
737k
    if (!PyUnicode_Check(unicode)) {
6845
0
        PyErr_BadArgument();
6846
0
        return NULL;
6847
0
    }
6848
6849
737k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
6850
737k
    if (len == 0) {
6851
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
6852
0
    }
6853
737k
    int kind = PyUnicode_KIND(unicode);
6854
737k
    const void *data = PyUnicode_DATA(unicode);
6855
6856
    /* Initial allocation is based on the longest-possible character
6857
     * escape.
6858
     *
6859
     * For UCS1 strings it's '\xxx', 4 bytes per source character.
6860
     * For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6861
     * For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character. */
6862
737k
    Py_ssize_t expandsize = kind * 2 + 2;
6863
737k
    if (len > PY_SSIZE_T_MAX / expandsize) {
6864
0
        return PyErr_NoMemory();
6865
0
    }
6866
6867
737k
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
6868
737k
    if (writer == NULL) {
6869
0
        return NULL;
6870
0
    }
6871
737k
    char *p = PyBytesWriter_GetData(writer);
6872
6873
1.47M
    for (Py_ssize_t i = 0; i < len; i++) {
6874
737k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6875
6876
        /* U+0000-U+00ff range */
6877
737k
        if (ch < 0x100) {
6878
731k
            if (ch >= ' ' && ch < 127) {
6879
33.3k
                if (ch != '\\') {
6880
                    /* Copy printable US ASCII as-is */
6881
0
                    *p++ = (char) ch;
6882
0
                }
6883
                /* Escape backslashes */
6884
33.3k
                else {
6885
33.3k
                    *p++ = '\\';
6886
33.3k
                    *p++ = '\\';
6887
33.3k
                }
6888
33.3k
            }
6889
6890
            /* Map special whitespace to '\t', \n', '\r' */
6891
698k
            else if (ch == '\t') {
6892
1.05k
                *p++ = '\\';
6893
1.05k
                *p++ = 't';
6894
1.05k
            }
6895
696k
            else if (ch == '\n') {
6896
3.48k
                *p++ = '\\';
6897
3.48k
                *p++ = 'n';
6898
3.48k
            }
6899
693k
            else if (ch == '\r') {
6900
484
                *p++ = '\\';
6901
484
                *p++ = 'r';
6902
484
            }
6903
6904
            /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6905
692k
            else {
6906
692k
                *p++ = '\\';
6907
692k
                *p++ = 'x';
6908
692k
                *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6909
692k
                *p++ = Py_hexdigits[ch & 0x000F];
6910
692k
            }
6911
731k
        }
6912
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
6913
6.22k
        else if (ch < 0x10000) {
6914
4.21k
            *p++ = '\\';
6915
4.21k
            *p++ = 'u';
6916
4.21k
            *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6917
4.21k
            *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6918
4.21k
            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6919
4.21k
            *p++ = Py_hexdigits[ch & 0x000F];
6920
4.21k
        }
6921
        /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6922
2.01k
        else {
6923
6924
            /* Make sure that the first two digits are zero */
6925
2.01k
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6926
2.01k
            *p++ = '\\';
6927
2.01k
            *p++ = 'U';
6928
2.01k
            *p++ = '0';
6929
2.01k
            *p++ = '0';
6930
2.01k
            *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6931
2.01k
            *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6932
2.01k
            *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6933
2.01k
            *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6934
2.01k
            *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6935
2.01k
            *p++ = Py_hexdigits[ch & 0x0000000F];
6936
2.01k
        }
6937
737k
    }
6938
6939
737k
    return PyBytesWriter_FinishWithPointer(writer, p);
6940
737k
}
6941
6942
/* --- Raw Unicode Escape Codec ------------------------------------------- */
6943
6944
PyObject *
6945
_PyUnicode_DecodeRawUnicodeEscapeStateful(const char *s,
6946
                                          Py_ssize_t size,
6947
                                          const char *errors,
6948
                                          Py_ssize_t *consumed)
6949
130
{
6950
130
    const char *starts = s;
6951
130
    _PyUnicodeWriter writer;
6952
130
    const char *end;
6953
130
    PyObject *errorHandler = NULL;
6954
130
    PyObject *exc = NULL;
6955
6956
130
    if (size == 0) {
6957
0
        if (consumed) {
6958
0
            *consumed = 0;
6959
0
        }
6960
0
        _Py_RETURN_UNICODE_EMPTY();
6961
0
    }
6962
6963
    /* Escaped strings will always be longer than the resulting
6964
       Unicode string, so we start with size here and then reduce the
6965
       length after conversion to the true value. (But decoding error
6966
       handler might have to resize the string) */
6967
130
    _PyUnicodeWriter_Init(&writer);
6968
130
    writer.min_length = size;
6969
130
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6970
0
        goto onError;
6971
0
    }
6972
6973
130
    end = s + size;
6974
1.42M
    while (s < end) {
6975
1.42M
        unsigned char c = (unsigned char) *s++;
6976
1.42M
        Py_UCS4 ch;
6977
1.42M
        int count;
6978
1.42M
        const char *message;
6979
6980
1.42M
#define WRITE_CHAR(ch)                                                        \
6981
1.42M
            do {                                                              \
6982
1.42M
                if (ch <= writer.maxchar) {                                   \
6983
1.42M
                    assert(writer.pos < writer.size);                         \
6984
1.42M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6985
1.42M
                }                                                             \
6986
1.42M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6987
0
                    goto onError;                                             \
6988
0
                }                                                             \
6989
1.42M
            } while(0)
6990
6991
        /* Non-escape characters are interpreted as Unicode ordinals */
6992
1.42M
        if (c != '\\' || (s >= end && !consumed)) {
6993
1.42M
            WRITE_CHAR(c);
6994
1.42M
            continue;
6995
1.42M
        }
6996
6997
1.94k
        Py_ssize_t startinpos = s - starts - 1;
6998
        /* \ - Escapes */
6999
1.94k
        if (s >= end) {
7000
0
            assert(consumed);
7001
            // Set message to silent compiler warning.
7002
            // Actually it is never used.
7003
0
            message = "\\ at end of string";
7004
0
            goto incomplete;
7005
0
        }
7006
7007
1.94k
        c = (unsigned char) *s++;
7008
1.94k
        if (c == 'u') {
7009
564
            count = 4;
7010
564
            message = "truncated \\uXXXX escape";
7011
564
        }
7012
1.37k
        else if (c == 'U') {
7013
437
            count = 8;
7014
437
            message = "truncated \\UXXXXXXXX escape";
7015
437
        }
7016
940
        else {
7017
940
            assert(writer.pos < writer.size);
7018
940
            PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
7019
940
            WRITE_CHAR(c);
7020
940
            continue;
7021
940
        }
7022
7023
        /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
7024
6.59k
        for (ch = 0; count; ++s, --count) {
7025
5.62k
            if (s >= end) {
7026
22
                goto incomplete;
7027
22
            }
7028
5.60k
            c = (unsigned char)*s;
7029
5.60k
            ch <<= 4;
7030
5.60k
            if (c >= '0' && c <= '9') {
7031
3.58k
                ch += c - '0';
7032
3.58k
            }
7033
2.01k
            else if (c >= 'a' && c <= 'f') {
7034
663
                ch += c - ('a' - 10);
7035
663
            }
7036
1.35k
            else if (c >= 'A' && c <= 'F') {
7037
1.34k
                ch += c - ('A' - 10);
7038
1.34k
            }
7039
12
            else {
7040
12
                goto error;
7041
12
            }
7042
5.60k
        }
7043
967
        if (ch > MAX_UNICODE) {
7044
4
            message = "\\Uxxxxxxxx out of range";
7045
4
            goto error;
7046
4
        }
7047
963
        WRITE_CHAR(ch);
7048
963
        continue;
7049
7050
963
      incomplete:
7051
22
        if (consumed) {
7052
0
            *consumed = startinpos;
7053
0
            break;
7054
0
        }
7055
38
      error:;
7056
38
        Py_ssize_t endinpos = s-starts;
7057
38
        writer.min_length = end - s + writer.pos;
7058
38
        if (unicode_decode_call_errorhandler_writer(
7059
38
                errors, &errorHandler,
7060
38
                "rawunicodeescape", message,
7061
38
                &starts, &end, &startinpos, &endinpos, &exc, &s,
7062
38
                &writer)) {
7063
38
            goto onError;
7064
38
        }
7065
38
        assert(end - s <= writer.size - writer.pos);
7066
7067
0
#undef WRITE_CHAR
7068
0
    }
7069
92
    Py_XDECREF(errorHandler);
7070
92
    Py_XDECREF(exc);
7071
92
    return _PyUnicodeWriter_Finish(&writer);
7072
7073
38
  onError:
7074
38
    _PyUnicodeWriter_Dealloc(&writer);
7075
38
    Py_XDECREF(errorHandler);
7076
38
    Py_XDECREF(exc);
7077
38
    return NULL;
7078
130
}
7079
7080
PyObject *
7081
PyUnicode_DecodeRawUnicodeEscape(const char *s,
7082
                                 Py_ssize_t size,
7083
                                 const char *errors)
7084
0
{
7085
0
    return _PyUnicode_DecodeRawUnicodeEscapeStateful(s, size, errors, NULL);
7086
0
}
7087
7088
7089
PyObject *
7090
PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
7091
286k
{
7092
286k
    if (!PyUnicode_Check(unicode)) {
7093
0
        PyErr_BadArgument();
7094
0
        return NULL;
7095
0
    }
7096
286k
    int kind = PyUnicode_KIND(unicode);
7097
286k
    const void *data = PyUnicode_DATA(unicode);
7098
286k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
7099
286k
    if (len == 0) {
7100
519
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7101
519
    }
7102
286k
    if (kind == PyUnicode_1BYTE_KIND) {
7103
286k
        return PyBytes_FromStringAndSize(data, len);
7104
286k
    }
7105
7106
    /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
7107
       bytes, and 1 byte characters 4. */
7108
361
    Py_ssize_t expandsize = kind * 2 + 2;
7109
361
    if (len > PY_SSIZE_T_MAX / expandsize) {
7110
0
        return PyErr_NoMemory();
7111
0
    }
7112
7113
361
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
7114
361
    if (writer == NULL) {
7115
0
        return NULL;
7116
0
    }
7117
361
    char *p = PyBytesWriter_GetData(writer);
7118
7119
5.05M
    for (Py_ssize_t pos = 0; pos < len; pos++) {
7120
5.05M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7121
7122
        /* U+0000-U+00ff range: Copy 8-bit characters as-is */
7123
5.05M
        if (ch < 0x100) {
7124
5.00M
            *p++ = (char) ch;
7125
5.00M
        }
7126
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
7127
45.6k
        else if (ch < 0x10000) {
7128
45.0k
            *p++ = '\\';
7129
45.0k
            *p++ = 'u';
7130
45.0k
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7131
45.0k
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7132
45.0k
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7133
45.0k
            *p++ = Py_hexdigits[ch & 15];
7134
45.0k
        }
7135
        /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
7136
680
        else {
7137
680
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
7138
680
            *p++ = '\\';
7139
680
            *p++ = 'U';
7140
680
            *p++ = '0';
7141
680
            *p++ = '0';
7142
680
            *p++ = Py_hexdigits[(ch >> 20) & 0xf];
7143
680
            *p++ = Py_hexdigits[(ch >> 16) & 0xf];
7144
680
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7145
680
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7146
680
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7147
680
            *p++ = Py_hexdigits[ch & 15];
7148
680
        }
7149
5.05M
    }
7150
7151
361
    return PyBytesWriter_FinishWithPointer(writer, p);
7152
361
}
7153
7154
/* --- Latin-1 Codec ------------------------------------------------------ */
7155
7156
PyObject *
7157
PyUnicode_DecodeLatin1(const char *s,
7158
                       Py_ssize_t size,
7159
                       const char *errors)
7160
3.55M
{
7161
    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
7162
3.55M
    return _PyUnicode_FromUCS1((const unsigned char*)s, size);
7163
3.55M
}
7164
7165
/* create or adjust a UnicodeEncodeError */
7166
static void
7167
make_encode_exception(PyObject **exceptionObject,
7168
                      const char *encoding,
7169
                      PyObject *unicode,
7170
                      Py_ssize_t startpos, Py_ssize_t endpos,
7171
                      const char *reason)
7172
2.80M
{
7173
2.80M
    if (*exceptionObject == NULL) {
7174
2.80M
        *exceptionObject = PyObject_CallFunction(
7175
2.80M
            PyExc_UnicodeEncodeError, "sOnns",
7176
2.80M
            encoding, unicode, startpos, endpos, reason);
7177
2.80M
    }
7178
0
    else {
7179
0
        if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
7180
0
            goto onError;
7181
0
        if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
7182
0
            goto onError;
7183
0
        if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
7184
0
            goto onError;
7185
0
        return;
7186
0
      onError:
7187
0
        Py_CLEAR(*exceptionObject);
7188
0
    }
7189
2.80M
}
7190
7191
/* raises a UnicodeEncodeError */
7192
static void
7193
raise_encode_exception(PyObject **exceptionObject,
7194
                       const char *encoding,
7195
                       PyObject *unicode,
7196
                       Py_ssize_t startpos, Py_ssize_t endpos,
7197
                       const char *reason)
7198
2.62M
{
7199
2.62M
    make_encode_exception(exceptionObject,
7200
2.62M
                          encoding, unicode, startpos, endpos, reason);
7201
2.62M
    if (*exceptionObject != NULL)
7202
2.62M
        PyCodec_StrictErrors(*exceptionObject);
7203
2.62M
}
7204
7205
/* error handling callback helper:
7206
   build arguments, call the callback and check the arguments,
7207
   put the result into newpos and return the replacement string, which
7208
   has to be freed by the caller */
7209
static PyObject *
7210
unicode_encode_call_errorhandler(const char *errors,
7211
                                 PyObject **errorHandler,
7212
                                 const char *encoding, const char *reason,
7213
                                 PyObject *unicode, PyObject **exceptionObject,
7214
                                 Py_ssize_t startpos, Py_ssize_t endpos,
7215
                                 Py_ssize_t *newpos)
7216
178k
{
7217
178k
    static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
7218
178k
    Py_ssize_t len;
7219
178k
    PyObject *restuple;
7220
178k
    PyObject *resunicode;
7221
7222
178k
    if (*errorHandler == NULL) {
7223
178k
        *errorHandler = PyCodec_LookupError(errors);
7224
178k
        if (*errorHandler == NULL)
7225
0
            return NULL;
7226
178k
    }
7227
7228
178k
    len = PyUnicode_GET_LENGTH(unicode);
7229
7230
178k
    make_encode_exception(exceptionObject,
7231
178k
                          encoding, unicode, startpos, endpos, reason);
7232
178k
    if (*exceptionObject == NULL)
7233
0
        return NULL;
7234
7235
178k
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
7236
178k
    if (restuple == NULL)
7237
178k
        return NULL;
7238
0
    if (!PyTuple_Check(restuple)) {
7239
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
7240
0
        Py_DECREF(restuple);
7241
0
        return NULL;
7242
0
    }
7243
0
    if (!PyArg_ParseTuple(restuple, argparse,
7244
0
                          &resunicode, newpos)) {
7245
0
        Py_DECREF(restuple);
7246
0
        return NULL;
7247
0
    }
7248
0
    if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
7249
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
7250
0
        Py_DECREF(restuple);
7251
0
        return NULL;
7252
0
    }
7253
0
    if (*newpos<0)
7254
0
        *newpos = len + *newpos;
7255
0
    if (*newpos<0 || *newpos>len) {
7256
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7257
0
        Py_DECREF(restuple);
7258
0
        return NULL;
7259
0
    }
7260
0
    Py_INCREF(resunicode);
7261
0
    Py_DECREF(restuple);
7262
0
    return resunicode;
7263
0
}
7264
7265
static PyObject *
7266
unicode_encode_ucs1(PyObject *unicode,
7267
                    const char *errors,
7268
                    const Py_UCS4 limit)
7269
2.64M
{
7270
    /* input state */
7271
2.64M
    Py_ssize_t pos=0, size;
7272
2.64M
    int kind;
7273
2.64M
    const void *data;
7274
2.64M
    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
7275
2.64M
    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
7276
2.64M
    PyObject *error_handler_obj = NULL;
7277
2.64M
    PyObject *exc = NULL;
7278
2.64M
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7279
2.64M
    PyObject *rep = NULL;
7280
7281
2.64M
    size = PyUnicode_GET_LENGTH(unicode);
7282
2.64M
    kind = PyUnicode_KIND(unicode);
7283
2.64M
    data = PyUnicode_DATA(unicode);
7284
    /* allocate enough for a simple encoding without
7285
       replacements, if we need more, we'll resize */
7286
2.64M
    if (size == 0)
7287
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7288
7289
    /* output object */
7290
2.64M
    PyBytesWriter *writer = PyBytesWriter_Create(size);
7291
2.64M
    if (writer == NULL) {
7292
0
        return NULL;
7293
0
    }
7294
    /* pointer into the output */
7295
2.64M
    char *str = PyBytesWriter_GetData(writer);
7296
7297
8.74M
    while (pos < size) {
7298
8.74M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7299
7300
        /* can we encode this? */
7301
8.74M
        if (ch < limit) {
7302
            /* no overflow check, because we know that the space is enough */
7303
6.10M
            *str++ = (char)ch;
7304
6.10M
            ++pos;
7305
6.10M
        }
7306
2.64M
        else {
7307
2.64M
            Py_ssize_t newpos, i;
7308
            /* startpos for collecting unencodable chars */
7309
2.64M
            Py_ssize_t collstart = pos;
7310
2.64M
            Py_ssize_t collend = collstart + 1;
7311
            /* find all unecodable characters */
7312
7313
6.41M
            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
7314
3.77M
                ++collend;
7315
7316
            /* Only overallocate the buffer if it's not the last write */
7317
2.64M
            writer->overallocate = (collend < size);
7318
7319
            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
7320
2.64M
            if (error_handler == _Py_ERROR_UNKNOWN)
7321
2.64M
                error_handler = _Py_GetErrorHandler(errors);
7322
7323
2.64M
            switch (error_handler) {
7324
2.62M
            case _Py_ERROR_STRICT:
7325
2.62M
                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
7326
2.62M
                goto onError;
7327
7328
4.86k
            case _Py_ERROR_REPLACE:
7329
4.86k
                memset(str, '?', collend - collstart);
7330
4.86k
                str += (collend - collstart);
7331
4.86k
                _Py_FALLTHROUGH;
7332
4.86k
            case _Py_ERROR_IGNORE:
7333
4.86k
                pos = collend;
7334
4.86k
                break;
7335
7336
0
            case _Py_ERROR_BACKSLASHREPLACE:
7337
0
                str = backslashreplace(writer, str,
7338
0
                                       unicode, collstart, collend);
7339
0
                if (str == NULL)
7340
0
                    goto onError;
7341
0
                pos = collend;
7342
0
                break;
7343
7344
0
            case _Py_ERROR_XMLCHARREFREPLACE:
7345
0
                str = xmlcharrefreplace(writer, str,
7346
0
                                        unicode, collstart, collend);
7347
0
                if (str == NULL)
7348
0
                    goto onError;
7349
0
                pos = collend;
7350
0
                break;
7351
7352
13.3k
            case _Py_ERROR_SURROGATEESCAPE:
7353
13.3k
                for (i = collstart; i < collend; ++i) {
7354
13.3k
                    ch = PyUnicode_READ(kind, data, i);
7355
13.3k
                    if (ch < 0xdc80 || 0xdcff < ch) {
7356
                        /* Not a UTF-8b surrogate */
7357
13.3k
                        break;
7358
13.3k
                    }
7359
0
                    *str++ = (char)(ch - 0xdc00);
7360
0
                    ++pos;
7361
0
                }
7362
13.3k
                if (i >= collend)
7363
0
                    break;
7364
13.3k
                collstart = pos;
7365
13.3k
                assert(collstart != collend);
7366
13.3k
                _Py_FALLTHROUGH;
7367
7368
13.3k
            default:
7369
13.3k
                rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
7370
13.3k
                                                       encoding, reason, unicode, &exc,
7371
13.3k
                                                       collstart, collend, &newpos);
7372
13.3k
                if (rep == NULL)
7373
13.3k
                    goto onError;
7374
7375
0
                if (newpos < collstart) {
7376
0
                    writer->overallocate = 1;
7377
0
                    str = PyBytesWriter_GrowAndUpdatePointer(writer,
7378
0
                                                             collstart - newpos,
7379
0
                                                             str);
7380
0
                    if (str == NULL) {
7381
0
                        goto onError;
7382
0
                    }
7383
0
                }
7384
0
                else {
7385
                    /* Only overallocate the buffer if it's not the last write */
7386
0
                    writer->overallocate = (newpos < size);
7387
7388
                    /* subtract preallocated bytes */
7389
0
                    if (PyBytesWriter_Grow(writer, -(newpos - collstart)) < 0) {
7390
0
                        goto onError;
7391
0
                    }
7392
0
                }
7393
7394
0
                const char *rep_str;
7395
0
                Py_ssize_t rep_len;
7396
0
                if (PyBytes_Check(rep)) {
7397
                    /* Directly copy bytes result to output. */
7398
0
                    rep_str = PyBytes_AS_STRING(rep);
7399
0
                    rep_len = PyBytes_GET_SIZE(rep);
7400
0
                }
7401
0
                else {
7402
0
                    assert(PyUnicode_Check(rep));
7403
7404
0
                    if (limit == 256 ?
7405
0
                        PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
7406
0
                        !PyUnicode_IS_ASCII(rep))
7407
0
                    {
7408
                        /* Not all characters are smaller than limit */
7409
0
                        raise_encode_exception(&exc, encoding, unicode,
7410
0
                                               collstart, collend, reason);
7411
0
                        goto onError;
7412
0
                    }
7413
0
                    assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
7414
0
                    rep_str = PyUnicode_DATA(rep);
7415
0
                    rep_len = PyUnicode_GET_LENGTH(rep);
7416
0
                }
7417
7418
0
                str = PyBytesWriter_GrowAndUpdatePointer(writer, rep_len, str);
7419
0
                if (str == NULL) {
7420
0
                    goto onError;
7421
0
                }
7422
0
                memcpy(str, rep_str, rep_len);
7423
0
                str += rep_len;
7424
7425
0
                pos = newpos;
7426
0
                Py_CLEAR(rep);
7427
2.64M
            }
7428
7429
            /* If overallocation was disabled, ensure that it was the last
7430
               write. Otherwise, we missed an optimization */
7431
2.64M
            assert(writer->overallocate || pos == size);
7432
4.86k
        }
7433
8.74M
    }
7434
7435
4.72k
    Py_XDECREF(error_handler_obj);
7436
4.72k
    Py_XDECREF(exc);
7437
4.72k
    return PyBytesWriter_FinishWithPointer(writer, str);
7438
7439
2.63M
  onError:
7440
2.63M
    Py_XDECREF(rep);
7441
2.63M
    PyBytesWriter_Discard(writer);
7442
2.63M
    Py_XDECREF(error_handler_obj);
7443
2.63M
    Py_XDECREF(exc);
7444
2.63M
    return NULL;
7445
2.64M
}
7446
7447
PyObject *
7448
_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
7449
10
{
7450
10
    if (!PyUnicode_Check(unicode)) {
7451
0
        PyErr_BadArgument();
7452
0
        return NULL;
7453
0
    }
7454
    /* Fast path: if it is a one-byte string, construct
7455
       bytes object directly. */
7456
10
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7457
10
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7458
10
                                         PyUnicode_GET_LENGTH(unicode));
7459
    /* Non-Latin-1 characters present. Defer to above function to
7460
       raise the exception. */
7461
0
    return unicode_encode_ucs1(unicode, errors, 256);
7462
10
}
7463
7464
PyObject*
7465
PyUnicode_AsLatin1String(PyObject *unicode)
7466
0
{
7467
0
    return _PyUnicode_AsLatin1String(unicode, NULL);
7468
0
}
7469
7470
/* --- 7-bit ASCII Codec -------------------------------------------------- */
7471
7472
PyObject *
7473
PyUnicode_DecodeASCII(const char *s,
7474
                      Py_ssize_t size,
7475
                      const char *errors)
7476
14.2M
{
7477
14.2M
    const char *starts = s;
7478
14.2M
    const char *e = s + size;
7479
14.2M
    PyObject *error_handler_obj = NULL;
7480
14.2M
    PyObject *exc = NULL;
7481
14.2M
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7482
7483
14.2M
    if (size == 0)
7484
0
        _Py_RETURN_UNICODE_EMPTY();
7485
7486
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
7487
14.2M
    if (size == 1 && (unsigned char)s[0] < 128) {
7488
697k
        return get_latin1_char((unsigned char)s[0]);
7489
697k
    }
7490
7491
    // Shortcut for simple case
7492
13.5M
    PyObject *u = PyUnicode_New(size, 127);
7493
13.5M
    if (u == NULL) {
7494
0
        return NULL;
7495
0
    }
7496
13.5M
    Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
7497
13.5M
    if (outpos == size) {
7498
10.8M
        return u;
7499
10.8M
    }
7500
7501
2.66M
    _PyUnicodeWriter writer;
7502
2.66M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
7503
2.66M
    writer.pos = outpos;
7504
7505
2.66M
    s += outpos;
7506
2.66M
    int kind = writer.kind;
7507
2.66M
    void *data = writer.data;
7508
2.66M
    Py_ssize_t startinpos, endinpos;
7509
7510
28.0M
    while (s < e) {
7511
27.9M
        unsigned char c = (unsigned char)*s;
7512
27.9M
        if (c < 128) {
7513
13.9M
            PyUnicode_WRITE(kind, data, writer.pos, c);
7514
13.9M
            writer.pos++;
7515
13.9M
            ++s;
7516
13.9M
            continue;
7517
13.9M
        }
7518
7519
        /* byte outsize range 0x00..0x7f: call the error handler */
7520
7521
14.0M
        if (error_handler == _Py_ERROR_UNKNOWN)
7522
2.66M
            error_handler = _Py_GetErrorHandler(errors);
7523
7524
14.0M
        switch (error_handler)
7525
14.0M
        {
7526
972k
        case _Py_ERROR_REPLACE:
7527
11.5M
        case _Py_ERROR_SURROGATEESCAPE:
7528
            /* Fast-path: the error handler only writes one character,
7529
               but we may switch to UCS2 at the first write */
7530
11.5M
            if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7531
0
                goto onError;
7532
11.5M
            assert(_PyUnicodeWriter_CanWrite(&writer));
7533
11.5M
            kind = writer.kind;
7534
11.5M
            data = writer.data;
7535
7536
11.5M
            if (error_handler == _Py_ERROR_REPLACE)
7537
972k
                PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7538
10.5M
            else
7539
10.5M
                PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7540
11.5M
            writer.pos++;
7541
11.5M
            ++s;
7542
11.5M
            break;
7543
7544
0
        case _Py_ERROR_IGNORE:
7545
0
            ++s;
7546
0
            break;
7547
7548
2.48M
        default:
7549
2.48M
            startinpos = s-starts;
7550
2.48M
            endinpos = startinpos + 1;
7551
2.48M
            if (unicode_decode_call_errorhandler_writer(
7552
2.48M
                    errors, &error_handler_obj,
7553
2.48M
                    "ascii", "ordinal not in range(128)",
7554
2.48M
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
7555
2.48M
                    &writer))
7556
2.48M
                goto onError;
7557
0
            kind = writer.kind;
7558
0
            data = writer.data;
7559
14.0M
        }
7560
14.0M
    }
7561
171k
    Py_XDECREF(error_handler_obj);
7562
171k
    Py_XDECREF(exc);
7563
171k
    return _PyUnicodeWriter_Finish(&writer);
7564
7565
2.48M
  onError:
7566
2.48M
    _PyUnicodeWriter_Dealloc(&writer);
7567
2.48M
    Py_XDECREF(error_handler_obj);
7568
2.48M
    Py_XDECREF(exc);
7569
2.48M
    return NULL;
7570
2.66M
}
7571
7572
PyObject *
7573
_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
7574
2.94M
{
7575
2.94M
    if (!PyUnicode_Check(unicode)) {
7576
0
        PyErr_BadArgument();
7577
0
        return NULL;
7578
0
    }
7579
    /* Fast path: if it is an ASCII-only string, construct bytes object
7580
       directly. Else defer to above function to raise the exception. */
7581
2.94M
    if (PyUnicode_IS_ASCII(unicode))
7582
307k
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7583
307k
                                         PyUnicode_GET_LENGTH(unicode));
7584
2.64M
    return unicode_encode_ucs1(unicode, errors, 128);
7585
2.94M
}
7586
7587
PyObject *
7588
PyUnicode_AsASCIIString(PyObject *unicode)
7589
114k
{
7590
114k
    return _PyUnicode_AsASCIIString(unicode, NULL);
7591
114k
}
7592
7593
#ifdef MS_WINDOWS
7594
7595
/* --- MBCS codecs for Windows -------------------------------------------- */
7596
7597
#if SIZEOF_INT < SIZEOF_SIZE_T
7598
#define NEED_RETRY
7599
#endif
7600
7601
/* INT_MAX is the theoretical largest chunk (or INT_MAX / 2 when
7602
   transcoding from UTF-16), but INT_MAX / 4 performs better in
7603
   both cases also and avoids partial characters overrunning the
7604
   length limit in MultiByteToWideChar on Windows */
7605
#define DECODING_CHUNK_SIZE (INT_MAX/4)
7606
7607
#ifndef WC_ERR_INVALID_CHARS
7608
#  define WC_ERR_INVALID_CHARS 0x0080
7609
#endif
7610
7611
static const char*
7612
code_page_name(UINT code_page, PyObject **obj)
7613
{
7614
    *obj = NULL;
7615
    if (code_page == CP_ACP)
7616
        return "mbcs";
7617
7618
    *obj = PyBytes_FromFormat("cp%u", code_page);
7619
    if (*obj == NULL)
7620
        return NULL;
7621
    return PyBytes_AS_STRING(*obj);
7622
}
7623
7624
static DWORD
7625
decode_code_page_flags(UINT code_page)
7626
{
7627
    if (code_page == CP_UTF7) {
7628
        /* The CP_UTF7 decoder only supports flags=0 */
7629
        return 0;
7630
    }
7631
    else
7632
        return MB_ERR_INVALID_CHARS;
7633
}
7634
7635
/*
7636
 * Decode a byte string from a Windows code page into unicode object in strict
7637
 * mode.
7638
 *
7639
 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7640
 * OSError and returns -1 on other error.
7641
 */
7642
static int
7643
decode_code_page_strict(UINT code_page,
7644
                        wchar_t **buf,
7645
                        Py_ssize_t *bufsize,
7646
                        const char *in,
7647
                        int insize)
7648
{
7649
    DWORD flags = MB_ERR_INVALID_CHARS;
7650
    wchar_t *out;
7651
    DWORD outsize;
7652
7653
    /* First get the size of the result */
7654
    assert(insize > 0);
7655
    while ((outsize = MultiByteToWideChar(code_page, flags,
7656
                                          in, insize, NULL, 0)) <= 0)
7657
    {
7658
        if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7659
            goto error;
7660
        }
7661
        /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7662
        flags = 0;
7663
    }
7664
7665
    /* Extend a wchar_t* buffer */
7666
    Py_ssize_t n = *bufsize;   /* Get the current length */
7667
    if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7668
        return -1;
7669
    }
7670
    out = *buf + n;
7671
7672
    /* Do the conversion */
7673
    outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7674
    if (outsize <= 0)
7675
        goto error;
7676
    return insize;
7677
7678
error:
7679
    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7680
        return -2;
7681
    PyErr_SetFromWindowsErr(0);
7682
    return -1;
7683
}
7684
7685
/*
7686
 * Decode a byte string from a code page into unicode object with an error
7687
 * handler.
7688
 *
7689
 * Returns consumed size if succeed, or raise an OSError or
7690
 * UnicodeDecodeError exception and returns -1 on error.
7691
 */
7692
static int
7693
decode_code_page_errors(UINT code_page,
7694
                        wchar_t **buf,
7695
                        Py_ssize_t *bufsize,
7696
                        const char *in, const int size,
7697
                        const char *errors, int final)
7698
{
7699
    const char *startin = in;
7700
    const char *endin = in + size;
7701
    DWORD flags = MB_ERR_INVALID_CHARS;
7702
    /* Ideally, we should get reason from FormatMessage. This is the Windows
7703
       2000 English version of the message. */
7704
    const char *reason = "No mapping for the Unicode character exists "
7705
                         "in the target code page.";
7706
    /* each step cannot decode more than 1 character, but a character can be
7707
       represented as a surrogate pair */
7708
    wchar_t buffer[2], *out;
7709
    int insize;
7710
    Py_ssize_t outsize;
7711
    PyObject *errorHandler = NULL;
7712
    PyObject *exc = NULL;
7713
    PyObject *encoding_obj = NULL;
7714
    const char *encoding;
7715
    DWORD err;
7716
    int ret = -1;
7717
7718
    assert(size > 0);
7719
7720
    encoding = code_page_name(code_page, &encoding_obj);
7721
    if (encoding == NULL)
7722
        return -1;
7723
7724
    if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
7725
        /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7726
           UnicodeDecodeError. */
7727
        make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7728
        if (exc != NULL) {
7729
            PyCodec_StrictErrors(exc);
7730
            Py_CLEAR(exc);
7731
        }
7732
        goto error;
7733
    }
7734
7735
    /* Extend a wchar_t* buffer */
7736
    Py_ssize_t n = *bufsize;   /* Get the current length */
7737
    if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7738
        PyErr_NoMemory();
7739
        goto error;
7740
    }
7741
    if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7742
        goto error;
7743
    }
7744
    out = *buf + n;
7745
7746
    /* Decode the byte string character per character */
7747
    while (in < endin)
7748
    {
7749
        /* Decode a character */
7750
        insize = 1;
7751
        do
7752
        {
7753
            outsize = MultiByteToWideChar(code_page, flags,
7754
                                          in, insize,
7755
                                          buffer, Py_ARRAY_LENGTH(buffer));
7756
            if (outsize > 0)
7757
                break;
7758
            err = GetLastError();
7759
            if (err == ERROR_INVALID_FLAGS && flags) {
7760
                /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7761
                flags = 0;
7762
                continue;
7763
            }
7764
            if (err != ERROR_NO_UNICODE_TRANSLATION
7765
                && err != ERROR_INSUFFICIENT_BUFFER)
7766
            {
7767
                PyErr_SetFromWindowsErr(err);
7768
                goto error;
7769
            }
7770
            insize++;
7771
        }
7772
        /* 4=maximum length of a UTF-8 sequence */
7773
        while (insize <= 4 && (in + insize) <= endin);
7774
7775
        if (outsize <= 0) {
7776
            Py_ssize_t startinpos, endinpos, outpos;
7777
7778
            /* last character in partial decode? */
7779
            if (in + insize >= endin && !final)
7780
                break;
7781
7782
            startinpos = in - startin;
7783
            endinpos = startinpos + 1;
7784
            outpos = out - *buf;
7785
            if (unicode_decode_call_errorhandler_wchar(
7786
                    errors, &errorHandler,
7787
                    encoding, reason,
7788
                    &startin, &endin, &startinpos, &endinpos, &exc, &in,
7789
                    buf, bufsize, &outpos))
7790
            {
7791
                goto error;
7792
            }
7793
            out = *buf + outpos;
7794
        }
7795
        else {
7796
            in += insize;
7797
            memcpy(out, buffer, outsize * sizeof(wchar_t));
7798
            out += outsize;
7799
        }
7800
    }
7801
7802
    /* Shrink the buffer */
7803
    assert(out - *buf <= *bufsize);
7804
    *bufsize = out - *buf;
7805
    /* (in - startin) <= size and size is an int */
7806
    ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
7807
7808
error:
7809
    Py_XDECREF(encoding_obj);
7810
    Py_XDECREF(errorHandler);
7811
    Py_XDECREF(exc);
7812
    return ret;
7813
}
7814
7815
static PyObject *
7816
decode_code_page_stateful(int code_page,
7817
                          const char *s, Py_ssize_t size,
7818
                          const char *errors, Py_ssize_t *consumed)
7819
{
7820
    wchar_t *buf = NULL;
7821
    Py_ssize_t bufsize = 0;
7822
    int chunk_size, final, converted, done;
7823
7824
    if (code_page < 0) {
7825
        PyErr_SetString(PyExc_ValueError, "invalid code page number");
7826
        return NULL;
7827
    }
7828
    if (size < 0) {
7829
        PyErr_BadInternalCall();
7830
        return NULL;
7831
    }
7832
7833
    if (consumed)
7834
        *consumed = 0;
7835
7836
    do
7837
    {
7838
#ifdef NEED_RETRY
7839
        if (size > DECODING_CHUNK_SIZE) {
7840
            chunk_size = DECODING_CHUNK_SIZE;
7841
            final = 0;
7842
            done = 0;
7843
        }
7844
        else
7845
#endif
7846
        {
7847
            chunk_size = (int)size;
7848
            final = (consumed == NULL);
7849
            done = 1;
7850
        }
7851
7852
        if (chunk_size == 0 && done) {
7853
            if (buf != NULL)
7854
                break;
7855
            _Py_RETURN_UNICODE_EMPTY();
7856
        }
7857
7858
        converted = decode_code_page_strict(code_page, &buf, &bufsize,
7859
                                            s, chunk_size);
7860
        if (converted == -2)
7861
            converted = decode_code_page_errors(code_page, &buf, &bufsize,
7862
                                                s, chunk_size,
7863
                                                errors, final);
7864
        assert(converted != 0 || done);
7865
7866
        if (converted < 0) {
7867
            PyMem_Free(buf);
7868
            return NULL;
7869
        }
7870
7871
        if (consumed)
7872
            *consumed += converted;
7873
7874
        s += converted;
7875
        size -= converted;
7876
    } while (!done);
7877
7878
    PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7879
    PyMem_Free(buf);
7880
    return v;
7881
}
7882
7883
PyObject *
7884
PyUnicode_DecodeCodePageStateful(int code_page,
7885
                                 const char *s,
7886
                                 Py_ssize_t size,
7887
                                 const char *errors,
7888
                                 Py_ssize_t *consumed)
7889
{
7890
    return decode_code_page_stateful(code_page, s, size, errors, consumed);
7891
}
7892
7893
PyObject *
7894
PyUnicode_DecodeMBCSStateful(const char *s,
7895
                             Py_ssize_t size,
7896
                             const char *errors,
7897
                             Py_ssize_t *consumed)
7898
{
7899
    return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7900
}
7901
7902
PyObject *
7903
PyUnicode_DecodeMBCS(const char *s,
7904
                     Py_ssize_t size,
7905
                     const char *errors)
7906
{
7907
    return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7908
}
7909
7910
static DWORD
7911
encode_code_page_flags(UINT code_page, const char *errors)
7912
{
7913
    if (code_page == CP_UTF8) {
7914
        return WC_ERR_INVALID_CHARS;
7915
    }
7916
    else if (code_page == CP_UTF7) {
7917
        /* CP_UTF7 only supports flags=0 */
7918
        return 0;
7919
    }
7920
    else {
7921
        if (errors != NULL && strcmp(errors, "replace") == 0)
7922
            return 0;
7923
        else
7924
            return WC_NO_BEST_FIT_CHARS;
7925
    }
7926
}
7927
7928
/*
7929
 * Encode a Unicode string to a Windows code page into a byte string in strict
7930
 * mode.
7931
 *
7932
 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7933
 * an OSError and returns -1 on other error.
7934
 */
7935
static int
7936
encode_code_page_strict(UINT code_page, PyBytesWriter **writer,
7937
                        PyObject *unicode, Py_ssize_t offset, int len,
7938
                        const char* errors)
7939
{
7940
    BOOL usedDefaultChar = FALSE;
7941
    BOOL *pusedDefaultChar = &usedDefaultChar;
7942
    int outsize;
7943
    wchar_t *p;
7944
    Py_ssize_t size;
7945
    const DWORD flags = encode_code_page_flags(code_page, NULL);
7946
    char *out;
7947
    /* Create a substring so that we can get the UTF-16 representation
7948
       of just the slice under consideration. */
7949
    PyObject *substring;
7950
    int ret = -1;
7951
7952
    assert(len > 0);
7953
7954
    if (code_page != CP_UTF8 && code_page != CP_UTF7)
7955
        pusedDefaultChar = &usedDefaultChar;
7956
    else
7957
        pusedDefaultChar = NULL;
7958
7959
    substring = PyUnicode_Substring(unicode, offset, offset+len);
7960
    if (substring == NULL)
7961
        return -1;
7962
    p = PyUnicode_AsWideCharString(substring, &size);
7963
    Py_CLEAR(substring);
7964
    if (p == NULL) {
7965
        return -1;
7966
    }
7967
    assert(size <= INT_MAX);
7968
7969
    /* First get the size of the result */
7970
    outsize = WideCharToMultiByte(code_page, flags,
7971
                                  p, (int)size,
7972
                                  NULL, 0,
7973
                                  NULL, pusedDefaultChar);
7974
    if (outsize <= 0)
7975
        goto error;
7976
    /* If we used a default char, then we failed! */
7977
    if (pusedDefaultChar && *pusedDefaultChar) {
7978
        ret = -2;
7979
        goto done;
7980
    }
7981
7982
    if (*writer == NULL) {
7983
        /* Create string object */
7984
        *writer = PyBytesWriter_Create(outsize);
7985
        if (*writer == NULL) {
7986
            goto done;
7987
        }
7988
        out = PyBytesWriter_GetData(*writer);
7989
    }
7990
    else {
7991
        /* Extend string object */
7992
        Py_ssize_t n = PyBytesWriter_GetSize(*writer);
7993
        if (PyBytesWriter_Grow(*writer, outsize) < 0) {
7994
            goto done;
7995
        }
7996
        out = (char*)PyBytesWriter_GetData(*writer) + n;
7997
    }
7998
7999
    /* Do the conversion */
8000
    outsize = WideCharToMultiByte(code_page, flags,
8001
                                  p, (int)size,
8002
                                  out, outsize,
8003
                                  NULL, pusedDefaultChar);
8004
    if (outsize <= 0)
8005
        goto error;
8006
    if (pusedDefaultChar && *pusedDefaultChar) {
8007
        ret = -2;
8008
        goto done;
8009
    }
8010
    ret = 0;
8011
8012
done:
8013
    PyMem_Free(p);
8014
    return ret;
8015
8016
error:
8017
    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
8018
        ret = -2;
8019
        goto done;
8020
    }
8021
    PyErr_SetFromWindowsErr(0);
8022
    goto done;
8023
}
8024
8025
/*
8026
 * Encode a Unicode string to a Windows code page into a byte string using an
8027
 * error handler.
8028
 *
8029
 * Returns consumed characters if succeed, or raise an OSError and returns
8030
 * -1 on other error.
8031
 */
8032
static int
8033
encode_code_page_errors(UINT code_page, PyBytesWriter **writer,
8034
                        PyObject *unicode, Py_ssize_t unicode_offset,
8035
                        Py_ssize_t insize, const char* errors)
8036
{
8037
    const DWORD flags = encode_code_page_flags(code_page, errors);
8038
    Py_ssize_t pos = unicode_offset;
8039
    Py_ssize_t endin = unicode_offset + insize;
8040
    /* Ideally, we should get reason from FormatMessage. This is the Windows
8041
       2000 English version of the message. */
8042
    const char *reason = "invalid character";
8043
    /* 4=maximum length of a UTF-8 sequence */
8044
    char buffer[4];
8045
    BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
8046
    Py_ssize_t outsize;
8047
    char *out;
8048
    PyObject *errorHandler = NULL;
8049
    PyObject *exc = NULL;
8050
    PyObject *encoding_obj = NULL;
8051
    const char *encoding;
8052
    Py_ssize_t newpos;
8053
    PyObject *rep;
8054
    int ret = -1;
8055
8056
    assert(insize > 0);
8057
8058
    encoding = code_page_name(code_page, &encoding_obj);
8059
    if (encoding == NULL)
8060
        return -1;
8061
8062
    if (errors == NULL || strcmp(errors, "strict") == 0) {
8063
        /* The last error was ERROR_NO_UNICODE_TRANSLATION,
8064
           then we raise a UnicodeEncodeError. */
8065
        make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
8066
        if (exc != NULL) {
8067
            PyCodec_StrictErrors(exc);
8068
            Py_DECREF(exc);
8069
        }
8070
        Py_XDECREF(encoding_obj);
8071
        return -1;
8072
    }
8073
8074
    if (code_page != CP_UTF8 && code_page != CP_UTF7)
8075
        pusedDefaultChar = &usedDefaultChar;
8076
    else
8077
        pusedDefaultChar = NULL;
8078
8079
    if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
8080
        PyErr_NoMemory();
8081
        goto error;
8082
    }
8083
    outsize = insize * Py_ARRAY_LENGTH(buffer);
8084
8085
    if (*writer == NULL) {
8086
        /* Create string object */
8087
        *writer = PyBytesWriter_Create(outsize);
8088
        if (*writer == NULL) {
8089
            goto error;
8090
        }
8091
        out = PyBytesWriter_GetData(*writer);
8092
    }
8093
    else {
8094
        /* Extend string object */
8095
        Py_ssize_t n = PyBytesWriter_GetSize(*writer);
8096
        if (PyBytesWriter_Grow(*writer, outsize) < 0) {
8097
            goto error;
8098
        }
8099
        out = (char*)PyBytesWriter_GetData(*writer) + n;
8100
    }
8101
8102
    /* Encode the string character per character */
8103
    while (pos < endin)
8104
    {
8105
        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
8106
        wchar_t chars[2];
8107
        int charsize;
8108
        if (ch < 0x10000) {
8109
            chars[0] = (wchar_t)ch;
8110
            charsize = 1;
8111
        }
8112
        else {
8113
            chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
8114
            chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
8115
            charsize = 2;
8116
        }
8117
8118
        outsize = WideCharToMultiByte(code_page, flags,
8119
                                      chars, charsize,
8120
                                      buffer, Py_ARRAY_LENGTH(buffer),
8121
                                      NULL, pusedDefaultChar);
8122
        if (outsize > 0) {
8123
            if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
8124
            {
8125
                pos++;
8126
                memcpy(out, buffer, outsize);
8127
                out += outsize;
8128
                continue;
8129
            }
8130
        }
8131
        else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
8132
            PyErr_SetFromWindowsErr(0);
8133
            goto error;
8134
        }
8135
8136
        rep = unicode_encode_call_errorhandler(
8137
                  errors, &errorHandler, encoding, reason,
8138
                  unicode, &exc,
8139
                  pos, pos + 1, &newpos);
8140
        if (rep == NULL)
8141
            goto error;
8142
8143
        Py_ssize_t morebytes = pos - newpos;
8144
        if (PyBytes_Check(rep)) {
8145
            outsize = PyBytes_GET_SIZE(rep);
8146
            morebytes += outsize;
8147
            if (morebytes > 0) {
8148
                out = PyBytesWriter_GrowAndUpdatePointer(*writer, morebytes, out);
8149
                if (out == NULL) {
8150
                    Py_DECREF(rep);
8151
                    goto error;
8152
                }
8153
            }
8154
            memcpy(out, PyBytes_AS_STRING(rep), outsize);
8155
            out += outsize;
8156
        }
8157
        else {
8158
            Py_ssize_t i;
8159
            int kind;
8160
            const void *data;
8161
8162
            outsize = PyUnicode_GET_LENGTH(rep);
8163
            morebytes += outsize;
8164
            if (morebytes > 0) {
8165
                out = PyBytesWriter_GrowAndUpdatePointer(*writer, morebytes, out);
8166
                if (out == NULL) {
8167
                    Py_DECREF(rep);
8168
                    goto error;
8169
                }
8170
            }
8171
            kind = PyUnicode_KIND(rep);
8172
            data = PyUnicode_DATA(rep);
8173
            for (i=0; i < outsize; i++) {
8174
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8175
                if (ch > 127) {
8176
                    raise_encode_exception(&exc,
8177
                        encoding, unicode,
8178
                        pos, pos + 1,
8179
                        "unable to encode error handler result to ASCII");
8180
                    Py_DECREF(rep);
8181
                    goto error;
8182
                }
8183
                *out = (unsigned char)ch;
8184
                out++;
8185
            }
8186
        }
8187
        pos = newpos;
8188
        Py_DECREF(rep);
8189
    }
8190
    /* write a NUL byte */
8191
    *out = 0;
8192
    outsize = out - (char*)PyBytesWriter_GetData(*writer);
8193
    assert(outsize <= PyBytesWriter_GetSize(*writer));
8194
    if (PyBytesWriter_Resize(*writer, outsize) < 0) {
8195
        goto error;
8196
    }
8197
    ret = 0;
8198
8199
error:
8200
    Py_XDECREF(encoding_obj);
8201
    Py_XDECREF(errorHandler);
8202
    Py_XDECREF(exc);
8203
    return ret;
8204
}
8205
8206
8207
PyObject *
8208
PyUnicode_EncodeCodePage(int code_page,
8209
                         PyObject *unicode,
8210
                         const char *errors)
8211
{
8212
    Py_ssize_t len;
8213
    PyBytesWriter *writer = NULL;
8214
    Py_ssize_t offset;
8215
    int chunk_len, ret, done;
8216
8217
    if (!PyUnicode_Check(unicode)) {
8218
        PyErr_BadArgument();
8219
        return NULL;
8220
    }
8221
8222
    len = PyUnicode_GET_LENGTH(unicode);
8223
8224
    if (code_page < 0) {
8225
        PyErr_SetString(PyExc_ValueError, "invalid code page number");
8226
        return NULL;
8227
    }
8228
8229
    if (len == 0)
8230
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
8231
8232
    offset = 0;
8233
    do
8234
    {
8235
#ifdef NEED_RETRY
8236
        if (len > DECODING_CHUNK_SIZE) {
8237
            chunk_len = DECODING_CHUNK_SIZE;
8238
            done = 0;
8239
        }
8240
        else
8241
#endif
8242
        {
8243
            chunk_len = (int)len;
8244
            done = 1;
8245
        }
8246
8247
        ret = encode_code_page_strict(code_page, &writer,
8248
                                      unicode, offset, chunk_len,
8249
                                      errors);
8250
        if (ret == -2)
8251
            ret = encode_code_page_errors(code_page, &writer,
8252
                                          unicode, offset,
8253
                                          chunk_len, errors);
8254
        if (ret < 0) {
8255
            PyBytesWriter_Discard(writer);
8256
            return NULL;
8257
        }
8258
8259
        offset += chunk_len;
8260
        len -= chunk_len;
8261
    } while (!done);
8262
8263
    return PyBytesWriter_Finish(writer);
8264
}
8265
8266
8267
PyObject *
8268
PyUnicode_AsMBCSString(PyObject *unicode)
8269
{
8270
    return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
8271
}
8272
8273
#undef NEED_RETRY
8274
8275
#endif /* MS_WINDOWS */
8276
8277
/* --- iconv Codec -------------------------------------------------------- */
8278
8279
#ifdef _Py_HAVE_ICONV
8280
8281
/* iconv pivot: native-endian UTF-32, a raw array of Py_UCS4.  One input unit is
8282
   one code point, so error handlers get the exact position.  A platform whose
8283
   iconv lacks a UTF-32 endpoint (e.g. UTF-8-only OpenBSD) reports every encoding
8284
   as unavailable. */
8285
#if PY_BIG_ENDIAN
8286
#  define ICONV_PIVOT "UTF-32BE"
8287
#else
8288
12.6k
#  define ICONV_PIVOT "UTF-32LE"
8289
#endif
8290
8291
/* A 2-byte string can be fed to iconv as "UCS-2" only where that is a strict
8292
   array of independent code points.  Some implementations alias "UCS-2" to
8293
   "UTF-16" and would combine an adjacent surrogate pair (a 2-byte string may
8294
   hold one as two code points); there the 2-byte kind is widened to UTF-32.
8295
   glibc and GNU libiconv keep UCS-2 and UTF-16 separate. */
8296
#if defined(__GLIBC__) || defined(_LIBICONV_VERSION)
8297
#  if PY_BIG_ENDIAN
8298
#    define ICONV_UCS2_PIVOT "UCS-2BE"
8299
#  else
8300
0
#    define ICONV_UCS2_PIVOT "UCS-2LE"
8301
#  endif
8302
#endif
8303
8304
static iconv_t
8305
iconv_open_or_set_error(const char *tocode, const char *fromcode,
8306
                        const char *encoding)
8307
85.0k
{
8308
85.0k
    iconv_t cd = iconv_open(tocode, fromcode);
8309
85.0k
    if (cd == (iconv_t)-1) {
8310
71.9k
        if (errno == EINVAL) {
8311
71.9k
            PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding);
8312
71.9k
        }
8313
0
        else {
8314
0
            PyErr_SetFromErrno(PyExc_OSError);
8315
0
        }
8316
71.9k
    }
8317
85.0k
    return cd;
8318
85.0k
}
8319
8320
/*
8321
 * Decode bytes with iconv() into a str.
8322
 *
8323
 * The input is converted to native-endian UTF-32 one chunk at a time and
8324
 * appended to a _PyUnicodeWriter.  If *consumed* is non-NULL the decode is
8325
 * stateful: a trailing incomplete sequence stops and sets *consumed*.
8326
 */
8327
PyObject *
8328
_PyUnicode_DecodeIconv(const char *encoding,
8329
                       const char *s, Py_ssize_t size,
8330
                       const char *errors, Py_ssize_t *consumed)
8331
12.6k
{
8332
12.6k
    if (size < 0) {
8333
0
        PyErr_BadInternalCall();
8334
0
        return NULL;
8335
0
    }
8336
8337
12.6k
    iconv_t cd = iconv_open_or_set_error(ICONV_PIVOT, encoding, encoding);
8338
12.6k
    if (cd == (iconv_t)-1) {
8339
0
        return NULL;
8340
0
    }
8341
8342
    /* Scratch buffer for one iconv() output chunk, as UTF-32 code points. */
8343
12.6k
    Py_UCS4 chunk[1024];
8344
12.6k
    const char *starts = s;
8345
12.6k
    const char *in = s;
8346
12.6k
    const char *inend = s + size;
8347
12.6k
    _PyUnicodeWriter writer;
8348
12.6k
    PyObject *errorHandler = NULL;
8349
12.6k
    PyObject *exc = NULL;
8350
8351
12.6k
    _PyUnicodeWriter_Init(&writer);
8352
12.6k
    writer.min_length = size;
8353
8354
422k
    while (in < inend) {
8355
420k
        char *inptr = (char *)in;
8356
420k
        size_t inleft = (size_t)(inend - in);
8357
420k
        char *outptr = (char *)chunk;
8358
420k
        size_t outleft = sizeof(chunk);
8359
8360
        /* Cast the input buffer through void*: iconv() declares its second
8361
           argument as "char **" on most systems but "const char **" on some
8362
           (e.g. illumos), and void* converts to either without a warning. */
8363
420k
        size_t ret = iconv(cd, (void *)&inptr, &inleft, &outptr, &outleft);
8364
420k
        int err = errno;
8365
420k
        in = inptr;
8366
8367
        /* Append whatever code points this call produced. */
8368
420k
        Py_ssize_t nch = (Py_UCS4 *)outptr - chunk;
8369
420k
        if (nch > 0 && PyUnicodeWriter_WriteUCS4((PyUnicodeWriter *)&writer,
8370
45.3k
                                                 chunk, nch) < 0) {
8371
0
            goto error;
8372
0
        }
8373
8374
420k
        if (ret != (size_t)-1) {
8375
8.49k
            assert(in == inend);
8376
8.49k
            break;
8377
8.49k
        }
8378
8379
411k
        if (err == E2BIG) {
8380
            /* The scratch buffer filled up; drain it and continue. */
8381
2.85k
            continue;
8382
2.85k
        }
8383
8384
408k
        const char *reason;
8385
408k
        if (err == EINVAL) {
8386
            /* Incomplete multibyte sequence at the end of the input. */
8387
21
            if (consumed != NULL) {
8388
                /* Stateful decoding: stop and report the consumed bytes. */
8389
0
                break;
8390
0
            }
8391
21
            reason = "incomplete multibyte sequence";
8392
21
        }
8393
408k
        else if (err == EILSEQ) {
8394
408k
            reason = "invalid multibyte sequence";
8395
408k
        }
8396
0
        else {
8397
0
            errno = err;
8398
0
            PyErr_SetFromErrno(PyExc_OSError);
8399
0
            goto error;
8400
0
        }
8401
8402
408k
        Py_ssize_t startinpos = in - starts;
8403
408k
        Py_ssize_t endinpos = startinpos + 1;
8404
408k
        if (unicode_decode_call_errorhandler_writer(
8405
408k
                errors, &errorHandler, encoding, reason,
8406
408k
                &starts, &inend, &startinpos, &endinpos, &exc, &in,
8407
408k
                &writer)) {
8408
2.11k
            goto error;
8409
2.11k
        }
8410
        /* The error handler may have skipped bytes; reset the conversion
8411
           descriptor to the initial shift state before continuing. */
8412
406k
        iconv(cd, NULL, NULL, NULL, NULL);
8413
406k
    }
8414
8415
10.5k
    if (consumed != NULL) {
8416
0
        *consumed = in - starts;
8417
0
    }
8418
10.5k
    iconv_close(cd);
8419
10.5k
    Py_XDECREF(errorHandler);
8420
10.5k
    Py_XDECREF(exc);
8421
10.5k
    return _PyUnicodeWriter_Finish(&writer);
8422
8423
2.11k
error:
8424
2.11k
    iconv_close(cd);
8425
2.11k
    _PyUnicodeWriter_Dealloc(&writer);
8426
2.11k
    Py_XDECREF(errorHandler);
8427
2.11k
    Py_XDECREF(exc);
8428
2.11k
    return NULL;
8429
12.6k
}
8430
8431
/* Grow the output buffer of a PyBytesWriter, keeping the raw cursor *pout and
8432
   the end pointer *poutend valid.  Returns 0 on success, -1 on error. */
8433
static int
8434
iconv_grow_writer(PyBytesWriter *writer, char **pout, char **poutend)
8435
0
{
8436
0
    char *base = PyBytesWriter_GetData(writer);
8437
0
    Py_ssize_t used = *pout - base;
8438
0
    Py_ssize_t cursize = PyBytesWriter_GetSize(writer);
8439
0
    Py_ssize_t growby = cursize > 0 ? cursize : 16;
8440
0
    if (PyBytesWriter_Grow(writer, growby) < 0) {
8441
0
        return -1;
8442
0
    }
8443
0
    base = PyBytesWriter_GetData(writer);
8444
0
    *pout = base + used;
8445
0
    *poutend = base + PyBytesWriter_GetSize(writer);
8446
0
    return 0;
8447
0
}
8448
8449
/*
8450
 * Encode a str to bytes with iconv().
8451
 *
8452
 * The string's own buffer is fed to iconv() using the source encoding for its
8453
 * kind, avoiding a widening copy: Latin-1 for 1-byte (not ASCII: it may hold
8454
 * U+0080..U+00FF), UTF-32 for 4-byte, and UCS-2 -- or a UTF-32 copy where that
8455
 * is unsafe (see ICONV_UCS2_PIVOT) -- for 2-byte.  One input unit is one code
8456
 * point, so the unit index is the string position.
8457
 */
8458
PyObject *
8459
_PyUnicode_EncodeIconv(const char *encoding, PyObject *unicode,
8460
                       const char *errors)
8461
72.3k
{
8462
72.3k
    if (!PyUnicode_Check(unicode)) {
8463
0
        PyErr_BadArgument();
8464
0
        return NULL;
8465
0
    }
8466
8467
72.3k
    Py_ssize_t ulen = PyUnicode_GET_LENGTH(unicode);
8468
72.3k
    const char *source;         /* iconv source encoding for this kind */
8469
72.3k
    const char *data;           /* the units to encode */
8470
72.3k
    Py_ssize_t unit;            /* bytes per code point in *data */
8471
72.3k
    Py_UCS4 *widened = NULL;    /* owned UTF-32 copy of a 2-byte string */
8472
72.3k
    int kind = PyUnicode_KIND(unicode);
8473
72.3k
    if (kind == PyUnicode_1BYTE_KIND) {
8474
72.3k
        source = "ISO-8859-1";
8475
72.3k
        data = (const char *)PyUnicode_1BYTE_DATA(unicode);
8476
72.3k
        unit = 1;
8477
72.3k
    }
8478
0
    else if (kind == PyUnicode_4BYTE_KIND) {
8479
0
        source = ICONV_PIVOT;
8480
0
        data = (const char *)PyUnicode_4BYTE_DATA(unicode);
8481
0
        unit = 4;
8482
0
    }
8483
0
    else {
8484
0
#ifdef ICONV_UCS2_PIVOT
8485
        /* Known-strict UCS-2: feed the 2-byte buffer directly. */
8486
0
        source = ICONV_UCS2_PIVOT;
8487
0
        data = (const char *)PyUnicode_2BYTE_DATA(unicode);
8488
0
        unit = 2;
8489
#else
8490
        /* UCS-2 may be aliased to UTF-16 here; widen to UTF-32 to be safe. */
8491
        widened = PyUnicode_AsUCS4Copy(unicode);
8492
        if (widened == NULL) {
8493
            return NULL;
8494
        }
8495
        source = ICONV_PIVOT;
8496
        data = (const char *)widened;
8497
        unit = 4;
8498
#endif
8499
0
    }
8500
8501
72.3k
    iconv_t cd = iconv_open_or_set_error(encoding, source, encoding);
8502
72.3k
    if (cd == (iconv_t)-1) {
8503
71.9k
        PyMem_Free(widened);
8504
71.9k
        return NULL;
8505
71.9k
    }
8506
8507
334
    PyBytesWriter *writer = NULL;
8508
334
    PyObject *errorHandler = NULL;
8509
334
    PyObject *exc = NULL;
8510
334
    PyObject *result = NULL;
8511
334
    const char *ustart = data;
8512
334
    const char *up = data;
8513
334
    const char *uend = data + (size_t)ulen * unit;
8514
334
    int flushing = 0;
8515
334
    int careful = 0;            /* feed one code point per iconv() call */
8516
8517
    /* A generous initial estimate for the output size. */
8518
334
    writer = PyBytesWriter_Create(ulen + (ulen >> 1) + 16);
8519
334
    if (writer == NULL) {
8520
0
        goto done;
8521
0
    }
8522
334
    char *out = PyBytesWriter_GetData(writer);
8523
334
    char *outend = out + PyBytesWriter_GetSize(writer);
8524
8525
668
    for (;;) {
8526
668
        char *inptr = (char *)up;
8527
668
        size_t inleft = (size_t)(uend - up);
8528
        /* One code point at a time, to pin a substitution to its position. */
8529
668
        if (careful && inleft > (size_t)unit) {
8530
0
            inleft = (size_t)unit;
8531
0
        }
8532
668
        char *out_before = out;
8533
668
        size_t outleft = (size_t)(outend - out);
8534
        /* When the whole string is converted, a final iconv() call with a
8535
           NULL input flushes any pending shift sequence (e.g. ISO-2022). */
8536
        /* See the note above on the void* cast of the iconv() input buffer. */
8537
668
        size_t ret = iconv(cd, flushing ? NULL : (void *)&inptr, &inleft, &out, &outleft);
8538
668
        if (!flushing) {
8539
334
            up = inptr;
8540
334
        }
8541
8542
668
        if (ret != (size_t)-1) {
8543
668
            if (flushing) {
8544
334
                break;
8545
334
            }
8546
            /* A positive result counts nonreversible conversions: iconv()
8547
               substituted an unencodable character instead of failing with
8548
               EILSEQ (musl and *BSD citrus do this).  Treat it as unencodable
8549
               and re-run one code point at a time to locate it. */
8550
334
            if (ret > 0) {
8551
0
                if (!careful) {
8552
0
                    careful = 1;
8553
0
                    iconv(cd, NULL, NULL, NULL, NULL);
8554
0
                    out = PyBytesWriter_GetData(writer);
8555
0
                    outend = out + PyBytesWriter_GetSize(writer);
8556
0
                    up = ustart;
8557
0
                    continue;
8558
0
                }
8559
                /* This code point was substituted; drop it and report it. */
8560
0
                out = out_before;
8561
0
                up -= unit;
8562
0
            }
8563
334
            else if (careful && up < uend) {
8564
0
                continue;
8565
0
            }
8566
334
            else {
8567
                /* All input consumed; switch to flushing the shift state. */
8568
334
                flushing = 1;
8569
334
                continue;
8570
334
            }
8571
334
        }
8572
0
        else if (errno == E2BIG) {
8573
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8574
0
                goto done;
8575
0
            }
8576
0
            continue;
8577
0
        }
8578
0
        else if (errno != EILSEQ && errno != EINVAL) {
8579
0
            PyErr_SetFromErrno(PyExc_OSError);
8580
0
            goto done;
8581
0
        }
8582
8583
        /* An unencodable code point at *up; one input unit is one code point. */
8584
0
        Py_ssize_t pos = (up - ustart) / unit;
8585
0
        Py_ssize_t newpos;
8586
0
        PyObject *rep = unicode_encode_call_errorhandler(
8587
0
                errors, &errorHandler, encoding, "invalid character",
8588
0
                unicode, &exc, pos, pos + 1, &newpos);
8589
0
        if (rep == NULL) {
8590
0
            goto done;
8591
0
        }
8592
8593
0
        const char *repdata;
8594
0
        Py_ssize_t replen;
8595
0
        PyObject *repbytes = NULL;
8596
0
        if (PyBytes_Check(rep)) {
8597
0
            repdata = PyBytes_AS_STRING(rep);
8598
0
            replen = PyBytes_GET_SIZE(rep);
8599
0
        }
8600
0
        else {
8601
            /* A str replacement is encoded through the same codec, but
8602
               strictly: handling its errors in turn could never terminate. */
8603
0
            assert(PyUnicode_Check(rep));
8604
0
            repbytes = _PyUnicode_EncodeIconv(encoding, rep, NULL);
8605
0
            Py_DECREF(rep);
8606
0
            if (repbytes == NULL) {
8607
0
                if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
8608
                    /* Report the input the caller knows about, not the
8609
                       replacement. */
8610
0
                    PyErr_Clear();
8611
0
                    raise_encode_exception(&exc, encoding, unicode, pos, pos + 1,
8612
0
                            "unable to encode error handler result");
8613
0
                }
8614
0
                goto done;
8615
0
            }
8616
0
            repdata = PyBytes_AS_STRING(repbytes);
8617
0
            replen = PyBytes_GET_SIZE(repbytes);
8618
0
        }
8619
8620
0
        while (outend - out < replen) {
8621
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8622
0
                if (repbytes != NULL) {
8623
0
                    Py_DECREF(repbytes);
8624
0
                }
8625
0
                else {
8626
0
                    Py_DECREF(rep);
8627
0
                }
8628
0
                goto done;
8629
0
            }
8630
0
        }
8631
0
        memcpy(out, repdata, replen);
8632
0
        out += replen;
8633
0
        if (repbytes != NULL) {
8634
0
            Py_DECREF(repbytes);
8635
0
        }
8636
0
        else {
8637
0
            Py_DECREF(rep);
8638
0
        }
8639
0
        up = ustart + (size_t)newpos * unit;
8640
        /* Reset the shift state after the injected replacement bytes. */
8641
0
        iconv(cd, NULL, NULL, NULL, NULL);
8642
0
    }
8643
8644
334
    result = PyBytesWriter_FinishWithPointer(writer, out);
8645
334
    writer = NULL;
8646
8647
334
done:
8648
334
    if (writer != NULL) {
8649
0
        PyBytesWriter_Discard(writer);
8650
0
    }
8651
334
    iconv_close(cd);
8652
334
    PyMem_Free(widened);
8653
334
    Py_XDECREF(errorHandler);
8654
334
    Py_XDECREF(exc);
8655
334
    return result;
8656
334
}
8657
8658
#endif /* _Py_HAVE_ICONV */
8659
8660
/* --- Character Mapping Codec -------------------------------------------- */
8661
8662
static int
8663
charmap_decode_string(const char *s,
8664
                      Py_ssize_t size,
8665
                      PyObject *mapping,
8666
                      const char *errors,
8667
                      _PyUnicodeWriter *writer)
8668
564k
{
8669
564k
    const char *starts = s;
8670
564k
    const char *e;
8671
564k
    Py_ssize_t startinpos, endinpos;
8672
564k
    PyObject *errorHandler = NULL, *exc = NULL;
8673
564k
    Py_ssize_t maplen;
8674
564k
    int mapkind;
8675
564k
    const void *mapdata;
8676
564k
    Py_UCS4 x;
8677
564k
    unsigned char ch;
8678
8679
564k
    maplen = PyUnicode_GET_LENGTH(mapping);
8680
564k
    mapdata = PyUnicode_DATA(mapping);
8681
564k
    mapkind = PyUnicode_KIND(mapping);
8682
8683
564k
    e = s + size;
8684
8685
564k
    if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
8686
        /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
8687
         * is disabled in encoding aliases, latin1 is preferred because
8688
         * its implementation is faster. */
8689
117
        const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
8690
117
        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8691
117
        Py_UCS4 maxchar = writer->maxchar;
8692
8693
117
        assert (writer->kind == PyUnicode_1BYTE_KIND);
8694
138k
        while (s < e) {
8695
137k
            ch = *s;
8696
137k
            x = mapdata_ucs1[ch];
8697
137k
            if (x > maxchar) {
8698
109
                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8699
0
                    goto onError;
8700
109
                maxchar = writer->maxchar;
8701
109
                outdata = (Py_UCS1 *)writer->data;
8702
109
            }
8703
137k
            outdata[writer->pos] = x;
8704
137k
            writer->pos++;
8705
137k
            ++s;
8706
137k
        }
8707
117
        return 0;
8708
117
    }
8709
8710
674k
    while (s < e) {
8711
657k
        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8712
657k
            int outkind = writer->kind;
8713
657k
            const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
8714
657k
            if (outkind == PyUnicode_1BYTE_KIND) {
8715
596k
                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8716
596k
                Py_UCS4 maxchar = writer->maxchar;
8717
12.4M
                while (s < e) {
8718
11.9M
                    ch = *s;
8719
11.9M
                    x = mapdata_ucs2[ch];
8720
11.9M
                    if (x > maxchar)
8721
70.8k
                        goto Error;
8722
11.8M
                    outdata[writer->pos] = x;
8723
11.8M
                    writer->pos++;
8724
11.8M
                    ++s;
8725
11.8M
                }
8726
525k
                break;
8727
596k
            }
8728
61.4k
            else if (outkind == PyUnicode_2BYTE_KIND) {
8729
61.4k
                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8730
29.0M
                while (s < e) {
8731
29.0M
                    ch = *s;
8732
29.0M
                    x = mapdata_ucs2[ch];
8733
29.0M
                    if (x == 0xFFFE)
8734
38.6k
                        goto Error;
8735
28.9M
                    outdata[writer->pos] = x;
8736
28.9M
                    writer->pos++;
8737
28.9M
                    ++s;
8738
28.9M
                }
8739
22.7k
                break;
8740
61.4k
            }
8741
657k
        }
8742
0
        ch = *s;
8743
8744
0
        if (ch < maplen)
8745
0
            x = PyUnicode_READ(mapkind, mapdata, ch);
8746
0
        else
8747
0
            x = 0xfffe; /* invalid value */
8748
109k
Error:
8749
109k
        if (x == 0xfffe)
8750
57.1k
        {
8751
            /* undefined mapping */
8752
57.1k
            startinpos = s-starts;
8753
57.1k
            endinpos = startinpos+1;
8754
57.1k
            if (unicode_decode_call_errorhandler_writer(
8755
57.1k
                    errors, &errorHandler,
8756
57.1k
                    "charmap", "character maps to <undefined>",
8757
57.1k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
8758
57.1k
                    writer)) {
8759
13
                goto onError;
8760
13
            }
8761
57.0k
            continue;
8762
57.1k
        }
8763
8764
52.4k
        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8765
0
            goto onError;
8766
52.4k
        ++s;
8767
52.4k
    }
8768
564k
    Py_XDECREF(errorHandler);
8769
564k
    Py_XDECREF(exc);
8770
564k
    return 0;
8771
8772
13
onError:
8773
13
    Py_XDECREF(errorHandler);
8774
13
    Py_XDECREF(exc);
8775
13
    return -1;
8776
564k
}
8777
8778
static int
8779
charmap_decode_mapping(const char *s,
8780
                       Py_ssize_t size,
8781
                       PyObject *mapping,
8782
                       const char *errors,
8783
                       _PyUnicodeWriter *writer)
8784
0
{
8785
0
    const char *starts = s;
8786
0
    const char *e;
8787
0
    Py_ssize_t startinpos, endinpos;
8788
0
    PyObject *errorHandler = NULL, *exc = NULL;
8789
0
    unsigned char ch;
8790
0
    PyObject *key, *item = NULL;
8791
8792
0
    e = s + size;
8793
8794
0
    while (s < e) {
8795
0
        ch = *s;
8796
8797
        /* Get mapping (char ordinal -> integer, Unicode char or None) */
8798
0
        key = PyLong_FromLong((long)ch);
8799
0
        if (key == NULL)
8800
0
            goto onError;
8801
8802
0
        int rc = PyMapping_GetOptionalItem(mapping, key, &item);
8803
0
        Py_DECREF(key);
8804
0
        if (rc == 0) {
8805
            /* No mapping found means: mapping is undefined. */
8806
0
            goto Undefined;
8807
0
        }
8808
0
        if (item == NULL) {
8809
0
            if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8810
                /* No mapping found means: mapping is undefined. */
8811
0
                PyErr_Clear();
8812
0
                goto Undefined;
8813
0
            } else
8814
0
                goto onError;
8815
0
        }
8816
8817
        /* Apply mapping */
8818
0
        if (item == Py_None)
8819
0
            goto Undefined;
8820
0
        if (PyLong_Check(item)) {
8821
0
            long value = PyLong_AsLong(item);
8822
0
            if (value == 0xFFFE)
8823
0
                goto Undefined;
8824
0
            if (value < 0 || value > MAX_UNICODE) {
8825
0
                PyErr_Format(PyExc_TypeError,
8826
0
                             "character mapping must be in range(0x%lx)",
8827
0
                             (unsigned long)MAX_UNICODE + 1);
8828
0
                goto onError;
8829
0
            }
8830
8831
0
            if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8832
0
                goto onError;
8833
0
        }
8834
0
        else if (PyUnicode_Check(item)) {
8835
0
            if (PyUnicode_GET_LENGTH(item) == 1) {
8836
0
                Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8837
0
                if (value == 0xFFFE)
8838
0
                    goto Undefined;
8839
0
                if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8840
0
                    goto onError;
8841
0
            }
8842
0
            else {
8843
0
                writer->overallocate = 1;
8844
0
                if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8845
0
                    goto onError;
8846
0
            }
8847
0
        }
8848
0
        else {
8849
            /* wrong return value */
8850
0
            PyErr_SetString(PyExc_TypeError,
8851
0
                            "character mapping must return integer, None or str");
8852
0
            goto onError;
8853
0
        }
8854
0
        Py_CLEAR(item);
8855
0
        ++s;
8856
0
        continue;
8857
8858
0
Undefined:
8859
        /* undefined mapping */
8860
0
        Py_CLEAR(item);
8861
0
        startinpos = s-starts;
8862
0
        endinpos = startinpos+1;
8863
0
        if (unicode_decode_call_errorhandler_writer(
8864
0
                errors, &errorHandler,
8865
0
                "charmap", "character maps to <undefined>",
8866
0
                &starts, &e, &startinpos, &endinpos, &exc, &s,
8867
0
                writer)) {
8868
0
            goto onError;
8869
0
        }
8870
0
    }
8871
0
    Py_XDECREF(errorHandler);
8872
0
    Py_XDECREF(exc);
8873
0
    return 0;
8874
8875
0
onError:
8876
0
    Py_XDECREF(item);
8877
0
    Py_XDECREF(errorHandler);
8878
0
    Py_XDECREF(exc);
8879
0
    return -1;
8880
0
}
8881
8882
PyObject *
8883
PyUnicode_DecodeCharmap(const char *s,
8884
                        Py_ssize_t size,
8885
                        PyObject *mapping,
8886
                        const char *errors)
8887
564k
{
8888
564k
    _PyUnicodeWriter writer;
8889
8890
    /* Default to Latin-1 */
8891
564k
    if (mapping == NULL)
8892
9
        return PyUnicode_DecodeLatin1(s, size, errors);
8893
8894
564k
    if (size == 0)
8895
0
        _Py_RETURN_UNICODE_EMPTY();
8896
564k
    _PyUnicodeWriter_Init(&writer);
8897
564k
    writer.min_length = size;
8898
564k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
8899
0
        goto onError;
8900
8901
564k
    if (PyUnicode_CheckExact(mapping)) {
8902
564k
        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8903
13
            goto onError;
8904
564k
    }
8905
0
    else {
8906
0
        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8907
0
            goto onError;
8908
0
    }
8909
564k
    return _PyUnicodeWriter_Finish(&writer);
8910
8911
13
  onError:
8912
13
    _PyUnicodeWriter_Dealloc(&writer);
8913
13
    return NULL;
8914
564k
}
8915
8916
/* Charmap encoding: the lookup table */
8917
8918
/*[clinic input]
8919
class EncodingMap "struct encoding_map *" "&EncodingMapType"
8920
[clinic start generated code]*/
8921
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=14e46bbb6c522d22]*/
8922
8923
struct encoding_map {
8924
    PyObject_HEAD
8925
    unsigned char level1[32];
8926
    int count2, count3;
8927
    unsigned char level23[1];
8928
};
8929
8930
/*[clinic input]
8931
EncodingMap.size
8932
8933
Return the size (in bytes) of this object.
8934
[clinic start generated code]*/
8935
8936
static PyObject *
8937
EncodingMap_size_impl(struct encoding_map *self)
8938
/*[clinic end generated code: output=c4c969e4c99342a4 input=004ff13f26bb5366]*/
8939
0
{
8940
0
    return PyLong_FromLong((sizeof(*self) - 1) + 16*self->count2 +
8941
0
                           128*self->count3);
8942
0
}
8943
8944
static PyMethodDef encoding_map_methods[] = {
8945
    ENCODINGMAP_SIZE_METHODDEF
8946
    {NULL, NULL}
8947
};
8948
8949
static PyTypeObject EncodingMapType = {
8950
    PyVarObject_HEAD_INIT(NULL, 0)
8951
    .tp_name = "EncodingMap",
8952
    .tp_basicsize = sizeof(struct encoding_map),
8953
    /* methods */
8954
    .tp_flags = Py_TPFLAGS_DEFAULT,
8955
    .tp_methods = encoding_map_methods,
8956
};
8957
8958
PyObject*
8959
PyUnicode_BuildEncodingMap(PyObject* string)
8960
147
{
8961
147
    PyObject *result;
8962
147
    struct encoding_map *mresult;
8963
147
    int i;
8964
147
    int need_dict = 0;
8965
147
    unsigned char level1[32];
8966
147
    unsigned char level2[512];
8967
147
    unsigned char *mlevel1, *mlevel2, *mlevel3;
8968
147
    int count2 = 0, count3 = 0;
8969
147
    int kind;
8970
147
    const void *data;
8971
147
    int length;
8972
147
    Py_UCS4 ch;
8973
8974
147
    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
8975
0
        PyErr_BadArgument();
8976
0
        return NULL;
8977
0
    }
8978
147
    kind = PyUnicode_KIND(string);
8979
147
    data = PyUnicode_DATA(string);
8980
147
    length = (int)Py_MIN(PyUnicode_GET_LENGTH(string), 256);
8981
147
    memset(level1, 0xFF, sizeof level1);
8982
147
    memset(level2, 0xFF, sizeof level2);
8983
8984
    /* If there isn't a one-to-one mapping of NULL to \0,
8985
       or if there are non-BMP characters, we need to use
8986
       a mapping dictionary. */
8987
147
    if (PyUnicode_READ(kind, data, 0) != 0)
8988
0
        need_dict = 1;
8989
37.6k
    for (i = 1; i < length; i++) {
8990
37.4k
        int l1, l2;
8991
37.4k
        ch = PyUnicode_READ(kind, data, i);
8992
37.4k
        if (ch == 0 || ch > 0xFFFF) {
8993
0
            need_dict = 1;
8994
0
            break;
8995
0
        }
8996
37.4k
        if (ch == 0xFFFE)
8997
            /* unmapped character */
8998
1.01k
            continue;
8999
36.4k
        l1 = ch >> 11;
9000
36.4k
        l2 = ch >> 7;
9001
36.4k
        if (level1[l1] == 0xFF)
9002
268
            level1[l1] = count2++;
9003
36.4k
        if (level2[l2] == 0xFF)
9004
786
            level2[l2] = count3++;
9005
36.4k
    }
9006
9007
147
    if (count2 >= 0xFF || count3 >= 0xFF)
9008
0
        need_dict = 1;
9009
9010
147
    if (need_dict) {
9011
0
        PyObject *result = PyDict_New();
9012
0
        if (!result)
9013
0
            return NULL;
9014
0
        for (i = 0; i < length; i++) {
9015
0
            Py_UCS4 c = PyUnicode_READ(kind, data, i);
9016
0
            PyObject *key = PyLong_FromLong(c);
9017
0
            if (key == NULL) {
9018
0
                Py_DECREF(result);
9019
0
                return NULL;
9020
0
            }
9021
0
            PyObject *value = PyLong_FromLong(i);
9022
0
            if (value == NULL) {
9023
0
                Py_DECREF(key);
9024
0
                Py_DECREF(result);
9025
0
                return NULL;
9026
0
            }
9027
0
            int rc = PyDict_SetItem(result, key, value);
9028
0
            Py_DECREF(key);
9029
0
            Py_DECREF(value);
9030
0
            if (rc < 0) {
9031
0
                Py_DECREF(result);
9032
0
                return NULL;
9033
0
            }
9034
0
        }
9035
0
        return result;
9036
0
    }
9037
9038
    /* Create a three-level trie */
9039
147
    result = PyObject_Malloc(sizeof(struct encoding_map) +
9040
147
                             16*count2 + 128*count3 - 1);
9041
147
    if (!result) {
9042
0
        return PyErr_NoMemory();
9043
0
    }
9044
9045
147
    _PyObject_Init(result, &EncodingMapType);
9046
147
    mresult = (struct encoding_map*)result;
9047
147
    mresult->count2 = count2;
9048
147
    mresult->count3 = count3;
9049
147
    mlevel1 = mresult->level1;
9050
147
    mlevel2 = mresult->level23;
9051
147
    mlevel3 = mresult->level23 + 16*count2;
9052
147
    memcpy(mlevel1, level1, 32);
9053
147
    memset(mlevel2, 0xFF, 16*count2);
9054
147
    memset(mlevel3, 0, 128*count3);
9055
147
    count3 = 0;
9056
37.6k
    for (i = 1; i < length; i++) {
9057
37.4k
        int o1, o2, o3, i2, i3;
9058
37.4k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9059
37.4k
        if (ch == 0xFFFE)
9060
            /* unmapped character */
9061
1.01k
            continue;
9062
36.4k
        o1 = ch>>11;
9063
36.4k
        o2 = (ch>>7) & 0xF;
9064
36.4k
        i2 = 16*mlevel1[o1] + o2;
9065
36.4k
        if (mlevel2[i2] == 0xFF)
9066
786
            mlevel2[i2] = count3++;
9067
36.4k
        o3 = ch & 0x7F;
9068
36.4k
        i3 = 128*mlevel2[i2] + o3;
9069
36.4k
        mlevel3[i3] = i;
9070
36.4k
    }
9071
147
    return result;
9072
147
}
9073
9074
static int
9075
encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
9076
0
{
9077
0
    struct encoding_map *map = (struct encoding_map*)mapping;
9078
0
    int l1 = c>>11;
9079
0
    int l2 = (c>>7) & 0xF;
9080
0
    int l3 = c & 0x7F;
9081
0
    int i;
9082
9083
0
    if (c > 0xFFFF)
9084
0
        return -1;
9085
0
    if (c == 0)
9086
0
        return 0;
9087
    /* level 1*/
9088
0
    i = map->level1[l1];
9089
0
    if (i == 0xFF) {
9090
0
        return -1;
9091
0
    }
9092
    /* level 2*/
9093
0
    i = map->level23[16*i+l2];
9094
0
    if (i == 0xFF) {
9095
0
        return -1;
9096
0
    }
9097
    /* level 3 */
9098
0
    i = map->level23[16*map->count2 + 128*i + l3];
9099
0
    if (i == 0) {
9100
0
        return -1;
9101
0
    }
9102
0
    return i;
9103
0
}
9104
9105
/* Lookup the character in the mapping.
9106
   On success, return PyLong, PyBytes or None (if the character can't be found).
9107
   If the result is PyLong, put its value in replace.
9108
   On error, return NULL.
9109
   */
9110
static PyObject *
9111
charmapencode_lookup(Py_UCS4 c, PyObject *mapping, unsigned char *replace)
9112
23.4k
{
9113
23.4k
    PyObject *w = PyLong_FromLong((long)c);
9114
23.4k
    PyObject *x;
9115
9116
23.4k
    if (w == NULL)
9117
0
        return NULL;
9118
23.4k
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9119
23.4k
    Py_DECREF(w);
9120
23.4k
    if (rc == 0) {
9121
        /* No mapping found means: mapping is undefined. */
9122
0
        Py_RETURN_NONE;
9123
0
    }
9124
23.4k
    if (x == NULL) {
9125
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9126
            /* No mapping found means: mapping is undefined. */
9127
0
            PyErr_Clear();
9128
0
            Py_RETURN_NONE;
9129
0
        } else
9130
0
            return NULL;
9131
0
    }
9132
23.4k
    else if (x == Py_None)
9133
0
        return x;
9134
23.4k
    else if (PyLong_Check(x)) {
9135
23.4k
        long value = PyLong_AsLong(x);
9136
23.4k
        if (value < 0 || value > 255) {
9137
0
            PyErr_SetString(PyExc_TypeError,
9138
0
                            "character mapping must be in range(256)");
9139
0
            Py_DECREF(x);
9140
0
            return NULL;
9141
0
        }
9142
23.4k
        *replace = (unsigned char)value;
9143
23.4k
        return x;
9144
23.4k
    }
9145
0
    else if (PyBytes_Check(x))
9146
0
        return x;
9147
0
    else {
9148
        /* wrong return value */
9149
0
        PyErr_Format(PyExc_TypeError,
9150
0
                     "character mapping must return integer, bytes or None, not %.400s",
9151
0
                     Py_TYPE(x)->tp_name);
9152
0
        Py_DECREF(x);
9153
0
        return NULL;
9154
0
    }
9155
23.4k
}
9156
9157
static int
9158
charmapencode_resize(PyBytesWriter *writer, Py_ssize_t *outpos, Py_ssize_t requiredsize)
9159
0
{
9160
0
    Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9161
    /* exponentially overallocate to minimize reallocations */
9162
0
    if (requiredsize < 2 * outsize)
9163
0
        requiredsize = 2 * outsize;
9164
0
    return PyBytesWriter_Resize(writer, requiredsize);
9165
0
}
9166
9167
typedef enum charmapencode_result {
9168
    enc_SUCCESS, enc_FAILED, enc_EXCEPTION
9169
} charmapencode_result;
9170
/* lookup the character, put the result in the output string and adjust
9171
   various state variables. Resize the output bytes object if not enough
9172
   space is available. Return a new reference to the object that
9173
   was put in the output buffer, or Py_None, if the mapping was undefined
9174
   (in which case no character was written) or NULL, if a
9175
   reallocation error occurred. The caller must decref the result */
9176
static charmapencode_result
9177
charmapencode_output(Py_UCS4 c, PyObject *mapping,
9178
                     PyBytesWriter *writer, Py_ssize_t *outpos)
9179
23.4k
{
9180
23.4k
    PyObject *rep;
9181
23.4k
    unsigned char replace;
9182
23.4k
    char *outstart;
9183
23.4k
    Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9184
9185
23.4k
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9186
0
        int res = encoding_map_lookup(c, mapping);
9187
0
        Py_ssize_t requiredsize = *outpos+1;
9188
0
        if (res == -1) {
9189
0
            return enc_FAILED;
9190
0
        }
9191
9192
0
        if (outsize<requiredsize) {
9193
0
            if (charmapencode_resize(writer, outpos, requiredsize)) {
9194
0
                return enc_EXCEPTION;
9195
0
            }
9196
0
        }
9197
0
        outstart = _PyBytesWriter_GetData(writer);
9198
0
        outstart[(*outpos)++] = (char)res;
9199
0
        return enc_SUCCESS;
9200
0
    }
9201
9202
23.4k
    rep = charmapencode_lookup(c, mapping, &replace);
9203
23.4k
    if (rep==NULL)
9204
0
        return enc_EXCEPTION;
9205
23.4k
    else if (rep==Py_None) {
9206
0
        Py_DECREF(rep);
9207
0
        return enc_FAILED;
9208
23.4k
    } else {
9209
23.4k
        if (PyLong_Check(rep)) {
9210
23.4k
            Py_ssize_t requiredsize = *outpos+1;
9211
23.4k
            if (outsize<requiredsize)
9212
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9213
0
                    Py_DECREF(rep);
9214
0
                    return enc_EXCEPTION;
9215
0
                }
9216
23.4k
            outstart = _PyBytesWriter_GetData(writer);
9217
23.4k
            outstart[(*outpos)++] = (char)replace;
9218
23.4k
        }
9219
0
        else {
9220
0
            const char *repchars = PyBytes_AS_STRING(rep);
9221
0
            Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
9222
0
            Py_ssize_t requiredsize = *outpos+repsize;
9223
0
            if (outsize<requiredsize)
9224
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9225
0
                    Py_DECREF(rep);
9226
0
                    return enc_EXCEPTION;
9227
0
                }
9228
0
            outstart = _PyBytesWriter_GetData(writer);
9229
0
            memcpy(outstart + *outpos, repchars, repsize);
9230
0
            *outpos += repsize;
9231
0
        }
9232
23.4k
    }
9233
23.4k
    Py_DECREF(rep);
9234
23.4k
    return enc_SUCCESS;
9235
23.4k
}
9236
9237
/* handle an error in _PyUnicode_EncodeCharmap()
9238
   Return 0 on success, -1 on error */
9239
static int
9240
charmap_encoding_error(
9241
    PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
9242
    PyObject **exceptionObject,
9243
    _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
9244
    PyBytesWriter *writer, Py_ssize_t *respos)
9245
0
{
9246
0
    PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9247
0
    Py_ssize_t size, repsize;
9248
0
    Py_ssize_t newpos;
9249
0
    int kind;
9250
0
    const void *data;
9251
0
    Py_ssize_t index;
9252
    /* startpos for collecting unencodable chars */
9253
0
    Py_ssize_t collstartpos = *inpos;
9254
0
    Py_ssize_t collendpos = *inpos+1;
9255
0
    Py_ssize_t collpos;
9256
0
    const char *encoding = "charmap";
9257
0
    const char *reason = "character maps to <undefined>";
9258
0
    charmapencode_result x;
9259
0
    Py_UCS4 ch;
9260
0
    int val;
9261
9262
0
    size = PyUnicode_GET_LENGTH(unicode);
9263
    /* find all unencodable characters */
9264
0
    while (collendpos < size) {
9265
0
        PyObject *rep;
9266
0
        unsigned char replace;
9267
0
        if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9268
0
            ch = PyUnicode_READ_CHAR(unicode, collendpos);
9269
0
            val = encoding_map_lookup(ch, mapping);
9270
0
            if (val != -1)
9271
0
                break;
9272
0
            ++collendpos;
9273
0
            continue;
9274
0
        }
9275
9276
0
        ch = PyUnicode_READ_CHAR(unicode, collendpos);
9277
0
        rep = charmapencode_lookup(ch, mapping, &replace);
9278
0
        if (rep==NULL)
9279
0
            return -1;
9280
0
        else if (rep!=Py_None) {
9281
0
            Py_DECREF(rep);
9282
0
            break;
9283
0
        }
9284
0
        Py_DECREF(rep);
9285
0
        ++collendpos;
9286
0
    }
9287
    /* cache callback name lookup
9288
     * (if not done yet, i.e. it's the first error) */
9289
0
    if (*error_handler == _Py_ERROR_UNKNOWN)
9290
0
        *error_handler = _Py_GetErrorHandler(errors);
9291
9292
0
    switch (*error_handler) {
9293
0
    case _Py_ERROR_STRICT:
9294
0
        raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9295
0
        return -1;
9296
9297
0
    case _Py_ERROR_REPLACE:
9298
0
        for (collpos = collstartpos; collpos<collendpos; ++collpos) {
9299
0
            x = charmapencode_output('?', mapping, writer, respos);
9300
0
            if (x==enc_EXCEPTION) {
9301
0
                return -1;
9302
0
            }
9303
0
            else if (x==enc_FAILED) {
9304
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9305
0
                return -1;
9306
0
            }
9307
0
        }
9308
0
        _Py_FALLTHROUGH;
9309
0
    case _Py_ERROR_IGNORE:
9310
0
        *inpos = collendpos;
9311
0
        break;
9312
9313
0
    case _Py_ERROR_XMLCHARREFREPLACE:
9314
        /* generate replacement (temporarily (mis)uses p) */
9315
0
        for (collpos = collstartpos; collpos < collendpos; ++collpos) {
9316
0
            char buffer[2+29+1+1];
9317
0
            char *cp;
9318
0
            sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
9319
0
            for (cp = buffer; *cp; ++cp) {
9320
0
                x = charmapencode_output(*cp, mapping, writer, respos);
9321
0
                if (x==enc_EXCEPTION)
9322
0
                    return -1;
9323
0
                else if (x==enc_FAILED) {
9324
0
                    raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9325
0
                    return -1;
9326
0
                }
9327
0
            }
9328
0
        }
9329
0
        *inpos = collendpos;
9330
0
        break;
9331
9332
0
    default:
9333
0
        repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
9334
0
                                                      encoding, reason, unicode, exceptionObject,
9335
0
                                                      collstartpos, collendpos, &newpos);
9336
0
        if (repunicode == NULL)
9337
0
            return -1;
9338
0
        if (PyBytes_Check(repunicode)) {
9339
            /* Directly copy bytes result to output. */
9340
0
            Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9341
0
            Py_ssize_t requiredsize;
9342
0
            repsize = PyBytes_Size(repunicode);
9343
0
            requiredsize = *respos + repsize;
9344
0
            if (requiredsize > outsize)
9345
                /* Make room for all additional bytes. */
9346
0
                if (charmapencode_resize(writer, respos, requiredsize)) {
9347
0
                    Py_DECREF(repunicode);
9348
0
                    return -1;
9349
0
                }
9350
0
            memcpy((char*)PyBytesWriter_GetData(writer) + *respos,
9351
0
                   PyBytes_AsString(repunicode),  repsize);
9352
0
            *respos += repsize;
9353
0
            *inpos = newpos;
9354
0
            Py_DECREF(repunicode);
9355
0
            break;
9356
0
        }
9357
        /* generate replacement  */
9358
0
        repsize = PyUnicode_GET_LENGTH(repunicode);
9359
0
        data = PyUnicode_DATA(repunicode);
9360
0
        kind = PyUnicode_KIND(repunicode);
9361
0
        for (index = 0; index < repsize; index++) {
9362
0
            Py_UCS4 repch = PyUnicode_READ(kind, data, index);
9363
0
            x = charmapencode_output(repch, mapping, writer, respos);
9364
0
            if (x==enc_EXCEPTION) {
9365
0
                Py_DECREF(repunicode);
9366
0
                return -1;
9367
0
            }
9368
0
            else if (x==enc_FAILED) {
9369
0
                Py_DECREF(repunicode);
9370
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9371
0
                return -1;
9372
0
            }
9373
0
        }
9374
0
        *inpos = newpos;
9375
0
        Py_DECREF(repunicode);
9376
0
    }
9377
0
    return 0;
9378
0
}
9379
9380
PyObject *
9381
_PyUnicode_EncodeCharmap(PyObject *unicode,
9382
                         PyObject *mapping,
9383
                         const char *errors)
9384
183
{
9385
    /* Default to Latin-1 */
9386
183
    if (mapping == NULL) {
9387
0
        return unicode_encode_ucs1(unicode, errors, 256);
9388
0
    }
9389
9390
183
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
9391
183
    if (size == 0) {
9392
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
9393
0
    }
9394
183
    const void *data = PyUnicode_DATA(unicode);
9395
183
    int kind = PyUnicode_KIND(unicode);
9396
9397
183
    PyObject *error_handler_obj = NULL;
9398
183
    PyObject *exc = NULL;
9399
9400
    /* output object */
9401
183
    PyBytesWriter *writer;
9402
    /* allocate enough for a simple encoding without
9403
       replacements, if we need more, we'll resize */
9404
183
    writer = PyBytesWriter_Create(size);
9405
183
    if (writer == NULL) {
9406
0
        goto onError;
9407
0
    }
9408
9409
    /* current input position */
9410
183
    Py_ssize_t inpos = 0;
9411
    /* current output position */
9412
183
    Py_ssize_t respos = 0;
9413
183
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
9414
9415
183
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9416
0
        char *outstart = _PyBytesWriter_GetData(writer);
9417
0
        Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9418
9419
0
        while (inpos<size) {
9420
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9421
9422
            /* try to encode it */
9423
0
            int res = encoding_map_lookup(ch, mapping);
9424
0
            Py_ssize_t requiredsize = respos+1;
9425
0
            if (res == -1) {
9426
0
                goto enc_FAILED;
9427
0
            }
9428
9429
0
            if (outsize<requiredsize) {
9430
0
                if (charmapencode_resize(writer, &respos, requiredsize)) {
9431
0
                    goto onError;
9432
0
                }
9433
0
                outstart = _PyBytesWriter_GetData(writer);
9434
0
                outsize = _PyBytesWriter_GetSize(writer);
9435
0
            }
9436
0
            outstart[respos++] = (char)res;
9437
9438
            /* done with this character => adjust input position */
9439
0
            ++inpos;
9440
0
            continue;
9441
9442
0
enc_FAILED:
9443
0
            if (charmap_encoding_error(unicode, &inpos, mapping,
9444
0
                                       &exc,
9445
0
                                       &error_handler, &error_handler_obj, errors,
9446
0
                                       writer, &respos)) {
9447
0
                goto onError;
9448
0
            }
9449
0
            outstart = _PyBytesWriter_GetData(writer);
9450
0
            outsize = _PyBytesWriter_GetSize(writer);
9451
0
        }
9452
0
    }
9453
183
    else {
9454
23.6k
        while (inpos<size) {
9455
23.4k
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9456
            /* try to encode it */
9457
23.4k
            charmapencode_result x = charmapencode_output(ch, mapping, writer, &respos);
9458
23.4k
            if (x==enc_EXCEPTION) { /* error */
9459
0
                goto onError;
9460
0
            }
9461
23.4k
            if (x==enc_FAILED) { /* unencodable character */
9462
0
                if (charmap_encoding_error(unicode, &inpos, mapping,
9463
0
                                           &exc,
9464
0
                                           &error_handler, &error_handler_obj, errors,
9465
0
                                           writer, &respos)) {
9466
0
                    goto onError;
9467
0
                }
9468
0
            }
9469
23.4k
            else {
9470
                /* done with this character => adjust input position */
9471
23.4k
                ++inpos;
9472
23.4k
            }
9473
23.4k
        }
9474
183
    }
9475
9476
183
    Py_XDECREF(exc);
9477
183
    Py_XDECREF(error_handler_obj);
9478
9479
    /* Resize if we allocated too much */
9480
183
    return PyBytesWriter_FinishWithSize(writer, respos);
9481
9482
0
  onError:
9483
0
    PyBytesWriter_Discard(writer);
9484
0
    Py_XDECREF(exc);
9485
0
    Py_XDECREF(error_handler_obj);
9486
0
    return NULL;
9487
183
}
9488
9489
PyObject *
9490
PyUnicode_AsCharmapString(PyObject *unicode,
9491
                          PyObject *mapping)
9492
0
{
9493
0
    if (!PyUnicode_Check(unicode) || mapping == NULL) {
9494
0
        PyErr_BadArgument();
9495
0
        return NULL;
9496
0
    }
9497
0
    return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
9498
0
}
9499
9500
/* create or adjust a UnicodeTranslateError */
9501
static void
9502
make_translate_exception(PyObject **exceptionObject,
9503
                         PyObject *unicode,
9504
                         Py_ssize_t startpos, Py_ssize_t endpos,
9505
                         const char *reason)
9506
0
{
9507
0
    if (*exceptionObject == NULL) {
9508
0
        *exceptionObject = _PyUnicodeTranslateError_Create(
9509
0
            unicode, startpos, endpos, reason);
9510
0
    }
9511
0
    else {
9512
0
        if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
9513
0
            goto onError;
9514
0
        if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
9515
0
            goto onError;
9516
0
        if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
9517
0
            goto onError;
9518
0
        return;
9519
0
      onError:
9520
0
        Py_CLEAR(*exceptionObject);
9521
0
    }
9522
0
}
9523
9524
/* error handling callback helper:
9525
   build arguments, call the callback and check the arguments,
9526
   put the result into newpos and return the replacement string, which
9527
   has to be freed by the caller */
9528
static PyObject *
9529
unicode_translate_call_errorhandler(const char *errors,
9530
                                    PyObject **errorHandler,
9531
                                    const char *reason,
9532
                                    PyObject *unicode, PyObject **exceptionObject,
9533
                                    Py_ssize_t startpos, Py_ssize_t endpos,
9534
                                    Py_ssize_t *newpos)
9535
0
{
9536
0
    static const char *argparse = "Un;translating error handler must return (str, int) tuple";
9537
9538
0
    Py_ssize_t i_newpos;
9539
0
    PyObject *restuple;
9540
0
    PyObject *resunicode;
9541
9542
0
    if (*errorHandler == NULL) {
9543
0
        *errorHandler = PyCodec_LookupError(errors);
9544
0
        if (*errorHandler == NULL)
9545
0
            return NULL;
9546
0
    }
9547
9548
0
    make_translate_exception(exceptionObject,
9549
0
                             unicode, startpos, endpos, reason);
9550
0
    if (*exceptionObject == NULL)
9551
0
        return NULL;
9552
9553
0
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
9554
0
    if (restuple == NULL)
9555
0
        return NULL;
9556
0
    if (!PyTuple_Check(restuple)) {
9557
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
9558
0
        Py_DECREF(restuple);
9559
0
        return NULL;
9560
0
    }
9561
0
    if (!PyArg_ParseTuple(restuple, argparse,
9562
0
                          &resunicode, &i_newpos)) {
9563
0
        Py_DECREF(restuple);
9564
0
        return NULL;
9565
0
    }
9566
0
    if (i_newpos<0)
9567
0
        *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
9568
0
    else
9569
0
        *newpos = i_newpos;
9570
0
    if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
9571
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
9572
0
        Py_DECREF(restuple);
9573
0
        return NULL;
9574
0
    }
9575
0
    Py_INCREF(resunicode);
9576
0
    Py_DECREF(restuple);
9577
0
    return resunicode;
9578
0
}
9579
9580
/* Lookup the character ch in the mapping and put the result in result,
9581
   which must be decrefed by the caller.
9582
   The result can be PyLong, PyUnicode, None or NULL.
9583
   If the result is PyLong, put its value in replace.
9584
   Return 0 on success, -1 on error */
9585
static int
9586
charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result, Py_UCS4 *replace)
9587
20.6k
{
9588
20.6k
    PyObject *w = PyLong_FromLong((long)c);
9589
20.6k
    PyObject *x;
9590
9591
20.6k
    if (w == NULL)
9592
0
        return -1;
9593
20.6k
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9594
20.6k
    Py_DECREF(w);
9595
20.6k
    if (rc == 0) {
9596
        /* No mapping found means: use 1:1 mapping. */
9597
6.95k
        *result = NULL;
9598
6.95k
        return 0;
9599
6.95k
    }
9600
13.6k
    if (x == NULL) {
9601
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9602
            /* No mapping found means: use 1:1 mapping. */
9603
0
            PyErr_Clear();
9604
0
            *result = NULL;
9605
0
            return 0;
9606
0
        } else
9607
0
            return -1;
9608
0
    }
9609
13.6k
    else if (x == Py_None) {
9610
0
        *result = x;
9611
0
        return 0;
9612
0
    }
9613
13.6k
    else if (PyLong_Check(x)) {
9614
0
        long value = PyLong_AsLong(x);
9615
0
        if (value < 0 || value > MAX_UNICODE) {
9616
0
            PyErr_Format(PyExc_ValueError,
9617
0
                         "character mapping must be in range(0x%lx)",
9618
0
                         (unsigned long)MAX_UNICODE + 1);
9619
0
            Py_DECREF(x);
9620
0
            return -1;
9621
0
        }
9622
0
        *result = x;
9623
0
        *replace = (Py_UCS4)value;
9624
0
        return 0;
9625
0
    }
9626
13.6k
    else if (PyUnicode_Check(x)) {
9627
13.6k
        *result = x;
9628
13.6k
        return 0;
9629
13.6k
    }
9630
0
    else {
9631
        /* wrong return value */
9632
0
        PyErr_SetString(PyExc_TypeError,
9633
0
                        "character mapping must return integer, None or str");
9634
0
        Py_DECREF(x);
9635
0
        return -1;
9636
0
    }
9637
13.6k
}
9638
9639
/* lookup the character, write the result into the writer.
9640
   Return 1 if the result was written into the writer, return 0 if the mapping
9641
   was undefined, raise an exception return -1 on error. */
9642
static int
9643
charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
9644
                        _PyUnicodeWriter *writer)
9645
6.99k
{
9646
6.99k
    PyObject *item;
9647
6.99k
    Py_UCS4 replace;
9648
9649
6.99k
    if (charmaptranslate_lookup(ch, mapping, &item, &replace))
9650
0
        return -1;
9651
9652
6.99k
    if (item == NULL) {
9653
        /* not found => default to 1:1 mapping */
9654
114
        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
9655
0
            return -1;
9656
0
        }
9657
114
        return 1;
9658
114
    }
9659
9660
6.88k
    if (item == Py_None) {
9661
0
        Py_DECREF(item);
9662
0
        return 0;
9663
0
    }
9664
9665
6.88k
    if (PyLong_Check(item)) {
9666
0
        if (_PyUnicodeWriter_WriteCharInline(writer, replace) < 0) {
9667
0
            Py_DECREF(item);
9668
0
            return -1;
9669
0
        }
9670
0
        Py_DECREF(item);
9671
0
        return 1;
9672
0
    }
9673
9674
6.88k
    if (!PyUnicode_Check(item)) {
9675
0
        Py_DECREF(item);
9676
0
        return -1;
9677
0
    }
9678
9679
6.88k
    if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
9680
0
        Py_DECREF(item);
9681
0
        return -1;
9682
0
    }
9683
9684
6.88k
    Py_DECREF(item);
9685
6.88k
    return 1;
9686
6.88k
}
9687
9688
static int
9689
unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
9690
                              Py_UCS1 *translate)
9691
13.6k
{
9692
13.6k
    PyObject *item = NULL;
9693
13.6k
    Py_UCS4 replace;
9694
13.6k
    int ret = 0;
9695
9696
13.6k
    if (charmaptranslate_lookup(ch, mapping, &item, &replace)) {
9697
0
        return -1;
9698
0
    }
9699
9700
13.6k
    if (item == Py_None) {
9701
        /* deletion */
9702
0
        translate[ch] = 0xfe;
9703
0
    }
9704
13.6k
    else if (item == NULL) {
9705
        /* not found => default to 1:1 mapping */
9706
6.83k
        translate[ch] = ch;
9707
6.83k
        return 1;
9708
6.83k
    }
9709
6.78k
    else if (PyLong_Check(item)) {
9710
0
        if (replace > 127) {
9711
            /* invalid character or character outside ASCII:
9712
               skip the fast translate */
9713
0
            goto exit;
9714
0
        }
9715
0
        translate[ch] = (Py_UCS1)replace;
9716
0
    }
9717
6.78k
    else if (PyUnicode_Check(item)) {
9718
6.78k
        if (PyUnicode_GET_LENGTH(item) != 1)
9719
6.78k
            goto exit;
9720
9721
0
        replace = PyUnicode_READ_CHAR(item, 0);
9722
0
        if (replace > 127)
9723
0
            goto exit;
9724
0
        translate[ch] = (Py_UCS1)replace;
9725
0
    }
9726
0
    else {
9727
        /* not None, NULL, long or unicode */
9728
0
        goto exit;
9729
0
    }
9730
0
    ret = 1;
9731
9732
6.78k
  exit:
9733
6.78k
    Py_DECREF(item);
9734
6.78k
    return ret;
9735
0
}
9736
9737
/* Fast path for ascii => ascii translation. Return 1 if the whole string
9738
   was translated into writer, return 0 if the input string was partially
9739
   translated into writer, raise an exception and return -1 on error. */
9740
static int
9741
unicode_fast_translate(PyObject *input, PyObject *mapping,
9742
                       _PyUnicodeWriter *writer, int ignore,
9743
                       Py_ssize_t *input_pos)
9744
13.5k
{
9745
13.5k
    Py_UCS1 ascii_table[128], ch, ch2;
9746
13.5k
    Py_ssize_t len;
9747
13.5k
    const Py_UCS1 *in, *end;
9748
13.5k
    Py_UCS1 *out;
9749
13.5k
    int res = 0;
9750
9751
13.5k
    len = PyUnicode_GET_LENGTH(input);
9752
9753
13.5k
    memset(ascii_table, 0xff, 128);
9754
9755
13.5k
    in = PyUnicode_1BYTE_DATA(input);
9756
13.5k
    end = in + len;
9757
9758
13.5k
    assert(PyUnicode_IS_ASCII(writer->buffer));
9759
13.5k
    assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9760
13.5k
    out = PyUnicode_1BYTE_DATA(writer->buffer);
9761
9762
20.4k
    for (; in < end; in++) {
9763
13.6k
        ch = *in;
9764
13.6k
        ch2 = ascii_table[ch];
9765
13.6k
        if (ch2 == 0xff) {
9766
13.6k
            int translate = unicode_fast_translate_lookup(mapping, ch,
9767
13.6k
                                                          ascii_table);
9768
13.6k
            if (translate < 0)
9769
0
                return -1;
9770
13.6k
            if (translate == 0)
9771
6.78k
                goto exit;
9772
6.83k
            ch2 = ascii_table[ch];
9773
6.83k
        }
9774
6.87k
        if (ch2 == 0xfe) {
9775
0
            if (ignore)
9776
0
                continue;
9777
0
            goto exit;
9778
0
        }
9779
6.87k
        assert(ch2 < 128);
9780
6.87k
        *out = ch2;
9781
6.87k
        out++;
9782
6.87k
    }
9783
6.76k
    res = 1;
9784
9785
13.5k
exit:
9786
13.5k
    writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
9787
13.5k
    *input_pos = in - PyUnicode_1BYTE_DATA(input);
9788
13.5k
    return res;
9789
6.76k
}
9790
9791
static PyObject *
9792
_PyUnicode_TranslateCharmap(PyObject *input,
9793
                            PyObject *mapping,
9794
                            const char *errors)
9795
13.5k
{
9796
    /* input object */
9797
13.5k
    const void *data;
9798
13.5k
    Py_ssize_t size, i;
9799
13.5k
    int kind;
9800
    /* output buffer */
9801
13.5k
    _PyUnicodeWriter writer;
9802
    /* error handler */
9803
13.5k
    const char *reason = "character maps to <undefined>";
9804
13.5k
    PyObject *errorHandler = NULL;
9805
13.5k
    PyObject *exc = NULL;
9806
13.5k
    int ignore;
9807
13.5k
    int res;
9808
9809
13.5k
    if (mapping == NULL) {
9810
0
        PyErr_BadArgument();
9811
0
        return NULL;
9812
0
    }
9813
9814
13.5k
    data = PyUnicode_DATA(input);
9815
13.5k
    kind = PyUnicode_KIND(input);
9816
13.5k
    size = PyUnicode_GET_LENGTH(input);
9817
9818
13.5k
    if (size == 0)
9819
0
        return PyUnicode_FromObject(input);
9820
9821
    /* allocate enough for a simple 1:1 translation without
9822
       replacements, if we need more, we'll resize */
9823
13.5k
    _PyUnicodeWriter_Init(&writer);
9824
13.5k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
9825
0
        goto onError;
9826
9827
13.5k
    ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9828
9829
13.5k
    if (PyUnicode_IS_ASCII(input)) {
9830
13.5k
        res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9831
13.5k
        if (res < 0) {
9832
0
            _PyUnicodeWriter_Dealloc(&writer);
9833
0
            return NULL;
9834
0
        }
9835
13.5k
        if (res == 1)
9836
6.76k
            return _PyUnicodeWriter_Finish(&writer);
9837
13.5k
    }
9838
0
    else {
9839
0
        i = 0;
9840
0
    }
9841
9842
13.7k
    while (i<size) {
9843
        /* try to encode it */
9844
6.99k
        int translate;
9845
6.99k
        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9846
6.99k
        Py_ssize_t newpos;
9847
        /* startpos for collecting untranslatable chars */
9848
6.99k
        Py_ssize_t collstart;
9849
6.99k
        Py_ssize_t collend;
9850
6.99k
        Py_UCS4 ch;
9851
9852
6.99k
        ch = PyUnicode_READ(kind, data, i);
9853
6.99k
        translate = charmaptranslate_output(ch, mapping, &writer);
9854
6.99k
        if (translate < 0)
9855
0
            goto onError;
9856
9857
6.99k
        if (translate != 0) {
9858
            /* it worked => adjust input pointer */
9859
6.99k
            ++i;
9860
6.99k
            continue;
9861
6.99k
        }
9862
9863
        /* untranslatable character */
9864
0
        collstart = i;
9865
0
        collend = i+1;
9866
9867
        /* find all untranslatable characters */
9868
0
        while (collend < size) {
9869
0
            PyObject *x;
9870
0
            Py_UCS4 replace;
9871
0
            ch = PyUnicode_READ(kind, data, collend);
9872
0
            if (charmaptranslate_lookup(ch, mapping, &x, &replace))
9873
0
                goto onError;
9874
0
            Py_XDECREF(x);
9875
0
            if (x != Py_None)
9876
0
                break;
9877
0
            ++collend;
9878
0
        }
9879
9880
0
        if (ignore) {
9881
0
            i = collend;
9882
0
        }
9883
0
        else {
9884
0
            repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9885
0
                                                             reason, input, &exc,
9886
0
                                                             collstart, collend, &newpos);
9887
0
            if (repunicode == NULL)
9888
0
                goto onError;
9889
0
            if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
9890
0
                Py_DECREF(repunicode);
9891
0
                goto onError;
9892
0
            }
9893
0
            Py_DECREF(repunicode);
9894
0
            i = newpos;
9895
0
        }
9896
0
    }
9897
6.78k
    Py_XDECREF(exc);
9898
6.78k
    Py_XDECREF(errorHandler);
9899
6.78k
    return _PyUnicodeWriter_Finish(&writer);
9900
9901
0
  onError:
9902
0
    _PyUnicodeWriter_Dealloc(&writer);
9903
0
    Py_XDECREF(exc);
9904
0
    Py_XDECREF(errorHandler);
9905
0
    return NULL;
9906
6.78k
}
9907
9908
PyObject *
9909
PyUnicode_Translate(PyObject *str,
9910
                    PyObject *mapping,
9911
                    const char *errors)
9912
0
{
9913
0
    if (ensure_unicode(str) < 0)
9914
0
        return NULL;
9915
0
    return _PyUnicode_TranslateCharmap(str, mapping, errors);
9916
0
}
9917
9918
PyObject *
9919
_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9920
9.88M
{
9921
9.88M
    if (!PyUnicode_Check(unicode)) {
9922
0
        PyErr_BadInternalCall();
9923
0
        return NULL;
9924
0
    }
9925
9.88M
    if (PyUnicode_IS_ASCII(unicode)) {
9926
        /* If the string is already ASCII, just return the same string */
9927
9.88M
        return Py_NewRef(unicode);
9928
9.88M
    }
9929
9930
2.80k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9931
2.80k
    PyObject *result = PyUnicode_New(len, 127);
9932
2.80k
    if (result == NULL) {
9933
0
        return NULL;
9934
0
    }
9935
9936
2.80k
    Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9937
2.80k
    int kind = PyUnicode_KIND(unicode);
9938
2.80k
    const void *data = PyUnicode_DATA(unicode);
9939
2.80k
    Py_ssize_t i;
9940
112k
    for (i = 0; i < len; ++i) {
9941
110k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9942
110k
        if (ch < 127) {
9943
107k
            out[i] = ch;
9944
107k
        }
9945
3.64k
        else if (Py_UNICODE_ISSPACE(ch)) {
9946
1.21k
            out[i] = ' ';
9947
1.21k
        }
9948
2.42k
        else {
9949
2.42k
            int decimal = Py_UNICODE_TODECIMAL(ch);
9950
2.42k
            if (decimal < 0) {
9951
478
                out[i] = '?';
9952
478
                out[i+1] = '\0';
9953
478
                _PyUnicode_LENGTH(result) = i + 1;
9954
478
                break;
9955
478
            }
9956
1.95k
            out[i] = '0' + decimal;
9957
1.95k
        }
9958
110k
    }
9959
9960
2.80k
    assert(_PyUnicode_CheckConsistency(result, 1));
9961
2.80k
    return result;
9962
2.80k
}
9963
9964
/* --- Helpers ------------------------------------------------------------ */
9965
9966
/* helper macro to fixup start/end slice values */
9967
#define ADJUST_INDICES(start, end, len) \
9968
91.5M
    do {                                \
9969
91.5M
        if (end > len) {                \
9970
63.2M
            end = len;                  \
9971
63.2M
        }                               \
9972
91.5M
        else if (end < 0) {             \
9973
0
            end += len;                 \
9974
0
            if (end < 0) {              \
9975
0
                end = 0;                \
9976
0
            }                           \
9977
0
        }                               \
9978
91.5M
        if (start < 0) {                \
9979
25.1k
            start += len;               \
9980
25.1k
            if (start < 0) {            \
9981
0
                start = 0;              \
9982
0
            }                           \
9983
25.1k
        }                               \
9984
91.5M
    } while (0)
9985
9986
static Py_ssize_t
9987
any_find_slice(PyObject* s1, PyObject* s2,
9988
               Py_ssize_t start,
9989
               Py_ssize_t end,
9990
               int direction)
9991
27.0M
{
9992
27.0M
    int kind1, kind2;
9993
27.0M
    const void *buf1, *buf2;
9994
27.0M
    Py_ssize_t len1, len2, result;
9995
9996
27.0M
    kind1 = PyUnicode_KIND(s1);
9997
27.0M
    kind2 = PyUnicode_KIND(s2);
9998
27.0M
    if (kind1 < kind2)
9999
0
        return -1;
10000
10001
27.0M
    len1 = PyUnicode_GET_LENGTH(s1);
10002
27.0M
    len2 = PyUnicode_GET_LENGTH(s2);
10003
27.0M
    ADJUST_INDICES(start, end, len1);
10004
27.0M
    if (end - start < len2)
10005
4.35M
        return -1;
10006
10007
22.7M
    buf1 = PyUnicode_DATA(s1);
10008
22.7M
    buf2 = PyUnicode_DATA(s2);
10009
22.7M
    if (len2 == 1) {
10010
22.7M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10011
22.7M
        result = findchar((const char *)buf1 + kind1*start,
10012
22.7M
                          kind1, end - start, ch, direction);
10013
22.7M
        if (result == -1)
10014
3.93M
            return -1;
10015
18.7M
        else
10016
18.7M
            return start + result;
10017
22.7M
    }
10018
10019
4.17k
    if (kind2 != kind1) {
10020
2.97k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10021
2.97k
        if (!buf2)
10022
0
            return -2;
10023
2.97k
    }
10024
10025
4.17k
    if (direction > 0) {
10026
4.17k
        switch (kind1) {
10027
1.20k
        case PyUnicode_1BYTE_KIND:
10028
1.20k
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
10029
599
                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
10030
603
            else
10031
603
                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
10032
1.20k
            break;
10033
2.27k
        case PyUnicode_2BYTE_KIND:
10034
2.27k
            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
10035
2.27k
            break;
10036
699
        case PyUnicode_4BYTE_KIND:
10037
699
            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
10038
699
            break;
10039
0
        default:
10040
0
            Py_UNREACHABLE();
10041
4.17k
        }
10042
4.17k
    }
10043
0
    else {
10044
0
        switch (kind1) {
10045
0
        case PyUnicode_1BYTE_KIND:
10046
0
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
10047
0
                result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
10048
0
            else
10049
0
                result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
10050
0
            break;
10051
0
        case PyUnicode_2BYTE_KIND:
10052
0
            result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
10053
0
            break;
10054
0
        case PyUnicode_4BYTE_KIND:
10055
0
            result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
10056
0
            break;
10057
0
        default:
10058
0
            Py_UNREACHABLE();
10059
0
        }
10060
0
    }
10061
10062
4.17k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
10063
4.17k
    if (kind2 != kind1)
10064
2.97k
        PyMem_Free((void *)buf2);
10065
10066
4.17k
    return result;
10067
4.17k
}
10068
10069
10070
Py_ssize_t
10071
PyUnicode_Count(PyObject *str,
10072
                PyObject *substr,
10073
                Py_ssize_t start,
10074
                Py_ssize_t end)
10075
0
{
10076
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10077
0
        return -1;
10078
10079
0
    return unicode_count_impl(str, substr, start, end);
10080
0
}
10081
10082
Py_ssize_t
10083
PyUnicode_Find(PyObject *str,
10084
               PyObject *substr,
10085
               Py_ssize_t start,
10086
               Py_ssize_t end,
10087
               int direction)
10088
0
{
10089
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10090
0
        return -2;
10091
10092
0
    return any_find_slice(str, substr, start, end, direction);
10093
0
}
10094
10095
Py_ssize_t
10096
PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
10097
                   Py_ssize_t start, Py_ssize_t end,
10098
                   int direction)
10099
3.09M
{
10100
3.09M
    int kind;
10101
3.09M
    Py_ssize_t len, result;
10102
3.09M
    len = PyUnicode_GET_LENGTH(str);
10103
3.09M
    ADJUST_INDICES(start, end, len);
10104
3.09M
    if (end - start < 1)
10105
0
        return -1;
10106
3.09M
    kind = PyUnicode_KIND(str);
10107
3.09M
    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
10108
3.09M
                      kind, end-start, ch, direction);
10109
3.09M
    if (result == -1)
10110
2.20M
        return -1;
10111
897k
    else
10112
897k
        return start + result;
10113
3.09M
}
10114
10115
static int
10116
tailmatch(PyObject *self,
10117
          PyObject *substring,
10118
          Py_ssize_t start,
10119
          Py_ssize_t end,
10120
          int direction)
10121
34.6M
{
10122
34.6M
    int kind_self;
10123
34.6M
    int kind_sub;
10124
34.6M
    const void *data_self;
10125
34.6M
    const void *data_sub;
10126
34.6M
    Py_ssize_t offset;
10127
34.6M
    Py_ssize_t i;
10128
34.6M
    Py_ssize_t end_sub;
10129
10130
34.6M
    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
10131
34.6M
    end -= PyUnicode_GET_LENGTH(substring);
10132
34.6M
    if (end < start)
10133
9.86M
        return 0;
10134
10135
24.7M
    if (PyUnicode_GET_LENGTH(substring) == 0)
10136
0
        return 1;
10137
10138
24.7M
    kind_self = PyUnicode_KIND(self);
10139
24.7M
    data_self = PyUnicode_DATA(self);
10140
24.7M
    kind_sub = PyUnicode_KIND(substring);
10141
24.7M
    data_sub = PyUnicode_DATA(substring);
10142
24.7M
    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
10143
10144
24.7M
    if (direction > 0)
10145
7.47M
        offset = end;
10146
17.2M
    else
10147
17.2M
        offset = start;
10148
10149
24.7M
    if (PyUnicode_READ(kind_self, data_self, offset) ==
10150
24.7M
        PyUnicode_READ(kind_sub, data_sub, 0) &&
10151
10.3M
        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
10152
10.3M
        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
10153
        /* If both are of the same kind, memcmp is sufficient */
10154
5.31M
        if (kind_self == kind_sub) {
10155
4.69M
            return ! memcmp((char *)data_self +
10156
4.69M
                                (offset * PyUnicode_KIND(substring)),
10157
4.69M
                            data_sub,
10158
4.69M
                            PyUnicode_GET_LENGTH(substring) *
10159
4.69M
                                PyUnicode_KIND(substring));
10160
4.69M
        }
10161
        /* otherwise we have to compare each character by first accessing it */
10162
617k
        else {
10163
            /* We do not need to compare 0 and len(substring)-1 because
10164
               the if statement above ensured already that they are equal
10165
               when we end up here. */
10166
656k
            for (i = 1; i < end_sub; ++i) {
10167
196k
                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
10168
196k
                    PyUnicode_READ(kind_sub, data_sub, i))
10169
156k
                    return 0;
10170
196k
            }
10171
460k
            return 1;
10172
617k
        }
10173
5.31M
    }
10174
10175
19.4M
    return 0;
10176
24.7M
}
10177
10178
Py_ssize_t
10179
PyUnicode_Tailmatch(PyObject *str,
10180
                    PyObject *substr,
10181
                    Py_ssize_t start,
10182
                    Py_ssize_t end,
10183
                    int direction)
10184
588
{
10185
588
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10186
0
        return -1;
10187
10188
588
    return tailmatch(str, substr, start, end, direction);
10189
588
}
10190
10191
static PyObject *
10192
ascii_upper_or_lower(PyObject *self, int lower)
10193
79.0M
{
10194
79.0M
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
10195
79.0M
    const char *data = PyUnicode_DATA(self);
10196
79.0M
    char *resdata;
10197
79.0M
    PyObject *res;
10198
10199
79.0M
    res = PyUnicode_New(len, 127);
10200
79.0M
    if (res == NULL)
10201
0
        return NULL;
10202
79.0M
    resdata = PyUnicode_DATA(res);
10203
79.0M
    if (lower)
10204
79.0M
        _Py_bytes_lower(resdata, data, len);
10205
306
    else
10206
306
        _Py_bytes_upper(resdata, data, len);
10207
79.0M
    return res;
10208
79.0M
}
10209
10210
static Py_UCS4
10211
handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
10212
9.42k
{
10213
9.42k
    Py_ssize_t j;
10214
9.42k
    int final_sigma;
10215
9.42k
    Py_UCS4 c = 0;   /* initialize to prevent gcc warning */
10216
    /* U+03A3 is in the Final_Sigma context when, it is found like this:
10217
10218
     \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
10219
10220
    where ! is a negation and \p{xxx} is a character with property xxx.
10221
    */
10222
11.6k
    for (j = i - 1; j >= 0; j--) {
10223
10.1k
        c = PyUnicode_READ(kind, data, j);
10224
10.1k
        if (!_PyUnicode_IsCaseIgnorable(c))
10225
7.90k
            break;
10226
10.1k
    }
10227
9.42k
    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
10228
9.42k
    if (final_sigma) {
10229
8.26k
        for (j = i + 1; j < length; j++) {
10230
7.30k
            c = PyUnicode_READ(kind, data, j);
10231
7.30k
            if (!_PyUnicode_IsCaseIgnorable(c))
10232
5.39k
                break;
10233
7.30k
        }
10234
6.35k
        final_sigma = j == length || !_PyUnicode_IsCased(c);
10235
6.35k
    }
10236
9.42k
    return (final_sigma) ? 0x3C2 : 0x3C3;
10237
9.42k
}
10238
10239
static int
10240
lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
10241
           Py_UCS4 c, Py_UCS4 *mapped)
10242
170M
{
10243
    /* Obscure special case. */
10244
170M
    if (c == 0x3A3) {
10245
9.42k
        mapped[0] = handle_capital_sigma(kind, data, length, i);
10246
9.42k
        return 1;
10247
9.42k
    }
10248
170M
    return _PyUnicode_ToLowerFull(c, mapped);
10249
170M
}
10250
10251
static Py_ssize_t
10252
do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10253
0
{
10254
0
    Py_ssize_t i, k = 0;
10255
0
    int n_res, j;
10256
0
    Py_UCS4 c, mapped[3];
10257
10258
0
    c = PyUnicode_READ(kind, data, 0);
10259
0
    n_res = _PyUnicode_ToTitleFull(c, mapped);
10260
0
    for (j = 0; j < n_res; j++) {
10261
0
        *maxchar = Py_MAX(*maxchar, mapped[j]);
10262
0
        res[k++] = mapped[j];
10263
0
    }
10264
0
    for (i = 1; i < length; i++) {
10265
0
        c = PyUnicode_READ(kind, data, i);
10266
0
        n_res = lower_ucs4(kind, data, length, i, c, mapped);
10267
0
        for (j = 0; j < n_res; j++) {
10268
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10269
0
            res[k++] = mapped[j];
10270
0
        }
10271
0
    }
10272
0
    return k;
10273
0
}
10274
10275
static Py_ssize_t
10276
0
do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
10277
0
    Py_ssize_t i, k = 0;
10278
10279
0
    for (i = 0; i < length; i++) {
10280
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10281
0
        int n_res, j;
10282
0
        if (Py_UNICODE_ISUPPER(c)) {
10283
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10284
0
        }
10285
0
        else if (Py_UNICODE_ISLOWER(c)) {
10286
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10287
0
        }
10288
0
        else {
10289
0
            n_res = 1;
10290
0
            mapped[0] = c;
10291
0
        }
10292
0
        for (j = 0; j < n_res; j++) {
10293
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10294
0
            res[k++] = mapped[j];
10295
0
        }
10296
0
    }
10297
0
    return k;
10298
0
}
10299
10300
static Py_ssize_t
10301
do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
10302
                  Py_UCS4 *maxchar, int lower)
10303
10.7M
{
10304
10.7M
    Py_ssize_t i, k = 0;
10305
10306
181M
    for (i = 0; i < length; i++) {
10307
170M
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10308
170M
        int n_res, j;
10309
170M
        if (lower)
10310
170M
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10311
0
        else
10312
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10313
340M
        for (j = 0; j < n_res; j++) {
10314
170M
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10315
170M
            res[k++] = mapped[j];
10316
170M
        }
10317
170M
    }
10318
10.7M
    return k;
10319
10.7M
}
10320
10321
static Py_ssize_t
10322
do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10323
0
{
10324
0
    return do_upper_or_lower(kind, data, length, res, maxchar, 0);
10325
0
}
10326
10327
static Py_ssize_t
10328
do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10329
10.7M
{
10330
10.7M
    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
10331
10.7M
}
10332
10333
static Py_ssize_t
10334
do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10335
0
{
10336
0
    Py_ssize_t i, k = 0;
10337
10338
0
    for (i = 0; i < length; i++) {
10339
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i);
10340
0
        Py_UCS4 mapped[3];
10341
0
        int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
10342
0
        for (j = 0; j < n_res; j++) {
10343
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10344
0
            res[k++] = mapped[j];
10345
0
        }
10346
0
    }
10347
0
    return k;
10348
0
}
10349
10350
static Py_ssize_t
10351
do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10352
0
{
10353
0
    Py_ssize_t i, k = 0;
10354
0
    int previous_is_cased;
10355
10356
0
    previous_is_cased = 0;
10357
0
    for (i = 0; i < length; i++) {
10358
0
        const Py_UCS4 c = PyUnicode_READ(kind, data, i);
10359
0
        Py_UCS4 mapped[3];
10360
0
        int n_res, j;
10361
10362
0
        if (previous_is_cased)
10363
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10364
0
        else
10365
0
            n_res = _PyUnicode_ToTitleFull(c, mapped);
10366
10367
0
        for (j = 0; j < n_res; j++) {
10368
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10369
0
            res[k++] = mapped[j];
10370
0
        }
10371
10372
0
        previous_is_cased = _PyUnicode_IsCased(c);
10373
0
    }
10374
0
    return k;
10375
0
}
10376
10377
static PyObject *
10378
case_operation(PyObject *self,
10379
               Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
10380
10.7M
{
10381
10.7M
    PyObject *res = NULL;
10382
10.7M
    Py_ssize_t length, newlength = 0;
10383
10.7M
    int kind, outkind;
10384
10.7M
    const void *data;
10385
10.7M
    void *outdata;
10386
10.7M
    Py_UCS4 maxchar = 0, *tmp, *tmpend;
10387
10388
10.7M
    kind = PyUnicode_KIND(self);
10389
10.7M
    data = PyUnicode_DATA(self);
10390
10.7M
    length = PyUnicode_GET_LENGTH(self);
10391
10.7M
    if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
10392
0
        PyErr_SetString(PyExc_OverflowError, "string is too long");
10393
0
        return NULL;
10394
0
    }
10395
10.7M
    tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
10396
10.7M
    if (tmp == NULL)
10397
0
        return PyErr_NoMemory();
10398
10.7M
    newlength = perform(kind, data, length, tmp, &maxchar);
10399
10.7M
    res = PyUnicode_New(newlength, maxchar);
10400
10.7M
    if (res == NULL)
10401
0
        goto leave;
10402
10.7M
    tmpend = tmp + newlength;
10403
10.7M
    outdata = PyUnicode_DATA(res);
10404
10.7M
    outkind = PyUnicode_KIND(res);
10405
10.7M
    switch (outkind) {
10406
791k
    case PyUnicode_1BYTE_KIND:
10407
791k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10408
791k
        break;
10409
9.78M
    case PyUnicode_2BYTE_KIND:
10410
9.78M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10411
9.78M
        break;
10412
174k
    case PyUnicode_4BYTE_KIND:
10413
174k
        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10414
174k
        break;
10415
0
    default:
10416
0
        Py_UNREACHABLE();
10417
10.7M
    }
10418
10.7M
  leave:
10419
10.7M
    PyMem_Free(tmp);
10420
10.7M
    return res;
10421
10.7M
}
10422
10423
PyObject *
10424
PyUnicode_Join(PyObject *separator, PyObject *seq)
10425
37.6M
{
10426
37.6M
    PyObject *res;
10427
37.6M
    PyObject *fseq;
10428
37.6M
    Py_ssize_t seqlen;
10429
37.6M
    PyObject **items;
10430
10431
37.6M
    fseq = PySequence_Fast(seq, "can only join an iterable");
10432
37.6M
    if (fseq == NULL) {
10433
650
        return NULL;
10434
650
    }
10435
10436
37.6M
    Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(seq);
10437
10438
37.6M
    items = PySequence_Fast_ITEMS(fseq);
10439
37.6M
    seqlen = PySequence_Fast_GET_SIZE(fseq);
10440
37.6M
    res = _PyUnicode_JoinArray(separator, items, seqlen);
10441
10442
37.6M
    Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
10443
10444
37.6M
    Py_DECREF(fseq);
10445
37.6M
    return res;
10446
37.6M
}
10447
10448
PyObject *
10449
_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
10450
65.6M
{
10451
65.6M
    PyObject *res = NULL; /* the result */
10452
65.6M
    PyObject *sep = NULL;
10453
65.6M
    Py_ssize_t seplen;
10454
65.6M
    PyObject *item;
10455
65.6M
    Py_ssize_t sz, i, res_offset;
10456
65.6M
    Py_UCS4 maxchar;
10457
    /* kinds is the bitwise OR of the PyUnicode_KIND() values (1, 2, 4). */
10458
65.6M
    unsigned int kinds = 0, all_ascii = 1;
10459
65.6M
    int use_memcpy;
10460
65.6M
    unsigned char *res_data = NULL, *sep_data = NULL;
10461
65.6M
    int kind = 0;
10462
10463
    /* If empty sequence, return u"". */
10464
65.6M
    if (seqlen == 0) {
10465
7.66M
        _Py_RETURN_UNICODE_EMPTY();
10466
7.66M
    }
10467
10468
    /* If singleton sequence with an exact Unicode, return that. */
10469
57.9M
    if (seqlen == 1) {
10470
20.9M
        if (PyUnicode_CheckExact(items[0])) {
10471
19.3M
            res = items[0];
10472
19.3M
            return Py_NewRef(res);
10473
19.3M
        }
10474
1.52M
        seplen = 0;
10475
1.52M
    }
10476
37.0M
    else {
10477
        /* Set up sep and seplen */
10478
37.0M
        if (separator == NULL) {
10479
            /* fall back to a blank space separator */
10480
0
            sep = PyUnicode_FromOrdinal(' ');
10481
0
            if (!sep)
10482
0
                goto onError;
10483
0
            seplen = 1;
10484
0
        }
10485
37.0M
        else {
10486
37.0M
            if (!PyUnicode_Check(separator)) {
10487
0
                PyErr_Format(PyExc_TypeError,
10488
0
                             "separator: expected str instance,"
10489
0
                             " %.80s found",
10490
0
                             Py_TYPE(separator)->tp_name);
10491
0
                goto onError;
10492
0
            }
10493
37.0M
            sep = separator;
10494
37.0M
            seplen = PyUnicode_GET_LENGTH(separator);
10495
            /* inc refcount to keep this code path symmetric with the
10496
               above case of a blank separator */
10497
37.0M
            Py_INCREF(sep);
10498
37.0M
        }
10499
37.0M
        kinds = PyUnicode_KIND(sep);
10500
37.0M
        all_ascii = PyUnicode_IS_ASCII(sep);
10501
37.0M
    }
10502
10503
    /* There are at least two things to join, or else we have a subclass
10504
     * of str in the sequence.
10505
     * Do a pre-pass to figure out the total amount of space we'll
10506
     * need (sz), and see whether all argument are strings.
10507
     */
10508
38.6M
    sz = 0;
10509
#ifdef Py_DEBUG
10510
    use_memcpy = 0;
10511
#else
10512
38.6M
    use_memcpy = 1;
10513
38.6M
#endif
10514
294M
    for (i = 0; i < seqlen; i++) {
10515
256M
        size_t add_sz;
10516
256M
        item = items[i];
10517
256M
        if (!PyUnicode_Check(item)) {
10518
0
            PyErr_Format(PyExc_TypeError,
10519
0
                         "sequence item %zd: expected str instance,"
10520
0
                         " %.80s found",
10521
0
                         i, Py_TYPE(item)->tp_name);
10522
0
            goto onError;
10523
0
        }
10524
        /* Count one separator per item; the extra one is removed below. */
10525
256M
        add_sz = (size_t)PyUnicode_GET_LENGTH(item) + (size_t)seplen;
10526
256M
        kinds |= PyUnicode_KIND(item);
10527
256M
        all_ascii &= PyUnicode_IS_ASCII(item);
10528
256M
        if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
10529
0
            PyErr_SetString(PyExc_OverflowError,
10530
0
                            "join() result is too long for a Python string");
10531
0
            goto onError;
10532
0
        }
10533
256M
        sz += add_sz;
10534
256M
    }
10535
38.6M
    sz -= seplen;
10536
    /* memcpy() can be used if the separator and all items have the same
10537
       kind: the result then has that kind too. */
10538
38.6M
    if (kinds & (kinds - 1)) {
10539
3.58M
        use_memcpy = 0;
10540
3.58M
    }
10541
38.6M
    if (all_ascii) {
10542
33.9M
        maxchar = 0x7f;
10543
33.9M
    }
10544
4.68M
    else if (kinds & PyUnicode_4BYTE_KIND) {
10545
286k
        maxchar = MAX_UNICODE;
10546
286k
    }
10547
4.39M
    else if (kinds & PyUnicode_2BYTE_KIND) {
10548
3.65M
        maxchar = 0xffff;
10549
3.65M
    }
10550
741k
    else {
10551
741k
        maxchar = 0xff;
10552
741k
    }
10553
10554
38.6M
    res = PyUnicode_New(sz, maxchar);
10555
38.6M
    if (res == NULL)
10556
0
        goto onError;
10557
10558
    /* Catenate everything. */
10559
#ifdef Py_DEBUG
10560
    use_memcpy = 0;
10561
#else
10562
38.6M
    if (use_memcpy) {
10563
35.0M
        res_data = PyUnicode_1BYTE_DATA(res);
10564
35.0M
        kind = PyUnicode_KIND(res);
10565
35.0M
        if (seplen != 0)
10566
99.7k
            sep_data = PyUnicode_1BYTE_DATA(sep);
10567
35.0M
    }
10568
38.6M
#endif
10569
38.6M
    if (use_memcpy) {
10570
186M
        for (i = 0; i < seqlen; ++i) {
10571
151M
            Py_ssize_t itemlen;
10572
151M
            item = items[i];
10573
10574
            /* Copy item, and maybe the separator. */
10575
151M
            if (i && seplen != 0) {
10576
1.27M
                memcpy(res_data,
10577
1.27M
                          sep_data,
10578
1.27M
                          kind * seplen);
10579
1.27M
                res_data += kind * seplen;
10580
1.27M
            }
10581
10582
151M
            itemlen = PyUnicode_GET_LENGTH(item);
10583
151M
            if (itemlen != 0) {
10584
140M
                memcpy(res_data,
10585
140M
                          PyUnicode_DATA(item),
10586
140M
                          kind * itemlen);
10587
140M
                res_data += kind * itemlen;
10588
140M
            }
10589
151M
        }
10590
35.0M
        assert(res_data == PyUnicode_1BYTE_DATA(res)
10591
35.0M
                           + kind * PyUnicode_GET_LENGTH(res));
10592
35.0M
    }
10593
3.58M
    else {
10594
108M
        for (i = 0, res_offset = 0; i < seqlen; ++i) {
10595
104M
            Py_ssize_t itemlen;
10596
104M
            item = items[i];
10597
10598
            /* Copy item, and maybe the separator. */
10599
104M
            if (i && seplen != 0) {
10600
7.11M
                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10601
7.11M
                res_offset += seplen;
10602
7.11M
            }
10603
10604
104M
            itemlen = PyUnicode_GET_LENGTH(item);
10605
104M
            if (itemlen != 0) {
10606
98.1M
                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
10607
98.1M
                res_offset += itemlen;
10608
98.1M
            }
10609
104M
        }
10610
3.58M
        assert(res_offset == PyUnicode_GET_LENGTH(res));
10611
3.58M
    }
10612
10613
38.6M
    Py_XDECREF(sep);
10614
38.6M
    assert(_PyUnicode_CheckConsistency(res, 1));
10615
38.6M
    return res;
10616
10617
0
  onError:
10618
0
    Py_XDECREF(sep);
10619
0
    Py_XDECREF(res);
10620
0
    return NULL;
10621
38.6M
}
10622
10623
void
10624
_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10625
                    Py_UCS4 fill_char)
10626
18.1k
{
10627
18.1k
    const int kind = PyUnicode_KIND(unicode);
10628
18.1k
    void *data = PyUnicode_DATA(unicode);
10629
18.1k
    assert(_PyUnicode_IsModifiable(unicode));
10630
18.1k
    assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10631
18.1k
    assert(start >= 0);
10632
18.1k
    assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10633
18.1k
    _PyUnicode_Fill(kind, data, fill_char, start, length);
10634
18.1k
}
10635
10636
Py_ssize_t
10637
PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10638
               Py_UCS4 fill_char)
10639
623
{
10640
623
    Py_ssize_t maxlen;
10641
10642
623
    if (!PyUnicode_Check(unicode)) {
10643
0
        PyErr_BadInternalCall();
10644
0
        return -1;
10645
0
    }
10646
623
    if (unicode_check_modifiable(unicode))
10647
0
        return -1;
10648
10649
623
    if (start < 0) {
10650
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
10651
0
        return -1;
10652
0
    }
10653
623
    if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10654
0
        PyErr_SetString(PyExc_ValueError,
10655
0
                         "fill character is bigger than "
10656
0
                         "the string maximum character");
10657
0
        return -1;
10658
0
    }
10659
10660
623
    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10661
623
    length = Py_MIN(maxlen, length);
10662
623
    if (length <= 0)
10663
0
        return 0;
10664
10665
623
    _PyUnicode_FastFill(unicode, start, length, fill_char);
10666
623
    return length;
10667
623
}
10668
10669
static PyObject *
10670
pad(PyObject *self,
10671
    Py_ssize_t left,
10672
    Py_ssize_t right,
10673
    Py_UCS4 fill)
10674
640
{
10675
640
    PyObject *u;
10676
640
    Py_UCS4 maxchar;
10677
640
    int kind;
10678
640
    void *data;
10679
10680
640
    if (left < 0)
10681
0
        left = 0;
10682
640
    if (right < 0)
10683
0
        right = 0;
10684
10685
640
    if (left == 0 && right == 0)
10686
0
        return unicode_result_unchanged(self);
10687
10688
640
    if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10689
640
        right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
10690
0
        PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10691
0
        return NULL;
10692
0
    }
10693
640
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10694
640
    maxchar = Py_MAX(maxchar, fill);
10695
640
    u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
10696
640
    if (!u)
10697
0
        return NULL;
10698
10699
640
    kind = PyUnicode_KIND(u);
10700
640
    data = PyUnicode_DATA(u);
10701
640
    if (left)
10702
0
        _PyUnicode_Fill(kind, data, fill, 0, left);
10703
640
    if (right)
10704
640
        _PyUnicode_Fill(kind, data, fill,
10705
640
                        left + _PyUnicode_LENGTH(self), right);
10706
640
    _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
10707
640
    assert(_PyUnicode_CheckConsistency(u, 1));
10708
640
    return u;
10709
640
}
10710
10711
PyObject *
10712
PyUnicode_Splitlines(PyObject *string, int keepends)
10713
17.4k
{
10714
17.4k
    PyObject *list;
10715
10716
17.4k
    if (ensure_unicode(string) < 0)
10717
0
        return NULL;
10718
10719
17.4k
    switch (PyUnicode_KIND(string)) {
10720
5.44k
    case PyUnicode_1BYTE_KIND:
10721
5.44k
        if (PyUnicode_IS_ASCII(string))
10722
4.36k
            list = asciilib_splitlines(
10723
4.36k
                string, PyUnicode_1BYTE_DATA(string),
10724
4.36k
                PyUnicode_GET_LENGTH(string), keepends);
10725
1.07k
        else
10726
1.07k
            list = ucs1lib_splitlines(
10727
1.07k
                string, PyUnicode_1BYTE_DATA(string),
10728
1.07k
                PyUnicode_GET_LENGTH(string), keepends);
10729
5.44k
        break;
10730
8.63k
    case PyUnicode_2BYTE_KIND:
10731
8.63k
        list = ucs2lib_splitlines(
10732
8.63k
            string, PyUnicode_2BYTE_DATA(string),
10733
8.63k
            PyUnicode_GET_LENGTH(string), keepends);
10734
8.63k
        break;
10735
3.41k
    case PyUnicode_4BYTE_KIND:
10736
3.41k
        list = ucs4lib_splitlines(
10737
3.41k
            string, PyUnicode_4BYTE_DATA(string),
10738
3.41k
            PyUnicode_GET_LENGTH(string), keepends);
10739
3.41k
        break;
10740
0
    default:
10741
0
        Py_UNREACHABLE();
10742
17.4k
    }
10743
17.4k
    return list;
10744
17.4k
}
10745
10746
static PyObject *
10747
split(PyObject *self,
10748
      PyObject *substring,
10749
      Py_ssize_t maxcount)
10750
25.7M
{
10751
25.7M
    int kind1, kind2;
10752
25.7M
    const void *buf1, *buf2;
10753
25.7M
    Py_ssize_t len1, len2;
10754
25.7M
    PyObject* out;
10755
25.7M
    len1 = PyUnicode_GET_LENGTH(self);
10756
25.7M
    kind1 = PyUnicode_KIND(self);
10757
10758
25.7M
    if (substring == NULL) {
10759
171k
        if (maxcount < 0) {
10760
152k
            maxcount = (len1 - 1) / 2 + 1;
10761
152k
        }
10762
171k
        switch (kind1) {
10763
93.7k
        case PyUnicode_1BYTE_KIND:
10764
93.7k
            if (PyUnicode_IS_ASCII(self))
10765
74.2k
                return asciilib_split_whitespace(
10766
74.2k
                    self,  PyUnicode_1BYTE_DATA(self),
10767
74.2k
                    len1, maxcount
10768
74.2k
                    );
10769
19.5k
            else
10770
19.5k
                return ucs1lib_split_whitespace(
10771
19.5k
                    self,  PyUnicode_1BYTE_DATA(self),
10772
19.5k
                    len1, maxcount
10773
19.5k
                    );
10774
58.2k
        case PyUnicode_2BYTE_KIND:
10775
58.2k
            return ucs2lib_split_whitespace(
10776
58.2k
                self,  PyUnicode_2BYTE_DATA(self),
10777
58.2k
                len1, maxcount
10778
58.2k
                );
10779
19.4k
        case PyUnicode_4BYTE_KIND:
10780
19.4k
            return ucs4lib_split_whitespace(
10781
19.4k
                self,  PyUnicode_4BYTE_DATA(self),
10782
19.4k
                len1, maxcount
10783
19.4k
                );
10784
0
        default:
10785
0
            Py_UNREACHABLE();
10786
171k
        }
10787
171k
    }
10788
10789
25.5M
    kind2 = PyUnicode_KIND(substring);
10790
25.5M
    len2 = PyUnicode_GET_LENGTH(substring);
10791
25.5M
    if (maxcount < 0) {
10792
        // if len2 == 0, it will raise ValueError.
10793
16.7M
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10794
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10795
16.7M
        maxcount = maxcount < 0 ? len1 : maxcount;
10796
16.7M
    }
10797
25.5M
    if (kind1 < kind2 || len1 < len2) {
10798
4.01M
        out = PyList_New(1);
10799
4.01M
        if (out == NULL)
10800
0
            return NULL;
10801
4.01M
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10802
4.01M
        return out;
10803
4.01M
    }
10804
21.5M
    buf1 = PyUnicode_DATA(self);
10805
21.5M
    buf2 = PyUnicode_DATA(substring);
10806
21.5M
    if (kind2 != kind1) {
10807
278k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10808
278k
        if (!buf2)
10809
0
            return NULL;
10810
278k
    }
10811
10812
21.5M
    switch (kind1) {
10813
21.2M
    case PyUnicode_1BYTE_KIND:
10814
21.2M
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10815
19.9M
            out = asciilib_split(
10816
19.9M
                self,  buf1, len1, buf2, len2, maxcount);
10817
1.38M
        else
10818
1.38M
            out = ucs1lib_split(
10819
1.38M
                self,  buf1, len1, buf2, len2, maxcount);
10820
21.2M
        break;
10821
224k
    case PyUnicode_2BYTE_KIND:
10822
224k
        out = ucs2lib_split(
10823
224k
            self,  buf1, len1, buf2, len2, maxcount);
10824
224k
        break;
10825
53.8k
    case PyUnicode_4BYTE_KIND:
10826
53.8k
        out = ucs4lib_split(
10827
53.8k
            self,  buf1, len1, buf2, len2, maxcount);
10828
53.8k
        break;
10829
0
    default:
10830
0
        out = NULL;
10831
21.5M
    }
10832
21.5M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10833
21.5M
    if (kind2 != kind1)
10834
278k
        PyMem_Free((void *)buf2);
10835
21.5M
    return out;
10836
21.5M
}
10837
10838
static PyObject *
10839
rsplit(PyObject *self,
10840
       PyObject *substring,
10841
       Py_ssize_t maxcount)
10842
42
{
10843
42
    int kind1, kind2;
10844
42
    const void *buf1, *buf2;
10845
42
    Py_ssize_t len1, len2;
10846
42
    PyObject* out;
10847
10848
42
    len1 = PyUnicode_GET_LENGTH(self);
10849
42
    kind1 = PyUnicode_KIND(self);
10850
10851
42
    if (substring == NULL) {
10852
0
        if (maxcount < 0) {
10853
0
            maxcount = (len1 - 1) / 2 + 1;
10854
0
        }
10855
0
        switch (kind1) {
10856
0
        case PyUnicode_1BYTE_KIND:
10857
0
            if (PyUnicode_IS_ASCII(self))
10858
0
                return asciilib_rsplit_whitespace(
10859
0
                    self,  PyUnicode_1BYTE_DATA(self),
10860
0
                    len1, maxcount
10861
0
                    );
10862
0
            else
10863
0
                return ucs1lib_rsplit_whitespace(
10864
0
                    self,  PyUnicode_1BYTE_DATA(self),
10865
0
                    len1, maxcount
10866
0
                    );
10867
0
        case PyUnicode_2BYTE_KIND:
10868
0
            return ucs2lib_rsplit_whitespace(
10869
0
                self,  PyUnicode_2BYTE_DATA(self),
10870
0
                len1, maxcount
10871
0
                );
10872
0
        case PyUnicode_4BYTE_KIND:
10873
0
            return ucs4lib_rsplit_whitespace(
10874
0
                self,  PyUnicode_4BYTE_DATA(self),
10875
0
                len1, maxcount
10876
0
                );
10877
0
        default:
10878
0
            Py_UNREACHABLE();
10879
0
        }
10880
0
    }
10881
42
    kind2 = PyUnicode_KIND(substring);
10882
42
    len2 = PyUnicode_GET_LENGTH(substring);
10883
42
    if (maxcount < 0) {
10884
        // if len2 == 0, it will raise ValueError.
10885
0
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10886
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10887
0
        maxcount = maxcount < 0 ? len1 : maxcount;
10888
0
    }
10889
42
    if (kind1 < kind2 || len1 < len2) {
10890
0
        out = PyList_New(1);
10891
0
        if (out == NULL)
10892
0
            return NULL;
10893
0
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10894
0
        return out;
10895
0
    }
10896
42
    buf1 = PyUnicode_DATA(self);
10897
42
    buf2 = PyUnicode_DATA(substring);
10898
42
    if (kind2 != kind1) {
10899
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10900
0
        if (!buf2)
10901
0
            return NULL;
10902
0
    }
10903
10904
42
    switch (kind1) {
10905
42
    case PyUnicode_1BYTE_KIND:
10906
42
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10907
42
            out = asciilib_rsplit(
10908
42
                self,  buf1, len1, buf2, len2, maxcount);
10909
0
        else
10910
0
            out = ucs1lib_rsplit(
10911
0
                self,  buf1, len1, buf2, len2, maxcount);
10912
42
        break;
10913
0
    case PyUnicode_2BYTE_KIND:
10914
0
        out = ucs2lib_rsplit(
10915
0
            self,  buf1, len1, buf2, len2, maxcount);
10916
0
        break;
10917
0
    case PyUnicode_4BYTE_KIND:
10918
0
        out = ucs4lib_rsplit(
10919
0
            self,  buf1, len1, buf2, len2, maxcount);
10920
0
        break;
10921
0
    default:
10922
0
        out = NULL;
10923
42
    }
10924
42
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10925
42
    if (kind2 != kind1)
10926
0
        PyMem_Free((void *)buf2);
10927
42
    return out;
10928
42
}
10929
10930
static Py_ssize_t
10931
anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
10932
            PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
10933
26.8M
{
10934
26.8M
    switch (kind) {
10935
10.3M
    case PyUnicode_1BYTE_KIND:
10936
10.3M
        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10937
4.37M
            return asciilib_find(buf1, len1, buf2, len2, offset);
10938
5.94M
        else
10939
5.94M
            return ucs1lib_find(buf1, len1, buf2, len2, offset);
10940
7.52M
    case PyUnicode_2BYTE_KIND:
10941
7.52M
        return ucs2lib_find(buf1, len1, buf2, len2, offset);
10942
9.03M
    case PyUnicode_4BYTE_KIND:
10943
9.03M
        return ucs4lib_find(buf1, len1, buf2, len2, offset);
10944
26.8M
    }
10945
26.8M
    Py_UNREACHABLE();
10946
26.8M
}
10947
10948
static Py_ssize_t
10949
anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
10950
             PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
10951
10.7M
{
10952
10.7M
    switch (kind) {
10953
9.91M
    case PyUnicode_1BYTE_KIND:
10954
9.91M
        return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10955
714k
    case PyUnicode_2BYTE_KIND:
10956
714k
        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10957
94.2k
    case PyUnicode_4BYTE_KIND:
10958
94.2k
        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10959
10.7M
    }
10960
10.7M
    Py_UNREACHABLE();
10961
10.7M
}
10962
10963
static void
10964
replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10965
                      Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10966
65.2k
{
10967
65.2k
    int kind = PyUnicode_KIND(u);
10968
65.2k
    void *data = PyUnicode_DATA(u);
10969
65.2k
    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10970
65.2k
    if (kind == PyUnicode_1BYTE_KIND) {
10971
39.2k
        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10972
39.2k
                                      (Py_UCS1 *)data + len,
10973
39.2k
                                      u1, u2, maxcount);
10974
39.2k
    }
10975
25.9k
    else if (kind == PyUnicode_2BYTE_KIND) {
10976
20.4k
        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10977
20.4k
                                      (Py_UCS2 *)data + len,
10978
20.4k
                                      u1, u2, maxcount);
10979
20.4k
    }
10980
5.52k
    else {
10981
5.52k
        assert(kind == PyUnicode_4BYTE_KIND);
10982
5.52k
        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10983
5.52k
                                      (Py_UCS4 *)data + len,
10984
5.52k
                                      u1, u2, maxcount);
10985
5.52k
    }
10986
65.2k
}
10987
10988
static PyObject *
10989
replace(PyObject *self, PyObject *str1,
10990
        PyObject *str2, Py_ssize_t maxcount)
10991
23.6M
{
10992
23.6M
    PyObject *u;
10993
23.6M
    const char *sbuf = PyUnicode_DATA(self);
10994
23.6M
    const void *buf1 = PyUnicode_DATA(str1);
10995
23.6M
    const void *buf2 = PyUnicode_DATA(str2);
10996
23.6M
    int srelease = 0, release1 = 0, release2 = 0;
10997
23.6M
    int skind = PyUnicode_KIND(self);
10998
23.6M
    int kind1 = PyUnicode_KIND(str1);
10999
23.6M
    int kind2 = PyUnicode_KIND(str2);
11000
23.6M
    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
11001
23.6M
    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
11002
23.6M
    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
11003
23.6M
    int mayshrink;
11004
23.6M
    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
11005
11006
23.6M
    if (slen < len1)
11007
12.4M
        goto nothing;
11008
11009
11.1M
    if (maxcount < 0)
11010
11.1M
        maxcount = PY_SSIZE_T_MAX;
11011
0
    else if (maxcount == 0)
11012
0
        goto nothing;
11013
11014
11.1M
    if (str1 == str2)
11015
0
        goto nothing;
11016
11017
11.1M
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
11018
11.1M
    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
11019
11.1M
    if (maxchar < maxchar_str1)
11020
        /* substring too wide to be present */
11021
0
        goto nothing;
11022
11.1M
    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
11023
    /* Replacing str1 with str2 may cause a maxchar reduction in the
11024
       result string. */
11025
11.1M
    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
11026
11.1M
    maxchar = Py_MAX(maxchar, maxchar_str2);
11027
11028
11.1M
    if (len1 == len2) {
11029
        /* same length */
11030
465k
        if (len1 == 0)
11031
0
            goto nothing;
11032
465k
        if (len1 == 1) {
11033
            /* replace characters */
11034
465k
            Py_UCS4 u1, u2;
11035
465k
            Py_ssize_t pos;
11036
11037
465k
            u1 = PyUnicode_READ(kind1, buf1, 0);
11038
465k
            pos = findchar(sbuf, skind, slen, u1, 1);
11039
465k
            if (pos < 0)
11040
400k
                goto nothing;
11041
65.2k
            u2 = PyUnicode_READ(kind2, buf2, 0);
11042
65.2k
            u = PyUnicode_New(slen, maxchar);
11043
65.2k
            if (!u)
11044
0
                goto error;
11045
11046
65.2k
            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
11047
65.2k
            replace_1char_inplace(u, pos, u1, u2, maxcount);
11048
65.2k
        }
11049
142
        else {
11050
142
            int rkind = skind;
11051
142
            char *res;
11052
142
            Py_ssize_t i;
11053
11054
142
            if (kind1 < rkind) {
11055
                /* widen substring */
11056
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
11057
0
                if (!buf1) goto error;
11058
0
                release1 = 1;
11059
0
            }
11060
142
            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
11061
142
            if (i < 0)
11062
142
                goto nothing;
11063
0
            if (rkind > kind2) {
11064
                /* widen replacement */
11065
0
                buf2 = unicode_askind(kind2, buf2, len2, rkind);
11066
0
                if (!buf2) goto error;
11067
0
                release2 = 1;
11068
0
            }
11069
0
            else if (rkind < kind2) {
11070
                /* widen self and buf1 */
11071
0
                rkind = kind2;
11072
0
                if (release1) {
11073
0
                    assert(buf1 != PyUnicode_DATA(str1));
11074
0
                    PyMem_Free((void *)buf1);
11075
0
                    buf1 = PyUnicode_DATA(str1);
11076
0
                    release1 = 0;
11077
0
                }
11078
0
                sbuf = unicode_askind(skind, sbuf, slen, rkind);
11079
0
                if (!sbuf) goto error;
11080
0
                srelease = 1;
11081
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
11082
0
                if (!buf1) goto error;
11083
0
                release1 = 1;
11084
0
            }
11085
0
            u = PyUnicode_New(slen, maxchar);
11086
0
            if (!u)
11087
0
                goto error;
11088
0
            assert(PyUnicode_KIND(u) == rkind);
11089
0
            res = PyUnicode_DATA(u);
11090
11091
0
            memcpy(res, sbuf, rkind * slen);
11092
            /* change everything in-place, starting with this one */
11093
0
            memcpy(res + rkind * i,
11094
0
                   buf2,
11095
0
                   rkind * len2);
11096
0
            i += len1;
11097
11098
0
            while ( --maxcount > 0) {
11099
0
                i = anylib_find(rkind, self,
11100
0
                                sbuf+rkind*i, slen-i,
11101
0
                                str1, buf1, len1, i);
11102
0
                if (i == -1)
11103
0
                    break;
11104
0
                memcpy(res + rkind * i,
11105
0
                       buf2,
11106
0
                       rkind * len2);
11107
0
                i += len1;
11108
0
            }
11109
0
        }
11110
465k
    }
11111
10.7M
    else {
11112
10.7M
        Py_ssize_t n, i, j, ires;
11113
10.7M
        Py_ssize_t new_size;
11114
10.7M
        int rkind = skind;
11115
10.7M
        char *res;
11116
11117
10.7M
        if (kind1 < rkind) {
11118
            /* widen substring */
11119
808k
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11120
808k
            if (!buf1) goto error;
11121
808k
            release1 = 1;
11122
808k
        }
11123
10.7M
        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
11124
10.7M
        if (n == 0)
11125
9.45M
            goto nothing;
11126
1.26M
        if (kind2 < rkind) {
11127
            /* widen replacement */
11128
44.3k
            buf2 = unicode_askind(kind2, buf2, len2, rkind);
11129
44.3k
            if (!buf2) goto error;
11130
44.3k
            release2 = 1;
11131
44.3k
        }
11132
1.21M
        else if (kind2 > rkind) {
11133
            /* widen self and buf1 */
11134
0
            rkind = kind2;
11135
0
            sbuf = unicode_askind(skind, sbuf, slen, rkind);
11136
0
            if (!sbuf) goto error;
11137
0
            srelease = 1;
11138
0
            if (release1) {
11139
0
                assert(buf1 != PyUnicode_DATA(str1));
11140
0
                PyMem_Free((void *)buf1);
11141
0
                buf1 = PyUnicode_DATA(str1);
11142
0
                release1 = 0;
11143
0
            }
11144
0
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11145
0
            if (!buf1) goto error;
11146
0
            release1 = 1;
11147
0
        }
11148
        /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
11149
           PyUnicode_GET_LENGTH(str1)); */
11150
1.26M
        if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
11151
0
                PyErr_SetString(PyExc_OverflowError,
11152
0
                                "replace string is too long");
11153
0
                goto error;
11154
0
        }
11155
1.26M
        new_size = slen + n * (len2 - len1);
11156
1.26M
        if (new_size == 0) {
11157
9
            u = _PyUnicode_GetEmpty();
11158
9
            goto done;
11159
9
        }
11160
1.26M
        if (new_size > (PY_SSIZE_T_MAX / rkind)) {
11161
0
            PyErr_SetString(PyExc_OverflowError,
11162
0
                            "replace string is too long");
11163
0
            goto error;
11164
0
        }
11165
1.26M
        u = PyUnicode_New(new_size, maxchar);
11166
1.26M
        if (!u)
11167
0
            goto error;
11168
1.26M
        assert(PyUnicode_KIND(u) == rkind);
11169
1.26M
        res = PyUnicode_DATA(u);
11170
1.26M
        ires = i = 0;
11171
1.26M
        if (len1 > 0) {
11172
28.1M
            while (n-- > 0) {
11173
                /* look for next match */
11174
26.8M
                j = anylib_find(rkind, self,
11175
26.8M
                                sbuf + rkind * i, slen-i,
11176
26.8M
                                str1, buf1, len1, i);
11177
26.8M
                if (j == -1)
11178
0
                    break;
11179
26.8M
                else if (j > i) {
11180
                    /* copy unchanged part [i:j] */
11181
4.58M
                    memcpy(res + rkind * ires,
11182
4.58M
                           sbuf + rkind * i,
11183
4.58M
                           rkind * (j-i));
11184
4.58M
                    ires += j - i;
11185
4.58M
                }
11186
                /* copy substitution string */
11187
26.8M
                if (len2 > 0) {
11188
26.6M
                    memcpy(res + rkind * ires,
11189
26.6M
                           buf2,
11190
26.6M
                           rkind * len2);
11191
26.6M
                    ires += len2;
11192
26.6M
                }
11193
26.8M
                i = j + len1;
11194
26.8M
            }
11195
1.26M
            if (i < slen)
11196
                /* copy tail [i:] */
11197
1.25M
                memcpy(res + rkind * ires,
11198
1.25M
                       sbuf + rkind * i,
11199
1.25M
                       rkind * (slen-i));
11200
1.26M
        }
11201
0
        else {
11202
            /* interleave */
11203
0
            while (n > 0) {
11204
0
                memcpy(res + rkind * ires,
11205
0
                       buf2,
11206
0
                       rkind * len2);
11207
0
                ires += len2;
11208
0
                if (--n <= 0)
11209
0
                    break;
11210
0
                memcpy(res + rkind * ires,
11211
0
                       sbuf + rkind * i,
11212
0
                       rkind);
11213
0
                ires++;
11214
0
                i++;
11215
0
            }
11216
0
            memcpy(res + rkind * ires,
11217
0
                   sbuf + rkind * i,
11218
0
                   rkind * (slen-i));
11219
0
        }
11220
1.26M
    }
11221
11222
1.32M
    if (mayshrink) {
11223
0
        unicode_adjust_maxchar(&u);
11224
0
        if (u == NULL)
11225
0
            goto error;
11226
0
    }
11227
11228
1.32M
  done:
11229
1.32M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11230
1.32M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11231
1.32M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11232
1.32M
    if (srelease)
11233
0
        PyMem_Free((void *)sbuf);
11234
1.32M
    if (release1)
11235
44.3k
        PyMem_Free((void *)buf1);
11236
1.32M
    if (release2)
11237
44.3k
        PyMem_Free((void *)buf2);
11238
1.32M
    assert(_PyUnicode_CheckConsistency(u, 1));
11239
1.32M
    return u;
11240
11241
22.3M
  nothing:
11242
    /* nothing to replace; return original string (when possible) */
11243
22.3M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11244
22.3M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11245
22.3M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11246
22.3M
    if (srelease)
11247
0
        PyMem_Free((void *)sbuf);
11248
22.3M
    if (release1)
11249
763k
        PyMem_Free((void *)buf1);
11250
22.3M
    if (release2)
11251
0
        PyMem_Free((void *)buf2);
11252
22.3M
    return unicode_result_unchanged(self);
11253
11254
0
  error:
11255
0
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11256
0
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11257
0
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11258
0
    if (srelease)
11259
0
        PyMem_Free((void *)sbuf);
11260
0
    if (release1)
11261
0
        PyMem_Free((void *)buf1);
11262
0
    if (release2)
11263
0
        PyMem_Free((void *)buf2);
11264
0
    return NULL;
11265
1.32M
}
11266
11267
/* --- Unicode Object Methods --------------------------------------------- */
11268
11269
/*[clinic input]
11270
str.title as unicode_title
11271
11272
Return a version of the string where each word is titlecased.
11273
11274
More specifically, words start with uppercased characters and all
11275
remaining cased characters have lower case.
11276
[clinic start generated code]*/
11277
11278
static PyObject *
11279
unicode_title_impl(PyObject *self)
11280
/*[clinic end generated code: output=c75ae03809574902 input=2a07e2c7df94627a]*/
11281
0
{
11282
0
    return case_operation(self, do_title);
11283
0
}
11284
11285
/*[clinic input]
11286
str.capitalize as unicode_capitalize
11287
11288
Return a capitalized version of the string.
11289
11290
More specifically, make the first character have upper case and the
11291
rest lower case.
11292
[clinic start generated code]*/
11293
11294
static PyObject *
11295
unicode_capitalize_impl(PyObject *self)
11296
/*[clinic end generated code: output=e49a4c333cdb7667 input=e50e50ed45a654cf]*/
11297
0
{
11298
0
    if (PyUnicode_GET_LENGTH(self) == 0)
11299
0
        return unicode_result_unchanged(self);
11300
0
    return case_operation(self, do_capitalize);
11301
0
}
11302
11303
/*[clinic input]
11304
str.casefold as unicode_casefold
11305
11306
Return a version of the string suitable for caseless comparisons.
11307
[clinic start generated code]*/
11308
11309
static PyObject *
11310
unicode_casefold_impl(PyObject *self)
11311
/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
11312
0
{
11313
0
    if (PyUnicode_IS_ASCII(self))
11314
0
        return ascii_upper_or_lower(self, 1);
11315
0
    return case_operation(self, do_casefold);
11316
0
}
11317
11318
11319
/* Argument converter. Accepts a single Unicode character. */
11320
11321
static int
11322
convert_uc(PyObject *obj, void *addr)
11323
1.19k
{
11324
1.19k
    Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
11325
11326
1.19k
    if (!PyUnicode_Check(obj)) {
11327
0
        PyErr_Format(PyExc_TypeError,
11328
0
                     "The fill character must be a unicode character, "
11329
0
                     "not %.100s", Py_TYPE(obj)->tp_name);
11330
0
        return 0;
11331
0
    }
11332
1.19k
    if (PyUnicode_GET_LENGTH(obj) != 1) {
11333
0
        PyErr_SetString(PyExc_TypeError,
11334
0
                        "The fill character must be exactly one character long");
11335
0
        return 0;
11336
0
    }
11337
1.19k
    *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
11338
1.19k
    return 1;
11339
1.19k
}
11340
11341
/*[clinic input]
11342
str.center as unicode_center
11343
11344
    width: Py_ssize_t
11345
    fillchar: Py_UCS4 = ' '
11346
    /
11347
11348
Return a centered string of length width.
11349
11350
Padding is done using the specified fill character (default is
11351
a space).
11352
[clinic start generated code]*/
11353
11354
static PyObject *
11355
unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
11356
/*[clinic end generated code: output=420c8859effc7c0c input=df91017dfd186a78]*/
11357
0
{
11358
0
    Py_ssize_t marg, left;
11359
11360
0
    if (PyUnicode_GET_LENGTH(self) >= width)
11361
0
        return unicode_result_unchanged(self);
11362
11363
0
    marg = width - PyUnicode_GET_LENGTH(self);
11364
0
    left = marg / 2 + (marg & width & 1);
11365
11366
0
    return pad(self, left, marg - left, fillchar);
11367
0
}
11368
11369
/* This function assumes that str1 and str2 are readied by the caller. */
11370
11371
static int
11372
unicode_compare(PyObject *str1, PyObject *str2)
11373
28.6M
{
11374
28.6M
#define COMPARE(TYPE1, TYPE2) \
11375
28.6M
    do { \
11376
27.4M
        TYPE1* p1 = (TYPE1 *)data1; \
11377
27.4M
        TYPE2* p2 = (TYPE2 *)data2; \
11378
27.4M
        TYPE1* end = p1 + len; \
11379
27.4M
        Py_UCS4 c1, c2; \
11380
27.4M
        for (; p1 != end; p1++, p2++) { \
11381
27.4M
            c1 = *p1; \
11382
27.4M
            c2 = *p2; \
11383
27.4M
            if (c1 != c2) \
11384
27.4M
                return (c1 < c2) ? -1 : 1; \
11385
27.4M
        } \
11386
27.4M
    } \
11387
27.4M
    while (0)
11388
11389
28.6M
    int kind1, kind2;
11390
28.6M
    const void *data1, *data2;
11391
28.6M
    Py_ssize_t len1, len2, len;
11392
11393
28.6M
    kind1 = PyUnicode_KIND(str1);
11394
28.6M
    kind2 = PyUnicode_KIND(str2);
11395
28.6M
    data1 = PyUnicode_DATA(str1);
11396
28.6M
    data2 = PyUnicode_DATA(str2);
11397
28.6M
    len1 = PyUnicode_GET_LENGTH(str1);
11398
28.6M
    len2 = PyUnicode_GET_LENGTH(str2);
11399
28.6M
    len = Py_MIN(len1, len2);
11400
11401
28.6M
    switch(kind1) {
11402
6.09M
    case PyUnicode_1BYTE_KIND:
11403
6.09M
    {
11404
6.09M
        switch(kind2) {
11405
861k
        case PyUnicode_1BYTE_KIND:
11406
861k
        {
11407
861k
            int cmp = memcmp(data1, data2, len);
11408
            /* normalize result of memcmp() into the range [-1; 1] */
11409
861k
            if (cmp < 0)
11410
770k
                return -1;
11411
90.7k
            if (cmp > 0)
11412
88.8k
                return 1;
11413
1.83k
            break;
11414
90.7k
        }
11415
4.74M
        case PyUnicode_2BYTE_KIND:
11416
4.74M
            COMPARE(Py_UCS1, Py_UCS2);
11417
0
            break;
11418
486k
        case PyUnicode_4BYTE_KIND:
11419
486k
            COMPARE(Py_UCS1, Py_UCS4);
11420
0
            break;
11421
0
        default:
11422
0
            Py_UNREACHABLE();
11423
6.09M
        }
11424
1.83k
        break;
11425
6.09M
    }
11426
22.2M
    case PyUnicode_2BYTE_KIND:
11427
22.2M
    {
11428
22.2M
        switch(kind2) {
11429
57.7k
        case PyUnicode_1BYTE_KIND:
11430
57.7k
            COMPARE(Py_UCS2, Py_UCS1);
11431
0
            break;
11432
22.1M
        case PyUnicode_2BYTE_KIND:
11433
22.1M
        {
11434
22.1M
            COMPARE(Py_UCS2, Py_UCS2);
11435
0
            break;
11436
22.1M
        }
11437
4.87k
        case PyUnicode_4BYTE_KIND:
11438
4.87k
            COMPARE(Py_UCS2, Py_UCS4);
11439
0
            break;
11440
0
        default:
11441
0
            Py_UNREACHABLE();
11442
22.2M
        }
11443
0
        break;
11444
22.2M
    }
11445
300k
    case PyUnicode_4BYTE_KIND:
11446
300k
    {
11447
300k
        switch(kind2) {
11448
1.65k
        case PyUnicode_1BYTE_KIND:
11449
1.65k
            COMPARE(Py_UCS4, Py_UCS1);
11450
0
            break;
11451
4.22k
        case PyUnicode_2BYTE_KIND:
11452
4.22k
            COMPARE(Py_UCS4, Py_UCS2);
11453
0
            break;
11454
294k
        case PyUnicode_4BYTE_KIND:
11455
294k
        {
11456
294k
#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11457
294k
            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11458
            /* normalize result of wmemcmp() into the range [-1; 1] */
11459
294k
            if (cmp < 0)
11460
145k
                return -1;
11461
149k
            if (cmp > 0)
11462
149k
                return 1;
11463
#else
11464
            COMPARE(Py_UCS4, Py_UCS4);
11465
#endif
11466
0
            break;
11467
149k
        }
11468
0
        default:
11469
0
            Py_UNREACHABLE();
11470
300k
        }
11471
0
        break;
11472
300k
    }
11473
0
    default:
11474
0
        Py_UNREACHABLE();
11475
28.6M
    }
11476
11477
1.83k
    if (len1 == len2)
11478
1.79k
        return 0;
11479
38
    if (len1 < len2)
11480
12
        return -1;
11481
26
    else
11482
26
        return 1;
11483
11484
38
#undef COMPARE
11485
38
}
11486
11487
11488
int
11489
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
11490
674M
{
11491
674M
    assert(PyUnicode_Check(str1));
11492
674M
    assert(PyUnicode_Check(str2));
11493
674M
    if (str1 == str2) {
11494
104M
        return 1;
11495
104M
    }
11496
570M
    return unicode_eq(str1, str2);
11497
674M
}
11498
11499
11500
int
11501
PyUnicode_Equal(PyObject *str1, PyObject *str2)
11502
0
{
11503
0
    if (!PyUnicode_Check(str1)) {
11504
0
        PyErr_Format(PyExc_TypeError,
11505
0
                     "first argument must be str, not %T", str1);
11506
0
        return -1;
11507
0
    }
11508
0
    if (!PyUnicode_Check(str2)) {
11509
0
        PyErr_Format(PyExc_TypeError,
11510
0
                     "second argument must be str, not %T", str2);
11511
0
        return -1;
11512
0
    }
11513
11514
0
    return _PyUnicode_Equal(str1, str2);
11515
0
}
11516
11517
11518
int
11519
PyUnicode_Compare(PyObject *left, PyObject *right)
11520
187k
{
11521
187k
    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11522
        /* a string is equal to itself */
11523
187k
        if (left == right)
11524
0
            return 0;
11525
11526
187k
        return unicode_compare(left, right);
11527
187k
    }
11528
0
    PyErr_Format(PyExc_TypeError,
11529
0
                 "Can't compare %.100s and %.100s",
11530
0
                 Py_TYPE(left)->tp_name,
11531
0
                 Py_TYPE(right)->tp_name);
11532
0
    return -1;
11533
187k
}
11534
11535
int
11536
PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11537
31.2M
{
11538
31.2M
    Py_ssize_t i;
11539
31.2M
    int kind;
11540
31.2M
    Py_UCS4 chr;
11541
11542
31.2M
    assert(_PyUnicode_CHECK(uni));
11543
31.2M
    kind = PyUnicode_KIND(uni);
11544
31.2M
    if (kind == PyUnicode_1BYTE_KIND) {
11545
31.2M
        const void *data = PyUnicode_1BYTE_DATA(uni);
11546
31.2M
        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
11547
31.2M
        size_t len, len2 = strlen(str);
11548
31.2M
        int cmp;
11549
11550
31.2M
        len = Py_MIN(len1, len2);
11551
31.2M
        cmp = memcmp(data, str, len);
11552
31.2M
        if (cmp != 0) {
11553
18.1M
            if (cmp < 0)
11554
32.6k
                return -1;
11555
18.1M
            else
11556
18.1M
                return 1;
11557
18.1M
        }
11558
13.1M
        if (len1 > len2)
11559
196
            return 1; /* uni is longer */
11560
13.1M
        if (len1 < len2)
11561
745
            return -1; /* str is longer */
11562
13.1M
        return 0;
11563
13.1M
    }
11564
2.10k
    else {
11565
2.10k
        const void *data = PyUnicode_DATA(uni);
11566
        /* Compare Unicode string and source character set string */
11567
3.59k
        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
11568
3.37k
            if (chr != (unsigned char)str[i])
11569
1.88k
                return (chr < (unsigned char)(str[i])) ? -1 : 1;
11570
        /* This check keeps Python strings that end in '\0' from comparing equal
11571
         to C strings identical up to that point. */
11572
221
        if (PyUnicode_GET_LENGTH(uni) != i || chr)
11573
221
            return 1; /* uni is longer */
11574
0
        if (str[i])
11575
0
            return -1; /* str is longer */
11576
0
        return 0;
11577
0
    }
11578
31.2M
}
11579
11580
int
11581
PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
11582
24
{
11583
24
    return PyUnicode_EqualToUTF8AndSize(unicode, str, strlen(str));
11584
24
}
11585
11586
int
11587
PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t size)
11588
24
{
11589
24
    assert(_PyUnicode_CHECK(unicode));
11590
24
    assert(str);
11591
11592
24
    if (PyUnicode_IS_ASCII(unicode)) {
11593
24
        Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11594
24
        return size == len &&
11595
0
            memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11596
24
    }
11597
0
    if (PyUnicode_UTF8(unicode) != NULL) {
11598
0
        Py_ssize_t len = PyUnicode_UTF8_LENGTH(unicode);
11599
0
        return size == len &&
11600
0
            memcmp(PyUnicode_UTF8(unicode), str, len) == 0;
11601
0
    }
11602
11603
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11604
0
    if ((size_t)len >= (size_t)size || (size_t)len < (size_t)size / 4) {
11605
0
        return 0;
11606
0
    }
11607
0
    const unsigned char *s = (const unsigned char *)str;
11608
0
    const unsigned char *ends = s + (size_t)size;
11609
0
    int kind = PyUnicode_KIND(unicode);
11610
0
    const void *data = PyUnicode_DATA(unicode);
11611
    /* Compare Unicode string and UTF-8 string */
11612
0
    for (Py_ssize_t i = 0; i < len; i++) {
11613
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11614
0
        if (ch < 0x80) {
11615
0
            if (ends == s || s[0] != ch) {
11616
0
                return 0;
11617
0
            }
11618
0
            s += 1;
11619
0
        }
11620
0
        else if (ch < 0x800) {
11621
0
            if ((ends - s) < 2 ||
11622
0
                s[0] != (0xc0 | (ch >> 6)) ||
11623
0
                s[1] != (0x80 | (ch & 0x3f)))
11624
0
            {
11625
0
                return 0;
11626
0
            }
11627
0
            s += 2;
11628
0
        }
11629
0
        else if (ch < 0x10000) {
11630
0
            if (Py_UNICODE_IS_SURROGATE(ch) ||
11631
0
                (ends - s) < 3 ||
11632
0
                s[0] != (0xe0 | (ch >> 12)) ||
11633
0
                s[1] != (0x80 | ((ch >> 6) & 0x3f)) ||
11634
0
                s[2] != (0x80 | (ch & 0x3f)))
11635
0
            {
11636
0
                return 0;
11637
0
            }
11638
0
            s += 3;
11639
0
        }
11640
0
        else {
11641
0
            assert(ch <= MAX_UNICODE);
11642
0
            if ((ends - s) < 4 ||
11643
0
                s[0] != (0xf0 | (ch >> 18)) ||
11644
0
                s[1] != (0x80 | ((ch >> 12) & 0x3f)) ||
11645
0
                s[2] != (0x80 | ((ch >> 6) & 0x3f)) ||
11646
0
                s[3] != (0x80 | (ch & 0x3f)))
11647
0
            {
11648
0
                return 0;
11649
0
            }
11650
0
            s += 4;
11651
0
        }
11652
0
    }
11653
0
    return s == ends;
11654
0
}
11655
11656
int
11657
_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11658
1.86M
{
11659
1.86M
    size_t len;
11660
1.86M
    assert(_PyUnicode_CHECK(unicode));
11661
1.86M
    assert(str);
11662
#ifndef NDEBUG
11663
    for (const char *p = str; *p; p++) {
11664
        assert((unsigned char)*p < 128);
11665
    }
11666
#endif
11667
1.86M
    if (!PyUnicode_IS_ASCII(unicode))
11668
10.3k
        return 0;
11669
1.85M
    len = (size_t)PyUnicode_GET_LENGTH(unicode);
11670
1.85M
    return strlen(str) == len &&
11671
230k
           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11672
1.86M
}
11673
11674
PyObject *
11675
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
11676
58.4M
{
11677
58.4M
    int result;
11678
11679
58.4M
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11680
201k
        Py_RETURN_NOTIMPLEMENTED;
11681
11682
58.2M
    if (left == right) {
11683
3.61k
        switch (op) {
11684
2.82k
        case Py_EQ:
11685
2.82k
        case Py_LE:
11686
2.82k
        case Py_GE:
11687
            /* a string is equal to itself */
11688
2.82k
            Py_RETURN_TRUE;
11689
786
        case Py_NE:
11690
786
        case Py_LT:
11691
786
        case Py_GT:
11692
786
            Py_RETURN_FALSE;
11693
0
        default:
11694
0
            PyErr_BadArgument();
11695
0
            return NULL;
11696
3.61k
        }
11697
3.61k
    }
11698
58.2M
    else if (op == Py_EQ || op == Py_NE) {
11699
29.7M
        result = unicode_eq(left, right);
11700
29.7M
        result ^= (op == Py_NE);
11701
29.7M
        return PyBool_FromLong(result);
11702
29.7M
    }
11703
28.4M
    else {
11704
28.4M
        result = unicode_compare(left, right);
11705
28.4M
        Py_RETURN_RICHCOMPARE(result, 0, op);
11706
28.4M
    }
11707
58.2M
}
11708
11709
int
11710
PyUnicode_Contains(PyObject *str, PyObject *substr)
11711
224M
{
11712
224M
    int kind1, kind2;
11713
224M
    const void *buf1, *buf2;
11714
224M
    Py_ssize_t len1, len2;
11715
224M
    int result;
11716
11717
224M
    if (!PyUnicode_Check(substr)) {
11718
0
        PyErr_Format(PyExc_TypeError,
11719
0
                     "'in <string>' requires string as left operand, not %.100s",
11720
0
                     Py_TYPE(substr)->tp_name);
11721
0
        return -1;
11722
0
    }
11723
224M
    if (ensure_unicode(str) < 0)
11724
0
        return -1;
11725
11726
224M
    kind1 = PyUnicode_KIND(str);
11727
224M
    kind2 = PyUnicode_KIND(substr);
11728
224M
    if (kind1 < kind2)
11729
17.5M
        return 0;
11730
206M
    len1 = PyUnicode_GET_LENGTH(str);
11731
206M
    len2 = PyUnicode_GET_LENGTH(substr);
11732
206M
    if (len1 < len2)
11733
872k
        return 0;
11734
205M
    buf1 = PyUnicode_DATA(str);
11735
205M
    buf2 = PyUnicode_DATA(substr);
11736
205M
    if (len2 == 1) {
11737
179M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11738
179M
        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11739
179M
        return result;
11740
179M
    }
11741
26.0M
    if (kind2 != kind1) {
11742
19.3k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11743
19.3k
        if (!buf2)
11744
0
            return -1;
11745
19.3k
    }
11746
11747
26.0M
    switch (kind1) {
11748
25.9M
    case PyUnicode_1BYTE_KIND:
11749
25.9M
        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11750
25.9M
        break;
11751
13.5k
    case PyUnicode_2BYTE_KIND:
11752
13.5k
        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11753
13.5k
        break;
11754
5.76k
    case PyUnicode_4BYTE_KIND:
11755
5.76k
        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11756
5.76k
        break;
11757
0
    default:
11758
0
        Py_UNREACHABLE();
11759
26.0M
    }
11760
11761
26.0M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
11762
26.0M
    if (kind2 != kind1)
11763
19.3k
        PyMem_Free((void *)buf2);
11764
11765
26.0M
    return result;
11766
26.0M
}
11767
11768
/* Concat to string or Unicode object giving a new Unicode object. */
11769
11770
PyObject *
11771
PyUnicode_Concat(PyObject *left, PyObject *right)
11772
32.4M
{
11773
32.4M
    PyObject *result;
11774
32.4M
    Py_UCS4 maxchar, maxchar2;
11775
32.4M
    Py_ssize_t left_len, right_len, new_len;
11776
11777
32.4M
    if (ensure_unicode(left) < 0)
11778
0
        return NULL;
11779
11780
32.4M
    if (!PyUnicode_Check(right)) {
11781
0
        PyErr_Format(PyExc_TypeError,
11782
0
            "can only concatenate str (not \"%.200s\") to str",
11783
0
            Py_TYPE(right)->tp_name);
11784
0
        return NULL;
11785
0
    }
11786
11787
    /* Shortcuts */
11788
32.4M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11789
32.4M
    if (left == empty) {
11790
1.24M
        return PyUnicode_FromObject(right);
11791
1.24M
    }
11792
31.2M
    if (right == empty) {
11793
2.61M
        return PyUnicode_FromObject(left);
11794
2.61M
    }
11795
11796
28.5M
    left_len = PyUnicode_GET_LENGTH(left);
11797
28.5M
    right_len = PyUnicode_GET_LENGTH(right);
11798
28.5M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11799
0
        PyErr_SetString(PyExc_OverflowError,
11800
0
                        "strings are too large to concat");
11801
0
        return NULL;
11802
0
    }
11803
28.5M
    new_len = left_len + right_len;
11804
11805
28.5M
    maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11806
28.5M
    maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11807
28.5M
    maxchar = Py_MAX(maxchar, maxchar2);
11808
11809
    /* Concat the two Unicode strings */
11810
28.5M
    result = PyUnicode_New(new_len, maxchar);
11811
28.5M
    if (result == NULL)
11812
0
        return NULL;
11813
28.5M
    _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11814
28.5M
    _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11815
28.5M
    assert(_PyUnicode_CheckConsistency(result, 1));
11816
28.5M
    return result;
11817
28.5M
}
11818
11819
void
11820
PyUnicode_Append(PyObject **p_left, PyObject *right)
11821
8.55M
{
11822
8.55M
    PyObject *left, *res;
11823
8.55M
    Py_UCS4 maxchar, maxchar2;
11824
8.55M
    Py_ssize_t left_len, right_len, new_len;
11825
11826
8.55M
    if (p_left == NULL) {
11827
0
        if (!PyErr_Occurred())
11828
0
            PyErr_BadInternalCall();
11829
0
        return;
11830
0
    }
11831
8.55M
    left = *p_left;
11832
8.55M
    if (right == NULL || left == NULL
11833
8.55M
        || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
11834
0
        if (!PyErr_Occurred())
11835
0
            PyErr_BadInternalCall();
11836
0
        goto error;
11837
0
    }
11838
11839
    /* Shortcuts */
11840
8.55M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11841
8.55M
    if (left == empty) {
11842
479k
        Py_DECREF(left);
11843
479k
        *p_left = Py_NewRef(right);
11844
479k
        return;
11845
479k
    }
11846
8.07M
    if (right == empty) {
11847
11.7k
        return;
11848
11.7k
    }
11849
11850
8.06M
    left_len = PyUnicode_GET_LENGTH(left);
11851
8.06M
    right_len = PyUnicode_GET_LENGTH(right);
11852
8.06M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11853
0
        PyErr_SetString(PyExc_OverflowError,
11854
0
                        "strings are too large to concat");
11855
0
        goto error;
11856
0
    }
11857
8.06M
    new_len = left_len + right_len;
11858
11859
8.06M
    if (_PyUnicode_IsModifiable(left)
11860
8.06M
        && PyUnicode_CheckExact(right)
11861
8.06M
        && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
11862
        /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11863
           to change the structure size, but characters are stored just after
11864
           the structure, and so it requires to move all characters which is
11865
           not so different than duplicating the string. */
11866
4.36M
        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11867
4.36M
    {
11868
        /* append inplace */
11869
4.36M
        if (unicode_resize(p_left, new_len) != 0)
11870
0
            goto error;
11871
11872
        /* copy 'right' into the newly allocated area of 'left' */
11873
4.36M
        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
11874
4.36M
    }
11875
3.70M
    else {
11876
3.70M
        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11877
3.70M
        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11878
3.70M
        maxchar = Py_MAX(maxchar, maxchar2);
11879
11880
        /* Concat the two Unicode strings */
11881
3.70M
        res = PyUnicode_New(new_len, maxchar);
11882
3.70M
        if (res == NULL)
11883
0
            goto error;
11884
3.70M
        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11885
3.70M
        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
11886
3.70M
        Py_DECREF(left);
11887
3.70M
        *p_left = res;
11888
3.70M
    }
11889
8.06M
    assert(_PyUnicode_CheckConsistency(*p_left, 1));
11890
8.06M
    return;
11891
11892
0
error:
11893
0
    Py_CLEAR(*p_left);
11894
0
}
11895
11896
void
11897
PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11898
8
{
11899
8
    PyUnicode_Append(pleft, right);
11900
8
    Py_XDECREF(right);
11901
8
}
11902
11903
/*[clinic input]
11904
@permit_long_summary
11905
@text_signature "($self, sub[, start[, end]], /)"
11906
str.count as unicode_count -> Py_ssize_t
11907
11908
    self as str: self
11909
    sub as substr: unicode
11910
    start: slice_index(accept={int, NoneType}, c_default='0') = None
11911
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
11912
    /
11913
11914
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
11915
11916
Optional arguments start and end are interpreted as in slice
11917
notation.
11918
[clinic start generated code]*/
11919
11920
static Py_ssize_t
11921
unicode_count_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
11922
                   Py_ssize_t end)
11923
/*[clinic end generated code: output=8fcc3aef0b18edbf input=c9209e05438cc352]*/
11924
26.7M
{
11925
26.7M
    assert(PyUnicode_Check(str));
11926
26.7M
    assert(PyUnicode_Check(substr));
11927
11928
26.7M
    Py_ssize_t result;
11929
26.7M
    int kind1, kind2;
11930
26.7M
    const void *buf1 = NULL, *buf2 = NULL;
11931
26.7M
    Py_ssize_t len1, len2;
11932
11933
26.7M
    kind1 = PyUnicode_KIND(str);
11934
26.7M
    kind2 = PyUnicode_KIND(substr);
11935
26.7M
    if (kind1 < kind2)
11936
0
        return 0;
11937
11938
26.7M
    len1 = PyUnicode_GET_LENGTH(str);
11939
26.7M
    len2 = PyUnicode_GET_LENGTH(substr);
11940
26.7M
    ADJUST_INDICES(start, end, len1);
11941
26.7M
    if (end - start < len2)
11942
9.49M
        return 0;
11943
11944
17.2M
    buf1 = PyUnicode_DATA(str);
11945
17.2M
    buf2 = PyUnicode_DATA(substr);
11946
17.2M
    if (kind2 != kind1) {
11947
246k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11948
246k
        if (!buf2)
11949
0
            goto onError;
11950
246k
    }
11951
11952
    // We don't reuse `anylib_count` here because of the explicit casts.
11953
17.2M
    switch (kind1) {
11954
16.9M
    case PyUnicode_1BYTE_KIND:
11955
16.9M
        result = ucs1lib_count(
11956
16.9M
            ((const Py_UCS1*)buf1) + start, end - start,
11957
16.9M
            buf2, len2, PY_SSIZE_T_MAX
11958
16.9M
            );
11959
16.9M
        break;
11960
200k
    case PyUnicode_2BYTE_KIND:
11961
200k
        result = ucs2lib_count(
11962
200k
            ((const Py_UCS2*)buf1) + start, end - start,
11963
200k
            buf2, len2, PY_SSIZE_T_MAX
11964
200k
            );
11965
200k
        break;
11966
45.8k
    case PyUnicode_4BYTE_KIND:
11967
45.8k
        result = ucs4lib_count(
11968
45.8k
            ((const Py_UCS4*)buf1) + start, end - start,
11969
45.8k
            buf2, len2, PY_SSIZE_T_MAX
11970
45.8k
            );
11971
45.8k
        break;
11972
0
    default:
11973
0
        Py_UNREACHABLE();
11974
17.2M
    }
11975
11976
17.2M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11977
17.2M
    if (kind2 != kind1)
11978
246k
        PyMem_Free((void *)buf2);
11979
11980
17.2M
    return result;
11981
0
  onError:
11982
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11983
0
    if (kind2 != kind1)
11984
0
        PyMem_Free((void *)buf2);
11985
0
    return -1;
11986
17.2M
}
11987
11988
/*[clinic input]
11989
str.encode as unicode_encode
11990
11991
    encoding: str(c_default="NULL") = 'utf-8'
11992
        The encoding in which to encode the string.
11993
    errors: str(c_default="NULL") = 'strict'
11994
        The error handling scheme to use for encoding errors.
11995
        The default is 'strict' meaning that encoding errors raise a
11996
        UnicodeEncodeError.  Other possible values are 'ignore', 'replace'
11997
        and 'xmlcharrefreplace' as well as any other name registered with
11998
        codecs.register_error that can handle UnicodeEncodeErrors.
11999
12000
Encode the string using the codec registered for encoding.
12001
[clinic start generated code]*/
12002
12003
static PyObject *
12004
unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
12005
/*[clinic end generated code: output=bf78b6e2a9470e3c input=b85a9645cb33b729]*/
12006
24.0M
{
12007
24.0M
    return PyUnicode_AsEncodedString(self, encoding, errors);
12008
24.0M
}
12009
12010
/*[clinic input]
12011
str.expandtabs as unicode_expandtabs
12012
12013
    tabsize: int = 8
12014
12015
Return a copy where all tab characters are expanded using spaces.
12016
12017
If tabsize is not given, a tab size of 8 characters is assumed.
12018
[clinic start generated code]*/
12019
12020
static PyObject *
12021
unicode_expandtabs_impl(PyObject *self, int tabsize)
12022
/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
12023
1.11M
{
12024
1.11M
    Py_ssize_t i, j, line_pos, src_len, incr;
12025
1.11M
    Py_UCS4 ch;
12026
1.11M
    PyObject *u;
12027
1.11M
    const void *src_data;
12028
1.11M
    void *dest_data;
12029
1.11M
    int kind;
12030
1.11M
    int found;
12031
12032
    /* First pass: determine size of output string */
12033
1.11M
    src_len = PyUnicode_GET_LENGTH(self);
12034
1.11M
    i = j = line_pos = 0;
12035
1.11M
    kind = PyUnicode_KIND(self);
12036
1.11M
    src_data = PyUnicode_DATA(self);
12037
1.11M
    found = 0;
12038
2.47M
    for (; i < src_len; i++) {
12039
1.35M
        ch = PyUnicode_READ(kind, src_data, i);
12040
1.35M
        if (ch == '\t') {
12041
417k
            found = 1;
12042
417k
            if (tabsize > 0) {
12043
417k
                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
12044
417k
                if (j > PY_SSIZE_T_MAX - incr)
12045
0
                    goto overflow;
12046
417k
                line_pos += incr;
12047
417k
                j += incr;
12048
417k
            }
12049
417k
        }
12050
938k
        else {
12051
938k
            if (j > PY_SSIZE_T_MAX - 1)
12052
0
                goto overflow;
12053
938k
            line_pos++;
12054
938k
            j++;
12055
938k
            if (ch == '\n' || ch == '\r')
12056
1.39k
                line_pos = 0;
12057
938k
        }
12058
1.35M
    }
12059
1.11M
    if (!found)
12060
1.07M
        return unicode_result_unchanged(self);
12061
12062
    /* Second pass: create output string and fill it */
12063
41.1k
    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
12064
41.1k
    if (!u)
12065
0
        return NULL;
12066
41.1k
    dest_data = PyUnicode_DATA(u);
12067
12068
41.1k
    i = j = line_pos = 0;
12069
12070
796k
    for (; i < src_len; i++) {
12071
755k
        ch = PyUnicode_READ(kind, src_data, i);
12072
755k
        if (ch == '\t') {
12073
417k
            if (tabsize > 0) {
12074
417k
                incr = tabsize - (line_pos % tabsize);
12075
417k
                line_pos += incr;
12076
417k
                _PyUnicode_Fill(kind, dest_data, ' ', j, incr);
12077
417k
                j += incr;
12078
417k
            }
12079
417k
        }
12080
338k
        else {
12081
338k
            line_pos++;
12082
338k
            PyUnicode_WRITE(kind, dest_data, j, ch);
12083
338k
            j++;
12084
338k
            if (ch == '\n' || ch == '\r')
12085
0
                line_pos = 0;
12086
338k
        }
12087
755k
    }
12088
41.1k
    assert (j == PyUnicode_GET_LENGTH(u));
12089
41.1k
    return unicode_result(u);
12090
12091
0
  overflow:
12092
0
    PyErr_SetString(PyExc_OverflowError, "new string is too long");
12093
0
    return NULL;
12094
41.1k
}
12095
12096
/*[clinic input]
12097
@permit_long_summary
12098
str.find as unicode_find = str.count
12099
12100
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12101
12102
Optional arguments start and end are interpreted as in slice
12103
notation.  Return -1 on failure.
12104
[clinic start generated code]*/
12105
12106
static Py_ssize_t
12107
unicode_find_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12108
                  Py_ssize_t end)
12109
/*[clinic end generated code: output=51dbe6255712e278 input=f57e93c59d1ee927]*/
12110
26.6M
{
12111
26.6M
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12112
26.6M
    if (result < 0) {
12113
8.27M
        return -1;
12114
8.27M
    }
12115
18.3M
    return result;
12116
26.6M
}
12117
12118
static PyObject *
12119
unicode_getitem(PyObject *self, Py_ssize_t index)
12120
64.3M
{
12121
64.3M
    const void *data;
12122
64.3M
    int kind;
12123
64.3M
    Py_UCS4 ch;
12124
12125
64.3M
    if (!PyUnicode_Check(self)) {
12126
0
        PyErr_BadArgument();
12127
0
        return NULL;
12128
0
    }
12129
64.3M
    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
12130
15.3k
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12131
15.3k
        return NULL;
12132
15.3k
    }
12133
64.2M
    kind = PyUnicode_KIND(self);
12134
64.2M
    data = PyUnicode_DATA(self);
12135
64.2M
    ch = PyUnicode_READ(kind, data, index);
12136
64.2M
    return unicode_char(ch);
12137
64.3M
}
12138
12139
/* Believe it or not, this produces the same value for ASCII strings
12140
   as bytes_hash(). */
12141
static Py_hash_t
12142
unicode_hash(PyObject *self)
12143
912M
{
12144
912M
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
12145
12146
#ifdef Py_DEBUG
12147
    assert(_Py_HashSecret_Initialized);
12148
#endif
12149
912M
    Py_hash_t hash = PyUnicode_HASH(self);
12150
912M
    if (hash != -1) {
12151
854M
        return hash;
12152
854M
    }
12153
57.4M
    x = Py_HashBuffer(PyUnicode_DATA(self),
12154
57.4M
                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
12155
12156
57.4M
    PyUnicode_SET_HASH(self, x);
12157
57.4M
    return x;
12158
912M
}
12159
12160
/*[clinic input]
12161
@permit_long_summary
12162
str.index as unicode_index = str.count
12163
12164
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12165
12166
Optional arguments start and end are interpreted as in slice
12167
notation.  Raises ValueError when the substring is not found.
12168
[clinic start generated code]*/
12169
12170
static Py_ssize_t
12171
unicode_index_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12172
                   Py_ssize_t end)
12173
/*[clinic end generated code: output=77558288837cdf40 input=5900ab84de55e628]*/
12174
216k
{
12175
216k
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12176
216k
    if (result == -1) {
12177
605
        PyErr_SetString(PyExc_ValueError, "substring not found");
12178
605
    }
12179
216k
    else if (result < 0) {
12180
0
        return -1;
12181
0
    }
12182
216k
    return result;
12183
216k
}
12184
12185
/*[clinic input]
12186
@permit_long_summary
12187
str.isascii as unicode_isascii
12188
12189
Return True if all characters in the string are ASCII, False otherwise.
12190
12191
ASCII characters have code points in the range U+0000-U+007F.
12192
Empty string is ASCII too.
12193
[clinic start generated code]*/
12194
12195
static PyObject *
12196
unicode_isascii_impl(PyObject *self)
12197
/*[clinic end generated code: output=c5910d64b5a8003f input=dc74e1ced821159f]*/
12198
37.5k
{
12199
37.5k
    return PyBool_FromLong(PyUnicode_IS_ASCII(self));
12200
37.5k
}
12201
12202
/*[clinic input]
12203
str.islower as unicode_islower
12204
12205
Return True if the string is a lowercase string, False otherwise.
12206
12207
A string is lowercase if all cased characters in the string are
12208
lowercase and there is at least one cased character in the string.
12209
[clinic start generated code]*/
12210
12211
static PyObject *
12212
unicode_islower_impl(PyObject *self)
12213
/*[clinic end generated code: output=dbd41995bd005b81 input=1879b48dfc628366]*/
12214
0
{
12215
0
    Py_ssize_t i, length;
12216
0
    int kind;
12217
0
    const void *data;
12218
0
    int cased;
12219
12220
0
    length = PyUnicode_GET_LENGTH(self);
12221
0
    kind = PyUnicode_KIND(self);
12222
0
    data = PyUnicode_DATA(self);
12223
12224
    /* Shortcut for single character strings */
12225
0
    if (length == 1)
12226
0
        return PyBool_FromLong(
12227
0
            Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
12228
12229
    /* Special case for empty strings */
12230
0
    if (length == 0)
12231
0
        Py_RETURN_FALSE;
12232
12233
0
    cased = 0;
12234
0
    for (i = 0; i < length; i++) {
12235
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12236
12237
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
12238
0
            Py_RETURN_FALSE;
12239
0
        else if (!cased && Py_UNICODE_ISLOWER(ch))
12240
0
            cased = 1;
12241
0
    }
12242
0
    return PyBool_FromLong(cased);
12243
0
}
12244
12245
/*[clinic input]
12246
str.isupper as unicode_isupper
12247
12248
Return True if the string is an uppercase string, False otherwise.
12249
12250
A string is uppercase if all cased characters in the string are
12251
uppercase and there is at least one cased character in the string.
12252
[clinic start generated code]*/
12253
12254
static PyObject *
12255
unicode_isupper_impl(PyObject *self)
12256
/*[clinic end generated code: output=049209c8e7f15f59 input=77d29904aef0e3a0]*/
12257
4.02k
{
12258
4.02k
    Py_ssize_t i, length;
12259
4.02k
    int kind;
12260
4.02k
    const void *data;
12261
4.02k
    int cased;
12262
12263
4.02k
    length = PyUnicode_GET_LENGTH(self);
12264
4.02k
    kind = PyUnicode_KIND(self);
12265
4.02k
    data = PyUnicode_DATA(self);
12266
12267
    /* Shortcut for single character strings */
12268
4.02k
    if (length == 1)
12269
0
        return PyBool_FromLong(
12270
0
            Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
12271
12272
    /* Special case for empty strings */
12273
4.02k
    if (length == 0)
12274
0
        Py_RETURN_FALSE;
12275
12276
4.02k
    cased = 0;
12277
51.7k
    for (i = 0; i < length; i++) {
12278
48.2k
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12279
12280
48.2k
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
12281
536
            Py_RETURN_FALSE;
12282
47.6k
        else if (!cased && Py_UNICODE_ISUPPER(ch))
12283
3.54k
            cased = 1;
12284
48.2k
    }
12285
3.49k
    return PyBool_FromLong(cased);
12286
4.02k
}
12287
12288
/*[clinic input]
12289
str.istitle as unicode_istitle
12290
12291
Return True if the string is a title-cased string, False otherwise.
12292
12293
In a title-cased string, upper- and title-case characters may only
12294
follow uncased characters and lowercase characters only cased ones.
12295
[clinic start generated code]*/
12296
12297
static PyObject *
12298
unicode_istitle_impl(PyObject *self)
12299
/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
12300
0
{
12301
0
    Py_ssize_t i, length;
12302
0
    int kind;
12303
0
    const void *data;
12304
0
    int cased, previous_is_cased;
12305
12306
0
    length = PyUnicode_GET_LENGTH(self);
12307
0
    kind = PyUnicode_KIND(self);
12308
0
    data = PyUnicode_DATA(self);
12309
12310
    /* Shortcut for single character strings */
12311
0
    if (length == 1) {
12312
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12313
0
        return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
12314
0
                               (Py_UNICODE_ISUPPER(ch) != 0));
12315
0
    }
12316
12317
    /* Special case for empty strings */
12318
0
    if (length == 0)
12319
0
        Py_RETURN_FALSE;
12320
12321
0
    cased = 0;
12322
0
    previous_is_cased = 0;
12323
0
    for (i = 0; i < length; i++) {
12324
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12325
12326
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
12327
0
            if (previous_is_cased)
12328
0
                Py_RETURN_FALSE;
12329
0
            previous_is_cased = 1;
12330
0
            cased = 1;
12331
0
        }
12332
0
        else if (Py_UNICODE_ISLOWER(ch)) {
12333
0
            if (!previous_is_cased)
12334
0
                Py_RETURN_FALSE;
12335
0
            previous_is_cased = 1;
12336
0
            cased = 1;
12337
0
        }
12338
0
        else
12339
0
            previous_is_cased = 0;
12340
0
    }
12341
0
    return PyBool_FromLong(cased);
12342
0
}
12343
12344
/*[clinic input]
12345
str.isspace as unicode_isspace
12346
12347
Return True if the string is a whitespace string, False otherwise.
12348
12349
A string is whitespace if all characters in the string are
12350
whitespace and there is at least one character in the string.
12351
[clinic start generated code]*/
12352
12353
static PyObject *
12354
unicode_isspace_impl(PyObject *self)
12355
/*[clinic end generated code: output=163a63bfa08ac2b9 input=29e09560fc23fbeb]*/
12356
1.88M
{
12357
1.88M
    Py_ssize_t i, length;
12358
1.88M
    int kind;
12359
1.88M
    const void *data;
12360
12361
1.88M
    length = PyUnicode_GET_LENGTH(self);
12362
1.88M
    kind = PyUnicode_KIND(self);
12363
1.88M
    data = PyUnicode_DATA(self);
12364
12365
    /* Shortcut for single character strings */
12366
1.88M
    if (length == 1)
12367
1.87M
        return PyBool_FromLong(
12368
1.87M
            Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
12369
12370
    /* Special case for empty strings */
12371
1.33k
    if (length == 0)
12372
284
        Py_RETURN_FALSE;
12373
12374
7.60k
    for (i = 0; i < length; i++) {
12375
7.50k
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12376
7.50k
        if (!Py_UNICODE_ISSPACE(ch))
12377
944
            Py_RETURN_FALSE;
12378
7.50k
    }
12379
1.04k
    Py_RETURN_TRUE;
12380
1.04k
}
12381
12382
/*[clinic input]
12383
str.isalpha as unicode_isalpha
12384
12385
Return True if the string is an alphabetic string, False otherwise.
12386
12387
A string is alphabetic if all characters in the string are
12388
alphabetic and there is at least one character in the string.
12389
[clinic start generated code]*/
12390
12391
static PyObject *
12392
unicode_isalpha_impl(PyObject *self)
12393
/*[clinic end generated code: output=cc81b9ac3883ec4f input=9906a07f3e04892e]*/
12394
19
{
12395
19
    Py_ssize_t i, length;
12396
19
    int kind;
12397
19
    const void *data;
12398
12399
19
    length = PyUnicode_GET_LENGTH(self);
12400
19
    kind = PyUnicode_KIND(self);
12401
19
    data = PyUnicode_DATA(self);
12402
12403
    /* Shortcut for single character strings */
12404
19
    if (length == 1)
12405
15
        return PyBool_FromLong(
12406
15
            Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
12407
12408
    /* Special case for empty strings */
12409
4
    if (length == 0)
12410
0
        Py_RETURN_FALSE;
12411
12412
4
    for (i = 0; i < length; i++) {
12413
4
        if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
12414
4
            Py_RETURN_FALSE;
12415
4
    }
12416
4
    Py_RETURN_TRUE;
12417
4
}
12418
12419
/*[clinic input]
12420
@permit_long_summary
12421
str.isalnum as unicode_isalnum
12422
12423
Return True if the string is an alpha-numeric string, False otherwise.
12424
12425
A string is alpha-numeric if all characters in the string are
12426
alpha-numeric and there is at least one character in the string.
12427
[clinic start generated code]*/
12428
12429
static PyObject *
12430
unicode_isalnum_impl(PyObject *self)
12431
/*[clinic end generated code: output=a5a23490ffc3660c input=892f64ebc171fd4f]*/
12432
256
{
12433
256
    int kind;
12434
256
    const void *data;
12435
256
    Py_ssize_t len, i;
12436
12437
256
    kind = PyUnicode_KIND(self);
12438
256
    data = PyUnicode_DATA(self);
12439
256
    len = PyUnicode_GET_LENGTH(self);
12440
12441
    /* Shortcut for single character strings */
12442
256
    if (len == 1) {
12443
256
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12444
256
        return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12445
256
    }
12446
12447
    /* Special case for empty strings */
12448
0
    if (len == 0)
12449
0
        Py_RETURN_FALSE;
12450
12451
0
    for (i = 0; i < len; i++) {
12452
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12453
0
        if (!Py_UNICODE_ISALNUM(ch))
12454
0
            Py_RETURN_FALSE;
12455
0
    }
12456
0
    Py_RETURN_TRUE;
12457
0
}
12458
12459
/*[clinic input]
12460
str.isdecimal as unicode_isdecimal
12461
12462
Return True if the string is a decimal string, False otherwise.
12463
12464
A string is a decimal string if all characters in the string are
12465
decimal and there is at least one character in the string.
12466
[clinic start generated code]*/
12467
12468
static PyObject *
12469
unicode_isdecimal_impl(PyObject *self)
12470
/*[clinic end generated code: output=fb2dcdb62d3fc548 input=63b0453c48cad0af]*/
12471
1.47k
{
12472
1.47k
    Py_ssize_t i, length;
12473
1.47k
    int kind;
12474
1.47k
    const void *data;
12475
12476
1.47k
    length = PyUnicode_GET_LENGTH(self);
12477
1.47k
    kind = PyUnicode_KIND(self);
12478
1.47k
    data = PyUnicode_DATA(self);
12479
12480
    /* Shortcut for single character strings */
12481
1.47k
    if (length == 1)
12482
411
        return PyBool_FromLong(
12483
411
            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
12484
12485
    /* Special case for empty strings */
12486
1.06k
    if (length == 0)
12487
0
        Py_RETURN_FALSE;
12488
12489
7.38k
    for (i = 0; i < length; i++) {
12490
6.83k
        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
12491
511
            Py_RETURN_FALSE;
12492
6.83k
    }
12493
1.06k
    Py_RETURN_TRUE;
12494
1.06k
}
12495
12496
/*[clinic input]
12497
str.isdigit as unicode_isdigit
12498
12499
Return True if the string is a digit string, False otherwise.
12500
12501
A string is a digit string if all characters in the string are
12502
digits and there is at least one character in the string.
12503
[clinic start generated code]*/
12504
12505
static PyObject *
12506
unicode_isdigit_impl(PyObject *self)
12507
/*[clinic end generated code: output=10a6985311da6858 input=353b03747b062e4b]*/
12508
1.58M
{
12509
1.58M
    Py_ssize_t i, length;
12510
1.58M
    int kind;
12511
1.58M
    const void *data;
12512
12513
1.58M
    length = PyUnicode_GET_LENGTH(self);
12514
1.58M
    kind = PyUnicode_KIND(self);
12515
1.58M
    data = PyUnicode_DATA(self);
12516
12517
    /* Shortcut for single character strings */
12518
1.58M
    if (length == 1) {
12519
1.58M
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12520
1.58M
        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12521
1.58M
    }
12522
12523
    /* Special case for empty strings */
12524
408
    if (length == 0)
12525
0
        Py_RETURN_FALSE;
12526
12527
1.45k
    for (i = 0; i < length; i++) {
12528
1.04k
        if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
12529
0
            Py_RETURN_FALSE;
12530
1.04k
    }
12531
408
    Py_RETURN_TRUE;
12532
408
}
12533
12534
/*[clinic input]
12535
str.isnumeric as unicode_isnumeric
12536
12537
Return True if the string is a numeric string, False otherwise.
12538
12539
A string is numeric if all characters in the string are numeric and
12540
there is at least one character in the string.
12541
[clinic start generated code]*/
12542
12543
static PyObject *
12544
unicode_isnumeric_impl(PyObject *self)
12545
/*[clinic end generated code: output=9172a32d9013051a input=83b2a072ed7aff48]*/
12546
0
{
12547
0
    Py_ssize_t i, length;
12548
0
    int kind;
12549
0
    const void *data;
12550
12551
0
    length = PyUnicode_GET_LENGTH(self);
12552
0
    kind = PyUnicode_KIND(self);
12553
0
    data = PyUnicode_DATA(self);
12554
12555
    /* Shortcut for single character strings */
12556
0
    if (length == 1)
12557
0
        return PyBool_FromLong(
12558
0
            Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
12559
12560
    /* Special case for empty strings */
12561
0
    if (length == 0)
12562
0
        Py_RETURN_FALSE;
12563
12564
0
    for (i = 0; i < length; i++) {
12565
0
        if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
12566
0
            Py_RETURN_FALSE;
12567
0
    }
12568
0
    Py_RETURN_TRUE;
12569
0
}
12570
12571
Py_ssize_t
12572
_PyUnicode_ScanIdentifier(PyObject *self)
12573
20.6k
{
12574
20.6k
    Py_ssize_t i;
12575
20.6k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12576
20.6k
    if (len == 0) {
12577
        /* an empty string is not a valid identifier */
12578
0
        return 0;
12579
0
    }
12580
12581
20.6k
    int kind = PyUnicode_KIND(self);
12582
20.6k
    const void *data = PyUnicode_DATA(self);
12583
20.6k
    Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12584
    /* PEP 3131 says that the first character must be in
12585
       XID_Start and subsequent characters in XID_Continue,
12586
       and for the ASCII range, the 2.x rules apply (i.e
12587
       start with letters and underscore, continue with
12588
       letters, digits, underscore). However, given the current
12589
       definition of XID_Start and XID_Continue, it is sufficient
12590
       to check just for these, except that _ must be allowed
12591
       as starting an identifier.  */
12592
20.6k
    if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12593
821
        return 0;
12594
821
    }
12595
12596
160k
    for (i = 1; i < len; i++) {
12597
141k
        ch = PyUnicode_READ(kind, data, i);
12598
141k
        if (!_PyUnicode_IsXidContinue(ch)) {
12599
292
            return i;
12600
292
        }
12601
141k
    }
12602
19.5k
    return i;
12603
19.8k
}
12604
12605
int
12606
PyUnicode_IsIdentifier(PyObject *self)
12607
7.95k
{
12608
7.95k
    Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12609
7.95k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12610
    /* an empty string is not a valid identifier */
12611
7.95k
    return len && i == len;
12612
7.95k
}
12613
12614
/*[clinic input]
12615
@permit_long_summary
12616
str.isidentifier as unicode_isidentifier
12617
12618
Return True if the string is a valid Python identifier, False otherwise.
12619
12620
Call keyword.iskeyword(s) to test whether string s is a reserved
12621
identifier, such as "def" or "class".
12622
[clinic start generated code]*/
12623
12624
static PyObject *
12625
unicode_isidentifier_impl(PyObject *self)
12626
/*[clinic end generated code: output=fe585a9666572905 input=cabde62c20a3be6b]*/
12627
5.25k
{
12628
5.25k
    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12629
5.25k
}
12630
12631
/*[clinic input]
12632
@permit_long_summary
12633
str.isprintable as unicode_isprintable
12634
12635
Return True if all characters in the string are printable, False otherwise.
12636
12637
A character is printable if repr() may use it in its output.
12638
[clinic start generated code]*/
12639
12640
static PyObject *
12641
unicode_isprintable_impl(PyObject *self)
12642
/*[clinic end generated code: output=3ab9626cd32dd1a0 input=18345ba847084ec5]*/
12643
1.85M
{
12644
1.85M
    Py_ssize_t i, length;
12645
1.85M
    int kind;
12646
1.85M
    const void *data;
12647
12648
1.85M
    length = PyUnicode_GET_LENGTH(self);
12649
1.85M
    kind = PyUnicode_KIND(self);
12650
1.85M
    data = PyUnicode_DATA(self);
12651
12652
    /* Shortcut for single character strings */
12653
1.85M
    if (length == 1)
12654
1.85M
        return PyBool_FromLong(
12655
1.85M
            Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
12656
12657
0
    for (i = 0; i < length; i++) {
12658
0
        if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
12659
0
            Py_RETURN_FALSE;
12660
0
        }
12661
0
    }
12662
0
    Py_RETURN_TRUE;
12663
0
}
12664
12665
/*[clinic input]
12666
str.join as unicode_join
12667
12668
    iterable: object
12669
    /
12670
12671
Concatenate any number of strings.
12672
12673
The string whose method is called is inserted in between each given
12674
string.  The result is returned as a new string.
12675
12676
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12677
[clinic start generated code]*/
12678
12679
static PyObject *
12680
unicode_join(PyObject *self, PyObject *iterable)
12681
/*[clinic end generated code: output=6857e7cecfe7bf98 input=fd330a11ee845fb2]*/
12682
25.2M
{
12683
25.2M
    return PyUnicode_Join(self, iterable);
12684
25.2M
}
12685
12686
static Py_ssize_t
12687
unicode_length(PyObject *self)
12688
43.6M
{
12689
43.6M
    return PyUnicode_GET_LENGTH(self);
12690
43.6M
}
12691
12692
/*[clinic input]
12693
str.ljust as unicode_ljust
12694
12695
    width: Py_ssize_t
12696
    fillchar: Py_UCS4 = ' '
12697
    /
12698
12699
Return a left-justified string of length width.
12700
12701
Padding is done using the specified fill character (default is
12702
a space).
12703
[clinic start generated code]*/
12704
12705
static PyObject *
12706
unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12707
/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=8a55f06694c20ed6]*/
12708
1.19k
{
12709
1.19k
    if (PyUnicode_GET_LENGTH(self) >= width)
12710
551
        return unicode_result_unchanged(self);
12711
12712
640
    return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
12713
1.19k
}
12714
12715
/*[clinic input]
12716
str.lower as unicode_lower
12717
12718
Return a copy of the string converted to lowercase.
12719
[clinic start generated code]*/
12720
12721
static PyObject *
12722
unicode_lower_impl(PyObject *self)
12723
/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
12724
89.7M
{
12725
89.7M
    if (PyUnicode_IS_ASCII(self))
12726
79.0M
        return ascii_upper_or_lower(self, 1);
12727
10.7M
    return case_operation(self, do_lower);
12728
89.7M
}
12729
12730
90.0M
#define LEFTSTRIP 0
12731
113M
#define RIGHTSTRIP 1
12732
59.5M
#define BOTHSTRIP 2
12733
12734
/* Arrays indexed by above */
12735
static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
12736
12737
0
#define STRIPNAME(i) (stripfuncnames[i])
12738
12739
/* externally visible for str.strip(unicode) */
12740
PyObject *
12741
_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
12742
2.38M
{
12743
2.38M
    const void *data;
12744
2.38M
    int kind;
12745
2.38M
    Py_ssize_t i, j, len;
12746
2.38M
    BLOOM_MASK sepmask;
12747
2.38M
    Py_ssize_t seplen;
12748
12749
2.38M
    kind = PyUnicode_KIND(self);
12750
2.38M
    data = PyUnicode_DATA(self);
12751
2.38M
    len = PyUnicode_GET_LENGTH(self);
12752
2.38M
    seplen = PyUnicode_GET_LENGTH(sepobj);
12753
2.38M
    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12754
2.38M
                              PyUnicode_DATA(sepobj),
12755
2.38M
                              seplen);
12756
12757
2.38M
    i = 0;
12758
2.38M
    if (striptype != RIGHTSTRIP) {
12759
537k
        while (i < len) {
12760
532k
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12761
532k
            if (!BLOOM(sepmask, ch))
12762
490k
                break;
12763
42.1k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12764
3.50k
                break;
12765
38.6k
            i++;
12766
38.6k
        }
12767
498k
    }
12768
12769
2.38M
    j = len;
12770
2.38M
    if (striptype != LEFTSTRIP) {
12771
1.88M
        j--;
12772
2.56M
        while (j >= i) {
12773
1.59M
            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12774
1.59M
            if (!BLOOM(sepmask, ch))
12775
867k
                break;
12776
728k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12777
50.6k
                break;
12778
677k
            j--;
12779
677k
        }
12780
12781
1.88M
        j++;
12782
1.88M
    }
12783
12784
2.38M
    return PyUnicode_Substring(self, i, j);
12785
2.38M
}
12786
12787
PyObject*
12788
_PyUnicode_BinarySlice(PyObject *container, PyObject *start_o, PyObject *stop_o)
12789
33.4M
{
12790
33.4M
    assert(PyUnicode_CheckExact(container));
12791
33.4M
    Py_ssize_t len = PyUnicode_GET_LENGTH(container);
12792
33.4M
    Py_ssize_t istart, istop;
12793
33.4M
    if (!_PyEval_UnpackIndices(start_o, stop_o, len, &istart, &istop)) {
12794
0
        return NULL;
12795
0
    }
12796
33.4M
    return PyUnicode_Substring(container, istart, istop);
12797
33.4M
}
12798
12799
PyObject*
12800
PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12801
281M
{
12802
281M
    const unsigned char *data;
12803
281M
    int kind;
12804
281M
    Py_ssize_t length;
12805
12806
281M
    length = PyUnicode_GET_LENGTH(self);
12807
281M
    end = Py_MIN(end, length);
12808
12809
281M
    if (start == 0 && end == length)
12810
89.3M
        return unicode_result_unchanged(self);
12811
12812
191M
    if (start < 0 || end < 0) {
12813
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12814
0
        return NULL;
12815
0
    }
12816
191M
    if (start >= length || end < start)
12817
11.3M
        _Py_RETURN_UNICODE_EMPTY();
12818
12819
180M
    length = end - start;
12820
180M
    if (PyUnicode_IS_ASCII(self)) {
12821
75.1M
        data = PyUnicode_1BYTE_DATA(self);
12822
75.1M
        return _PyUnicode_FromASCII((const char*)(data + start), length);
12823
75.1M
    }
12824
105M
    else {
12825
105M
        kind = PyUnicode_KIND(self);
12826
105M
        data = PyUnicode_1BYTE_DATA(self);
12827
105M
        return PyUnicode_FromKindAndData(kind,
12828
105M
                                         data + kind * start,
12829
105M
                                         length);
12830
105M
    }
12831
180M
}
12832
12833
static PyObject *
12834
do_strip(PyObject *self, int striptype)
12835
85.3M
{
12836
85.3M
    Py_ssize_t len, i, j;
12837
12838
85.3M
    len = PyUnicode_GET_LENGTH(self);
12839
12840
85.3M
    if (PyUnicode_IS_ASCII(self)) {
12841
68.8M
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12842
12843
68.8M
        i = 0;
12844
68.8M
        if (striptype != RIGHTSTRIP) {
12845
57.2M
            while (i < len) {
12846
39.1M
                Py_UCS1 ch = data[i];
12847
39.1M
                if (!_Py_ascii_whitespace[ch])
12848
31.3M
                    break;
12849
7.81M
                i++;
12850
7.81M
            }
12851
49.4M
        }
12852
12853
68.8M
        j = len;
12854
68.8M
        if (striptype != LEFTSTRIP) {
12855
68.4M
            j--;
12856
77.7M
            while (j >= i) {
12857
49.1M
                Py_UCS1 ch = data[j];
12858
49.1M
                if (!_Py_ascii_whitespace[ch])
12859
39.9M
                    break;
12860
9.24M
                j--;
12861
9.24M
            }
12862
68.4M
            j++;
12863
68.4M
        }
12864
68.8M
    }
12865
16.4M
    else {
12866
16.4M
        int kind = PyUnicode_KIND(self);
12867
16.4M
        const void *data = PyUnicode_DATA(self);
12868
12869
16.4M
        i = 0;
12870
16.4M
        if (striptype != RIGHTSTRIP) {
12871
15.2M
            while (i < len) {
12872
15.2M
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12873
15.2M
                if (!Py_UNICODE_ISSPACE(ch))
12874
11.9M
                    break;
12875
3.29M
                i++;
12876
3.29M
            }
12877
11.9M
        }
12878
12879
16.4M
        j = len;
12880
16.4M
        if (striptype != LEFTSTRIP) {
12881
15.0M
            j--;
12882
18.9M
            while (j >= i) {
12883
18.9M
                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12884
18.9M
                if (!Py_UNICODE_ISSPACE(ch))
12885
15.0M
                    break;
12886
3.89M
                j--;
12887
3.89M
            }
12888
15.0M
            j++;
12889
15.0M
        }
12890
16.4M
    }
12891
12892
85.3M
    return PyUnicode_Substring(self, i, j);
12893
85.3M
}
12894
12895
12896
static PyObject *
12897
do_argstrip(PyObject *self, int striptype, PyObject *sep)
12898
87.7M
{
12899
87.7M
    if (sep != Py_None) {
12900
2.38M
        if (PyUnicode_Check(sep))
12901
2.38M
            return _PyUnicode_XStrip(self, striptype, sep);
12902
0
        else {
12903
0
            PyErr_Format(PyExc_TypeError,
12904
0
                         "%s arg must be None or str",
12905
0
                         STRIPNAME(striptype));
12906
0
            return NULL;
12907
0
        }
12908
2.38M
    }
12909
12910
85.3M
    return do_strip(self, striptype);
12911
87.7M
}
12912
12913
12914
/*[clinic input]
12915
@permit_long_summary
12916
str.strip as unicode_strip
12917
12918
    chars: object = None
12919
    /
12920
12921
Return a copy of the string with leading and trailing whitespace removed.
12922
12923
If chars is given and not None, remove characters in chars instead.
12924
[clinic start generated code]*/
12925
12926
static PyObject *
12927
unicode_strip_impl(PyObject *self, PyObject *chars)
12928
/*[clinic end generated code: output=ca19018454345d57 input=8bc6353450345fbd]*/
12929
59.5M
{
12930
59.5M
    return do_argstrip(self, BOTHSTRIP, chars);
12931
59.5M
}
12932
12933
12934
/*[clinic input]
12935
str.lstrip as unicode_lstrip
12936
12937
    chars: object = None
12938
    /
12939
12940
Return a copy of the string with leading whitespace removed.
12941
12942
If chars is given and not None, remove characters in chars instead.
12943
[clinic start generated code]*/
12944
12945
static PyObject *
12946
unicode_lstrip_impl(PyObject *self, PyObject *chars)
12947
/*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
12948
2.34M
{
12949
2.34M
    return do_argstrip(self, LEFTSTRIP, chars);
12950
2.34M
}
12951
12952
12953
/*[clinic input]
12954
str.rstrip as unicode_rstrip
12955
12956
    chars: object = None
12957
    /
12958
12959
Return a copy of the string with trailing whitespace removed.
12960
12961
If chars is given and not None, remove characters in chars instead.
12962
[clinic start generated code]*/
12963
12964
static PyObject *
12965
unicode_rstrip_impl(PyObject *self, PyObject *chars)
12966
/*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
12967
25.8M
{
12968
25.8M
    return do_argstrip(self, RIGHTSTRIP, chars);
12969
25.8M
}
12970
12971
12972
PyObject *
12973
_PyUnicode_Repeat(PyObject *str, Py_ssize_t len)
12974
308k
{
12975
308k
    PyObject *u;
12976
308k
    Py_ssize_t nchars, n;
12977
12978
308k
    if (len < 1)
12979
42.9k
        _Py_RETURN_UNICODE_EMPTY();
12980
12981
    /* no repeat, return original string */
12982
265k
    if (len == 1)
12983
33.5k
        return unicode_result_unchanged(str);
12984
12985
231k
    if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
12986
0
        PyErr_SetString(PyExc_OverflowError,
12987
0
                        "repeated string is too long");
12988
0
        return NULL;
12989
0
    }
12990
231k
    nchars = len * PyUnicode_GET_LENGTH(str);
12991
12992
231k
    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
12993
231k
    if (!u)
12994
0
        return NULL;
12995
231k
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
12996
12997
231k
    if (PyUnicode_GET_LENGTH(str) == 1) {
12998
229k
        int kind = PyUnicode_KIND(str);
12999
229k
        Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
13000
229k
        if (kind == PyUnicode_1BYTE_KIND) {
13001
229k
            void *to = PyUnicode_DATA(u);
13002
229k
            memset(to, (unsigned char)fill_char, len);
13003
229k
        }
13004
0
        else if (kind == PyUnicode_2BYTE_KIND) {
13005
0
            Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
13006
0
            for (n = 0; n < len; ++n)
13007
0
                ucs2[n] = fill_char;
13008
0
        } else {
13009
0
            Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
13010
0
            assert(kind == PyUnicode_4BYTE_KIND);
13011
0
            for (n = 0; n < len; ++n)
13012
0
                ucs4[n] = fill_char;
13013
0
        }
13014
229k
    }
13015
2.05k
    else {
13016
2.05k
        Py_ssize_t char_size = PyUnicode_KIND(str);
13017
2.05k
        char *to = (char *) PyUnicode_DATA(u);
13018
2.05k
        _PyBytes_RepeatBuffer(to, nchars * char_size, PyUnicode_DATA(str),
13019
2.05k
            PyUnicode_GET_LENGTH(str) * char_size);
13020
2.05k
    }
13021
13022
231k
    assert(_PyUnicode_CheckConsistency(u, 1));
13023
231k
    return u;
13024
231k
}
13025
13026
PyObject *
13027
PyUnicode_Replace(PyObject *str,
13028
                  PyObject *substr,
13029
                  PyObject *replstr,
13030
                  Py_ssize_t maxcount)
13031
0
{
13032
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
13033
0
            ensure_unicode(replstr) < 0)
13034
0
        return NULL;
13035
0
    return replace(str, substr, replstr, maxcount);
13036
0
}
13037
13038
/*[clinic input]
13039
str.replace as unicode_replace
13040
13041
    old: unicode
13042
    new: unicode
13043
    /
13044
    count: Py_ssize_t = -1
13045
        Maximum number of occurrences to replace.
13046
        -1 (the default value) means replace all occurrences.
13047
13048
Return a copy with all occurrences of substring old replaced by new.
13049
13050
If count is given, only the first count occurrences are replaced.
13051
If count is not specified or -1, then all occurrences are replaced.
13052
[clinic start generated code]*/
13053
13054
static PyObject *
13055
unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
13056
                     Py_ssize_t count)
13057
/*[clinic end generated code: output=b63f1a8b5eebf448 input=d15a6886b05e2edc]*/
13058
23.6M
{
13059
23.6M
    return replace(self, old, new, count);
13060
23.6M
}
13061
13062
/*[clinic input]
13063
str.removeprefix as unicode_removeprefix
13064
13065
    prefix: unicode
13066
    /
13067
13068
Return a str with the given prefix string removed if present.
13069
13070
If the string starts with the prefix string, return
13071
string[len(prefix):].  Otherwise, return a copy of the original
13072
string.
13073
[clinic start generated code]*/
13074
13075
static PyObject *
13076
unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
13077
/*[clinic end generated code: output=f1e5945e9763bcb9 input=90d162724944bfa7]*/
13078
7.06k
{
13079
7.06k
    int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
13080
7.06k
    if (match == -1) {
13081
0
        return NULL;
13082
0
    }
13083
7.06k
    if (match) {
13084
19
        return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
13085
19
                                   PyUnicode_GET_LENGTH(self));
13086
19
    }
13087
7.04k
    return unicode_result_unchanged(self);
13088
7.06k
}
13089
13090
/*[clinic input]
13091
str.removesuffix as unicode_removesuffix
13092
13093
    suffix: unicode
13094
    /
13095
13096
Return a str with the given suffix string removed if present.
13097
13098
If the string ends with the suffix string and that suffix is not
13099
empty, return string[:-len(suffix)].  Otherwise, return a copy of
13100
the original string.
13101
[clinic start generated code]*/
13102
13103
static PyObject *
13104
unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
13105
/*[clinic end generated code: output=d36629e227636822 input=6efc96152d4bfcd5]*/
13106
912
{
13107
912
    int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
13108
912
    if (match == -1) {
13109
0
        return NULL;
13110
0
    }
13111
912
    if (match) {
13112
0
        return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
13113
0
                                            - PyUnicode_GET_LENGTH(suffix));
13114
0
    }
13115
912
    return unicode_result_unchanged(self);
13116
912
}
13117
13118
static PyObject *
13119
unicode_repr(PyObject *unicode)
13120
23.3M
{
13121
23.3M
    Py_ssize_t isize = PyUnicode_GET_LENGTH(unicode);
13122
23.3M
    const void *idata = PyUnicode_DATA(unicode);
13123
13124
    /* Compute length of output, quote characters, and
13125
       maximum character */
13126
23.3M
    Py_ssize_t osize = 0;
13127
23.3M
    Py_UCS4 maxch = 127;
13128
23.3M
    Py_ssize_t squote = 0;
13129
23.3M
    Py_ssize_t dquote = 0;
13130
23.3M
    int ikind = PyUnicode_KIND(unicode);
13131
393M
    for (Py_ssize_t i = 0; i < isize; i++) {
13132
370M
        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
13133
370M
        Py_ssize_t incr = 1;
13134
370M
        switch (ch) {
13135
376k
        case '\'': squote++; break;
13136
834k
        case '"':  dquote++; break;
13137
12.8M
        case '\\': case '\t': case '\r': case '\n':
13138
12.8M
            incr = 2;
13139
12.8M
            break;
13140
356M
        default:
13141
            /* Fast-path ASCII */
13142
356M
            if (ch < ' ' || ch == 0x7f)
13143
175M
                incr = 4; /* \xHH */
13144
180M
            else if (ch < 0x7f)
13145
161M
                ;
13146
19.1M
            else if (Py_UNICODE_ISPRINTABLE(ch))
13147
16.0M
                maxch = (ch > maxch) ? ch : maxch;
13148
3.17M
            else if (ch < 0x100)
13149
79.9k
                incr = 4; /* \xHH */
13150
3.09M
            else if (ch < 0x10000)
13151
101k
                incr = 6; /* \uHHHH */
13152
2.99M
            else
13153
2.99M
                incr = 10; /* \uHHHHHHHH */
13154
370M
        }
13155
370M
        if (osize > PY_SSIZE_T_MAX - incr) {
13156
0
            PyErr_SetString(PyExc_OverflowError,
13157
0
                            "string is too long to generate repr");
13158
0
            return NULL;
13159
0
        }
13160
370M
        osize += incr;
13161
370M
    }
13162
13163
23.3M
    Py_UCS4 quote = '\'';
13164
23.3M
    int changed = (osize != isize);
13165
23.3M
    if (squote) {
13166
128k
        changed = 1;
13167
128k
        if (dquote)
13168
            /* Both squote and dquote present. Use squote,
13169
               and escape them */
13170
11.4k
            osize += squote;
13171
117k
        else
13172
117k
            quote = '"';
13173
128k
    }
13174
23.3M
    osize += 2;   /* quotes */
13175
13176
23.3M
    PyObject *repr = PyUnicode_New(osize, maxch);
13177
23.3M
    if (repr == NULL)
13178
0
        return NULL;
13179
23.3M
    int okind = PyUnicode_KIND(repr);
13180
23.3M
    void *odata = PyUnicode_DATA(repr);
13181
13182
23.3M
    if (!changed) {
13183
10.6M
        PyUnicode_WRITE(okind, odata, 0, quote);
13184
13185
10.6M
        _PyUnicode_FastCopyCharacters(repr, 1,
13186
10.6M
                                      unicode, 0,
13187
10.6M
                                      isize);
13188
13189
10.6M
        PyUnicode_WRITE(okind, odata, osize-1, quote);
13190
10.6M
    }
13191
12.6M
    else {
13192
12.6M
        switch (okind) {
13193
12.3M
        case PyUnicode_1BYTE_KIND:
13194
12.3M
            ucs1lib_repr(unicode, quote, odata);
13195
12.3M
            break;
13196
355k
        case PyUnicode_2BYTE_KIND:
13197
355k
            ucs2lib_repr(unicode, quote, odata);
13198
355k
            break;
13199
8.49k
        default:
13200
8.49k
            assert(okind == PyUnicode_4BYTE_KIND);
13201
8.49k
            ucs4lib_repr(unicode, quote, odata);
13202
12.6M
        }
13203
12.6M
    }
13204
13205
23.3M
    assert(_PyUnicode_CheckConsistency(repr, 1));
13206
23.3M
    return repr;
13207
23.3M
}
13208
13209
/*[clinic input]
13210
@permit_long_summary
13211
str.rfind as unicode_rfind = str.count
13212
13213
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13214
13215
Optional arguments start and end are interpreted as in slice
13216
notation.  Return -1 on failure.
13217
[clinic start generated code]*/
13218
13219
static Py_ssize_t
13220
unicode_rfind_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13221
                   Py_ssize_t end)
13222
/*[clinic end generated code: output=880b29f01dd014c8 input=2e67789533baf2f5]*/
13223
216k
{
13224
216k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13225
216k
    if (result < 0) {
13226
17.8k
        return -1;
13227
17.8k
    }
13228
198k
    return result;
13229
216k
}
13230
13231
/*[clinic input]
13232
@permit_long_summary
13233
str.rindex as unicode_rindex = str.count
13234
13235
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13236
13237
Optional arguments start and end are interpreted as in slice
13238
notation.  Raises ValueError when the substring is not found.
13239
[clinic start generated code]*/
13240
13241
static Py_ssize_t
13242
unicode_rindex_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13243
                    Py_ssize_t end)
13244
/*[clinic end generated code: output=5f3aef124c867fe1 input=e29d446c8234c9d9]*/
13245
2.61k
{
13246
2.61k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13247
2.61k
    if (result == -1) {
13248
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
13249
0
    }
13250
2.61k
    else if (result < 0) {
13251
0
        return -1;
13252
0
    }
13253
2.61k
    return result;
13254
2.61k
}
13255
13256
/*[clinic input]
13257
str.rjust as unicode_rjust
13258
13259
    width: Py_ssize_t
13260
    fillchar: Py_UCS4 = ' '
13261
    /
13262
13263
Return a right-justified string of length width.
13264
13265
Padding is done using the specified fill character (default is
13266
a space).
13267
[clinic start generated code]*/
13268
13269
static PyObject *
13270
unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
13271
/*[clinic end generated code: output=804a1a57fbe8d5cf input=1256a8d659589907]*/
13272
0
{
13273
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13274
0
        return unicode_result_unchanged(self);
13275
13276
0
    return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
13277
0
}
13278
13279
PyObject *
13280
PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13281
0
{
13282
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13283
0
        return NULL;
13284
13285
0
    return split(s, sep, maxsplit);
13286
0
}
13287
13288
/*[clinic input]
13289
@permit_long_summary
13290
str.split as unicode_split
13291
13292
    sep: object = None
13293
        The separator used to split the string.
13294
13295
        When set to None (the default value), will split on any
13296
        whitespace character (including \n \r \t \f and spaces) and
13297
        will discard empty strings from the result.
13298
    maxsplit: Py_ssize_t = -1
13299
        Maximum number of splits.
13300
        -1 (the default value) means no limit.
13301
13302
Return a list of the substrings in the string, using sep as the separator string.
13303
13304
Splitting starts at the front of the string and works to the end.
13305
13306
Note, str.split() is mainly useful for data that has been
13307
intentionally delimited.  With natural text that includes
13308
punctuation, consider using the regular expression module.
13309
13310
[clinic start generated code]*/
13311
13312
static PyObject *
13313
unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13314
/*[clinic end generated code: output=3a65b1db356948dc input=288cfd6bc8828f5a]*/
13315
25.7M
{
13316
25.7M
    if (sep == Py_None)
13317
171k
        return split(self, NULL, maxsplit);
13318
25.5M
    if (PyUnicode_Check(sep))
13319
25.5M
        return split(self, sep, maxsplit);
13320
13321
0
    PyErr_Format(PyExc_TypeError,
13322
0
                 "must be str or None, not %.100s",
13323
0
                 Py_TYPE(sep)->tp_name);
13324
0
    return NULL;
13325
25.5M
}
13326
13327
PyObject *
13328
PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
13329
9.34M
{
13330
9.34M
    PyObject* out;
13331
9.34M
    int kind1, kind2;
13332
9.34M
    const void *buf1, *buf2;
13333
9.34M
    Py_ssize_t len1, len2;
13334
13335
9.34M
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13336
0
        return NULL;
13337
13338
9.34M
    kind1 = PyUnicode_KIND(str_obj);
13339
9.34M
    kind2 = PyUnicode_KIND(sep_obj);
13340
9.34M
    len1 = PyUnicode_GET_LENGTH(str_obj);
13341
9.34M
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13342
9.34M
    if (kind1 < kind2 || len1 < len2) {
13343
1.34k
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13344
1.34k
        return PyTuple_Pack(3, str_obj, empty, empty);
13345
1.34k
    }
13346
9.34M
    buf1 = PyUnicode_DATA(str_obj);
13347
9.34M
    buf2 = PyUnicode_DATA(sep_obj);
13348
9.34M
    if (kind2 != kind1) {
13349
98.7k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13350
98.7k
        if (!buf2)
13351
0
            return NULL;
13352
98.7k
    }
13353
13354
9.34M
    switch (kind1) {
13355
9.24M
    case PyUnicode_1BYTE_KIND:
13356
9.24M
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13357
2.88M
            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13358
6.35M
        else
13359
6.35M
            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13360
9.24M
        break;
13361
84.7k
    case PyUnicode_2BYTE_KIND:
13362
84.7k
        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13363
84.7k
        break;
13364
14.0k
    case PyUnicode_4BYTE_KIND:
13365
14.0k
        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13366
14.0k
        break;
13367
0
    default:
13368
0
        Py_UNREACHABLE();
13369
9.34M
    }
13370
13371
9.34M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13372
9.34M
    if (kind2 != kind1)
13373
98.7k
        PyMem_Free((void *)buf2);
13374
13375
9.34M
    return out;
13376
9.34M
}
13377
13378
13379
PyObject *
13380
PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
13381
30.3k
{
13382
30.3k
    PyObject* out;
13383
30.3k
    int kind1, kind2;
13384
30.3k
    const void *buf1, *buf2;
13385
30.3k
    Py_ssize_t len1, len2;
13386
13387
30.3k
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13388
0
        return NULL;
13389
13390
30.3k
    kind1 = PyUnicode_KIND(str_obj);
13391
30.3k
    kind2 = PyUnicode_KIND(sep_obj);
13392
30.3k
    len1 = PyUnicode_GET_LENGTH(str_obj);
13393
30.3k
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13394
30.3k
    if (kind1 < kind2 || len1 < len2) {
13395
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13396
0
        return PyTuple_Pack(3, empty, empty, str_obj);
13397
0
    }
13398
30.3k
    buf1 = PyUnicode_DATA(str_obj);
13399
30.3k
    buf2 = PyUnicode_DATA(sep_obj);
13400
30.3k
    if (kind2 != kind1) {
13401
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13402
0
        if (!buf2)
13403
0
            return NULL;
13404
0
    }
13405
13406
30.3k
    switch (kind1) {
13407
30.3k
    case PyUnicode_1BYTE_KIND:
13408
30.3k
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13409
30.3k
            out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13410
0
        else
13411
0
            out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13412
30.3k
        break;
13413
0
    case PyUnicode_2BYTE_KIND:
13414
0
        out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13415
0
        break;
13416
0
    case PyUnicode_4BYTE_KIND:
13417
0
        out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13418
0
        break;
13419
0
    default:
13420
0
        Py_UNREACHABLE();
13421
30.3k
    }
13422
13423
30.3k
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13424
30.3k
    if (kind2 != kind1)
13425
0
        PyMem_Free((void *)buf2);
13426
13427
30.3k
    return out;
13428
30.3k
}
13429
13430
/*[clinic input]
13431
str.partition as unicode_partition
13432
13433
    sep: object
13434
    /
13435
13436
Partition the string into three parts using the given separator.
13437
13438
This will search for the separator in the string.  If the separator
13439
is found, returns a 3-tuple containing the part before the
13440
separator, the separator itself, and the part after it.
13441
13442
If the separator is not found, returns a 3-tuple containing
13443
the original string and two empty strings.
13444
[clinic start generated code]*/
13445
13446
static PyObject *
13447
unicode_partition(PyObject *self, PyObject *sep)
13448
/*[clinic end generated code: output=e4ced7bd253ca3c4 input=e45faa8c26270cb1]*/
13449
9.34M
{
13450
9.34M
    return PyUnicode_Partition(self, sep);
13451
9.34M
}
13452
13453
/*[clinic input]
13454
str.rpartition as unicode_rpartition = str.partition
13455
13456
Partition the string into three parts using the given separator.
13457
13458
This will search for the separator in the string, starting at the
13459
end.  If the separator is found, returns a 3-tuple containing the
13460
part before the separator, the separator itself, and the part after
13461
it.
13462
13463
If the separator is not found, returns a 3-tuple containing two
13464
empty strings and the original string.
13465
[clinic start generated code]*/
13466
13467
static PyObject *
13468
unicode_rpartition(PyObject *self, PyObject *sep)
13469
/*[clinic end generated code: output=1aa13cf1156572aa input=53a7f8cb19975b7c]*/
13470
30.3k
{
13471
30.3k
    return PyUnicode_RPartition(self, sep);
13472
30.3k
}
13473
13474
PyObject *
13475
PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13476
0
{
13477
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13478
0
        return NULL;
13479
13480
0
    return rsplit(s, sep, maxsplit);
13481
0
}
13482
13483
/*[clinic input]
13484
@permit_long_summary
13485
str.rsplit as unicode_rsplit = str.split
13486
13487
Return a list of the substrings in the string, using sep as the separator string.
13488
13489
Splitting starts at the end of the string and works to the front.
13490
[clinic start generated code]*/
13491
13492
static PyObject *
13493
unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13494
/*[clinic end generated code: output=c2b815c63bcabffc input=0f762e30d267fa83]*/
13495
42
{
13496
42
    if (sep == Py_None)
13497
0
        return rsplit(self, NULL, maxsplit);
13498
42
    if (PyUnicode_Check(sep))
13499
42
        return rsplit(self, sep, maxsplit);
13500
13501
0
    PyErr_Format(PyExc_TypeError,
13502
0
                 "must be str or None, not %.100s",
13503
0
                 Py_TYPE(sep)->tp_name);
13504
0
    return NULL;
13505
42
}
13506
13507
/*[clinic input]
13508
@permit_long_summary
13509
str.splitlines as unicode_splitlines
13510
13511
    keepends: bool = False
13512
13513
Return a list of the lines in the string, breaking at line boundaries.
13514
13515
Line breaks are not included in the resulting list unless keepends
13516
is given and true.
13517
[clinic start generated code]*/
13518
13519
static PyObject *
13520
unicode_splitlines_impl(PyObject *self, int keepends)
13521
/*[clinic end generated code: output=f664dcdad153ec40 input=b45ea0f87645a06d]*/
13522
17.4k
{
13523
17.4k
    return PyUnicode_Splitlines(self, keepends);
13524
17.4k
}
13525
13526
static
13527
PyObject *unicode_str(PyObject *self)
13528
3.22M
{
13529
3.22M
    return unicode_result_unchanged(self);
13530
3.22M
}
13531
13532
/*[clinic input]
13533
@permit_long_summary
13534
str.swapcase as unicode_swapcase
13535
13536
Convert uppercase characters to lowercase and lowercase characters to uppercase.
13537
[clinic start generated code]*/
13538
13539
static PyObject *
13540
unicode_swapcase_impl(PyObject *self)
13541
/*[clinic end generated code: output=5d28966bf6d7b2af input=85bc39a9b4e8ee91]*/
13542
0
{
13543
0
    return case_operation(self, do_swapcase);
13544
0
}
13545
13546
static int
13547
unicode_maketrans_from_dict(PyObject *x, PyObject *newdict)
13548
0
{
13549
0
    PyObject *key, *value;
13550
0
    Py_ssize_t i = 0;
13551
0
    int res;
13552
0
    while (PyDict_Next(x, &i, &key, &value)) {
13553
0
        if (PyUnicode_Check(key)) {
13554
0
            PyObject *newkey;
13555
0
            int kind;
13556
0
            const void *data;
13557
0
            if (PyUnicode_GET_LENGTH(key) != 1) {
13558
0
                PyErr_SetString(PyExc_ValueError, "string keys in translate"
13559
0
                                "table must be of length 1");
13560
0
                return -1;
13561
0
            }
13562
0
            kind = PyUnicode_KIND(key);
13563
0
            data = PyUnicode_DATA(key);
13564
0
            newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
13565
0
            if (!newkey)
13566
0
                return -1;
13567
0
            res = PyDict_SetItem(newdict, newkey, value);
13568
0
            Py_DECREF(newkey);
13569
0
            if (res < 0)
13570
0
                return -1;
13571
0
        }
13572
0
        else if (PyLong_Check(key)) {
13573
0
            if (PyDict_SetItem(newdict, key, value) < 0)
13574
0
                return -1;
13575
0
        }
13576
0
        else {
13577
0
            PyErr_SetString(PyExc_TypeError, "keys in translate table must"
13578
0
                            "be strings or integers");
13579
0
            return -1;
13580
0
        }
13581
0
    }
13582
0
    return 0;
13583
0
}
13584
13585
/*[clinic input]
13586
13587
@staticmethod
13588
str.maketrans as unicode_maketrans
13589
13590
  x: object
13591
13592
  y: unicode=NULL
13593
13594
  z: unicode=NULL
13595
13596
  /
13597
13598
Return a translation table usable for str.translate().
13599
13600
If there is only one argument, it must be a dictionary mapping
13601
Unicode ordinals (integers) or characters to Unicode ordinals,
13602
strings or None.  Character keys will be then converted to ordinals.
13603
If there are two arguments, they must be strings of equal length,
13604
and in the resulting dictionary, each character in x will be mapped
13605
to the character at the same position in y.  If there is a third
13606
argument, it must be a string, whose characters will be mapped to
13607
None in the result.
13608
[clinic start generated code]*/
13609
13610
static PyObject *
13611
unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
13612
/*[clinic end generated code: output=a925c89452bd5881 input=66bc00a1b4258a6e]*/
13613
4
{
13614
4
    PyObject *new = NULL, *key, *value;
13615
4
    Py_ssize_t i = 0;
13616
4
    int res;
13617
13618
4
    new = PyDict_New();
13619
4
    if (!new)
13620
0
        return NULL;
13621
4
    if (y != NULL) {
13622
4
        int x_kind, y_kind, z_kind;
13623
4
        const void *x_data, *y_data, *z_data;
13624
13625
        /* x must be a string too, of equal length */
13626
4
        if (!PyUnicode_Check(x)) {
13627
0
            PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13628
0
                            "be a string if there is a second argument");
13629
0
            goto err;
13630
0
        }
13631
4
        if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
13632
0
            PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13633
0
                            "arguments must have equal length");
13634
0
            goto err;
13635
0
        }
13636
        /* create entries for translating chars in x to those in y */
13637
4
        x_kind = PyUnicode_KIND(x);
13638
4
        y_kind = PyUnicode_KIND(y);
13639
4
        x_data = PyUnicode_DATA(x);
13640
4
        y_data = PyUnicode_DATA(y);
13641
36
        for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13642
32
            key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
13643
32
            if (!key)
13644
0
                goto err;
13645
32
            value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
13646
32
            if (!value) {
13647
0
                Py_DECREF(key);
13648
0
                goto err;
13649
0
            }
13650
32
            res = PyDict_SetItem(new, key, value);
13651
32
            Py_DECREF(key);
13652
32
            Py_DECREF(value);
13653
32
            if (res < 0)
13654
0
                goto err;
13655
32
        }
13656
        /* create entries for deleting chars in z */
13657
4
        if (z != NULL) {
13658
0
            z_kind = PyUnicode_KIND(z);
13659
0
            z_data = PyUnicode_DATA(z);
13660
0
            for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
13661
0
                key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
13662
0
                if (!key)
13663
0
                    goto err;
13664
0
                res = PyDict_SetItem(new, key, Py_None);
13665
0
                Py_DECREF(key);
13666
0
                if (res < 0)
13667
0
                    goto err;
13668
0
            }
13669
0
        }
13670
4
    } else {
13671
        /* x must be a dict */
13672
0
        if (!PyAnyDict_CheckExact(x)) {
13673
0
            PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13674
0
                            "to maketrans it must be a dict");
13675
0
            goto err;
13676
0
        }
13677
        /* copy entries into the new dict, converting string keys to int keys */
13678
0
        int errcode;
13679
0
        Py_BEGIN_CRITICAL_SECTION(x);
13680
0
        errcode = unicode_maketrans_from_dict(x, new);
13681
0
        Py_END_CRITICAL_SECTION();
13682
0
        if (errcode < 0)
13683
0
            goto err;
13684
0
    }
13685
4
    return new;
13686
0
  err:
13687
0
    Py_DECREF(new);
13688
0
    return NULL;
13689
4
}
13690
13691
/*[clinic input]
13692
@permit_long_summary
13693
str.translate as unicode_translate
13694
13695
    table: object
13696
        Translation table, which must be a mapping of Unicode ordinals
13697
        to Unicode ordinals, strings, or None.
13698
    /
13699
13700
Replace each character in the string using the given translation table.
13701
13702
The table must implement lookup/indexing via __getitem__, for
13703
instance a dictionary or list.  If this operation raises
13704
LookupError, the character is left untouched.  Characters mapped to
13705
None are deleted.
13706
[clinic start generated code]*/
13707
13708
static PyObject *
13709
unicode_translate(PyObject *self, PyObject *table)
13710
/*[clinic end generated code: output=3cb448ff2fd96bf3 input=48cf0efe06bc1b75]*/
13711
13.5k
{
13712
13.5k
    return _PyUnicode_TranslateCharmap(self, table, "ignore");
13713
13.5k
}
13714
13715
/*[clinic input]
13716
str.upper as unicode_upper
13717
13718
Return a copy of the string converted to uppercase.
13719
[clinic start generated code]*/
13720
13721
static PyObject *
13722
unicode_upper_impl(PyObject *self)
13723
/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
13724
306
{
13725
306
    if (PyUnicode_IS_ASCII(self))
13726
306
        return ascii_upper_or_lower(self, 0);
13727
0
    return case_operation(self, do_upper);
13728
306
}
13729
13730
/*[clinic input]
13731
@permit_long_summary
13732
str.zfill as unicode_zfill
13733
13734
    width: Py_ssize_t
13735
    /
13736
13737
Pad a numeric string with zeros on the left, to fill a field of the given width.
13738
13739
The string is never truncated.
13740
[clinic start generated code]*/
13741
13742
static PyObject *
13743
unicode_zfill_impl(PyObject *self, Py_ssize_t width)
13744
/*[clinic end generated code: output=e13fb6bdf8e3b9df input=25a4ee0ea3e58ce0]*/
13745
0
{
13746
0
    Py_ssize_t fill;
13747
0
    PyObject *u;
13748
0
    int kind;
13749
0
    const void *data;
13750
0
    Py_UCS4 chr;
13751
13752
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13753
0
        return unicode_result_unchanged(self);
13754
13755
0
    fill = width - PyUnicode_GET_LENGTH(self);
13756
13757
0
    u = pad(self, fill, 0, '0');
13758
13759
0
    if (u == NULL)
13760
0
        return NULL;
13761
13762
0
    kind = PyUnicode_KIND(u);
13763
0
    data = PyUnicode_DATA(u);
13764
0
    chr = PyUnicode_READ(kind, data, fill);
13765
13766
0
    if (chr == '+' || chr == '-') {
13767
        /* move sign to beginning of string */
13768
0
        PyUnicode_WRITE(kind, data, 0, chr);
13769
0
        PyUnicode_WRITE(kind, data, fill, '0');
13770
0
    }
13771
13772
0
    assert(_PyUnicode_CheckConsistency(u, 1));
13773
0
    return u;
13774
0
}
13775
13776
/*[clinic input]
13777
@permit_long_summary
13778
@text_signature "($self, prefix[, start[, end]], /)"
13779
str.startswith as unicode_startswith
13780
13781
    prefix as subobj: object
13782
        A string or a tuple of strings to try.
13783
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13784
        Optional start position. Default: start of the string.
13785
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13786
        Optional stop position. Default: end of the string.
13787
    /
13788
13789
Return True if the string starts with the specified prefix, False otherwise.
13790
[clinic start generated code]*/
13791
13792
static PyObject *
13793
unicode_startswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13794
                        Py_ssize_t end)
13795
/*[clinic end generated code: output=4bd7cfd0803051d4 input=766bdbd33df251dc]*/
13796
20.5M
{
13797
20.5M
    if (PyTuple_Check(subobj)) {
13798
1.47M
        Py_ssize_t i;
13799
5.40M
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13800
3.94M
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13801
3.94M
            if (!PyUnicode_Check(substring)) {
13802
0
                PyErr_Format(PyExc_TypeError,
13803
0
                             "tuple for startswith must only contain str, "
13804
0
                             "not %.100s",
13805
0
                             Py_TYPE(substring)->tp_name);
13806
0
                return NULL;
13807
0
            }
13808
3.94M
            int result = tailmatch(self, substring, start, end, -1);
13809
3.94M
            if (result < 0) {
13810
0
                return NULL;
13811
0
            }
13812
3.94M
            if (result) {
13813
17.9k
                Py_RETURN_TRUE;
13814
17.9k
            }
13815
3.94M
        }
13816
        /* nothing matched */
13817
1.47M
        Py_RETURN_FALSE;
13818
1.47M
    }
13819
19.0M
    if (!PyUnicode_Check(subobj)) {
13820
0
        PyErr_Format(PyExc_TypeError,
13821
0
                     "startswith first arg must be str or "
13822
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13823
0
        return NULL;
13824
0
    }
13825
19.0M
    int result = tailmatch(self, subobj, start, end, -1);
13826
19.0M
    if (result < 0) {
13827
0
        return NULL;
13828
0
    }
13829
19.0M
    return PyBool_FromLong(result);
13830
19.0M
}
13831
13832
13833
/*[clinic input]
13834
@permit_long_summary
13835
@text_signature "($self, suffix[, start[, end]], /)"
13836
str.endswith as unicode_endswith
13837
13838
    suffix as subobj: object
13839
        A string or a tuple of strings to try.
13840
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13841
        Optional start position. Default: start of the string.
13842
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13843
        Optional stop position. Default: end of the string.
13844
    /
13845
13846
Return True if the string ends with the specified suffix, False otherwise.
13847
[clinic start generated code]*/
13848
13849
static PyObject *
13850
unicode_endswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13851
                      Py_ssize_t end)
13852
/*[clinic end generated code: output=cce6f8ceb0102ca9 input=b66bf6d5547ba1aa]*/
13853
11.5M
{
13854
11.5M
    if (PyTuple_Check(subobj)) {
13855
179k
        Py_ssize_t i;
13856
332k
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13857
308k
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13858
308k
            if (!PyUnicode_Check(substring)) {
13859
0
                PyErr_Format(PyExc_TypeError,
13860
0
                             "tuple for endswith must only contain str, "
13861
0
                             "not %.100s",
13862
0
                             Py_TYPE(substring)->tp_name);
13863
0
                return NULL;
13864
0
            }
13865
308k
            int result = tailmatch(self, substring, start, end, +1);
13866
308k
            if (result < 0) {
13867
0
                return NULL;
13868
0
            }
13869
308k
            if (result) {
13870
155k
                Py_RETURN_TRUE;
13871
155k
            }
13872
308k
        }
13873
179k
        Py_RETURN_FALSE;
13874
179k
    }
13875
11.3M
    if (!PyUnicode_Check(subobj)) {
13876
0
        PyErr_Format(PyExc_TypeError,
13877
0
                     "endswith first arg must be str or "
13878
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13879
0
        return NULL;
13880
0
    }
13881
11.3M
    int result = tailmatch(self, subobj, start, end, +1);
13882
11.3M
    if (result < 0) {
13883
0
        return NULL;
13884
0
    }
13885
11.3M
    return PyBool_FromLong(result);
13886
11.3M
}
13887
13888
13889
#include "stringlib/unicode_format.h"
13890
13891
PyDoc_STRVAR(format__doc__,
13892
             "format($self, /, *args, **kwargs)\n\
13893
--\n\
13894
\n\
13895
Return a formatted version of the string, using substitutions from args and kwargs.\n\
13896
The substitutions are identified by braces ('{' and '}').");
13897
13898
PyDoc_STRVAR(format_map__doc__,
13899
             "format_map($self, mapping, /)\n\
13900
--\n\
13901
\n\
13902
Return a formatted version of the string, using substitutions from mapping.\n\
13903
The substitutions are identified by braces ('{' and '}').");
13904
13905
/*[clinic input]
13906
@permit_long_summary
13907
str.__format__ as unicode___format__
13908
13909
    format_spec: unicode
13910
    /
13911
13912
Return a formatted version of the string as described by format_spec.
13913
[clinic start generated code]*/
13914
13915
static PyObject *
13916
unicode___format___impl(PyObject *self, PyObject *format_spec)
13917
/*[clinic end generated code: output=45fceaca6d2ba4c8 input=77a2a19f3f7969f2]*/
13918
0
{
13919
0
    _PyUnicodeWriter writer;
13920
0
    int ret;
13921
13922
0
    _PyUnicodeWriter_Init(&writer);
13923
0
    ret = _PyUnicode_FormatAdvancedWriter(&writer,
13924
0
                                          self, format_spec, 0,
13925
0
                                          PyUnicode_GET_LENGTH(format_spec));
13926
0
    if (ret == -1) {
13927
0
        _PyUnicodeWriter_Dealloc(&writer);
13928
0
        return NULL;
13929
0
    }
13930
0
    return _PyUnicodeWriter_Finish(&writer);
13931
0
}
13932
13933
/*[clinic input]
13934
str.__sizeof__ as unicode_sizeof
13935
13936
Return the size of the string in memory, in bytes.
13937
[clinic start generated code]*/
13938
13939
static PyObject *
13940
unicode_sizeof_impl(PyObject *self)
13941
/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
13942
0
{
13943
0
    Py_ssize_t size;
13944
13945
    /* If it's a compact object, account for base structure +
13946
       character data. */
13947
0
    if (PyUnicode_IS_COMPACT_ASCII(self)) {
13948
0
        size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13949
0
    }
13950
0
    else if (PyUnicode_IS_COMPACT(self)) {
13951
0
        size = sizeof(PyCompactUnicodeObject) +
13952
0
            (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
13953
0
    }
13954
0
    else {
13955
        /* If it is a two-block object, account for base object, and
13956
           for character block if present. */
13957
0
        size = sizeof(PyUnicodeObject);
13958
0
        if (_PyUnicode_DATA_ANY(self))
13959
0
            size += (PyUnicode_GET_LENGTH(self) + 1) *
13960
0
                PyUnicode_KIND(self);
13961
0
    }
13962
0
    if (_PyUnicode_HAS_UTF8_MEMORY(self))
13963
0
        size += PyUnicode_UTF8_LENGTH(self) + 1;
13964
13965
0
    return PyLong_FromSsize_t(size);
13966
0
}
13967
13968
static PyObject *
13969
unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
13970
0
{
13971
0
    PyObject *copy = _PyUnicode_Copy(v);
13972
0
    if (!copy)
13973
0
        return NULL;
13974
0
    return Py_BuildValue("(N)", copy);
13975
0
}
13976
13977
/*
13978
This function searchs the longest common leading whitespace
13979
of all lines in the [src, end).
13980
It returns the length of the common leading whitespace and sets `output` to
13981
point to the beginning of the common leading whitespace if length > 0.
13982
*/
13983
static Py_ssize_t
13984
search_longest_common_leading_whitespace(
13985
    const char *const src,
13986
    const char *const end,
13987
    const char **output)
13988
0
{
13989
    // [_start, _start + _len)
13990
    // describes the current longest common leading whitespace
13991
0
    const char *_start = NULL;
13992
0
    Py_ssize_t _len = 0;
13993
13994
0
    for (const char *iter = src; iter < end; ++iter) {
13995
0
        const char *line_start = iter;
13996
0
        const char *leading_whitespace_end = NULL;
13997
13998
        // scan the whole line
13999
0
        while (iter < end && *iter != '\n') {
14000
0
            if (!leading_whitespace_end && *iter != ' ' && *iter != '\t') {
14001
                /* `iter` points to the first non-whitespace character
14002
                   in this line */
14003
0
                if (iter == line_start) {
14004
                    // some line has no indent, fast exit!
14005
0
                    return 0;
14006
0
                }
14007
0
                leading_whitespace_end = iter;
14008
0
            }
14009
0
            ++iter;
14010
0
        }
14011
14012
        // if this line has all white space, skip it
14013
0
        if (!leading_whitespace_end) {
14014
0
            continue;
14015
0
        }
14016
14017
0
        if (!_start) {
14018
            // update the first leading whitespace
14019
0
            _start = line_start;
14020
0
            _len = leading_whitespace_end - line_start;
14021
0
            assert(_len > 0);
14022
0
        }
14023
0
        else {
14024
            /* We then compare with the current longest leading whitespace.
14025
14026
               [line_start, leading_whitespace_end) is the leading
14027
               whitespace of this line,
14028
14029
               [_start, _start + _len) is the leading whitespace of the
14030
               current longest leading whitespace. */
14031
0
            Py_ssize_t new_len = 0;
14032
0
            const char *_iter = _start, *line_iter = line_start;
14033
14034
0
            while (_iter < _start + _len && line_iter < leading_whitespace_end
14035
0
                   && *_iter == *line_iter)
14036
0
            {
14037
0
                ++_iter;
14038
0
                ++line_iter;
14039
0
                ++new_len;
14040
0
            }
14041
14042
0
            _len = new_len;
14043
0
            if (_len == 0) {
14044
                // No common things now, fast exit!
14045
0
                return 0;
14046
0
            }
14047
0
        }
14048
0
    }
14049
14050
0
    assert(_len >= 0);
14051
0
    if (_len > 0) {
14052
0
        *output = _start;
14053
0
    }
14054
0
    return _len;
14055
0
}
14056
14057
/* Dedent a string.
14058
   Intended to dedent Python source. Unlike `textwrap.dedent`, this
14059
   only supports spaces and tabs and doesn't normalize empty lines.
14060
   Return a new reference on success, NULL with exception set on error.
14061
   */
14062
PyObject *
14063
_PyUnicode_Dedent(PyObject *unicode)
14064
0
{
14065
0
    Py_ssize_t src_len = 0;
14066
0
    const char *src = PyUnicode_AsUTF8AndSize(unicode, &src_len);
14067
0
    if (!src) {
14068
0
        return NULL;
14069
0
    }
14070
0
    assert(src_len >= 0);
14071
0
    if (src_len == 0) {
14072
0
        return Py_NewRef(unicode);
14073
0
    }
14074
14075
0
    const char *const end = src + src_len;
14076
14077
    // [whitespace_start, whitespace_start + whitespace_len)
14078
    // describes the current longest common leading whitespace
14079
0
    const char *whitespace_start = NULL;
14080
0
    Py_ssize_t whitespace_len = search_longest_common_leading_whitespace(
14081
0
        src, end, &whitespace_start);
14082
14083
0
    if (whitespace_len == 0) {
14084
0
        return Py_NewRef(unicode);
14085
0
    }
14086
14087
    // now we should trigger a dedent
14088
0
    char *dest = PyMem_Malloc(src_len);
14089
0
    if (!dest) {
14090
0
        PyErr_NoMemory();
14091
0
        return NULL;
14092
0
    }
14093
0
    char *dest_iter = dest;
14094
14095
0
    for (const char *iter = src; iter < end; ++iter) {
14096
0
        const char *line_start = iter;
14097
0
        bool in_leading_space = true;
14098
14099
        // iterate over a line to find the end of a line
14100
0
        while (iter < end && *iter != '\n') {
14101
0
            if (in_leading_space && *iter != ' ' && *iter != '\t') {
14102
0
                in_leading_space = false;
14103
0
            }
14104
0
            ++iter;
14105
0
        }
14106
14107
        // invariant: *iter == '\n' or iter == end
14108
0
        bool append_newline = iter < end;
14109
14110
        // if this line has all white space, write '\n' and continue
14111
0
        if (in_leading_space && append_newline) {
14112
0
            *dest_iter++ = '\n';
14113
0
            continue;
14114
0
        }
14115
14116
        /* copy [new_line_start + whitespace_len, iter) to buffer, then
14117
            conditionally append '\n' */
14118
14119
0
        Py_ssize_t new_line_len = iter - line_start - whitespace_len;
14120
0
        assert(new_line_len >= 0);
14121
0
        memcpy(dest_iter, line_start + whitespace_len, new_line_len);
14122
14123
0
        dest_iter += new_line_len;
14124
14125
0
        if (append_newline) {
14126
0
            *dest_iter++ = '\n';
14127
0
        }
14128
0
    }
14129
14130
0
    PyObject *res = PyUnicode_FromStringAndSize(dest, dest_iter - dest);
14131
0
    PyMem_Free(dest);
14132
0
    return res;
14133
0
}
14134
14135
static PyMethodDef unicode_methods[] = {
14136
    UNICODE_ENCODE_METHODDEF
14137
    UNICODE_REPLACE_METHODDEF
14138
    UNICODE_SPLIT_METHODDEF
14139
    UNICODE_RSPLIT_METHODDEF
14140
    UNICODE_JOIN_METHODDEF
14141
    UNICODE_CAPITALIZE_METHODDEF
14142
    UNICODE_CASEFOLD_METHODDEF
14143
    UNICODE_TITLE_METHODDEF
14144
    UNICODE_CENTER_METHODDEF
14145
    UNICODE_COUNT_METHODDEF
14146
    UNICODE_EXPANDTABS_METHODDEF
14147
    UNICODE_FIND_METHODDEF
14148
    UNICODE_PARTITION_METHODDEF
14149
    UNICODE_INDEX_METHODDEF
14150
    UNICODE_LJUST_METHODDEF
14151
    UNICODE_LOWER_METHODDEF
14152
    UNICODE_LSTRIP_METHODDEF
14153
    UNICODE_RFIND_METHODDEF
14154
    UNICODE_RINDEX_METHODDEF
14155
    UNICODE_RJUST_METHODDEF
14156
    UNICODE_RSTRIP_METHODDEF
14157
    UNICODE_RPARTITION_METHODDEF
14158
    UNICODE_SPLITLINES_METHODDEF
14159
    UNICODE_STRIP_METHODDEF
14160
    UNICODE_SWAPCASE_METHODDEF
14161
    UNICODE_TRANSLATE_METHODDEF
14162
    UNICODE_UPPER_METHODDEF
14163
    UNICODE_STARTSWITH_METHODDEF
14164
    UNICODE_ENDSWITH_METHODDEF
14165
    UNICODE_REMOVEPREFIX_METHODDEF
14166
    UNICODE_REMOVESUFFIX_METHODDEF
14167
    UNICODE_ISASCII_METHODDEF
14168
    UNICODE_ISLOWER_METHODDEF
14169
    UNICODE_ISUPPER_METHODDEF
14170
    UNICODE_ISTITLE_METHODDEF
14171
    UNICODE_ISSPACE_METHODDEF
14172
    UNICODE_ISDECIMAL_METHODDEF
14173
    UNICODE_ISDIGIT_METHODDEF
14174
    UNICODE_ISNUMERIC_METHODDEF
14175
    UNICODE_ISALPHA_METHODDEF
14176
    UNICODE_ISALNUM_METHODDEF
14177
    UNICODE_ISIDENTIFIER_METHODDEF
14178
    UNICODE_ISPRINTABLE_METHODDEF
14179
    UNICODE_ZFILL_METHODDEF
14180
    {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
14181
    {"format_map", do_string_format_map, METH_O, format_map__doc__},
14182
    UNICODE___FORMAT___METHODDEF
14183
    UNICODE_MAKETRANS_METHODDEF
14184
    UNICODE_SIZEOF_METHODDEF
14185
    {"__getnewargs__",  unicode_getnewargs, METH_NOARGS},
14186
    {NULL, NULL}
14187
};
14188
14189
static PyObject *
14190
unicode_mod(PyObject *v, PyObject *w)
14191
13.5M
{
14192
13.5M
    if (!PyUnicode_Check(v))
14193
0
        Py_RETURN_NOTIMPLEMENTED;
14194
13.5M
    return PyUnicode_Format(v, w);
14195
13.5M
}
14196
14197
static PyNumberMethods unicode_as_number = {
14198
    0,              /*nb_add*/
14199
    0,              /*nb_subtract*/
14200
    0,              /*nb_multiply*/
14201
    unicode_mod,            /*nb_remainder*/
14202
};
14203
14204
static PySequenceMethods unicode_as_sequence = {
14205
    unicode_length,     /* sq_length */
14206
    PyUnicode_Concat,   /* sq_concat */
14207
    _PyUnicode_Repeat,  /* sq_repeat */
14208
    unicode_getitem,    /* sq_item */
14209
    0,                  /* sq_slice */
14210
    0,                  /* sq_ass_item */
14211
    0,                  /* sq_ass_slice */
14212
    PyUnicode_Contains, /* sq_contains */
14213
};
14214
14215
static PyObject*
14216
unicode_subscript(PyObject* self, PyObject* item)
14217
75.7M
{
14218
75.7M
    if (_PyIndex_Check(item)) {
14219
64.3M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
14220
64.3M
        if (i == -1 && PyErr_Occurred())
14221
0
            return NULL;
14222
64.3M
        if (i < 0)
14223
68.4k
            i += PyUnicode_GET_LENGTH(self);
14224
64.3M
        return unicode_getitem(self, i);
14225
64.3M
    } else if (PySlice_Check(item)) {
14226
11.3M
        Py_ssize_t start, stop, step, slicelength, i;
14227
11.3M
        size_t cur;
14228
11.3M
        PyObject *result;
14229
11.3M
        const void *src_data;
14230
11.3M
        void *dest_data;
14231
11.3M
        int src_kind, dest_kind;
14232
11.3M
        Py_UCS4 ch, max_char, kind_limit;
14233
14234
11.3M
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
14235
0
            return NULL;
14236
0
        }
14237
11.3M
        slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14238
11.3M
                                            &start, &stop, step);
14239
14240
11.3M
        if (slicelength <= 0) {
14241
1.11M
            _Py_RETURN_UNICODE_EMPTY();
14242
10.2M
        } else if (start == 0 && step == 1 &&
14243
283k
                   slicelength == PyUnicode_GET_LENGTH(self)) {
14244
2.28k
            return unicode_result_unchanged(self);
14245
10.2M
        } else if (step == 1) {
14246
10.2M
            return PyUnicode_Substring(self,
14247
10.2M
                                       start, start + slicelength);
14248
10.2M
        }
14249
        /* General case */
14250
0
        src_kind = PyUnicode_KIND(self);
14251
0
        src_data = PyUnicode_DATA(self);
14252
0
        if (!PyUnicode_IS_ASCII(self)) {
14253
0
            kind_limit = kind_maxchar_limit(src_kind);
14254
0
            max_char = 0;
14255
0
            for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14256
0
                ch = PyUnicode_READ(src_kind, src_data, cur);
14257
0
                if (ch > max_char) {
14258
0
                    max_char = ch;
14259
0
                    if (max_char >= kind_limit)
14260
0
                        break;
14261
0
                }
14262
0
            }
14263
0
        }
14264
0
        else
14265
0
            max_char = 127;
14266
0
        result = PyUnicode_New(slicelength, max_char);
14267
0
        if (result == NULL)
14268
0
            return NULL;
14269
0
        dest_kind = PyUnicode_KIND(result);
14270
0
        dest_data = PyUnicode_DATA(result);
14271
14272
0
        for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14273
0
            Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14274
0
            PyUnicode_WRITE(dest_kind, dest_data, i, ch);
14275
0
        }
14276
0
        assert(_PyUnicode_CheckConsistency(result, 1));
14277
0
        return result;
14278
0
    } else {
14279
0
        PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
14280
0
                     Py_TYPE(item)->tp_name);
14281
0
        return NULL;
14282
0
    }
14283
75.7M
}
14284
14285
static PyMappingMethods unicode_as_mapping = {
14286
    unicode_length,     /* mp_length */
14287
    unicode_subscript,  /* mp_subscript */
14288
    0,                  /* mp_ass_subscript */
14289
};
14290
14291
14292
static PyObject *
14293
unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
14294
14295
/*[clinic input]
14296
@classmethod
14297
str.__new__ as unicode_new
14298
14299
    object as x: object = NULL
14300
    encoding: str = NULL
14301
    errors: str = NULL
14302
14303
[clinic start generated code]*/
14304
14305
static PyObject *
14306
unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
14307
                 const char *errors)
14308
/*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
14309
22.8M
{
14310
22.8M
    PyObject *unicode;
14311
22.8M
    if (x == NULL) {
14312
0
        unicode = _PyUnicode_GetEmpty();
14313
0
    }
14314
22.8M
    else if (encoding == NULL && errors == NULL) {
14315
22.8M
        unicode = PyObject_Str(x);
14316
22.8M
    }
14317
0
    else {
14318
0
        unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
14319
0
    }
14320
14321
22.8M
    if (unicode != NULL && type != &PyUnicode_Type) {
14322
22.8M
        Py_SETREF(unicode, unicode_subtype_new(type, unicode));
14323
22.8M
    }
14324
22.8M
    return unicode;
14325
22.8M
}
14326
14327
static const char *
14328
arg_as_utf8(PyObject *obj, const char *name)
14329
19.5M
{
14330
19.5M
    if (!PyUnicode_Check(obj)) {
14331
0
        PyErr_Format(PyExc_TypeError,
14332
0
                     "str() argument '%s' must be str, not %T",
14333
0
                     name, obj);
14334
0
        return NULL;
14335
0
    }
14336
19.5M
    return _PyUnicode_AsUTF8NoNUL(obj);
14337
19.5M
}
14338
14339
static PyObject *
14340
unicode_vectorcall(PyObject *type, PyObject *const *args,
14341
                   size_t nargsf, PyObject *kwnames)
14342
18.7M
{
14343
18.7M
    assert(Py_Is(_PyType_CAST(type), &PyUnicode_Type));
14344
14345
18.7M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
14346
18.7M
    if (kwnames != NULL && PyTuple_GET_SIZE(kwnames) != 0) {
14347
        // Fallback to unicode_new()
14348
0
        PyObject *tuple = PyTuple_FromArray(args, nargs);
14349
0
        if (tuple == NULL) {
14350
0
            return NULL;
14351
0
        }
14352
0
        PyObject *dict = _PyStack_AsDict(args + nargs, kwnames);
14353
0
        if (dict == NULL) {
14354
0
            Py_DECREF(tuple);
14355
0
            return NULL;
14356
0
        }
14357
0
        PyObject *ret = unicode_new(_PyType_CAST(type), tuple, dict);
14358
0
        Py_DECREF(tuple);
14359
0
        Py_DECREF(dict);
14360
0
        return ret;
14361
0
    }
14362
18.7M
    if (!_PyArg_CheckPositional("str", nargs, 0, 3)) {
14363
0
        return NULL;
14364
0
    }
14365
18.7M
    if (nargs == 0) {
14366
4.50k
        return _PyUnicode_GetEmpty();
14367
4.50k
    }
14368
18.7M
    PyObject *object = args[0];
14369
18.7M
    if (nargs == 1) {
14370
1.05k
        return PyObject_Str(object);
14371
1.05k
    }
14372
18.7M
    const char *encoding = arg_as_utf8(args[1], "encoding");
14373
18.7M
    if (encoding == NULL) {
14374
0
        return NULL;
14375
0
    }
14376
18.7M
    const char *errors = NULL;
14377
18.7M
    if (nargs == 3) {
14378
769k
        errors = arg_as_utf8(args[2], "errors");
14379
769k
        if (errors == NULL) {
14380
0
            return NULL;
14381
0
        }
14382
769k
    }
14383
18.7M
    return PyUnicode_FromEncodedObject(object, encoding, errors);
14384
18.7M
}
14385
14386
static PyObject *
14387
unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
14388
22.8M
{
14389
22.8M
    PyObject *self;
14390
22.8M
    Py_ssize_t length, char_size;
14391
22.8M
    int share_utf8;
14392
22.8M
    int kind;
14393
22.8M
    void *data;
14394
14395
22.8M
    assert(PyType_IsSubtype(type, &PyUnicode_Type));
14396
22.8M
    assert(_PyUnicode_CHECK(unicode));
14397
14398
22.8M
    self = type->tp_alloc(type, 0);
14399
22.8M
    if (self == NULL) {
14400
0
        return NULL;
14401
0
    }
14402
22.8M
    kind = PyUnicode_KIND(unicode);
14403
22.8M
    length = PyUnicode_GET_LENGTH(unicode);
14404
14405
22.8M
    _PyUnicode_LENGTH(self) = length;
14406
#ifdef Py_DEBUG
14407
    _PyUnicode_HASH(self) = -1;
14408
#else
14409
22.8M
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14410
22.8M
#endif
14411
22.8M
    _PyUnicode_STATE(self).interned = 0;
14412
22.8M
    _PyUnicode_STATE(self).kind = kind;
14413
22.8M
    _PyUnicode_STATE(self).compact = 0;
14414
22.8M
    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
14415
22.8M
    _PyUnicode_STATE(self).statically_allocated = 0;
14416
22.8M
    PyUnicode_SET_UTF8_LENGTH(self, 0);
14417
22.8M
    PyUnicode_SET_UTF8(self, NULL);
14418
22.8M
    _PyUnicode_DATA_ANY(self) = NULL;
14419
14420
22.8M
    share_utf8 = 0;
14421
22.8M
    if (kind == PyUnicode_1BYTE_KIND) {
14422
19.5M
        char_size = 1;
14423
19.5M
        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14424
19.4M
            share_utf8 = 1;
14425
19.5M
    }
14426
3.28M
    else if (kind == PyUnicode_2BYTE_KIND) {
14427
3.21M
        char_size = 2;
14428
3.21M
    }
14429
68.6k
    else {
14430
68.6k
        assert(kind == PyUnicode_4BYTE_KIND);
14431
68.6k
        char_size = 4;
14432
68.6k
    }
14433
14434
    /* Ensure we won't overflow the length. */
14435
22.8M
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14436
0
        PyErr_NoMemory();
14437
0
        goto onError;
14438
0
    }
14439
22.8M
    data = PyMem_Malloc((length + 1) * char_size);
14440
22.8M
    if (data == NULL) {
14441
0
        PyErr_NoMemory();
14442
0
        goto onError;
14443
0
    }
14444
14445
22.8M
    _PyUnicode_DATA_ANY(self) = data;
14446
22.8M
    if (share_utf8) {
14447
19.4M
        PyUnicode_SET_UTF8_LENGTH(self, length);
14448
19.4M
        PyUnicode_SET_UTF8(self, data);
14449
19.4M
    }
14450
14451
22.8M
    memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
14452
22.8M
    assert(_PyUnicode_CheckConsistency(self, 1));
14453
#ifdef Py_DEBUG
14454
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14455
#endif
14456
22.8M
    return self;
14457
14458
0
onError:
14459
0
    Py_DECREF(self);
14460
0
    return NULL;
14461
22.8M
}
14462
14463
static _PyObjectIndexPair
14464
unicode_iteritem(PyObject *obj, Py_ssize_t index)
14465
68.3M
{
14466
68.3M
    if (index >= PyUnicode_GET_LENGTH(obj)) {
14467
13.2M
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
14468
13.2M
    }
14469
55.0M
    const void *data = PyUnicode_DATA(obj);
14470
55.0M
    int kind = PyUnicode_KIND(obj);
14471
55.0M
    Py_UCS4 ch = PyUnicode_READ(kind, data, index);
14472
55.0M
    PyObject *result = unicode_char(ch);
14473
55.0M
    index = (result == NULL) ? -1 : index + 1;
14474
55.0M
    return (_PyObjectIndexPair) { .object = result, .index = index };
14475
68.3M
}
14476
14477
void
14478
_PyUnicode_ExactDealloc(PyObject *op)
14479
103M
{
14480
103M
    assert(PyUnicode_CheckExact(op));
14481
103M
    unicode_dealloc(op);
14482
103M
}
14483
14484
PyDoc_STRVAR(unicode_doc,
14485
"str(object='') -> str\n\
14486
str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
14487
\n\
14488
Create a new string object from the given object. If encoding or\n\
14489
errors is specified, then the object must expose a data buffer\n\
14490
that will be decoded using the given encoding and error handler.\n\
14491
Otherwise, returns the result of object.__str__() (if defined)\n\
14492
or repr(object).\n\
14493
encoding defaults to 'utf-8'.\n\
14494
errors defaults to 'strict'.");
14495
14496
static PyObject *unicode_iter(PyObject *seq);
14497
14498
PyTypeObject PyUnicode_Type = {
14499
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
14500
    "str",                        /* tp_name */
14501
    sizeof(PyUnicodeObject),      /* tp_basicsize */
14502
    0,                            /* tp_itemsize */
14503
    /* Slots */
14504
    unicode_dealloc,              /* tp_dealloc */
14505
    0,                            /* tp_vectorcall_offset */
14506
    0,                            /* tp_getattr */
14507
    0,                            /* tp_setattr */
14508
    0,                            /* tp_as_async */
14509
    unicode_repr,                 /* tp_repr */
14510
    &unicode_as_number,           /* tp_as_number */
14511
    &unicode_as_sequence,         /* tp_as_sequence */
14512
    &unicode_as_mapping,          /* tp_as_mapping */
14513
    unicode_hash,                 /* tp_hash*/
14514
    0,                            /* tp_call*/
14515
    unicode_str,                  /* tp_str */
14516
    PyObject_GenericGetAttr,      /* tp_getattro */
14517
    0,                            /* tp_setattro */
14518
    0,                            /* tp_as_buffer */
14519
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
14520
        Py_TPFLAGS_UNICODE_SUBCLASS |
14521
        _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
14522
    unicode_doc,                  /* tp_doc */
14523
    0,                            /* tp_traverse */
14524
    0,                            /* tp_clear */
14525
    PyUnicode_RichCompare,        /* tp_richcompare */
14526
    0,                            /* tp_weaklistoffset */
14527
    unicode_iter,                 /* tp_iter */
14528
    0,                            /* tp_iternext */
14529
    unicode_methods,              /* tp_methods */
14530
    0,                            /* tp_members */
14531
    0,                            /* tp_getset */
14532
    0,                            /* tp_base */
14533
    0,                            /* tp_dict */
14534
    0,                            /* tp_descr_get */
14535
    0,                            /* tp_descr_set */
14536
    0,                            /* tp_dictoffset */
14537
    0,                            /* tp_init */
14538
    0,                            /* tp_alloc */
14539
    unicode_new,                  /* tp_new */
14540
    PyObject_Free,                /* tp_free */
14541
    .tp_version_tag = _Py_TYPE_VERSION_STR,
14542
    .tp_vectorcall = unicode_vectorcall,
14543
    ._tp_iteritem = unicode_iteritem,
14544
};
14545
14546
/* Initialize the Unicode implementation */
14547
14548
static void
14549
_init_global_state(void)
14550
37
{
14551
37
    static int initialized = 0;
14552
37
    if (initialized) {
14553
0
        return;
14554
0
    }
14555
37
    initialized = 1;
14556
14557
    /* initialize the linebreak bloom filter */
14558
37
    const Py_UCS2 linebreak[] = {
14559
37
        0x000A, /* LINE FEED */
14560
37
        0x000D, /* CARRIAGE RETURN */
14561
37
        0x001C, /* FILE SEPARATOR */
14562
37
        0x001D, /* GROUP SEPARATOR */
14563
37
        0x001E, /* RECORD SEPARATOR */
14564
37
        0x0085, /* NEXT LINE */
14565
37
        0x2028, /* LINE SEPARATOR */
14566
37
        0x2029, /* PARAGRAPH SEPARATOR */
14567
37
    };
14568
37
    bloom_linebreak = make_bloom_mask(
14569
37
        PyUnicode_2BYTE_KIND, linebreak,
14570
37
        Py_ARRAY_LENGTH(linebreak));
14571
37
}
14572
14573
void
14574
_PyUnicode_InitState(PyInterpreterState *interp)
14575
37
{
14576
37
    if (!_Py_IsMainInterpreter(interp)) {
14577
0
        return;
14578
0
    }
14579
37
    _init_global_state();
14580
37
}
14581
14582
14583
PyStatus
14584
_PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
14585
37
{
14586
37
    if (_Py_IsMainInterpreter(interp)) {
14587
37
        PyStatus status = init_global_interned_strings(interp);
14588
37
        if (_PyStatus_EXCEPTION(status)) {
14589
0
            return status;
14590
0
        }
14591
37
    }
14592
37
    assert(INTERNED_STRINGS);
14593
14594
37
    if (init_interned_dict(interp)) {
14595
0
        PyErr_Clear();
14596
0
        return _PyStatus_ERR("failed to create interned dict");
14597
0
    }
14598
14599
37
    return _PyStatus_OK();
14600
37
}
14601
14602
14603
PyStatus
14604
_PyUnicode_InitTypes(PyInterpreterState *interp)
14605
37
{
14606
37
    if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
14607
0
        goto error;
14608
0
    }
14609
37
    if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
14610
0
        goto error;
14611
0
    }
14612
37
    if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
14613
0
        goto error;
14614
0
    }
14615
37
    return _PyStatus_OK();
14616
14617
0
error:
14618
0
    return _PyStatus_ERR("Can't initialize unicode types");
14619
37
}
14620
14621
static /* non-null */ PyObject*
14622
intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
14623
43.1k
{
14624
    // Note that this steals a reference to `s`, but in many cases that
14625
    // stolen ref is returned, requiring no decref/incref.
14626
14627
43.1k
    assert(s != NULL);
14628
43.1k
    assert(_PyUnicode_CHECK(s));
14629
43.1k
    assert(_PyUnicode_STATE(s).statically_allocated);
14630
43.1k
    assert(!PyUnicode_CHECK_INTERNED(s));
14631
14632
#ifdef Py_DEBUG
14633
    /* We must not add process-global interned string if there's already a
14634
     * per-interpreter interned_dict, which might contain duplicates.
14635
     */
14636
    PyObject *interned = get_interned_dict(interp);
14637
    assert(interned == NULL);
14638
#endif
14639
14640
    /* Look in the global cache first. */
14641
43.1k
    PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14642
    /* We should only init each string once */
14643
43.1k
    assert(r == NULL);
14644
    /* but just in case (for the non-debug build), handle this */
14645
43.1k
    if (r != NULL && r != s) {
14646
0
        assert(_PyUnicode_STATE(r).interned == SSTATE_INTERNED_IMMORTAL_STATIC);
14647
0
        assert(_PyUnicode_CHECK(r));
14648
0
        Py_DECREF(s);
14649
0
        return Py_NewRef(r);
14650
0
    }
14651
14652
43.1k
    if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < 0) {
14653
0
        Py_FatalError("failed to intern static string");
14654
0
    }
14655
14656
43.1k
    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
14657
43.1k
    return s;
14658
43.1k
}
14659
14660
void
14661
_PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
14662
43.1k
{
14663
    // This should only be called as part of runtime initialization
14664
43.1k
    assert(!Py_IsInitialized());
14665
14666
43.1k
    *p = intern_static(interp, *p);
14667
43.1k
    assert(*p);
14668
43.1k
}
14669
14670
static void
14671
immortalize_interned(PyObject *s)
14672
281k
{
14673
281k
    assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
14674
281k
    assert(!_Py_IsImmortal(s));
14675
#ifdef Py_REF_DEBUG
14676
    /* The reference count value should be excluded from the RefTotal.
14677
       The decrements to these objects will not be registered so they
14678
       need to be accounted for in here. */
14679
    for (Py_ssize_t i = 0; i < Py_REFCNT(s); i++) {
14680
        _Py_DecRefTotal(_PyThreadState_GET());
14681
    }
14682
#endif
14683
281k
    _Py_SetImmortal(s);
14684
    // The switch to SSTATE_INTERNED_IMMORTAL must be the last thing done here
14685
    // to synchronize with the check in intern_common() that avoids locking if
14686
    // the string is already immortal.
14687
281k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_IMMORTAL);
14688
281k
}
14689
14690
#ifdef Py_GIL_DISABLED
14691
static bool
14692
can_immortalize_safely(PyObject *s)
14693
{
14694
    if (_Py_IsOwnedByCurrentThread(s) || _Py_IsImmortal(s)) {
14695
        return true;
14696
    }
14697
    Py_ssize_t shared = _Py_atomic_load_ssize(&s->ob_ref_shared);
14698
    return _Py_REF_IS_MERGED(shared);
14699
}
14700
#endif
14701
14702
static /* non-null */ PyObject*
14703
intern_common(PyInterpreterState *interp, PyObject *s /* stolen */,
14704
              bool immortalize)
14705
126M
{
14706
    // Note that this steals a reference to `s`, but in many cases that
14707
    // stolen ref is returned, requiring no decref/incref.
14708
14709
#ifdef Py_DEBUG
14710
    assert(s != NULL);
14711
    assert(_PyUnicode_CHECK(s));
14712
#else
14713
126M
    if (s == NULL || !PyUnicode_Check(s)) {
14714
0
        return s;
14715
0
    }
14716
126M
#endif
14717
14718
    /* If it's a subclass, we don't really know what putting
14719
       it in the interned dict might do. */
14720
126M
    if (!PyUnicode_CheckExact(s)) {
14721
0
        return s;
14722
0
    }
14723
14724
    /* Is it already interned? */
14725
126M
    switch (PyUnicode_CHECK_INTERNED(s)) {
14726
7.27M
        case SSTATE_NOT_INTERNED:
14727
            // no, go on
14728
7.27M
            break;
14729
23.7k
        case SSTATE_INTERNED_MORTAL:
14730
23.7k
#ifndef Py_GIL_DISABLED
14731
            // yes but we might need to make it immortal
14732
23.7k
            if (immortalize) {
14733
2.29k
                immortalize_interned(s);
14734
2.29k
            }
14735
23.7k
            return s;
14736
#else
14737
            // not fully interned yet; fall through to the locking path
14738
            break;
14739
#endif
14740
119M
        default:
14741
            // all done
14742
119M
            return s;
14743
126M
    }
14744
14745
    /* Statically allocated strings must be already interned. */
14746
126M
    assert(!_PyUnicode_STATE(s).statically_allocated);
14747
14748
#ifdef Py_GIL_DISABLED
14749
    /* In the free-threaded build, all interned strings are immortal */
14750
    immortalize = 1;
14751
#endif
14752
14753
    /* If it's already immortal, intern it as such */
14754
7.27M
    if (_Py_IsImmortal(s)) {
14755
0
        immortalize = 1;
14756
0
    }
14757
14758
    /* if it's a short string, get the singleton */
14759
7.27M
    if (PyUnicode_GET_LENGTH(s) == 1 &&
14760
6.71k
                PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) {
14761
0
        PyObject *r = LATIN1(*(unsigned char*)PyUnicode_DATA(s));
14762
0
        assert(PyUnicode_CHECK_INTERNED(r));
14763
0
        Py_DECREF(s);
14764
0
        return r;
14765
0
    }
14766
#ifdef Py_DEBUG
14767
    assert(!unicode_is_singleton(s));
14768
#endif
14769
14770
    /* Look in the global cache now. */
14771
7.27M
    {
14772
7.27M
        PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14773
7.27M
        if (r != NULL) {
14774
244k
            assert(_PyUnicode_STATE(r).statically_allocated);
14775
244k
            assert(r != s);  // r must be statically_allocated; s is not
14776
244k
            Py_DECREF(s);
14777
244k
            return Py_NewRef(r);
14778
244k
        }
14779
7.27M
    }
14780
14781
    /* Do a setdefault on the per-interpreter cache. */
14782
7.02M
    PyObject *interned = get_interned_dict(interp);
14783
7.02M
    assert(interned != NULL);
14784
#ifdef Py_GIL_DISABLED
14785
#  define INTERN_MUTEX &_Py_INTERP_CACHED_OBJECT(interp, interned_mutex)
14786
    // Lock-free fast path: check if there's already an interned copy that
14787
    // is in its final immortal state.
14788
    PyObject *r;
14789
    int res = PyDict_GetItemRef(interned, s, &r);
14790
    if (res < 0) {
14791
        PyErr_Clear();
14792
        return s;
14793
    }
14794
    if (res > 0) {
14795
        unsigned int state = _Py_atomic_load_uint8(&_PyUnicode_STATE(r).interned);
14796
        if (state == SSTATE_INTERNED_IMMORTAL) {
14797
            Py_DECREF(s);
14798
            return r;
14799
        }
14800
        // Not yet fully interned; fall through to the locking path.
14801
        Py_DECREF(r);
14802
    }
14803
#endif
14804
14805
#ifdef Py_GIL_DISABLED
14806
    // Immortalization writes to the refcount fields non-atomically. That
14807
    // races with Py_INCREF / Py_DECREF on the thread that owns `s`. If we
14808
    // don't own it (and its refcount hasn't been merged), intern a copy
14809
    // we own instead.
14810
    if (!can_immortalize_safely(s)) {
14811
        PyObject *copy = _PyUnicode_Copy(s);
14812
        if (copy == NULL) {
14813
            PyErr_Clear();
14814
            return s;
14815
        }
14816
        Py_DECREF(s);
14817
        s = copy;
14818
    }
14819
#endif
14820
14821
    // Why _Py_LOCK_DONT_DETACH is used here: waiting for the interned mutex
14822
    // must not detach the thread state. Extension code is expected to
14823
    // detach before blocking on opaque external synchronization. However,
14824
    // the lock used for C++ static initialization is hidden, making
14825
    // that difficult, and it is common for C++ extensions to call
14826
    // PyUnicode_InternFromString() from static initializers. Detaching here
14827
    // can therefore deadlock: a stop-the-world pause may prevent the lock
14828
    // owner from reattaching while the pause waits for another attached
14829
    // thread blocked on the hidden lock.
14830
7.02M
    FT_MUTEX_LOCK_FLAGS(INTERN_MUTEX, _Py_LOCK_DONT_DETACH);
14831
7.02M
    PyObject *t;
14832
7.02M
    {
14833
7.02M
        int res = PyDict_SetDefaultRef(interned, s, s, &t);
14834
7.02M
        if (res < 0) {
14835
0
            PyErr_Clear();
14836
0
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14837
0
            return s;
14838
0
        }
14839
7.02M
        else if (res == 1) {
14840
            // value was already present (not inserted)
14841
6.56M
            Py_DECREF(s);
14842
6.56M
            if (immortalize &&
14843
155k
                    PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
14844
9.40k
                immortalize_interned(t);
14845
9.40k
            }
14846
6.56M
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14847
6.56M
            return t;
14848
6.56M
        }
14849
460k
        else {
14850
            // value was newly inserted
14851
460k
            assert (s == t);
14852
460k
            Py_DECREF(t);
14853
460k
        }
14854
7.02M
    }
14855
14856
    /* NOT_INTERNED -> INTERNED_MORTAL */
14857
14858
7.02M
    assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
14859
14860
460k
    if (!_Py_IsImmortal(s)) {
14861
        /* The two references in interned dict (key and value) are not counted.
14862
        unicode_dealloc() and _PyUnicode_ClearInterned() take care of this. */
14863
460k
        Py_DECREF(s);
14864
460k
        Py_DECREF(s);
14865
460k
    }
14866
460k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_MORTAL);
14867
14868
    /* INTERNED_MORTAL -> INTERNED_IMMORTAL (if needed) */
14869
14870
#ifdef Py_DEBUG
14871
    if (_Py_IsImmortal(s)) {
14872
        assert(immortalize);
14873
    }
14874
#endif
14875
460k
    if (immortalize) {
14876
269k
        immortalize_interned(s);
14877
269k
    }
14878
14879
460k
    FT_MUTEX_UNLOCK(INTERN_MUTEX);
14880
460k
    return s;
14881
7.02M
}
14882
14883
void
14884
_PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
14885
1.59M
{
14886
1.59M
    *p = intern_common(interp, *p, 1);
14887
1.59M
    assert(*p);
14888
1.59M
}
14889
14890
void
14891
_PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
14892
125M
{
14893
125M
    *p = intern_common(interp, *p, 0);
14894
125M
    assert(*p);
14895
125M
}
14896
14897
14898
void
14899
_PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
14900
0
{
14901
0
    _PyUnicode_InternImmortal(interp, p);
14902
0
    return;
14903
0
}
14904
14905
void
14906
PyUnicode_InternInPlace(PyObject **p)
14907
8
{
14908
8
    PyInterpreterState *interp = _PyInterpreterState_GET();
14909
8
    _PyUnicode_InternMortal(interp, p);
14910
8
}
14911
14912
// Public-looking name kept for the stable ABI; user should not call this:
14913
PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
14914
void
14915
PyUnicode_InternImmortal(PyObject **p)
14916
0
{
14917
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14918
0
    _PyUnicode_InternImmortal(interp, p);
14919
0
}
14920
14921
PyObject *
14922
PyUnicode_InternFromString(const char *cp)
14923
1.02M
{
14924
1.02M
    PyObject *s = PyUnicode_FromString(cp);
14925
1.02M
    if (s == NULL) {
14926
0
        return NULL;
14927
0
    }
14928
1.02M
    PyInterpreterState *interp = _PyInterpreterState_GET();
14929
1.02M
    _PyUnicode_InternMortal(interp, &s);
14930
1.02M
    return s;
14931
1.02M
}
14932
14933
14934
void
14935
_PyUnicode_ClearInterned(PyInterpreterState *interp)
14936
0
{
14937
0
    PyObject *interned = get_interned_dict(interp);
14938
0
    if (interned == NULL) {
14939
0
        return;
14940
0
    }
14941
0
    assert(PyDict_CheckExact(interned));
14942
14943
0
    if (has_shared_intern_dict(interp)) {
14944
        // the dict doesn't belong to this interpreter, skip the debug
14945
        // checks on it and just clear the pointer to it
14946
0
        clear_interned_dict(interp);
14947
0
        return;
14948
0
    }
14949
14950
#ifdef INTERNED_STATS
14951
    fprintf(stderr, "releasing %zd interned strings\n",
14952
            PyDict_GET_SIZE(interned));
14953
14954
    Py_ssize_t total_length = 0;
14955
#endif
14956
0
    Py_ssize_t pos = 0;
14957
0
    PyObject *s, *ignored_value;
14958
0
    while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
14959
0
        int shared = 0;
14960
0
        switch (PyUnicode_CHECK_INTERNED(s)) {
14961
0
        case SSTATE_INTERNED_IMMORTAL:
14962
            /* Make immortal interned strings mortal again. */
14963
            // Skip the Immortal Instance check and restore
14964
            // the two references (key and value) ignored
14965
            // by PyUnicode_InternInPlace().
14966
0
            _Py_SetMortal(s, 2);
14967
#ifdef Py_REF_DEBUG
14968
            /* let's be pedantic with the ref total */
14969
            _Py_IncRefTotal(_PyThreadState_GET());
14970
            _Py_IncRefTotal(_PyThreadState_GET());
14971
#endif
14972
#ifdef INTERNED_STATS
14973
            total_length += PyUnicode_GET_LENGTH(s);
14974
#endif
14975
0
            break;
14976
0
        case SSTATE_INTERNED_IMMORTAL_STATIC:
14977
            /* It is shared between interpreters, so we should unmark it
14978
               only when this is the last interpreter in which it's
14979
               interned.  We immortalize all the statically initialized
14980
               strings during startup, so we can rely on the
14981
               main interpreter to be the last one. */
14982
0
            if (!_Py_IsMainInterpreter(interp)) {
14983
0
                shared = 1;
14984
0
            }
14985
0
            break;
14986
0
        case SSTATE_INTERNED_MORTAL:
14987
            // Restore 2 references held by the interned dict; these will
14988
            // be decref'd by clear_interned_dict's PyDict_Clear.
14989
0
            _Py_RefcntAdd(s, 2);
14990
#ifdef Py_REF_DEBUG
14991
            /* let's be pedantic with the ref total */
14992
            _Py_IncRefTotal(_PyThreadState_GET());
14993
            _Py_IncRefTotal(_PyThreadState_GET());
14994
#endif
14995
0
            break;
14996
0
        case SSTATE_NOT_INTERNED:
14997
0
            _Py_FALLTHROUGH;
14998
0
        default:
14999
0
            Py_UNREACHABLE();
15000
0
        }
15001
0
        if (!shared) {
15002
0
            FT_ATOMIC_STORE_UINT8_RELAXED(_PyUnicode_STATE(s).interned, SSTATE_NOT_INTERNED);
15003
0
        }
15004
0
    }
15005
#ifdef INTERNED_STATS
15006
    fprintf(stderr,
15007
            "total length of all interned strings: %zd characters\n",
15008
            total_length);
15009
#endif
15010
15011
0
    struct _Py_unicode_state *state = &interp->unicode;
15012
0
    struct _Py_unicode_ids *ids = &state->ids;
15013
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
15014
0
        Py_XINCREF(ids->array[i]);
15015
0
    }
15016
0
    clear_interned_dict(interp);
15017
0
    if (_Py_IsMainInterpreter(interp)) {
15018
0
        clear_global_interned_strings();
15019
0
    }
15020
0
}
15021
15022
15023
/********************* Unicode Iterator **************************/
15024
15025
typedef struct {
15026
    PyObject_HEAD
15027
    Py_ssize_t it_index;
15028
    PyObject *it_seq;    /* Set to NULL when iterator is exhausted */
15029
} unicodeiterobject;
15030
15031
static void
15032
unicodeiter_dealloc(PyObject *op)
15033
3.67M
{
15034
3.67M
    unicodeiterobject *it = (unicodeiterobject *)op;
15035
3.67M
    _PyObject_GC_UNTRACK(it);
15036
3.67M
    Py_XDECREF(it->it_seq);
15037
3.67M
    PyObject_GC_Del(it);
15038
3.67M
}
15039
15040
static int
15041
unicodeiter_traverse(PyObject *op, visitproc visit, void *arg)
15042
22
{
15043
22
    unicodeiterobject *it = (unicodeiterobject *)op;
15044
22
    Py_VISIT(it->it_seq);
15045
22
    return 0;
15046
22
}
15047
15048
static PyObject *
15049
unicodeiter_next(PyObject *op)
15050
175M
{
15051
175M
    unicodeiterobject *it = (unicodeiterobject *)op;
15052
175M
    PyObject *seq;
15053
15054
175M
    assert(it != NULL);
15055
175M
    seq = it->it_seq;
15056
175M
    if (seq == NULL)
15057
0
        return NULL;
15058
175M
    assert(_PyUnicode_CHECK(seq));
15059
15060
175M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15061
174M
        int kind = PyUnicode_KIND(seq);
15062
174M
        const void *data = PyUnicode_DATA(seq);
15063
174M
        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15064
174M
        it->it_index++;
15065
174M
        return unicode_char(chr);
15066
174M
    }
15067
15068
1.84M
    it->it_seq = NULL;
15069
1.84M
    Py_DECREF(seq);
15070
1.84M
    return NULL;
15071
175M
}
15072
15073
static PyObject *
15074
unicode_ascii_iter_next(PyObject *op)
15075
11.5M
{
15076
11.5M
    unicodeiterobject *it = (unicodeiterobject *)op;
15077
11.5M
    assert(it != NULL);
15078
11.5M
    PyObject *seq = it->it_seq;
15079
11.5M
    if (seq == NULL) {
15080
0
        return NULL;
15081
0
    }
15082
11.5M
    assert(_PyUnicode_CHECK(seq));
15083
11.5M
    assert(PyUnicode_IS_COMPACT_ASCII(seq));
15084
11.5M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15085
9.70M
        const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
15086
9.70M
        Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
15087
9.70M
                                              data, it->it_index);
15088
9.70M
        it->it_index++;
15089
9.70M
        return (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
15090
9.70M
    }
15091
1.81M
    it->it_seq = NULL;
15092
1.81M
    Py_DECREF(seq);
15093
1.81M
    return NULL;
15094
11.5M
}
15095
15096
static PyObject *
15097
unicodeiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
15098
2.01M
{
15099
2.01M
    unicodeiterobject *it = (unicodeiterobject *)op;
15100
2.01M
    Py_ssize_t len = 0;
15101
2.01M
    if (it->it_seq)
15102
2.01M
        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
15103
2.01M
    return PyLong_FromSsize_t(len);
15104
2.01M
}
15105
15106
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15107
15108
static PyObject *
15109
unicodeiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
15110
0
{
15111
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15112
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
15113
15114
    /* _PyEval_GetBuiltin can invoke arbitrary code,
15115
     * call must be before access of iterator pointers.
15116
     * see issue #101765 */
15117
15118
0
    if (it->it_seq != NULL) {
15119
0
        return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
15120
0
    } else {
15121
0
        PyObject *u = _PyUnicode_GetEmpty();
15122
0
        if (u == NULL) {
15123
0
            Py_XDECREF(iter);
15124
0
            return NULL;
15125
0
        }
15126
0
        return Py_BuildValue("N(N)", iter, u);
15127
0
    }
15128
0
}
15129
15130
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15131
15132
static PyObject *
15133
unicodeiter_setstate(PyObject *op, PyObject *state)
15134
0
{
15135
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15136
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
15137
0
    if (index == -1 && PyErr_Occurred())
15138
0
        return NULL;
15139
0
    if (it->it_seq != NULL) {
15140
0
        if (index < 0)
15141
0
            index = 0;
15142
0
        else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15143
0
            index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15144
0
        it->it_index = index;
15145
0
    }
15146
0
    Py_RETURN_NONE;
15147
0
}
15148
15149
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15150
15151
static PyMethodDef unicodeiter_methods[] = {
15152
    {"__length_hint__", unicodeiter_len, METH_NOARGS, length_hint_doc},
15153
    {"__reduce__",      unicodeiter_reduce, METH_NOARGS, reduce_doc},
15154
    {"__setstate__",    unicodeiter_setstate, METH_O, setstate_doc},
15155
    {NULL,      NULL}       /* sentinel */
15156
};
15157
15158
PyTypeObject PyUnicodeIter_Type = {
15159
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15160
    "str_iterator",         /* tp_name */
15161
    sizeof(unicodeiterobject),      /* tp_basicsize */
15162
    0,                  /* tp_itemsize */
15163
    /* methods */
15164
    unicodeiter_dealloc,/* tp_dealloc */
15165
    0,                  /* tp_vectorcall_offset */
15166
    0,                  /* tp_getattr */
15167
    0,                  /* tp_setattr */
15168
    0,                  /* tp_as_async */
15169
    0,                  /* tp_repr */
15170
    0,                  /* tp_as_number */
15171
    0,                  /* tp_as_sequence */
15172
    0,                  /* tp_as_mapping */
15173
    0,                  /* tp_hash */
15174
    0,                  /* tp_call */
15175
    0,                  /* tp_str */
15176
    PyObject_GenericGetAttr,        /* tp_getattro */
15177
    0,                  /* tp_setattro */
15178
    0,                  /* tp_as_buffer */
15179
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15180
    0,                  /* tp_doc */
15181
    unicodeiter_traverse, /* tp_traverse */
15182
    0,                  /* tp_clear */
15183
    0,                  /* tp_richcompare */
15184
    0,                  /* tp_weaklistoffset */
15185
    PyObject_SelfIter,          /* tp_iter */
15186
    unicodeiter_next,   /* tp_iternext */
15187
    unicodeiter_methods,            /* tp_methods */
15188
    0,
15189
};
15190
15191
PyTypeObject _PyUnicodeASCIIIter_Type = {
15192
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15193
    .tp_name = "str_ascii_iterator",
15194
    .tp_basicsize = sizeof(unicodeiterobject),
15195
    .tp_dealloc = unicodeiter_dealloc,
15196
    .tp_getattro = PyObject_GenericGetAttr,
15197
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
15198
    .tp_traverse = unicodeiter_traverse,
15199
    .tp_iter = PyObject_SelfIter,
15200
    .tp_iternext = unicode_ascii_iter_next,
15201
    .tp_methods = unicodeiter_methods,
15202
};
15203
15204
static PyObject *
15205
unicode_iter(PyObject *seq)
15206
3.67M
{
15207
3.67M
    unicodeiterobject *it;
15208
15209
3.67M
    if (!PyUnicode_Check(seq)) {
15210
0
        PyErr_BadInternalCall();
15211
0
        return NULL;
15212
0
    }
15213
3.67M
    if (PyUnicode_IS_COMPACT_ASCII(seq)) {
15214
1.83M
        it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
15215
1.83M
    }
15216
1.84M
    else {
15217
1.84M
        it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15218
1.84M
    }
15219
3.67M
    if (it == NULL)
15220
0
        return NULL;
15221
3.67M
    it->it_index = 0;
15222
3.67M
    it->it_seq = Py_NewRef(seq);
15223
3.67M
    _PyObject_GC_TRACK(it);
15224
3.67M
    return (PyObject *)it;
15225
3.67M
}
15226
15227
static int
15228
encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
15229
148
{
15230
148
    assert(str != NULL);
15231
15232
148
    size_t unused_output_length;
15233
148
    int res = _Py_EncodeUTF8(wstr, str, &unused_output_length,
15234
148
                             NULL, 1, _Py_ERROR_STRICT);
15235
148
    if (res == -2) {
15236
0
        PyErr_Format(PyExc_RuntimeError, "cannot encode %s", name);
15237
0
        return -1;
15238
0
    }
15239
148
    if (res < 0) {
15240
0
        PyErr_NoMemory();
15241
0
        return -1;
15242
0
    }
15243
148
    return 0;
15244
148
}
15245
15246
15247
static int
15248
config_get_codec_name(wchar_t **config_encoding)
15249
74
{
15250
74
    char *encoding;
15251
74
    if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15252
0
        return -1;
15253
0
    }
15254
15255
74
    PyObject *name_obj = NULL;
15256
74
    PyObject *codec = _PyCodec_Lookup(encoding);
15257
74
    PyMem_RawFree(encoding);
15258
15259
74
    if (!codec)
15260
0
        goto error;
15261
15262
74
    name_obj = PyObject_GetAttrString(codec, "name");
15263
74
    Py_CLEAR(codec);
15264
74
    if (!name_obj) {
15265
0
        goto error;
15266
0
    }
15267
15268
74
    wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
15269
74
    Py_DECREF(name_obj);
15270
74
    if (wname == NULL) {
15271
0
        goto error;
15272
0
    }
15273
15274
74
    wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
15275
74
    if (raw_wname == NULL) {
15276
0
        PyMem_Free(wname);
15277
0
        PyErr_NoMemory();
15278
0
        goto error;
15279
0
    }
15280
15281
74
    PyMem_RawFree(*config_encoding);
15282
74
    *config_encoding = raw_wname;
15283
15284
74
    PyMem_Free(wname);
15285
74
    return 0;
15286
15287
0
error:
15288
0
    Py_XDECREF(codec);
15289
0
    Py_XDECREF(name_obj);
15290
0
    return -1;
15291
74
}
15292
15293
15294
static PyStatus
15295
init_stdio_encoding(PyInterpreterState *interp)
15296
37
{
15297
    /* Update the stdio encoding to the normalized Python codec name. */
15298
37
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15299
37
    if (config->stdio_encoding == NULL) {
15300
        /* gh-86427: The encoding is determined for every stream. */
15301
0
        return _PyStatus_OK();
15302
0
    }
15303
37
    if (config_get_codec_name(&config->stdio_encoding) < 0) {
15304
0
        return _PyStatus_ERR("failed to get the Python codec name "
15305
0
                             "of the stdio encoding");
15306
0
    }
15307
37
    return _PyStatus_OK();
15308
37
}
15309
15310
15311
static int
15312
init_fs_codec(PyInterpreterState *interp)
15313
37
{
15314
37
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
15315
15316
37
    _Py_error_handler error_handler;
15317
37
    error_handler = get_error_handler_wide(config->filesystem_errors);
15318
37
    if (error_handler == _Py_ERROR_UNKNOWN) {
15319
0
        PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
15320
0
        return -1;
15321
0
    }
15322
15323
37
    char *encoding, *errors;
15324
37
    if (encode_wstr_utf8(config->filesystem_encoding,
15325
37
                         &encoding,
15326
37
                         "filesystem_encoding") < 0) {
15327
0
        return -1;
15328
0
    }
15329
15330
37
    if (encode_wstr_utf8(config->filesystem_errors,
15331
37
                         &errors,
15332
37
                         "filesystem_errors") < 0) {
15333
0
        PyMem_RawFree(encoding);
15334
0
        return -1;
15335
0
    }
15336
15337
37
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
15338
37
    PyMem_RawFree(fs_codec->encoding);
15339
37
    fs_codec->encoding = encoding;
15340
    /* encoding has been normalized by init_fs_encoding() */
15341
37
    fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
15342
37
    PyMem_RawFree(fs_codec->errors);
15343
37
    fs_codec->errors = errors;
15344
37
    fs_codec->error_handler = error_handler;
15345
15346
#ifdef _Py_FORCE_UTF8_FS_ENCODING
15347
    assert(fs_codec->utf8 == 1);
15348
#endif
15349
15350
    /* At this point, PyUnicode_EncodeFSDefault() and
15351
       PyUnicode_DecodeFSDefault() can now use the Python codec rather than
15352
       the C implementation of the filesystem encoding. */
15353
15354
    /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
15355
       global configuration variables. */
15356
37
    if (_Py_IsMainInterpreter(interp)) {
15357
15358
37
        if (_Py_SetFileSystemEncoding(fs_codec->encoding,
15359
37
                                      fs_codec->errors) < 0) {
15360
0
            PyErr_NoMemory();
15361
0
            return -1;
15362
0
        }
15363
37
    }
15364
37
    return 0;
15365
37
}
15366
15367
15368
static PyStatus
15369
init_fs_encoding(PyThreadState *tstate)
15370
37
{
15371
37
    PyInterpreterState *interp = tstate->interp;
15372
15373
    /* Update the filesystem encoding to the normalized Python codec name.
15374
       For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
15375
       (Python codec name). */
15376
37
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15377
37
    if (config_get_codec_name(&config->filesystem_encoding) < 0) {
15378
0
        _Py_DumpPathConfig(tstate);
15379
0
        return _PyStatus_ERR("failed to get the Python codec "
15380
0
                             "of the filesystem encoding");
15381
0
    }
15382
15383
37
    if (init_fs_codec(interp) < 0) {
15384
0
        return _PyStatus_ERR("cannot initialize filesystem codec");
15385
0
    }
15386
37
    return _PyStatus_OK();
15387
37
}
15388
15389
15390
PyStatus
15391
_PyUnicode_InitEncodings(PyThreadState *tstate)
15392
37
{
15393
37
    PyStatus status = _PyCodec_InitRegistry(tstate->interp);
15394
37
    if (_PyStatus_EXCEPTION(status)) {
15395
0
        return status;
15396
0
    }
15397
37
    status = init_fs_encoding(tstate);
15398
37
    if (_PyStatus_EXCEPTION(status)) {
15399
0
        return status;
15400
0
    }
15401
15402
37
    return init_stdio_encoding(tstate->interp);
15403
37
}
15404
15405
15406
static void
15407
_PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
15408
0
{
15409
0
    PyMem_RawFree(fs_codec->encoding);
15410
0
    fs_codec->encoding = NULL;
15411
0
    fs_codec->utf8 = 0;
15412
0
    PyMem_RawFree(fs_codec->errors);
15413
0
    fs_codec->errors = NULL;
15414
0
    fs_codec->error_handler = _Py_ERROR_UNKNOWN;
15415
0
}
15416
15417
15418
#ifdef Py_DEBUG
15419
static inline int
15420
unicode_is_finalizing(void)
15421
{
15422
    return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
15423
}
15424
#endif
15425
15426
15427
void
15428
_PyUnicode_FiniTypes(PyInterpreterState *interp)
15429
0
{
15430
0
    _PyStaticType_FiniBuiltin(interp, &EncodingMapType);
15431
0
    _PyStaticType_FiniBuiltin(interp, &PyFieldNameIter_Type);
15432
0
    _PyStaticType_FiniBuiltin(interp, &PyFormatterIter_Type);
15433
0
}
15434
15435
15436
void
15437
_PyUnicode_Fini(PyInterpreterState *interp)
15438
0
{
15439
0
    struct _Py_unicode_state *state = &interp->unicode;
15440
15441
0
    if (!has_shared_intern_dict(interp)) {
15442
        // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
15443
0
        assert(get_interned_dict(interp) == NULL);
15444
0
    }
15445
15446
0
    _PyUnicode_FiniEncodings(&state->fs_codec);
15447
15448
    // bpo-47182: force a unicodedata CAPI capsule re-import on
15449
    // subsequent initialization of interpreter.
15450
0
    interp->unicode.ucnhash_capi = NULL;
15451
15452
0
    unicode_clear_identifiers(state);
15453
0
}
15454
15455
/* A _string module, to export formatter_parser and formatter_field_name_split
15456
   to the string.Formatter class implemented in Python. */
15457
15458
static PyMethodDef _string_methods[] = {
15459
    {"formatter_field_name_split", formatter_field_name_split,
15460
     METH_O, PyDoc_STR("split the argument as a field name")},
15461
    {"formatter_parser", formatter_parser,
15462
     METH_O, PyDoc_STR("parse the argument as a format string")},
15463
    {NULL, NULL}
15464
};
15465
15466
static PyModuleDef_Slot module_slots[] = {
15467
    _Py_ABI_SLOT,
15468
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
15469
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
15470
    {0, NULL}
15471
};
15472
15473
static struct PyModuleDef _string_module = {
15474
    PyModuleDef_HEAD_INIT,
15475
    .m_name = "_string",
15476
    .m_doc = PyDoc_STR("string helper module"),
15477
    .m_size = 0,
15478
    .m_methods = _string_methods,
15479
    .m_slots = module_slots,
15480
};
15481
15482
PyMODINIT_FUNC
15483
PyInit__string(void)
15484
8
{
15485
8
    return PyModuleDef_Init(&_string_module);
15486
8
}
15487
15488
15489
#undef PyUnicode_KIND
15490
int PyUnicode_KIND(PyObject *op)
15491
0
{
15492
0
    if (!PyUnicode_Check(op)) {
15493
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15494
0
        return -1;
15495
0
    }
15496
0
    return _PyASCIIObject_CAST(op)->state.kind;
15497
0
}
15498
15499
#undef PyUnicode_DATA
15500
void* PyUnicode_DATA(PyObject *op)
15501
0
{
15502
0
    if (!PyUnicode_Check(op)) {
15503
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15504
0
        return NULL;
15505
0
    }
15506
0
    return _PyUnicode_DATA(op);
15507
0
}