Coverage Report

Created: 2026-11-20 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/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
2.94M
#define MAX_UNICODE _Py_MAX_UNICODE
109
350M
#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
2.18M
{
119
2.18M
    assert(_PyUnicode_CHECK(op));
120
2.18M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
121
2.14M
        return ((char*)(_PyASCIIObject_CAST(op) + 1));
122
2.14M
    }
123
39.5k
    else {
124
39.5k
         return _PyUnicode_UTF8(op);
125
39.5k
    }
126
2.18M
}
127
128
static inline void PyUnicode_SET_UTF8(PyObject *op, char *utf8)
129
12.2k
{
130
12.2k
    FT_ATOMIC_STORE_PTR_RELEASE(_PyCompactUnicodeObject_CAST(op)->utf8, utf8);
131
12.2k
}
132
133
static inline Py_ssize_t PyUnicode_UTF8_LENGTH(PyObject *op)
134
721k
{
135
721k
    assert(_PyUnicode_CHECK(op));
136
721k
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
137
718k
         return _PyASCIIObject_CAST(op)->length;
138
718k
    }
139
3.49k
    else {
140
3.49k
         return _PyCompactUnicodeObject_CAST(op)->utf8_length;
141
3.49k
    }
142
721k
}
143
144
static inline void PyUnicode_SET_UTF8_LENGTH(PyObject *op, Py_ssize_t length)
145
12.2k
{
146
12.2k
    _PyCompactUnicodeObject_CAST(op)->utf8_length = length;
147
12.2k
}
148
149
#define _PyUnicode_LENGTH(op)                           \
150
37.7M
    (_PyASCIIObject_CAST(op)->length)
151
#define _PyUnicode_STATE(op)                            \
152
197M
    (_PyASCIIObject_CAST(op)->state)
153
#define _PyUnicode_HASH(op)                             \
154
28.2M
    (_PyASCIIObject_CAST(op)->hash)
155
156
37.5M
#define PyUnicode_HASH PyUnstable_Unicode_GET_CACHED_HASH
157
158
static inline void PyUnicode_SET_HASH(PyObject *op, Py_hash_t hash)
159
5.50M
{
160
5.50M
    FT_ATOMIC_STORE_SSIZE_RELAXED(_PyASCIIObject_CAST(op)->hash, hash);
161
5.50M
}
162
163
#define _PyUnicode_DATA_ANY(op)                         \
164
98
    (_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
160M
#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
42.6M
{
194
42.6M
    _Py_DECLARE_STR(empty, "");
195
42.6M
    return &_Py_STR(empty);
196
42.6M
}
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
1.35M
{
203
1.35M
    return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
204
1.35M
}
205
206
/* This hashtable holds statically allocated interned strings.
207
 * See InternalDocs/string_interning.md for details.
208
 */
209
1.32M
#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
1.39M
{
246
1.39M
    return unicode_hash((PyObject *)key);
247
1.39M
}
248
249
static int
250
hashtable_unicode_compare(const void *key1, const void *key2)
251
92.3k
{
252
92.3k
    PyObject *obj1 = (PyObject *)key1;
253
92.3k
    PyObject *obj2 = (PyObject *)key2;
254
92.3k
    if (obj1 != NULL && obj2 != NULL) {
255
92.3k
        return unicode_eq(obj1, obj2);
256
92.3k
    }
257
0
    else {
258
0
        return obj1 == obj2;
259
0
    }
260
92.3k
}
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
22
{
275
22
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
276
22
    return interp != main_interp  && interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC;
277
22
}
278
279
static int
280
init_interned_dict(PyInterpreterState *interp)
281
22
{
282
22
    assert(get_interned_dict(interp) == NULL);
283
22
    PyObject *interned;
284
22
    if (has_shared_intern_dict(interp)) {
285
0
        interned = get_interned_dict(_PyInterpreterState_Main());
286
0
        Py_INCREF(interned);
287
0
    }
288
22
    else {
289
22
        interned = PyDict_New();
290
22
        if (interned == NULL) {
291
0
            return -1;
292
0
        }
293
22
    }
294
22
    _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
295
22
    return 0;
296
22
}
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
22
{
315
22
    assert(INTERNED_STRINGS == NULL);
316
22
    _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
317
318
22
    INTERNED_STRINGS = _Py_hashtable_new_full(
319
22
        hashtable_unicode_hash,
320
22
        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
22
        NULL,
324
22
        NULL,
325
22
        &hashtable_alloc
326
22
    );
327
22
    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
22
    _PyUnicode_InitStaticStrings(interp);
340
341
5.65k
    for (int i = 0; i < 256; i++) {
342
5.63k
        PyObject *s = LATIN1(i);
343
5.63k
        _PyUnicode_InternStatic(interp, &s);
344
5.63k
        assert(s == LATIN1(i));
345
5.63k
    }
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
22
    return _PyStatus_OK();
354
22
}
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
25.2M
    do {                             \
366
25.2M
        return _PyUnicode_GetEmpty();\
367
25.2M
    } 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
40.2k
{
461
40.2k
    if (errors == NULL || strcmp(errors, "strict") == 0) {
462
29.9k
        return _Py_ERROR_STRICT;
463
29.9k
    }
464
10.2k
    if (strcmp(errors, "surrogateescape") == 0) {
465
6.96k
        return _Py_ERROR_SURROGATEESCAPE;
466
6.96k
    }
467
3.29k
    if (strcmp(errors, "replace") == 0) {
468
2.47k
        return _Py_ERROR_REPLACE;
469
2.47k
    }
470
818
    if (strcmp(errors, "ignore") == 0) {
471
0
        return _Py_ERROR_IGNORE;
472
0
    }
473
818
    if (strcmp(errors, "backslashreplace") == 0) {
474
279
        return _Py_ERROR_BACKSLASHREPLACE;
475
279
    }
476
539
    if (strcmp(errors, "surrogatepass") == 0) {
477
539
        return _Py_ERROR_SURROGATEPASS;
478
539
    }
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
8.05k
{
489
8.05k
    if (errors == NULL || wcscmp(errors, L"strict") == 0) {
490
0
        return _Py_ERROR_STRICT;
491
0
    }
492
8.05k
    if (wcscmp(errors, L"surrogateescape") == 0) {
493
8.05k
        return _Py_ERROR_SURROGATEESCAPE;
494
8.05k
    }
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
859k
{
517
859k
    if (encoding == NULL && errors == NULL) {
518
0
        return 0;
519
0
    }
520
521
859k
    PyInterpreterState *interp = _PyInterpreterState_GET();
522
859k
#ifndef Py_DEBUG
523
    /* In release mode, only check in development mode (-X dev) */
524
859k
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
525
859k
        return 0;
526
859k
    }
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
69.2M
{
580
69.2M
#define CHECK(expr) \
581
323M
    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
69.2M
# define CHECK_IF_GIL(expr) CHECK(expr)
587
69.2M
# define CHECK_IF_FT(expr) (void)(expr)
588
69.2M
#endif
589
590
69.2M
    assert(op != NULL);
591
69.2M
    CHECK(PyUnicode_Check(op));
592
593
69.2M
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
594
0
    int kind = ascii->state.kind;
595
596
69.2M
    if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
597
44.7M
        CHECK(kind == PyUnicode_1BYTE_KIND);
598
44.7M
    }
599
24.4M
    else {
600
24.4M
        PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
601
0
        void *data;
602
603
24.4M
        if (ascii->state.compact == 1) {
604
24.4M
            data = compact + 1;
605
24.4M
            CHECK(kind == PyUnicode_1BYTE_KIND
606
24.4M
                                 || kind == PyUnicode_2BYTE_KIND
607
24.4M
                                 || kind == PyUnicode_4BYTE_KIND);
608
24.4M
            CHECK(ascii->state.ascii == 0);
609
24.4M
            CHECK(_PyUnicode_UTF8(op) != data);
610
24.4M
        }
611
49
        else {
612
49
            PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
613
614
0
            data = unicode->data.any;
615
49
            CHECK(kind == PyUnicode_1BYTE_KIND
616
49
                     || kind == PyUnicode_2BYTE_KIND
617
49
                     || kind == PyUnicode_4BYTE_KIND);
618
49
            CHECK(ascii->state.compact == 0);
619
49
            CHECK(data != NULL);
620
49
            if (ascii->state.ascii) {
621
49
                CHECK(_PyUnicode_UTF8(op) == data);
622
49
                CHECK(compact->utf8_length == ascii->length);
623
49
            }
624
0
            else {
625
0
                CHECK(_PyUnicode_UTF8(op) != data);
626
0
            }
627
49
        }
628
24.4M
#ifndef Py_GIL_DISABLED
629
24.4M
        if (_PyUnicode_UTF8(op) == NULL)
630
24.1M
            CHECK(compact->utf8_length == 0);
631
24.4M
#endif
632
24.4M
    }
633
634
    /* check that the best kind is used: O(n) operation */
635
69.2M
    const void *data = PyUnicode_DATA(ascii);
636
69.2M
    if (check_content) {
637
31.4M
        Py_ssize_t i;
638
31.4M
        Py_UCS4 maxchar = 0;
639
31.4M
        Py_UCS4 ch;
640
641
29.7G
        for (i=0; i < ascii->length; i++)
642
29.7G
        {
643
29.7G
            ch = PyUnicode_READ(kind, data, i);
644
29.7G
            if (ch > maxchar)
645
40.1M
                maxchar = ch;
646
29.7G
        }
647
31.4M
        if (kind == PyUnicode_1BYTE_KIND) {
648
21.2M
            if (ascii->state.ascii == 0) {
649
1.43M
                CHECK(maxchar >= 128);
650
1.43M
                CHECK(maxchar <= 255);
651
1.43M
            }
652
19.8M
            else
653
19.8M
                CHECK(maxchar < 128);
654
21.2M
        }
655
10.2M
        else if (kind == PyUnicode_2BYTE_KIND) {
656
8.83M
            CHECK(maxchar >= 0x100);
657
8.83M
            CHECK(maxchar <= 0xFFFF);
658
8.83M
        }
659
1.40M
        else {
660
1.40M
            CHECK(maxchar >= 0x10000);
661
1.40M
            CHECK(maxchar <= MAX_UNICODE);
662
1.40M
        }
663
31.4M
    }
664
665
    // Detect buffer overflow: check if the trailing null character
666
    // has been overridden
667
69.2M
    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
69.2M
    return 1;
704
705
69.2M
#undef CHECK
706
69.2M
}
707
708
PyObject*
709
_PyUnicode_Result(PyObject *unicode)
710
629k
{
711
629k
    assert(_PyUnicode_CHECK(unicode));
712
713
629k
    Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
714
629k
    if (length == 0) {
715
1
        PyObject *empty = _PyUnicode_GetEmpty();
716
1
        if (unicode != empty) {
717
0
            Py_DECREF(unicode);
718
0
        }
719
1
        return empty;
720
1
    }
721
722
629k
    if (length == 1) {
723
590k
        int kind = PyUnicode_KIND(unicode);
724
590k
        if (kind == PyUnicode_1BYTE_KIND) {
725
73.8k
            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
726
73.8k
            Py_UCS1 ch = data[0];
727
73.8k
            PyObject *latin1_char = LATIN1(ch);
728
73.8k
            if (unicode != latin1_char) {
729
0
                Py_DECREF(unicode);
730
0
            }
731
73.8k
            return latin1_char;
732
73.8k
        }
733
590k
    }
734
735
629k
    assert(_PyUnicode_CheckConsistency(unicode, 1));
736
555k
    return unicode;
737
555k
}
738
629k
#define unicode_result _PyUnicode_Result
739
740
static PyObject*
741
unicode_result_unchanged(PyObject *unicode)
742
174k
{
743
174k
    if (PyUnicode_CheckExact(unicode)) {
744
174k
        return Py_NewRef(unicode);
745
174k
    }
746
0
    else
747
        /* Subtype -- return genuine unicode string with the same value. */
748
0
        return _PyUnicode_Copy(unicode);
749
174k
}
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
10.3k
{
757
10.3k
    Py_ssize_t size, i;
758
10.3k
    Py_UCS4 ch;
759
10.3k
    int kind;
760
10.3k
    const void *data;
761
762
10.3k
    kind = PyUnicode_KIND(unicode);
763
10.3k
    data = PyUnicode_DATA(unicode);
764
765
10.3k
    size = 0;
766
    /* determine replacement size */
767
116k
    for (i = collstart; i < collend; ++i) {
768
106k
        Py_ssize_t incr;
769
770
106k
        ch = PyUnicode_READ(kind, data, i);
771
106k
        if (ch < 0x100)
772
106k
            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
106k
        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
106k
        size += incr;
785
106k
    }
786
    /* subtract preallocated bytes */
787
10.3k
    size -= (collend - collstart);
788
789
10.3k
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
790
10.3k
    if (str == NULL) {
791
0
        return NULL;
792
0
    }
793
794
    /* generate replacement */
795
116k
    for (i = collstart; i < collend; ++i) {
796
106k
        ch = PyUnicode_READ(kind, data, i);
797
106k
        *str++ = '\\';
798
106k
        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
106k
        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
106k
        else
813
106k
            *str++ = 'x';
814
106k
        *str++ = Py_hexdigits[(ch>>4)&0xf];
815
106k
        *str++ = Py_hexdigits[ch&0xf];
816
106k
    }
817
10.3k
    return str;
818
10.3k
}
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
36.4k
#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
36.1k
#define BLOOM_MASK unsigned long
907
908
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
909
910
18.1k
#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
911
912
#define BLOOM_LINEBREAK(ch)                                             \
913
0
    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
914
0
     (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
18.1k
{
919
18.1k
#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
920
18.1k
    do {                                               \
921
18.1k
        TYPE *data = (TYPE *)PTR;                      \
922
18.1k
        TYPE *end = data + LEN;                        \
923
18.1k
        Py_UCS4 ch;                                    \
924
36.4k
        for (; data != end; data++) {                  \
925
18.2k
            ch = *data;                                \
926
18.2k
            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
927
18.2k
        }                                              \
928
18.1k
        break;                                         \
929
18.1k
    } while (0)
930
931
    /* calculate simple bloom-style bitmask for a given unicode string */
932
933
18.1k
    BLOOM_MASK mask;
934
935
18.1k
    mask = 0;
936
18.1k
    switch (kind) {
937
18.0k
    case PyUnicode_1BYTE_KIND:
938
18.0k
        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
939
18.0k
        break;
940
22
    case PyUnicode_2BYTE_KIND:
941
22
        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
942
22
        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
18.1k
    }
949
18.1k
    return mask;
950
951
18.1k
#undef BLOOM_UPDATE
952
18.1k
}
953
954
/* Compilation of templated routines */
955
956
2.50k
#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
30.3M
{
1009
30.3M
    switch (kind) {
1010
30.3M
    case PyUnicode_1BYTE_KIND:
1011
30.3M
        if ((Py_UCS1) ch != ch)
1012
1.87k
            return -1;
1013
30.3M
        if (direction > 0)
1014
30.3M
            return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1015
4.16k
        else
1016
4.16k
            return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1017
10.3k
    case PyUnicode_2BYTE_KIND:
1018
10.3k
        if ((Py_UCS2) ch != ch)
1019
0
            return -1;
1020
10.3k
        if (direction > 0)
1021
9.38k
            return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1022
933
        else
1023
933
            return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1024
2.42k
    case PyUnicode_4BYTE_KIND:
1025
2.42k
        if (direction > 0)
1026
1.17k
            return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
1027
1.25k
        else
1028
1.25k
            return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
1029
0
    default:
1030
0
        Py_UNREACHABLE();
1031
30.3M
    }
1032
30.3M
}
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
9.50M
{
1071
9.50M
    Py_ssize_t char_size;
1072
9.50M
    Py_ssize_t struct_size;
1073
9.50M
    Py_ssize_t new_size;
1074
9.50M
    PyObject *new_unicode;
1075
#ifdef Py_DEBUG
1076
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1077
#endif
1078
1079
9.50M
    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
9.50M
    assert(PyUnicode_IS_COMPACT(unicode));
1088
1089
9.50M
    char_size = PyUnicode_KIND(unicode);
1090
9.50M
    if (PyUnicode_IS_ASCII(unicode))
1091
7.21M
        struct_size = sizeof(PyASCIIObject);
1092
2.28M
    else
1093
2.28M
        struct_size = sizeof(PyCompactUnicodeObject);
1094
1095
9.50M
    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1096
0
        PyErr_NoMemory();
1097
0
        return NULL;
1098
0
    }
1099
9.50M
    new_size = (struct_size + (length + 1) * char_size);
1100
1101
9.50M
    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
9.50M
    _PyReftracerTrack(unicode, PyRefTracer_DESTROY);
1110
1111
9.50M
    new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
1112
9.50M
    if (new_unicode == NULL) {
1113
0
        _Py_NewReferenceNoTotal(unicode);
1114
0
        PyErr_NoMemory();
1115
0
        return NULL;
1116
0
    }
1117
9.50M
    unicode = new_unicode;
1118
9.50M
    _Py_NewReferenceNoTotal(unicode);
1119
1120
9.50M
    _PyUnicode_LENGTH(unicode) = length;
1121
#ifdef Py_DEBUG
1122
    unicode_fill_invalid(unicode, old_length);
1123
#endif
1124
9.50M
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1125
9.50M
                    length, 0);
1126
9.50M
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1127
9.50M
    return unicode;
1128
9.50M
}
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
37.1M
{
1273
    /* Optimization for empty strings */
1274
37.1M
    if (size == 0) {
1275
8.85M
        return _PyUnicode_GetEmpty();
1276
8.85M
    }
1277
1278
28.2M
    PyObject *obj;
1279
28.2M
    PyCompactUnicodeObject *unicode;
1280
28.2M
    void *data;
1281
28.2M
    int kind;
1282
28.2M
    int is_ascii;
1283
28.2M
    Py_ssize_t char_size;
1284
28.2M
    Py_ssize_t struct_size;
1285
1286
28.2M
    is_ascii = 0;
1287
28.2M
    struct_size = sizeof(PyCompactUnicodeObject);
1288
28.2M
    if (maxchar < 128) {
1289
17.7M
        kind = PyUnicode_1BYTE_KIND;
1290
17.7M
        char_size = 1;
1291
17.7M
        is_ascii = 1;
1292
17.7M
        struct_size = sizeof(PyASCIIObject);
1293
17.7M
    }
1294
10.4M
    else if (maxchar < 256) {
1295
447k
        kind = PyUnicode_1BYTE_KIND;
1296
447k
        char_size = 1;
1297
447k
    }
1298
10.0M
    else if (maxchar < 65536) {
1299
8.60M
        kind = PyUnicode_2BYTE_KIND;
1300
8.60M
        char_size = 2;
1301
8.60M
    }
1302
1.43M
    else {
1303
1.43M
        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
1.43M
        kind = PyUnicode_4BYTE_KIND;
1309
1.43M
        char_size = 4;
1310
1.43M
    }
1311
1312
    /* Ensure we won't overflow the size. */
1313
28.2M
    if (size < 0) {
1314
0
        PyErr_SetString(PyExc_SystemError,
1315
0
                        "Negative size passed to PyUnicode_New");
1316
0
        return NULL;
1317
0
    }
1318
28.2M
    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
28.2M
    obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
1326
28.2M
    if (obj == NULL) {
1327
0
        return PyErr_NoMemory();
1328
0
    }
1329
28.2M
    _PyObject_Init(obj, &PyUnicode_Type);
1330
1331
28.2M
    unicode = (PyCompactUnicodeObject *)obj;
1332
28.2M
    if (is_ascii)
1333
17.7M
        data = ((PyASCIIObject*)obj) + 1;
1334
10.4M
    else
1335
10.4M
        data = unicode + 1;
1336
28.2M
    _PyUnicode_LENGTH(unicode) = size;
1337
28.2M
    _PyUnicode_HASH(unicode) = -1;
1338
28.2M
    _PyUnicode_STATE(unicode).interned = 0;
1339
28.2M
    _PyUnicode_STATE(unicode).kind = kind;
1340
28.2M
    _PyUnicode_STATE(unicode).compact = 1;
1341
28.2M
    _PyUnicode_STATE(unicode).ascii = is_ascii;
1342
28.2M
    _PyUnicode_STATE(unicode).statically_allocated = 0;
1343
28.2M
    if (is_ascii) {
1344
17.7M
        ((char*)data)[size] = 0;
1345
17.7M
    }
1346
10.4M
    else if (kind == PyUnicode_1BYTE_KIND) {
1347
447k
        ((char*)data)[size] = 0;
1348
447k
        unicode->utf8 = NULL;
1349
447k
        unicode->utf8_length = 0;
1350
447k
    }
1351
10.0M
    else {
1352
10.0M
        unicode->utf8 = NULL;
1353
10.0M
        unicode->utf8_length = 0;
1354
10.0M
        if (kind == PyUnicode_2BYTE_KIND)
1355
8.60M
            ((Py_UCS2*)data)[size] = 0;
1356
1.43M
        else /* kind == PyUnicode_4BYTE_KIND */
1357
1.43M
            ((Py_UCS4*)data)[size] = 0;
1358
10.0M
    }
1359
#ifdef Py_DEBUG
1360
    unicode_fill_invalid((PyObject*)unicode, 0);
1361
#endif
1362
28.2M
    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
1363
28.2M
    return obj;
1364
28.2M
}
1365
1366
static int
1367
unicode_check_modifiable(PyObject *unicode)
1368
555
{
1369
555
    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
555
    return 0;
1375
555
}
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
38.4M
{
1382
38.4M
    int from_kind, to_kind;
1383
38.4M
    const void *from_data;
1384
38.4M
    void *to_data;
1385
1386
38.4M
    assert(0 <= how_many);
1387
38.4M
    assert(0 <= from_start);
1388
38.4M
    assert(0 <= to_start);
1389
38.4M
    assert(PyUnicode_Check(from));
1390
38.4M
    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
1391
1392
38.4M
    assert(to == NULL || PyUnicode_Check(to));
1393
1394
38.4M
    if (how_many == 0) {
1395
540k
        return 0;
1396
540k
    }
1397
1398
38.4M
    assert(to != NULL);
1399
37.9M
    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1400
1401
37.9M
    from_kind = PyUnicode_KIND(from);
1402
37.9M
    from_data = PyUnicode_DATA(from);
1403
37.9M
    to_kind = PyUnicode_KIND(to);
1404
37.9M
    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
37.9M
    if (from_kind == to_kind) {
1421
12.8M
        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
12.8M
        memcpy((char*)to_data + to_kind * to_start,
1433
12.8M
                  (const char*)from_data + from_kind * from_start,
1434
12.8M
                  to_kind * how_many);
1435
12.8M
    }
1436
25.0M
    else if (from_kind == PyUnicode_1BYTE_KIND
1437
24.9M
             && to_kind == PyUnicode_2BYTE_KIND)
1438
23.3M
    {
1439
23.3M
        _PyUnicode_CONVERT_BYTES(
1440
23.3M
            Py_UCS1, Py_UCS2,
1441
23.3M
            PyUnicode_1BYTE_DATA(from) + from_start,
1442
23.3M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1443
23.3M
            PyUnicode_2BYTE_DATA(to) + to_start
1444
23.3M
            );
1445
23.3M
    }
1446
1.74M
    else if (from_kind == PyUnicode_1BYTE_KIND
1447
1.61M
             && to_kind == PyUnicode_4BYTE_KIND)
1448
1.61M
    {
1449
1.61M
        _PyUnicode_CONVERT_BYTES(
1450
1.61M
            Py_UCS1, Py_UCS4,
1451
1.61M
            PyUnicode_1BYTE_DATA(from) + from_start,
1452
1.61M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1453
1.61M
            PyUnicode_4BYTE_DATA(to) + to_start
1454
1.61M
            );
1455
1.61M
    }
1456
127k
    else if (from_kind == PyUnicode_2BYTE_KIND
1457
101k
             && to_kind == PyUnicode_4BYTE_KIND)
1458
91.7k
    {
1459
91.7k
        _PyUnicode_CONVERT_BYTES(
1460
91.7k
            Py_UCS2, Py_UCS4,
1461
91.7k
            PyUnicode_2BYTE_DATA(from) + from_start,
1462
91.7k
            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1463
91.7k
            PyUnicode_4BYTE_DATA(to) + to_start
1464
91.7k
            );
1465
91.7k
    }
1466
36.2k
    else {
1467
36.2k
        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1468
1469
36.2k
        if (!check_maxchar) {
1470
36.2k
            if (from_kind == PyUnicode_2BYTE_KIND
1471
9.50k
                && to_kind == PyUnicode_1BYTE_KIND)
1472
9.50k
            {
1473
9.50k
                _PyUnicode_CONVERT_BYTES(
1474
9.50k
                    Py_UCS2, Py_UCS1,
1475
9.50k
                    PyUnicode_2BYTE_DATA(from) + from_start,
1476
9.50k
                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1477
9.50k
                    PyUnicode_1BYTE_DATA(to) + to_start
1478
9.50k
                    );
1479
9.50k
            }
1480
26.7k
            else if (from_kind == PyUnicode_4BYTE_KIND
1481
26.7k
                     && to_kind == PyUnicode_1BYTE_KIND)
1482
20.0k
            {
1483
20.0k
                _PyUnicode_CONVERT_BYTES(
1484
20.0k
                    Py_UCS4, Py_UCS1,
1485
20.0k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1486
20.0k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1487
20.0k
                    PyUnicode_1BYTE_DATA(to) + to_start
1488
20.0k
                    );
1489
20.0k
            }
1490
6.73k
            else if (from_kind == PyUnicode_4BYTE_KIND
1491
6.73k
                     && to_kind == PyUnicode_2BYTE_KIND)
1492
6.73k
            {
1493
6.73k
                _PyUnicode_CONVERT_BYTES(
1494
6.73k
                    Py_UCS4, Py_UCS2,
1495
6.73k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1496
6.73k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1497
6.73k
                    PyUnicode_2BYTE_DATA(to) + to_start
1498
6.73k
                    );
1499
6.73k
            }
1500
0
            else {
1501
0
                Py_UNREACHABLE();
1502
0
            }
1503
36.2k
        }
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
36.2k
    }
1517
37.9M
    return 0;
1518
37.9M
}
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
38.4M
{
1525
38.4M
    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1526
38.4M
}
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
15.0k
{
1598
15.0k
    const wchar_t *iter;
1599
15.0k
    Py_UCS4 ch;
1600
1601
15.0k
    assert(num_surrogates != NULL && maxchar != NULL);
1602
15.0k
    *num_surrogates = 0;
1603
15.0k
    *maxchar = 0;
1604
1605
306k
    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
291k
        {
1618
291k
            ch = *iter;
1619
291k
            iter++;
1620
291k
        }
1621
291k
        if (ch > *maxchar) {
1622
56.9k
            *maxchar = ch;
1623
56.9k
            if (*maxchar > MAX_UNICODE) {
1624
0
                unicode_invalid_character(PyExc_ValueError, ch);
1625
0
                return -1;
1626
0
            }
1627
56.9k
        }
1628
291k
    }
1629
15.0k
    return 0;
1630
15.0k
}
1631
1632
static void
1633
unicode_dealloc(PyObject *unicode)
1634
27.9M
{
1635
#ifdef Py_DEBUG
1636
    if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
1637
        _Py_FatalRefcountError("deallocating an Unicode singleton");
1638
    }
1639
#endif
1640
55.9M
    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
27.9M
    switch (_PyUnicode_STATE(unicode).interned) {
1652
27.7M
        case SSTATE_NOT_INTERNED:
1653
27.7M
            break;
1654
172k
        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
172k
            assert(Py_REFCNT(unicode) == 0);
1660
172k
            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
172k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1667
172k
            PyObject *interned = get_interned_dict(interp);
1668
172k
            assert(interned != NULL);
1669
172k
            PyObject *popped;
1670
172k
            int r = PyDict_Pop(interned, unicode, &popped);
1671
172k
            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
172k
            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
172k
            assert(popped == unicode);
1694
            // Only our `popped` reference should be left; remove it too.
1695
172k
            assert(Py_REFCNT(unicode) == 1);
1696
172k
            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
172k
            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
27.9M
    }
1710
27.9M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1711
12.1k
        PyMem_Free(_PyUnicode_UTF8(unicode));
1712
12.1k
    }
1713
27.9M
    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
1714
0
        PyMem_Free(_PyUnicode_DATA_ANY(unicode));
1715
0
    }
1716
1717
27.9M
    Py_TYPE(unicode)->tp_free(unicode);
1718
27.9M
}
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
22.7M
{
1743
22.7M
    assert(_PyUnicode_CHECK(unicode));
1744
22.7M
    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
22.7M
    if (!_PyObject_IsUniquelyReferenced(unicode))
1749
645k
        return 0;
1750
22.1M
    if (PyUnicode_HASH(unicode) != -1)
1751
0
        return 0;
1752
22.1M
    if (PyUnicode_CHECK_INTERNED(unicode))
1753
0
        return 0;
1754
22.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
22.1M
    return 1;
1762
22.1M
}
1763
1764
static int
1765
unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1766
6.32M
{
1767
6.32M
    PyObject *unicode;
1768
6.32M
    Py_ssize_t old_length;
1769
1770
6.32M
    assert(p_unicode != NULL);
1771
6.32M
    unicode = *p_unicode;
1772
1773
6.32M
    assert(unicode != NULL);
1774
6.32M
    assert(PyUnicode_Check(unicode));
1775
6.32M
    assert(0 <= length);
1776
1777
6.32M
    old_length = PyUnicode_GET_LENGTH(unicode);
1778
6.32M
    if (old_length == length)
1779
0
        return 0;
1780
1781
6.32M
    if (length == 0) {
1782
0
        PyObject *empty = _PyUnicode_GetEmpty();
1783
0
        Py_SETREF(*p_unicode, empty);
1784
0
        return 0;
1785
0
    }
1786
1787
6.32M
    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
6.32M
    if (PyUnicode_IS_COMPACT(unicode)) {
1796
6.32M
        PyObject *new_unicode = _PyUnicode_ResizeCompact(unicode, length);
1797
6.32M
        if (new_unicode == NULL)
1798
0
            return -1;
1799
6.32M
        *p_unicode = new_unicode;
1800
6.32M
        return 0;
1801
6.32M
    }
1802
0
    return resize_inplace(unicode, length);
1803
6.32M
}
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
160M
{
1825
160M
    PyObject *o = LATIN1(ch);
1826
160M
    return o;
1827
160M
}
1828
1829
static PyObject*
1830
unicode_char(Py_UCS4 ch)
1831
116M
{
1832
116M
    if (ch < 256) {
1833
108M
        return get_latin1_char(ch);
1834
108M
    }
1835
1836
    // Raise SystemError if the character is not in range [U+0000; MAX_UNICODE]
1837
7.70M
    PyObject *unicode = PyUnicode_New(1, ch);
1838
7.70M
    if (unicode == NULL) {
1839
0
        return NULL;
1840
0
    }
1841
1842
7.70M
    assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1843
15.4M
    if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
1844
6.82M
        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1845
6.82M
    } else {
1846
875k
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1847
875k
        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1848
875k
    }
1849
7.70M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
1850
7.70M
    return unicode;
1851
7.70M
}
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
15.0k
{
1859
15.0k
    switch (kind) {
1860
15.0k
    case PyUnicode_1BYTE_KIND:
1861
15.0k
        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, u, u + size, data);
1862
15.0k
        break;
1863
1864
0
    case PyUnicode_2BYTE_KIND:
1865
#if SIZEOF_WCHAR_T == 2
1866
        memcpy(data, u, size * 2);
1867
#else
1868
0
        _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2, u, u + size, data);
1869
0
#endif
1870
0
        break;
1871
1872
0
    case PyUnicode_4BYTE_KIND:
1873
0
    {
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
0
        assert(num_surrogates == 0);
1899
0
        memcpy(data, u, size * 4);
1900
0
#endif
1901
0
        break;
1902
0
    }
1903
0
    default:
1904
0
        Py_UNREACHABLE();
1905
15.0k
    }
1906
15.0k
}
1907
1908
1909
PyObject *
1910
PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
1911
15.0k
{
1912
15.0k
    PyObject *unicode;
1913
15.0k
    Py_UCS4 maxchar = 0;
1914
15.0k
    Py_ssize_t num_surrogates;
1915
1916
15.0k
    if (u == NULL && size != 0) {
1917
0
        PyErr_BadInternalCall();
1918
0
        return NULL;
1919
0
    }
1920
1921
15.0k
    if (size == -1) {
1922
902
        size = wcslen(u);
1923
902
    }
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
15.0k
    if (size == 0)
1930
44
        _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
15.0k
    if (size == 1 && (Py_UCS4)*u < 256)
1949
0
        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
15.0k
    if (find_maxchar_surrogates(u, u + size,
1954
15.0k
                                &maxchar, &num_surrogates) == -1)
1955
0
        return NULL;
1956
1957
15.0k
    unicode = PyUnicode_New(size - num_surrogates, maxchar);
1958
15.0k
    if (!unicode)
1959
0
        return NULL;
1960
1961
15.0k
    unicode_write_widechar(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1962
15.0k
                           u, size, num_surrogates);
1963
1964
15.0k
    return unicode_result(unicode);
1965
15.0k
}
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
112k
{
2022
112k
    if (size < 0) {
2023
0
        PyErr_SetString(PyExc_SystemError,
2024
0
                        "Negative size passed to PyUnicode_FromStringAndSize");
2025
0
        return NULL;
2026
0
    }
2027
112k
    if (u != NULL) {
2028
112k
        return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2029
112k
    }
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
4.69M
{
2041
4.69M
    size_t size = strlen(u);
2042
4.69M
    if (size > PY_SSIZE_T_MAX) {
2043
0
        PyErr_SetString(PyExc_OverflowError, "input too long");
2044
0
        return NULL;
2045
0
    }
2046
4.69M
    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
2047
4.69M
}
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
9.24M
{
2136
9.24M
    const unsigned char *s = (const unsigned char *)buffer;
2137
9.24M
    PyObject *unicode;
2138
9.24M
    if (size == 1) {
2139
#ifdef Py_DEBUG
2140
        assert((unsigned char)s[0] < 128);
2141
#endif
2142
144k
        return get_latin1_char(s[0]);
2143
144k
    }
2144
9.10M
    unicode = PyUnicode_New(size, 127);
2145
9.10M
    if (!unicode)
2146
0
        return NULL;
2147
9.10M
    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2148
9.10M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
2149
9.10M
    return unicode;
2150
9.10M
}
2151
2152
static Py_UCS4
2153
kind_maxchar_limit(int kind)
2154
751
{
2155
751
    switch (kind) {
2156
71
    case PyUnicode_1BYTE_KIND:
2157
71
        return 0x80;
2158
45
    case PyUnicode_2BYTE_KIND:
2159
45
        return 0x100;
2160
635
    case PyUnicode_4BYTE_KIND:
2161
635
        return 0x10000;
2162
0
    default:
2163
0
        Py_UNREACHABLE();
2164
751
    }
2165
751
}
2166
2167
static PyObject*
2168
_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
2169
7.83M
{
2170
7.83M
    PyObject *res;
2171
7.83M
    unsigned char max_char;
2172
2173
7.83M
    if (size == 0) {
2174
7.55M
        _Py_RETURN_UNICODE_EMPTY();
2175
7.55M
    }
2176
7.83M
    assert(size > 0);
2177
284k
    if (size == 1) {
2178
19.6k
        return get_latin1_char(u[0]);
2179
19.6k
    }
2180
2181
265k
    max_char = ucs1lib_find_max_char(u, u + size);
2182
265k
    res = PyUnicode_New(size, max_char);
2183
265k
    if (!res)
2184
0
        return NULL;
2185
265k
    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
2186
265k
    assert(_PyUnicode_CheckConsistency(res, 1));
2187
265k
    return res;
2188
265k
}
2189
2190
static PyObject*
2191
_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
2192
7.05M
{
2193
7.05M
    PyObject *res;
2194
7.05M
    Py_UCS2 max_char;
2195
2196
7.05M
    if (size == 0)
2197
6.65M
        _Py_RETURN_UNICODE_EMPTY();
2198
7.05M
    assert(size > 0);
2199
393k
    if (size == 1)
2200
45.1k
        return unicode_char(u[0]);
2201
2202
348k
    max_char = ucs2lib_find_max_char(u, u + size);
2203
348k
    res = PyUnicode_New(size, max_char);
2204
348k
    if (!res)
2205
0
        return NULL;
2206
348k
    if (max_char >= 256)
2207
178k
        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
2208
169k
    else {
2209
169k
        _PyUnicode_CONVERT_BYTES(
2210
169k
            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2211
169k
    }
2212
348k
    assert(_PyUnicode_CheckConsistency(res, 1));
2213
348k
    return res;
2214
348k
}
2215
2216
static PyObject*
2217
_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
2218
11.4M
{
2219
11.4M
    PyObject *res;
2220
2221
11.4M
    if (size == 0)
2222
10.3M
        _Py_RETURN_UNICODE_EMPTY();
2223
11.4M
    assert(size > 0);
2224
2225
1.13M
    if (size == 1) {
2226
        // Raise SystemError if the character is invalid
2227
463k
        return unicode_char(u[0]);
2228
463k
    }
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
670k
    Py_UCS4 max_char = ucs4lib_find_max_char(u, u + size);
2248
670k
#endif
2249
2250
670k
    res = PyUnicode_New(size, max_char);
2251
670k
    if (!res)
2252
0
        return NULL;
2253
670k
    if (max_char < 256)
2254
584k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2255
670k
                                 PyUnicode_1BYTE_DATA(res));
2256
85.9k
    else if (max_char < 0x10000)
2257
63.7k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2258
85.9k
                                 PyUnicode_2BYTE_DATA(res));
2259
22.1k
    else
2260
22.1k
        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
2261
670k
    assert(_PyUnicode_CheckConsistency(res, 1));
2262
670k
    return res;
2263
670k
}
2264
2265
2266
int
2267
PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *pub_writer,
2268
                          const Py_UCS4 *str,
2269
                          Py_ssize_t size)
2270
2.68k
{
2271
2.68k
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
2272
2273
2.68k
    if (size < 0) {
2274
0
        PyErr_SetString(PyExc_ValueError,
2275
0
                        "size must be positive");
2276
0
        return -1;
2277
0
    }
2278
2279
2.68k
    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
2.68k
    Py_UCS4 maxchar = ucs4lib_find_max_char(str, str + size);
2301
2.68k
#endif
2302
2303
2.68k
    if (_PyUnicodeWriter_Prepare(writer, size, maxchar) < 0) {
2304
0
        return -1;
2305
0
    }
2306
2.68k
    assert(_PyUnicodeWriter_CanWrite(writer));
2307
2308
2.68k
    int kind = writer->kind;
2309
2.68k
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2310
2.68k
    if (kind == PyUnicode_1BYTE_KIND) {
2311
199
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1,
2312
199
                                 str, str + size,
2313
199
                                 data);
2314
199
    }
2315
2.48k
    else if (kind == PyUnicode_2BYTE_KIND) {
2316
2.45k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2,
2317
2.45k
                                 str, str + size,
2318
2.45k
                                 data);
2319
2.45k
    }
2320
36
    else {
2321
36
        memcpy(data, str, size * sizeof(Py_UCS4));
2322
36
    }
2323
2.68k
    writer->pos += size;
2324
2325
2.68k
    return 0;
2326
2.68k
}
2327
2328
2329
PyObject*
2330
PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2331
5.63M
{
2332
5.63M
    if (size < 0) {
2333
0
        PyErr_SetString(PyExc_ValueError, "size must be positive");
2334
0
        return NULL;
2335
0
    }
2336
5.63M
    switch (kind) {
2337
201k
    case PyUnicode_1BYTE_KIND:
2338
201k
        return _PyUnicode_FromUCS1(buffer, size);
2339
306k
    case PyUnicode_2BYTE_KIND:
2340
306k
        return _PyUnicode_FromUCS2(buffer, size);
2341
5.12M
    case PyUnicode_4BYTE_KIND:
2342
5.12M
        return _PyUnicode_FromUCS4(buffer, size);
2343
0
    default:
2344
0
        PyErr_SetString(PyExc_SystemError, "invalid kind");
2345
0
        return NULL;
2346
5.63M
    }
2347
5.63M
}
2348
2349
Py_UCS4
2350
_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2351
1.66M
{
2352
1.66M
    int kind;
2353
1.66M
    const void *startptr, *endptr;
2354
2355
1.66M
    assert(0 <= start);
2356
1.66M
    assert(end <= PyUnicode_GET_LENGTH(unicode));
2357
1.66M
    assert(start <= end);
2358
2359
1.66M
    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2360
0
        return PyUnicode_MAX_CHAR_VALUE(unicode);
2361
2362
1.66M
    if (start == end)
2363
0
        return 127;
2364
2365
1.66M
    if (PyUnicode_IS_ASCII(unicode))
2366
1.60M
        return 127;
2367
2368
56.9k
    kind = PyUnicode_KIND(unicode);
2369
56.9k
    startptr = PyUnicode_DATA(unicode);
2370
56.9k
    endptr = (char *)startptr + end * kind;
2371
56.9k
    startptr = (char *)startptr + start * kind;
2372
56.9k
    switch(kind) {
2373
4.87k
    case PyUnicode_1BYTE_KIND:
2374
4.87k
        return ucs1lib_find_max_char(startptr, endptr);
2375
20.3k
    case PyUnicode_2BYTE_KIND:
2376
20.3k
        return ucs2lib_find_max_char(startptr, endptr);
2377
31.7k
    case PyUnicode_4BYTE_KIND:
2378
31.7k
        return ucs4lib_find_max_char(startptr, endptr);
2379
0
    default:
2380
0
        Py_UNREACHABLE();
2381
56.9k
    }
2382
56.9k
}
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
0
{
2433
0
    Py_ssize_t length;
2434
0
    PyObject *copy;
2435
2436
0
    if (!PyUnicode_Check(unicode)) {
2437
0
        PyErr_BadInternalCall();
2438
0
        return NULL;
2439
0
    }
2440
2441
0
    length = PyUnicode_GET_LENGTH(unicode);
2442
0
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
2443
0
    if (!copy)
2444
0
        return NULL;
2445
0
    assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2446
2447
0
    memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2448
0
              length * PyUnicode_KIND(unicode));
2449
0
    assert(_PyUnicode_CheckConsistency(copy, 1));
2450
0
    return copy;
2451
0
}
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
10.2k
{
2460
10.2k
    void *result;
2461
2462
10.2k
    assert(skind < kind);
2463
10.2k
    switch (kind) {
2464
5.47k
    case PyUnicode_2BYTE_KIND:
2465
5.47k
        result = PyMem_New(Py_UCS2, len);
2466
5.47k
        if (!result)
2467
0
            return PyErr_NoMemory();
2468
5.47k
        assert(skind == PyUnicode_1BYTE_KIND);
2469
5.47k
        _PyUnicode_CONVERT_BYTES(
2470
5.47k
            Py_UCS1, Py_UCS2,
2471
5.47k
            (const Py_UCS1 *)data,
2472
5.47k
            ((const Py_UCS1 *)data) + len,
2473
5.47k
            result);
2474
5.47k
        return result;
2475
4.81k
    case PyUnicode_4BYTE_KIND:
2476
4.81k
        result = PyMem_New(Py_UCS4, len);
2477
4.81k
        if (!result)
2478
0
            return PyErr_NoMemory();
2479
4.81k
        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
4.81k
        else {
2487
4.81k
            assert(skind == PyUnicode_1BYTE_KIND);
2488
4.81k
            _PyUnicode_CONVERT_BYTES(
2489
4.81k
                Py_UCS1, Py_UCS4,
2490
4.81k
                (const Py_UCS1 *)data,
2491
4.81k
                ((const Py_UCS1 *)data) + len,
2492
4.81k
                result);
2493
4.81k
        }
2494
4.81k
        return result;
2495
0
    default:
2496
0
        Py_UNREACHABLE();
2497
0
        return NULL;
2498
10.2k
    }
2499
10.2k
}
2500
2501
static Py_UCS4*
2502
as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2503
        int copy_null)
2504
0
{
2505
0
    int kind;
2506
0
    const void *data;
2507
0
    Py_ssize_t len, targetlen;
2508
0
    kind = PyUnicode_KIND(string);
2509
0
    data = PyUnicode_DATA(string);
2510
0
    len = PyUnicode_GET_LENGTH(string);
2511
0
    targetlen = len;
2512
0
    if (copy_null)
2513
0
        targetlen++;
2514
0
    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
0
    else {
2522
0
        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
0
    }
2530
0
    if (kind == PyUnicode_1BYTE_KIND) {
2531
0
        const Py_UCS1 *start = (const Py_UCS1 *) data;
2532
0
        _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
2533
0
    }
2534
0
    else if (kind == PyUnicode_2BYTE_KIND) {
2535
0
        const Py_UCS2 *start = (const Py_UCS2 *) data;
2536
0
        _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2537
0
    }
2538
0
    else if (kind == PyUnicode_4BYTE_KIND) {
2539
0
        memcpy(target, data, len * sizeof(Py_UCS4));
2540
0
    }
2541
0
    else {
2542
0
        Py_UNREACHABLE();
2543
0
    }
2544
0
    if (copy_null)
2545
0
        target[len] = 0;
2546
0
    return target;
2547
0
}
2548
2549
Py_UCS4*
2550
PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2551
                 int copy_null)
2552
0
{
2553
0
    if (target == NULL || targetsize < 0) {
2554
0
        PyErr_BadInternalCall();
2555
0
        return NULL;
2556
0
    }
2557
0
    return as_ucs4(string, target, targetsize, copy_null);
2558
0
}
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
87.2k
{
2576
87.2k
    Py_ssize_t length, fill, arglen;
2577
87.2k
    Py_UCS4 maxchar;
2578
2579
87.2k
    length = PyUnicode_GET_LENGTH(str);
2580
87.2k
    if ((precision == -1 || precision >= length) && width <= length) {
2581
85.8k
        return _PyUnicodeWriter_WriteStr(writer, str);
2582
85.8k
    }
2583
2584
1.39k
    if (precision != -1)
2585
1.39k
        length = Py_MIN(precision, length);
2586
2587
1.39k
    arglen = Py_MAX(length, width);
2588
1.39k
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2589
391
        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2590
1.00k
    else
2591
1.00k
        maxchar = writer->maxchar;
2592
2593
1.39k
    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1) {
2594
0
        return -1;
2595
0
    }
2596
1.39k
    assert(_PyUnicodeWriter_CanWrite(writer));
2597
2598
1.39k
    fill = Py_MAX(width - length, 0);
2599
1.39k
    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
1.39k
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2606
1.39k
                                  str, 0, length);
2607
1.39k
    writer->pos += length;
2608
2609
1.39k
    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
1.39k
    return 0;
2616
1.39k
}
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
245k
{
2622
    /* UTF-8 */
2623
245k
    Py_ssize_t *pconsumed = NULL;
2624
245k
    Py_ssize_t length;
2625
245k
    if (precision == -1) {
2626
121k
        length = strlen(str);
2627
121k
    }
2628
124k
    else {
2629
124k
        length = 0;
2630
2.15M
        while (length < precision && str[length]) {
2631
2.02M
            length++;
2632
2.02M
        }
2633
124k
        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
1.14k
            pconsumed = &length;
2640
1.14k
        }
2641
124k
    }
2642
2643
245k
    if (width < 0) {
2644
245k
        return _PyUnicode_DecodeUTF8Writer(writer, str, length,
2645
245k
                                           _Py_ERROR_REPLACE, "replace", pconsumed);
2646
245k
    }
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
0
#define F_LONGLONG 2
2690
70.9k
#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
396k
{
2698
396k
    const char *p;
2699
396k
    Py_ssize_t len;
2700
396k
    int flags = 0;
2701
396k
    Py_ssize_t width;
2702
396k
    Py_ssize_t precision;
2703
2704
396k
    p = f;
2705
396k
    f++;
2706
396k
    if (*f == '%') {
2707
0
        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
2708
0
            return NULL;
2709
0
        f++;
2710
0
        return f;
2711
0
    }
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
398k
    while (1) {
2719
398k
        switch (*f++) {
2720
0
        case '-': flags |= F_LJUST; continue;
2721
1.90k
        case '0': flags |= F_ZERO; continue;
2722
0
        case '#': flags |= F_ALT; continue;
2723
398k
        }
2724
396k
        f--;
2725
396k
        break;
2726
398k
    }
2727
2728
    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2729
396k
    width = -1;
2730
396k
    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
396k
    else if (Py_ISDIGIT((unsigned)*f)) {
2739
1.90k
        width = *f - '0';
2740
1.90k
        f++;
2741
1.90k
        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
1.90k
    }
2751
396k
    precision = -1;
2752
396k
    if (*f == '.') {
2753
129k
        f++;
2754
129k
        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
129k
        else if (Py_ISDIGIT((unsigned)*f)) {
2762
129k
            precision = (*f - '0');
2763
129k
            f++;
2764
384k
            while (Py_ISDIGIT((unsigned)*f)) {
2765
255k
                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
255k
                precision = (precision * 10) + (*f - '0');
2771
255k
                f++;
2772
255k
            }
2773
129k
        }
2774
129k
    }
2775
2776
396k
    int sizemod = 0;
2777
396k
    if (*f == 'l') {
2778
0
        if (f[1] == 'l') {
2779
0
            sizemod = F_LONGLONG;
2780
0
            f += 2;
2781
0
        }
2782
0
        else {
2783
0
            sizemod = F_LONG;
2784
0
            ++f;
2785
0
        }
2786
0
    }
2787
396k
    else if (*f == 'z') {
2788
35.4k
        sizemod = F_SIZE;
2789
35.4k
        ++f;
2790
35.4k
    }
2791
361k
    else if (*f == 't') {
2792
0
        sizemod = F_PTRDIFF;
2793
0
        ++f;
2794
0
    }
2795
361k
    else if (*f == 'j') {
2796
0
        sizemod = F_INTMAX;
2797
0
        ++f;
2798
0
    }
2799
396k
    if (f[0] != '\0' && f[1] == '\0')
2800
55.1k
        writer->overallocate = 0;
2801
2802
396k
    switch (*f) {
2803
44.3k
    case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
2804
44.3k
        break;
2805
19.2k
    case 'c': case 'p':
2806
19.2k
        if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
2807
19.2k
        break;
2808
245k
    case 's':
2809
245k
    case 'V':
2810
245k
        if (sizemod && sizemod != F_LONG) goto invalid_format;
2811
245k
        break;
2812
245k
    default:
2813
87.2k
        if (sizemod) goto invalid_format;
2814
87.2k
        break;
2815
396k
    }
2816
2817
396k
    switch (*f) {
2818
19.2k
    case 'c':
2819
19.2k
    {
2820
19.2k
        int ordinal = va_arg(*vargs, int);
2821
19.2k
        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
19.2k
        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
2827
0
            return NULL;
2828
19.2k
        break;
2829
19.2k
    }
2830
2831
42.3k
    case 'd': case 'i':
2832
44.3k
    case 'o': case 'u': case 'x': case 'X':
2833
44.3k
    {
2834
44.3k
        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
44.3k
        #define SPRINT(SIZE_SPEC, FMT_CHAR, TYPE) \
2848
44.3k
            sprintf(buffer, "%" SIZE_SPEC FMT_CHAR, va_arg(*vargs, TYPE))
2849
2850
        // One inner switch to handle all format variants
2851
44.3k
        #define DO_SPRINTS(SIZE_SPEC, SIGNED_TYPE, UNSIGNED_TYPE)             \
2852
44.3k
            switch (*f) {                                                     \
2853
0
                case 'o': len = SPRINT(SIZE_SPEC, "o", UNSIGNED_TYPE); break; \
2854
0
                case 'u': len = SPRINT(SIZE_SPEC, "u", UNSIGNED_TYPE); break; \
2855
1.29k
                case 'x': len = SPRINT(SIZE_SPEC, "x", UNSIGNED_TYPE); break; \
2856
763
                case 'X': len = SPRINT(SIZE_SPEC, "X", UNSIGNED_TYPE); break; \
2857
42.3k
                default:  len = SPRINT(SIZE_SPEC, "d", SIGNED_TYPE); break;   \
2858
44.3k
            }
2859
2860
        // Outer switch to handle all the sizes/types
2861
44.3k
        switch (sizemod) {
2862
0
            case F_LONG:     DO_SPRINTS("l", long, unsigned long); break;
2863
0
            case F_LONGLONG: DO_SPRINTS("ll", long long, unsigned long long); break;
2864
35.4k
            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
8.90k
            default:         DO_SPRINTS("", int, unsigned int); break;
2868
44.3k
        }
2869
44.3k
        #undef SPRINT
2870
44.3k
        #undef DO_SPRINTS
2871
2872
44.3k
        assert(len >= 1);
2873
2874
44.3k
        int sign = (buffer[0] == '-');
2875
44.3k
        len -= sign;
2876
2877
44.3k
        precision = Py_MAX(precision, len);
2878
44.3k
        width = Py_MAX(width, precision + sign);
2879
44.3k
        if ((flags & F_ZERO) && !(flags & F_LJUST)) {
2880
1.90k
            precision = width - sign;
2881
1.90k
        }
2882
2883
44.3k
        Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
2884
44.3k
        Py_ssize_t zeropad = Py_MAX(precision - len, 0);
2885
2886
44.3k
        if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1) {
2887
0
            return NULL;
2888
0
        }
2889
44.3k
        assert(_PyUnicodeWriter_CanWrite(writer));
2890
2891
44.3k
        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
44.3k
        if (sign) {
2898
0
            if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
2899
0
                return NULL;
2900
0
        }
2901
2902
44.3k
        if (zeropad) {
2903
555
            if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
2904
0
                return NULL;
2905
555
            writer->pos += zeropad;
2906
555
        }
2907
2908
44.3k
        if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
2909
0
            return NULL;
2910
2911
44.3k
        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
44.3k
        break;
2917
44.3k
    }
2918
2919
44.3k
    case 'p':
2920
0
    {
2921
0
        char number[MAX_INTMAX_CHARS];
2922
2923
0
        len = sprintf(number, "%p", va_arg(*vargs, void*));
2924
0
        assert(len >= 0);
2925
2926
        /* %p is ill-defined:  ensure leading 0x. */
2927
0
        if (number[1] == 'X')
2928
0
            number[1] = 'x';
2929
0
        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
0
        if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
2938
0
            return NULL;
2939
0
        break;
2940
0
    }
2941
2942
245k
    case 's':
2943
245k
    {
2944
245k
        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
245k
        else {
2950
            /* UTF-8 */
2951
245k
            const char *s = va_arg(*vargs, const char*);
2952
245k
            if (unicode_fromformat_write_utf8(writer, s, width, precision, flags) < 0)
2953
0
                return NULL;
2954
245k
        }
2955
245k
        break;
2956
245k
    }
2957
2958
245k
    case 'U':
2959
80.2k
    {
2960
80.2k
        PyObject *obj = va_arg(*vargs, PyObject *);
2961
80.2k
        assert(obj && _PyUnicode_CHECK(obj));
2962
2963
80.2k
        if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2964
0
            return NULL;
2965
80.2k
        break;
2966
80.2k
    }
2967
2968
80.2k
    case 'V':
2969
155
    {
2970
155
        PyObject *obj = va_arg(*vargs, PyObject *);
2971
155
        const char *str;
2972
155
        const wchar_t *wstr;
2973
155
        if (sizemod) {
2974
0
            wstr = va_arg(*vargs, const wchar_t*);
2975
0
        }
2976
155
        else {
2977
155
            str = va_arg(*vargs, const char *);
2978
155
        }
2979
155
        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
155
        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
155
        else {
2990
155
            assert(str != NULL);
2991
155
            if (unicode_fromformat_write_utf8(writer, str, width, precision, flags) < 0)
2992
0
                return NULL;
2993
155
        }
2994
155
        break;
2995
155
    }
2996
2997
177
    case 'S':
2998
177
    {
2999
177
        PyObject *obj = va_arg(*vargs, PyObject *);
3000
177
        PyObject *str;
3001
177
        assert(obj);
3002
177
        str = PyObject_Str(obj);
3003
177
        if (!str)
3004
0
            return NULL;
3005
177
        if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
3006
0
            Py_DECREF(str);
3007
0
            return NULL;
3008
0
        }
3009
177
        Py_DECREF(str);
3010
177
        break;
3011
177
    }
3012
3013
6.85k
    case 'R':
3014
6.85k
    {
3015
6.85k
        PyObject *obj = va_arg(*vargs, PyObject *);
3016
6.85k
        PyObject *repr;
3017
6.85k
        assert(obj);
3018
6.85k
        repr = PyObject_Repr(obj);
3019
6.85k
        if (!repr)
3020
0
            return NULL;
3021
6.85k
        if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
3022
0
            Py_DECREF(repr);
3023
0
            return NULL;
3024
0
        }
3025
6.85k
        Py_DECREF(repr);
3026
6.85k
        break;
3027
6.85k
    }
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
0
    case 'T':
3046
0
    {
3047
0
        PyObject *obj = va_arg(*vargs, PyObject *);
3048
0
        PyTypeObject *type = (PyTypeObject *)Py_NewRef(Py_TYPE(obj));
3049
3050
0
        PyObject *type_name;
3051
0
        if (flags & F_ALT) {
3052
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3053
0
        }
3054
0
        else {
3055
0
            type_name = PyType_GetFullyQualifiedName(type);
3056
0
        }
3057
0
        Py_DECREF(type);
3058
0
        if (!type_name) {
3059
0
            return NULL;
3060
0
        }
3061
3062
0
        if (unicode_fromformat_write_str(writer, type_name,
3063
0
                                         width, precision, flags) == -1) {
3064
0
            Py_DECREF(type_name);
3065
0
            return NULL;
3066
0
        }
3067
0
        Py_DECREF(type_name);
3068
0
        break;
3069
0
    }
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
396k
    }
3106
3107
396k
    f++;
3108
396k
    return f;
3109
396k
}
3110
3111
static int
3112
unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
3113
225k
{
3114
225k
    Py_ssize_t len = strlen(format);
3115
225k
    writer->min_length += len + 100;
3116
225k
    writer->overallocate = 1;
3117
3118
    // Copy varags to be able to pass a reference to a subfunction.
3119
225k
    va_list vargs2;
3120
225k
    va_copy(vargs2, vargs);
3121
3122
    // _PyUnicodeWriter_WriteASCIIString() below requires the format string
3123
    // to be encoded to ASCII.
3124
225k
    int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)format, (Py_UCS1*)format + len) < 128);
3125
225k
    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
1.10M
    for (const char *f = format; *f; ) {
3136
882k
        if (*f == '%') {
3137
396k
            f = unicode_fromformat_arg(writer, f, &vargs2);
3138
396k
            if (f == NULL)
3139
0
                goto fail;
3140
396k
        }
3141
485k
        else {
3142
485k
            const char *p = strchr(f, '%');
3143
485k
            if (p != NULL) {
3144
315k
                len = p - f;
3145
315k
            }
3146
170k
            else {
3147
170k
                len = strlen(f);
3148
170k
                writer->overallocate = 0;
3149
170k
            }
3150
3151
485k
            if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
3152
0
                goto fail;
3153
0
            }
3154
485k
            f += len;
3155
485k
        }
3156
882k
    }
3157
225k
    va_end(vargs2);
3158
225k
    return 0;
3159
3160
0
  fail:
3161
0
    va_end(vargs2);
3162
0
    return -1;
3163
225k
}
3164
3165
PyObject *
3166
PyUnicode_FromFormatV(const char *format, va_list vargs)
3167
225k
{
3168
225k
    _PyUnicodeWriter writer;
3169
225k
    _PyUnicodeWriter_Init(&writer);
3170
3171
225k
    if (unicode_from_format(&writer, format, vargs) < 0) {
3172
0
        _PyUnicodeWriter_Dealloc(&writer);
3173
0
        return NULL;
3174
0
    }
3175
225k
    return _PyUnicodeWriter_Finish(&writer);
3176
225k
}
3177
3178
PyObject *
3179
PyUnicode_FromFormat(const char *format, ...)
3180
62.6k
{
3181
62.6k
    PyObject* ret;
3182
62.6k
    va_list vargs;
3183
3184
62.6k
    va_start(vargs, format);
3185
62.6k
    ret = PyUnicode_FromFormatV(format, vargs);
3186
62.6k
    va_end(vargs);
3187
62.6k
    return ret;
3188
62.6k
}
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
2.43k
{
3223
2.43k
    Py_ssize_t res;
3224
3225
2.43k
    assert(unicode != NULL);
3226
2.43k
    assert(_PyUnicode_CHECK(unicode));
3227
3228
2.43k
    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
0
    return res;
3241
2.43k
}
3242
3243
static void
3244
unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3245
2.43k
{
3246
2.43k
    assert(unicode != NULL);
3247
2.43k
    assert(_PyUnicode_CHECK(unicode));
3248
3249
4.86k
    if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
3250
0
        memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
3251
0
        return;
3252
0
    }
3253
3254
4.86k
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3255
2.43k
        const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3256
133k
        for (; size--; ++s, ++w) {
3257
131k
            *w = *s;
3258
131k
        }
3259
2.43k
    }
3260
0
    else {
3261
0
#if SIZEOF_WCHAR_T == 4
3262
0
        assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3263
0
        const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3264
0
        for (; size--; ++s, ++w) {
3265
0
            *w = *s;
3266
0
        }
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
0
    }
3286
2.43k
}
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
2.43k
{
3344
2.43k
    wchar_t *buffer;
3345
2.43k
    Py_ssize_t buflen;
3346
3347
2.43k
    if (unicode == NULL) {
3348
0
        PyErr_BadInternalCall();
3349
0
        return NULL;
3350
0
    }
3351
2.43k
    if (!PyUnicode_Check(unicode)) {
3352
0
        PyErr_BadArgument();
3353
0
        return NULL;
3354
0
    }
3355
3356
2.43k
    buflen = unicode_get_widechar_size(unicode);
3357
2.43k
    buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
3358
2.43k
    if (buffer == NULL) {
3359
0
        PyErr_NoMemory();
3360
0
        return NULL;
3361
0
    }
3362
2.43k
    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
2.43k
    if (size != NULL) {
3375
1.54k
        *size = buflen;
3376
1.54k
    }
3377
892
    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
2.43k
    return buffer;
3384
2.43k
}
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
493k
{
3439
493k
    if (ordinal < 0 || ordinal > MAX_UNICODE) {
3440
0
        PyErr_SetString(PyExc_ValueError,
3441
0
                        "chr() arg not in range(0x110000)");
3442
0
        return NULL;
3443
0
    }
3444
3445
493k
    return unicode_char((Py_UCS4)ordinal);
3446
493k
}
3447
3448
PyObject *
3449
PyUnicode_FromObject(PyObject *obj)
3450
90.2k
{
3451
    /* XXX Perhaps we should make this API an alias of
3452
       PyObject_Str() instead ?! */
3453
90.2k
    if (PyUnicode_CheckExact(obj)) {
3454
90.2k
        return Py_NewRef(obj);
3455
90.2k
    }
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
216k
{
3472
216k
    Py_buffer buffer;
3473
216k
    PyObject *v;
3474
3475
216k
    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
216k
    if (PyBytes_Check(obj)) {
3482
216k
        if (PyBytes_GET_SIZE(obj) == 0) {
3483
119k
            if (unicode_check_encoding_errors(encoding, errors) < 0) {
3484
0
                return NULL;
3485
0
            }
3486
119k
            _Py_RETURN_UNICODE_EMPTY();
3487
119k
        }
3488
96.8k
        return PyUnicode_Decode(
3489
96.8k
                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3490
96.8k
                encoding, errors);
3491
216k
    }
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
740k
{
3529
740k
    const char *e;
3530
740k
    char *l;
3531
740k
    char *l_end;
3532
740k
    int punct;
3533
3534
740k
    assert(encoding != NULL);
3535
3536
740k
    e = encoding;
3537
740k
    l = lower;
3538
740k
    l_end = &lower[lower_len - 1];
3539
740k
    punct = 0;
3540
17.1M
    while (1) {
3541
17.1M
        char c = *e;
3542
17.1M
        if (c == 0) {
3543
740k
            break;
3544
740k
        }
3545
3546
16.4M
        if (Py_ISALNUM(c) || c == '.') {
3547
15.9M
            if (punct && l != lower) {
3548
34.7k
                if (l == l_end) {
3549
3
                    return 0;
3550
3
                }
3551
34.7k
                *l++ = '_';
3552
34.7k
            }
3553
15.9M
            punct = 0;
3554
3555
15.9M
            if (l == l_end) {
3556
94
                return 0;
3557
94
            }
3558
15.9M
            *l++ = to_lower ? Py_TOLOWER(c) : c;
3559
15.9M
        }
3560
475k
        else {
3561
475k
            punct = 1;
3562
475k
        }
3563
3564
16.4M
        e++;
3565
16.4M
    }
3566
740k
    *l = '\0';
3567
740k
    return 1;
3568
740k
}
3569
3570
PyObject *
3571
PyUnicode_Decode(const char *s,
3572
                 Py_ssize_t size,
3573
                 const char *encoding,
3574
                 const char *errors)
3575
693k
{
3576
693k
    PyObject *buffer = NULL, *unicode;
3577
693k
    Py_buffer info;
3578
693k
    char buflower[11];   /* strlen("iso-8859-1\0") == 11, longest shortcut */
3579
3580
693k
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3581
0
        return NULL;
3582
0
    }
3583
3584
693k
    if (size == 0) {
3585
2
        _Py_RETURN_UNICODE_EMPTY();
3586
2
    }
3587
3588
693k
    if (encoding == NULL) {
3589
0
        return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3590
0
    }
3591
3592
    /* Shortcuts for common default encodings */
3593
693k
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3594
693k
        char *lower = buflower;
3595
3596
        /* Fast paths */
3597
693k
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3598
222k
            lower += 3;
3599
222k
            if (*lower == '_') {
3600
                /* Match "utf8" and "utf_8" */
3601
21.1k
                lower++;
3602
21.1k
            }
3603
3604
222k
            if (lower[0] == '8' && lower[1] == 0) {
3605
11.9k
                return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3606
11.9k
            }
3607
210k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3608
109
                return PyUnicode_DecodeUTF16(s, size, errors, 0);
3609
109
            }
3610
210k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3611
22
                return PyUnicode_DecodeUTF32(s, size, errors, 0);
3612
22
            }
3613
222k
        }
3614
470k
        else {
3615
470k
            if (strcmp(lower, "ascii") == 0
3616
410k
                || strcmp(lower, "us_ascii") == 0) {
3617
59.9k
                return PyUnicode_DecodeASCII(s, size, errors);
3618
59.9k
            }
3619
    #ifdef MS_WINDOWS
3620
            else if (strcmp(lower, "mbcs") == 0) {
3621
                return PyUnicode_DecodeMBCS(s, size, errors);
3622
            }
3623
    #endif
3624
410k
            else if (strcmp(lower, "latin1") == 0
3625
405k
                     || strcmp(lower, "latin_1") == 0
3626
405k
                     || strcmp(lower, "iso_8859_1") == 0
3627
405k
                     || strcmp(lower, "iso8859_1") == 0) {
3628
5.46k
                return PyUnicode_DecodeLatin1(s, size, errors);
3629
5.46k
            }
3630
470k
        }
3631
693k
    }
3632
3633
    /* Decode via the codec registry */
3634
615k
    buffer = NULL;
3635
615k
    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
3636
0
        goto onError;
3637
615k
    buffer = PyMemoryView_FromBuffer(&info);
3638
615k
    if (buffer == NULL)
3639
0
        goto onError;
3640
615k
    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
3641
615k
    if (unicode == NULL)
3642
2.74k
        goto onError;
3643
613k
    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
613k
    Py_DECREF(buffer);
3653
613k
    return unicode_result(unicode);
3654
3655
2.74k
  onError:
3656
2.74k
    Py_XDECREF(buffer);
3657
2.74k
    return NULL;
3658
613k
}
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
902
{
3741
902
    Py_ssize_t wlen;
3742
902
    wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3743
902
    if (wstr == NULL) {
3744
0
        return NULL;
3745
0
    }
3746
3747
902
    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
902
    char *str;
3754
902
    size_t str_len;
3755
902
    size_t error_pos;
3756
902
    int res = _Py_EncodeLocale(wstr, &str, &str_len, &error_pos,
3757
902
                               current_locale, error_handler);
3758
902
    PyMem_Free(wstr);
3759
3760
902
    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
902
    PyObject *bytes = PyBytes_FromStringAndSize(str, str_len);
3785
902
    PyMem_RawFree(str);
3786
902
    return bytes;
3787
902
}
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
8.82k
{
3799
8.82k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3800
8.82k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3801
8.82k
    if (fs_codec->utf8) {
3802
7.92k
        return unicode_encode_utf8(unicode,
3803
7.92k
                                   fs_codec->error_handler,
3804
7.92k
                                   fs_codec->errors);
3805
7.92k
    }
3806
902
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3807
902
    else if (fs_codec->encoding) {
3808
0
        return PyUnicode_AsEncodedString(unicode,
3809
0
                                         fs_codec->encoding,
3810
0
                                         fs_codec->errors);
3811
0
    }
3812
902
#endif
3813
902
    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
902
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3818
902
        const wchar_t *filesystem_errors = config->filesystem_errors;
3819
902
        assert(filesystem_errors != NULL);
3820
902
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3821
902
        assert(errors != _Py_ERROR_UNKNOWN);
3822
#ifdef _Py_FORCE_UTF8_FS_ENCODING
3823
        return unicode_encode_utf8(unicode, errors, NULL);
3824
#else
3825
902
        return unicode_encode_locale(unicode, errors, 0);
3826
902
#endif
3827
902
    }
3828
8.82k
}
3829
3830
PyObject *
3831
PyUnicode_AsEncodedString(PyObject *unicode,
3832
                          const char *encoding,
3833
                          const char *errors)
3834
46.6k
{
3835
46.6k
    PyObject *v;
3836
46.6k
    char buflower[11];   /* strlen("iso_8859_1\0") == 11, longest shortcut */
3837
3838
46.6k
    if (!PyUnicode_Check(unicode)) {
3839
0
        PyErr_BadArgument();
3840
0
        return NULL;
3841
0
    }
3842
3843
46.6k
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3844
0
        return NULL;
3845
0
    }
3846
3847
46.6k
    if (encoding == NULL) {
3848
0
        return _PyUnicode_AsUTF8String(unicode, errors);
3849
0
    }
3850
3851
    /* Shortcuts for common default encodings */
3852
46.6k
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3853
46.6k
        char *lower = buflower;
3854
3855
        /* Fast paths */
3856
46.6k
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3857
66
            lower += 3;
3858
66
            if (*lower == '_') {
3859
                /* Match "utf8" and "utf_8" */
3860
66
                lower++;
3861
66
            }
3862
3863
66
            if (lower[0] == '8' && lower[1] == 0) {
3864
66
                return _PyUnicode_AsUTF8String(unicode, errors);
3865
66
            }
3866
0
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3867
0
                return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3868
0
            }
3869
0
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3870
0
                return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3871
0
            }
3872
66
        }
3873
46.5k
        else {
3874
46.5k
            if (strcmp(lower, "ascii") == 0
3875
31.8k
                || strcmp(lower, "us_ascii") == 0) {
3876
31.8k
                return _PyUnicode_AsASCIIString(unicode, errors);
3877
31.8k
            }
3878
#ifdef MS_WINDOWS
3879
            else if (strcmp(lower, "mbcs") == 0) {
3880
                return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3881
            }
3882
#endif
3883
14.7k
            else if (strcmp(lower, "latin1") == 0 ||
3884
14.7k
                     strcmp(lower, "latin_1") == 0 ||
3885
14.7k
                     strcmp(lower, "iso_8859_1") == 0 ||
3886
14.7k
                     strcmp(lower, "iso8859_1") == 0) {
3887
0
                return _PyUnicode_AsLatin1String(unicode, errors);
3888
0
            }
3889
46.5k
        }
3890
46.6k
    }
3891
3892
    /* Encode via the codec registry */
3893
14.7k
    v = _PyCodec_EncodeText(unicode, encoding, errors);
3894
14.7k
    if (v == NULL)
3895
0
        return NULL;
3896
3897
    /* The normal path */
3898
14.7k
    if (PyBytes_Check(v))
3899
14.7k
        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
13.9k
{
3968
13.9k
    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
13.9k
    wchar_t *wstr;
3974
13.9k
    size_t wlen;
3975
13.9k
    int res = _Py_DecodeLocale(str, &wstr, &wlen, current_locale, errors);
3976
13.9k
    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
13.9k
    PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
4001
13.9k
    PyMem_RawFree(wstr);
4002
13.9k
    return unicode;
4003
13.9k
}
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
6.79k
{
4016
6.79k
    Py_ssize_t size = (Py_ssize_t)strlen(str);
4017
6.79k
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
4018
6.79k
    return unicode_decode_locale(str, size, error_handler, 1);
4019
6.79k
}
4020
4021
4022
PyObject*
4023
26.3k
PyUnicode_DecodeFSDefault(const char *s) {
4024
26.3k
    Py_ssize_t size = (Py_ssize_t)strlen(s);
4025
26.3k
    return PyUnicode_DecodeFSDefaultAndSize(s, size);
4026
26.3k
}
4027
4028
PyObject*
4029
PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
4030
35.3k
{
4031
35.3k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4032
35.3k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
4033
35.3k
    if (fs_codec->utf8) {
4034
28.2k
        return unicode_decode_utf8(s, size,
4035
28.2k
                                   fs_codec->error_handler,
4036
28.2k
                                   fs_codec->errors,
4037
28.2k
                                   NULL);
4038
28.2k
    }
4039
7.12k
#ifndef _Py_FORCE_UTF8_FS_ENCODING
4040
7.12k
    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
7.12k
#endif
4046
7.12k
    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
7.12k
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
4051
7.12k
        const wchar_t *filesystem_errors = config->filesystem_errors;
4052
7.12k
        assert(filesystem_errors != NULL);
4053
7.12k
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
4054
7.12k
        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
7.12k
        return unicode_decode_locale(s, size, errors, 0);
4059
7.12k
#endif
4060
7.12k
    }
4061
35.3k
}
4062
4063
4064
int
4065
PyUnicode_FSConverter(PyObject* arg, void* addr)
4066
6.07k
{
4067
6.07k
    PyObject *path = NULL;
4068
6.07k
    PyObject *output = NULL;
4069
6.07k
    Py_ssize_t size;
4070
6.07k
    const char *data;
4071
6.07k
    if (arg == NULL) {
4072
0
        Py_DECREF(*(PyObject**)addr);
4073
0
        *(PyObject**)addr = NULL;
4074
0
        return 1;
4075
0
    }
4076
6.07k
    path = PyOS_FSPath(arg);
4077
6.07k
    if (path == NULL) {
4078
0
        return 0;
4079
0
    }
4080
6.07k
    if (PyBytes_Check(path)) {
4081
0
        output = path;
4082
0
    }
4083
6.07k
    else {  // PyOS_FSPath() guarantees its returned value is bytes or str.
4084
6.07k
        output = PyUnicode_EncodeFSDefault(path);
4085
6.07k
        Py_DECREF(path);
4086
6.07k
        if (!output) {
4087
0
            return 0;
4088
0
        }
4089
6.07k
        assert(PyBytes_Check(output));
4090
6.07k
    }
4091
4092
6.07k
    size = PyBytes_GET_SIZE(output);
4093
6.07k
    data = PyBytes_AS_STRING(output);
4094
6.07k
    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
6.07k
    *(PyObject**)addr = output;
4100
6.07k
    return Py_CLEANUP_SUPPORTED;
4101
6.07k
}
4102
4103
4104
int
4105
PyUnicode_FSDecoder(PyObject* arg, void* addr)
4106
33
{
4107
33
    if (arg == NULL) {
4108
0
        Py_DECREF(*(PyObject**)addr);
4109
0
        *(PyObject**)addr = NULL;
4110
0
        return 1;
4111
0
    }
4112
4113
33
    PyObject *path = PyOS_FSPath(arg);
4114
33
    if (path == NULL) {
4115
0
        return 0;
4116
0
    }
4117
4118
33
    PyObject *output = NULL;
4119
33
    if (PyUnicode_Check(path)) {
4120
33
        output = path;
4121
33
    }
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
33
    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
4139
33
                 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
33
    *(PyObject**)addr = output;
4145
33
    return Py_CLEANUP_SUPPORTED;
4146
33
}
4147
4148
4149
static int unicode_fill_utf8(PyObject *unicode);
4150
4151
4152
static int
4153
unicode_ensure_utf8(PyObject *unicode)
4154
1.07M
{
4155
1.07M
    int err = 0;
4156
1.07M
    if (PyUnicode_UTF8(unicode) == NULL) {
4157
12.2k
        Py_BEGIN_CRITICAL_SECTION(unicode);
4158
12.2k
        if (PyUnicode_UTF8(unicode) == NULL) {
4159
12.2k
            err = unicode_fill_utf8(unicode);
4160
12.2k
        }
4161
12.2k
        Py_END_CRITICAL_SECTION();
4162
12.2k
    }
4163
1.07M
    return err;
4164
1.07M
}
4165
4166
const char *
4167
PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
4168
1.07M
{
4169
1.07M
    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
1.07M
    if (unicode_ensure_utf8(unicode) == -1) {
4178
38
        if (psize) {
4179
38
            *psize = -1;
4180
38
        }
4181
38
        return NULL;
4182
38
    }
4183
4184
1.07M
    if (psize) {
4185
713k
        *psize = PyUnicode_UTF8_LENGTH(unicode);
4186
713k
    }
4187
1.07M
    return PyUnicode_UTF8(unicode);
4188
1.07M
}
4189
4190
const char *
4191
PyUnicode_AsUTF8(PyObject *unicode)
4192
362k
{
4193
362k
    return PyUnicode_AsUTF8AndSize(unicode, NULL);
4194
362k
}
4195
4196
const char *
4197
_PyUnicode_AsUTF8NoNUL(PyObject *unicode)
4198
495k
{
4199
495k
    Py_ssize_t size;
4200
495k
    const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
4201
495k
    if (s && strlen(s) != (size_t)size) {
4202
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4203
0
        return NULL;
4204
0
    }
4205
495k
    return s;
4206
495k
}
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
702
{
4227
702
    if (!PyUnicode_Check(unicode)) {
4228
0
        PyErr_BadArgument();
4229
0
        return -1;
4230
0
    }
4231
702
    return PyUnicode_GET_LENGTH(unicode);
4232
702
}
4233
4234
Py_UCS4
4235
PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4236
585k
{
4237
585k
    const void *data;
4238
585k
    int kind;
4239
4240
585k
    if (!PyUnicode_Check(unicode)) {
4241
0
        PyErr_BadArgument();
4242
0
        return (Py_UCS4)-1;
4243
0
    }
4244
585k
    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
585k
    data = PyUnicode_DATA(unicode);
4249
585k
    kind = PyUnicode_KIND(unicode);
4250
585k
    return PyUnicode_READ(kind, data, index);
4251
585k
}
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
318k
{
4289
318k
    if (*exceptionObject == NULL) {
4290
5.93k
        *exceptionObject = PyUnicodeDecodeError_Create(
4291
5.93k
            encoding, input, length, startpos, endpos, reason);
4292
5.93k
    }
4293
312k
    else {
4294
312k
        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4295
0
            goto onError;
4296
312k
        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4297
0
            goto onError;
4298
312k
        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4299
0
            goto onError;
4300
312k
    }
4301
318k
    return;
4302
4303
318k
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
318k
{
4442
318k
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4443
4444
318k
    PyObject *restuple = NULL;
4445
318k
    PyObject *repunicode = NULL;
4446
318k
    Py_ssize_t insize;
4447
318k
    Py_ssize_t newpos;
4448
318k
    Py_ssize_t replen;
4449
318k
    Py_ssize_t remain;
4450
318k
    PyObject *inputobj = NULL;
4451
318k
    int need_to_grow = 0;
4452
318k
    const char *new_inptr;
4453
4454
318k
    if (*errorHandler == NULL) {
4455
5.93k
        *errorHandler = PyCodec_LookupError(errors);
4456
5.93k
        if (*errorHandler == NULL)
4457
0
            goto onError;
4458
5.93k
    }
4459
4460
318k
    make_decode_exception(exceptionObject,
4461
318k
        encoding,
4462
318k
        *input, *inend - *input,
4463
318k
        *startinpos, *endinpos,
4464
318k
        reason);
4465
318k
    if (*exceptionObject == NULL)
4466
0
        goto onError;
4467
4468
318k
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4469
318k
    if (restuple == NULL)
4470
5.44k
        goto onError;
4471
312k
    if (!PyTuple_Check(restuple)) {
4472
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4473
0
        goto onError;
4474
0
    }
4475
312k
    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
312k
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4481
312k
    if (!inputobj)
4482
0
        goto onError;
4483
312k
    remain = *inend - *input - *endinpos;
4484
312k
    *input = PyBytes_AS_STRING(inputobj);
4485
312k
    insize = PyBytes_GET_SIZE(inputobj);
4486
312k
    *inend = *input + insize;
4487
    /* we can DECREF safely, as the exception has another reference,
4488
       so the object won't go away. */
4489
312k
    Py_DECREF(inputobj);
4490
4491
312k
    if (newpos<0)
4492
0
        newpos = insize+newpos;
4493
312k
    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
312k
    replen = PyUnicode_GET_LENGTH(repunicode);
4499
312k
    if (replen > 1) {
4500
0
        writer->min_length += replen - 1;
4501
0
        need_to_grow = 1;
4502
0
    }
4503
312k
    new_inptr = *input + newpos;
4504
312k
    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
53
        writer->min_length += *inend - new_inptr - remain;
4511
53
        need_to_grow = 1;
4512
53
    }
4513
312k
    if (need_to_grow) {
4514
53
        writer->overallocate = 1;
4515
53
        if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
4516
53
                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4517
0
            goto onError;
4518
53
    }
4519
312k
    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4520
0
        goto onError;
4521
4522
312k
    *endinpos = newpos;
4523
312k
    *inptr = new_inptr;
4524
4525
    /* we made it! */
4526
312k
    Py_DECREF(restuple);
4527
312k
    return 0;
4528
4529
5.44k
  onError:
4530
5.44k
    Py_XDECREF(restuple);
4531
5.44k
    return -1;
4532
312k
}
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
18.9k
    (((c) >= 'A' && (c) <= 'Z') ||     \
4544
18.9k
     ((c) >= 'a' && (c) <= 'z') ||     \
4545
18.9k
     ((c) >= '0' && (c) <= '9') ||     \
4546
18.9k
     (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
15.9k
    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
4552
15.9k
     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
4553
14.1k
     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
4554
8.30k
     (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
25.6k
    ((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
138
{
4633
138
    const char *starts = s;
4634
138
    Py_ssize_t startinpos;
4635
138
    Py_ssize_t endinpos;
4636
138
    const char *e;
4637
138
    _PyUnicodeWriter writer;
4638
138
    const char *errmsg = "";
4639
138
    int inShift = 0;
4640
138
    Py_ssize_t shiftOutStart;
4641
138
    unsigned int base64bits = 0;
4642
138
    unsigned long base64buffer = 0;
4643
138
    Py_UCS4 surrogate = 0;
4644
138
    PyObject *errorHandler = NULL;
4645
138
    PyObject *exc = NULL;
4646
4647
138
    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
138
    _PyUnicodeWriter_Init(&writer);
4655
138
    writer.min_length = size;
4656
4657
138
    shiftOutStart = 0;
4658
138
    e = s + size;
4659
4660
44.2k
    while (s < e) {
4661
44.1k
        Py_UCS4 ch;
4662
44.1k
      restart:
4663
44.1k
        ch = (unsigned char) *s;
4664
4665
44.1k
        if (inShift) { /* in a base-64 section */
4666
17.4k
            if (IS_BASE64(ch)) { /* consume a base-64 character */
4667
15.9k
                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4668
15.9k
                base64bits += 6;
4669
15.9k
                s++;
4670
15.9k
                if (base64bits >= 16) {
4671
                    /* we have enough bits for a UTF-16 value */
4672
5.85k
                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
4673
5.85k
                    base64bits -= 16;
4674
5.85k
                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4675
5.85k
                    assert(outCh <= 0xffff);
4676
5.85k
                    if (surrogate) {
4677
                        /* expecting a second surrogate */
4678
884
                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4679
687
                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
4680
687
                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
4681
0
                                goto onError;
4682
687
                            surrogate = 0;
4683
687
                            continue;
4684
687
                        }
4685
197
                        else {
4686
197
                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4687
0
                                goto onError;
4688
197
                            surrogate = 0;
4689
197
                        }
4690
884
                    }
4691
5.16k
                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
4692
                        /* first surrogate */
4693
1.56k
                        surrogate = outCh;
4694
1.56k
                    }
4695
3.60k
                    else {
4696
3.60k
                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
4697
0
                            goto onError;
4698
3.60k
                    }
4699
5.16k
                }
4700
15.9k
            }
4701
1.47k
            else { /* now leaving a base-64 section */
4702
1.47k
                inShift = 0;
4703
1.47k
                if (base64bits > 0) { /* left-over bits */
4704
858
                    if (base64bits >= 6) {
4705
                        /* We've seen at least one base-64 character */
4706
25
                        s++;
4707
25
                        errmsg = "partial character in shift sequence";
4708
25
                        goto utf7Error;
4709
25
                    }
4710
833
                    else {
4711
                        /* Some bits remain; they should be zero */
4712
833
                        if (base64buffer != 0) {
4713
8
                            s++;
4714
8
                            errmsg = "non-zero padding bits in shift sequence";
4715
8
                            goto utf7Error;
4716
8
                        }
4717
833
                    }
4718
858
                }
4719
1.44k
                if (surrogate && DECODE_DIRECT(ch)) {
4720
676
                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4721
0
                        goto onError;
4722
676
                }
4723
1.44k
                surrogate = 0;
4724
1.44k
                if (ch == '-') {
4725
                    /* '-' is absorbed; other terminating
4726
                       characters are preserved */
4727
366
                    s++;
4728
366
                }
4729
1.44k
            }
4730
17.4k
        }
4731
26.7k
        else if ( ch == '+' ) {
4732
1.75k
            startinpos = s-starts;
4733
1.75k
            s++; /* consume '+' */
4734
1.75k
            if (s < e && *s == '-') { /* '+-' encodes '+' */
4735
229
                s++;
4736
229
                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
4737
0
                    goto onError;
4738
229
            }
4739
1.52k
            else if (s < e && !IS_BASE64(*s)) {
4740
10
                s++;
4741
10
                errmsg = "ill-formed sequence";
4742
10
                goto utf7Error;
4743
10
            }
4744
1.51k
            else { /* begin base64-encoded section */
4745
1.51k
                inShift = 1;
4746
1.51k
                surrogate = 0;
4747
1.51k
                shiftOutStart = writer.pos;
4748
1.51k
                base64bits = 0;
4749
1.51k
                base64buffer = 0;
4750
1.51k
            }
4751
1.75k
        }
4752
24.9k
        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
4753
24.9k
            s++;
4754
24.9k
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
4755
0
                goto onError;
4756
24.9k
        }
4757
8
        else {
4758
8
            startinpos = s-starts;
4759
8
            s++;
4760
8
            errmsg = "unexpected special character";
4761
8
            goto utf7Error;
4762
8
        }
4763
43.4k
        continue;
4764
43.4k
utf7Error:
4765
51
        endinpos = s-starts;
4766
51
        if (unicode_decode_call_errorhandler_writer(
4767
51
                errors, &errorHandler,
4768
51
                "utf7", errmsg,
4769
51
                &starts, &e, &startinpos, &endinpos, &exc, &s,
4770
51
                &writer))
4771
51
            goto onError;
4772
51
    }
4773
4774
    /* end of string */
4775
4776
87
    if (inShift && !consumed) { /* in shift sequence, no more to follow */
4777
        /* if we're in an inconsistent state, that's an error */
4778
39
        inShift = 0;
4779
39
        if (surrogate ||
4780
35
                (base64bits >= 6) ||
4781
25
                (base64bits > 0 && base64buffer != 0)) {
4782
25
            endinpos = size;
4783
25
            if (unicode_decode_call_errorhandler_writer(
4784
25
                    errors, &errorHandler,
4785
25
                    "utf7", "unterminated shift sequence",
4786
25
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
4787
25
                    &writer))
4788
25
                goto onError;
4789
0
            if (s < e)
4790
0
                goto restart;
4791
0
        }
4792
39
    }
4793
4794
    /* return state */
4795
62
    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
62
    Py_XDECREF(errorHandler);
4809
62
    Py_XDECREF(exc);
4810
62
    return _PyUnicodeWriter_Finish(&writer);
4811
4812
76
  onError:
4813
76
    Py_XDECREF(errorHandler);
4814
76
    Py_XDECREF(exc);
4815
76
    _PyUnicodeWriter_Dealloc(&writer);
4816
76
    return NULL;
4817
62
}
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
59.4M
{
4923
59.4M
    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4924
59.4M
}
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
29.4M
# define ASCII_CHAR_MASK 0x8080808080808080ULL
4946
// used to count codepoints in UTF-8 string.
4947
25.5M
# define VECTOR_0101     0x0101010101010101ULL
4948
318k
# 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
1.31M
{
4962
1.31M
    return __builtin_ctzll((unsigned long long)v);
4963
1.31M
}
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
12.3M
{
4986
12.3M
    union {
4987
12.3M
        size_t s;
4988
12.3M
        unsigned char b[SIZEOF_SIZE_T];
4989
12.3M
    } u;
4990
12.3M
    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
12.3M
    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.40M
    case 7:
5001
2.40M
        u.b[6] = p[6];
5002
2.40M
        _Py_FALLTHROUGH;
5003
4.34M
    case 6:
5004
4.34M
        u.b[5] = p[5];
5005
4.34M
        _Py_FALLTHROUGH;
5006
7.27M
    case 5:
5007
7.27M
        u.b[4] = p[4];
5008
7.27M
        _Py_FALLTHROUGH;
5009
7.27M
#endif
5010
7.95M
    case 4:
5011
7.95M
        u.b[3] = p[3];
5012
7.95M
        _Py_FALLTHROUGH;
5013
9.46M
    case 3:
5014
9.46M
        u.b[2] = p[2];
5015
9.46M
        _Py_FALLTHROUGH;
5016
11.6M
    case 2:
5017
11.6M
        u.b[1] = p[1];
5018
11.6M
        _Py_FALLTHROUGH;
5019
11.9M
    case 1:
5020
11.9M
        u.b[0] = p[0];
5021
11.9M
        break;
5022
385k
    case 0:
5023
385k
        break;
5024
12.3M
    }
5025
12.3M
    return u.s;
5026
12.3M
}
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
13.0M
{
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
13.0M
    const unsigned char *p = start;
5045
5046
13.0M
    if (end - start >= SIZEOF_SIZE_T) {
5047
        // Avoid unaligned read.
5048
3.01M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5049
3.01M
        size_t u;
5050
3.01M
        memcpy(&u, p, sizeof(size_t));
5051
3.01M
        u &= ASCII_CHAR_MASK;
5052
3.01M
        if (u) {
5053
556k
            return (ctz(u) - 7) / 8;
5054
556k
        }
5055
2.46M
        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
10.4M
        for (; end - p >= 8 * SIZEOF_SIZE_T; p += 8 * SIZEOF_SIZE_T) {
5068
8.00M
            const size_t *w = (const size_t *)p;
5069
8.00M
            if ((w[0] | w[1] | w[2] | w[3] |
5070
8.00M
                 w[4] | w[5] | w[6] | w[7]) & ASCII_CHAR_MASK)
5071
38.4k
            {
5072
38.4k
                break;
5073
38.4k
            }
5074
8.00M
        }
5075
5076
2.46M
        const unsigned char *e = end - SIZEOF_SIZE_T;
5077
5.30M
        while (p <= e) {
5078
2.93M
            size_t u = (*(const size_t *)p) & ASCII_CHAR_MASK;
5079
2.93M
            if (u) {
5080
94.8k
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5081
94.8k
                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
94.8k
            }
5088
2.84M
            p += SIZEOF_SIZE_T;
5089
2.84M
        }
5090
2.46M
    }
5091
12.3M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5092
13.0M
    assert((end - p) < SIZEOF_SIZE_T);
5093
    // we can not use *(const size_t*)p to avoid buffer overrun.
5094
12.3M
    size_t u = load_unaligned(p, end - p) & ASCII_CHAR_MASK;
5095
12.3M
    if (u) {
5096
661k
        return p - start + (ctz(u) - 7) / 8;
5097
661k
    }
5098
11.7M
    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
12.3M
}
5109
5110
static inline int
5111
scalar_utf8_start_char(unsigned int ch)
5112
1.19M
{
5113
    // 0xxxxxxx or 11xxxxxx are first byte.
5114
1.19M
    return (~ch >> 7 | ch >> 6) & 1;
5115
1.19M
}
5116
5117
static inline size_t
5118
vector_utf8_start_chars(size_t v)
5119
25.5M
{
5120
25.5M
    return ((~v >> 7) | (v >> 6)) & VECTOR_0101;
5121
25.5M
}
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
342k
{
5128
342k
    Py_ssize_t len = 0;
5129
5130
342k
    if (end - s >= SIZEOF_SIZE_T) {
5131
286k
        while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
5132
211k
            len += scalar_utf8_start_char(*s++);
5133
211k
        }
5134
5135
234k
        while (s + SIZEOF_SIZE_T <= end) {
5136
159k
            const unsigned char *e = end;
5137
159k
            if (e - s > SIZEOF_SIZE_T * 255) {
5138
97.4k
                e = s + SIZEOF_SIZE_T * 255;
5139
97.4k
            }
5140
159k
            Py_ssize_t vstart = 0;
5141
25.7M
            while (s + SIZEOF_SIZE_T <= e) {
5142
25.5M
                size_t v = *(size_t*)s;
5143
25.5M
                size_t vs = vector_utf8_start_chars(v);
5144
25.5M
                vstart += vs;
5145
25.5M
                s += SIZEOF_SIZE_T;
5146
25.5M
            }
5147
159k
            vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF);
5148
159k
            vstart += vstart >> 16;
5149
159k
#if SIZEOF_SIZE_T == 8
5150
159k
            vstart += vstart >> 32;
5151
159k
#endif
5152
159k
            len += vstart & 0x7ff;
5153
159k
        }
5154
75.1k
    }
5155
1.32M
    while (s < end) {
5156
981k
        len += scalar_utf8_start_char(*s++);
5157
981k
    }
5158
342k
    return len;
5159
342k
}
5160
5161
static Py_ssize_t
5162
ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
5163
397k
{
5164
397k
#if SIZEOF_SIZE_T <= SIZEOF_VOID_P
5165
397k
    if (_Py_IS_ALIGNED(start, ALIGNOF_SIZE_T)
5166
154k
        && _Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T))
5167
84.9k
    {
5168
        /* Fast path, see in STRINGLIB(utf8_decode) for
5169
           an explanation. */
5170
84.9k
        const char *p = start;
5171
84.9k
        Py_UCS1 *q = dest;
5172
3.23M
        while (p + SIZEOF_SIZE_T <= end) {
5173
3.14M
            size_t value = *(const size_t *) p;
5174
3.14M
            if (value & ASCII_CHAR_MASK)
5175
448
                break;
5176
3.14M
            *((size_t *)q) = value;
5177
3.14M
            p += SIZEOF_SIZE_T;
5178
3.14M
            q += SIZEOF_SIZE_T;
5179
3.14M
        }
5180
344k
        while (p < end) {
5181
260k
            if ((unsigned char)*p & 0x80)
5182
665
                break;
5183
260k
            *q++ = *p++;
5184
260k
        }
5185
84.9k
        return p - start;
5186
84.9k
    }
5187
312k
#endif
5188
312k
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)start,
5189
312k
                                         (const unsigned char*)end);
5190
312k
    memcpy(dest, start, pos);
5191
312k
    return pos;
5192
397k
}
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
1.32M
{
5201
1.32M
    Py_ssize_t startinpos, endinpos;
5202
1.32M
    const char *errmsg = "";
5203
1.32M
    PyObject *error_handler_obj = NULL;
5204
1.32M
    PyObject *exc = NULL;
5205
5206
2.38M
    while (s < end) {
5207
2.09M
        Py_UCS4 ch;
5208
2.09M
        int kind = writer->kind;
5209
5210
2.09M
        if (kind == PyUnicode_1BYTE_KIND) {
5211
1.24M
            if (PyUnicode_IS_ASCII(writer->buffer))
5212
969k
                ch = asciilib_utf8_decode(&s, end, writer->data, &writer->pos);
5213
271k
            else
5214
271k
                ch = ucs1lib_utf8_decode(&s, end, writer->data, &writer->pos);
5215
1.24M
        } else if (kind == PyUnicode_2BYTE_KIND) {
5216
394k
            ch = ucs2lib_utf8_decode(&s, end, writer->data, &writer->pos);
5217
463k
        } else {
5218
463k
            assert(kind == PyUnicode_4BYTE_KIND);
5219
463k
            ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos);
5220
463k
        }
5221
5222
2.09M
        switch (ch) {
5223
1.03M
        case 0:
5224
1.03M
            if (s == end || consumed)
5225
1.03M
                goto End;
5226
2.48k
            errmsg = "unexpected end of data";
5227
2.48k
            startinpos = s - starts;
5228
2.48k
            endinpos = end - starts;
5229
2.48k
            break;
5230
30.5k
        case 1:
5231
30.5k
            errmsg = "invalid start byte";
5232
30.5k
            startinpos = s - starts;
5233
30.5k
            endinpos = startinpos + 1;
5234
30.5k
            break;
5235
31.4k
        case 2:
5236
31.4k
            if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5237
7
                && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
5238
5
            {
5239
                /* Truncated surrogate code in range D800-DFFF */
5240
5
                goto End;
5241
5
            }
5242
31.4k
            _Py_FALLTHROUGH;
5243
36.1k
        case 3:
5244
37.8k
        case 4:
5245
37.8k
            errmsg = "invalid continuation byte";
5246
37.8k
            startinpos = s - starts;
5247
37.8k
            endinpos = startinpos + ch - 1;
5248
37.8k
            break;
5249
997k
        default:
5250
            // ch doesn't fit into kind, so change the buffer kind to write
5251
            // the character
5252
997k
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
5253
0
                goto onError;
5254
997k
            continue;
5255
2.09M
        }
5256
5257
70.8k
        if (error_handler == _Py_ERROR_UNKNOWN)
5258
3.13k
            error_handler = _Py_GetErrorHandler(errors);
5259
5260
70.8k
        switch (error_handler) {
5261
0
        case _Py_ERROR_IGNORE:
5262
0
            s += (endinpos - startinpos);
5263
0
            break;
5264
5265
61.2k
        case _Py_ERROR_REPLACE:
5266
61.2k
            if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0)
5267
0
                goto onError;
5268
61.2k
            s += (endinpos - startinpos);
5269
61.2k
            break;
5270
5271
0
        case _Py_ERROR_SURROGATEESCAPE:
5272
0
        {
5273
0
            Py_ssize_t i;
5274
5275
0
            if (_PyUnicodeWriter_PrepareKind(writer, PyUnicode_2BYTE_KIND) < 0)
5276
0
                goto onError;
5277
0
            assert(_PyUnicodeWriter_CanWrite(writer));
5278
0
            for (i=startinpos; i<endinpos; i++) {
5279
0
                ch = (Py_UCS4)(unsigned char)(starts[i]);
5280
0
                PyUnicode_WRITE(writer->kind, writer->data, writer->pos,
5281
0
                                ch + 0xdc00);
5282
0
                writer->pos++;
5283
0
            }
5284
0
            s += (endinpos - startinpos);
5285
0
            break;
5286
0
        }
5287
5288
9.64k
        default:
5289
9.64k
            if (unicode_decode_call_errorhandler_writer(
5290
9.64k
                    errors, &error_handler_obj,
5291
9.64k
                    "utf-8", errmsg,
5292
9.64k
                    &starts, &end, &startinpos, &endinpos, &exc, &s,
5293
9.64k
                    writer)) {
5294
4.52k
                goto onError;
5295
4.52k
            }
5296
5297
5.11k
            if (_PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) {
5298
0
                goto onError;
5299
0
            }
5300
70.8k
        }
5301
70.8k
    }
5302
5303
1.31M
End:
5304
1.31M
    if (consumed)
5305
65
        *consumed = s - starts;
5306
5307
1.31M
    Py_XDECREF(error_handler_obj);
5308
1.31M
    Py_XDECREF(exc);
5309
1.31M
    return 0;
5310
5311
4.52k
onError:
5312
4.52k
    Py_XDECREF(error_handler_obj);
5313
4.52k
    Py_XDECREF(exc);
5314
4.52k
    return -1;
5315
1.32M
}
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
64.5M
{
5323
64.5M
    if (size == 0) {
5324
610k
        if (consumed) {
5325
0
            *consumed = 0;
5326
0
        }
5327
610k
        _Py_RETURN_UNICODE_EMPTY();
5328
610k
    }
5329
5330
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5331
63.9M
    if (size == 1 && (unsigned char)s[0] < 128) {
5332
51.2M
        if (consumed) {
5333
0
            *consumed = 1;
5334
0
        }
5335
51.2M
        return get_latin1_char((unsigned char)s[0]);
5336
51.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
12.7M
    if (PY_SSIZE_T_MAX - sizeof(PyCompactUnicodeObject) < (size_t)size) {
5341
0
        PyErr_NoMemory();
5342
0
        return NULL;
5343
0
    }
5344
5345
12.7M
    const char *starts = s;
5346
12.7M
    const char *end = s + size;
5347
5348
12.7M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end);
5349
12.7M
    if (pos == size) {  // fast path: ASCII string.
5350
11.3M
        PyObject *u = PyUnicode_New(size, 127);
5351
11.3M
        if (u == NULL) {
5352
0
            return NULL;
5353
0
        }
5354
11.3M
        memcpy(PyUnicode_1BYTE_DATA(u), s, size);
5355
11.3M
        if (consumed) {
5356
0
            *consumed = size;
5357
0
        }
5358
11.3M
        return u;
5359
11.3M
    }
5360
5361
1.31M
    int maxchr = 127;
5362
1.31M
    Py_ssize_t maxsize = size;
5363
5364
1.31M
    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
1.31M
    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
342k
        maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end);
5377
342k
        if (ch < 0xc4) { // latin1
5378
219k
            maxchr = 0xff;
5379
219k
        }
5380
123k
        else if (ch < 0xf0) { // ucs2
5381
70.5k
            maxchr = 0xffff;
5382
70.5k
        }
5383
53.2k
        else { // ucs4
5384
53.2k
            maxchr = 0x10ffff;
5385
53.2k
        }
5386
342k
    }
5387
1.31M
    PyObject *u = PyUnicode_New(maxsize, maxchr);
5388
1.31M
    if (!u) {
5389
0
        return NULL;
5390
0
    }
5391
5392
    // Use _PyUnicodeWriter after fast path is failed.
5393
1.31M
    _PyUnicodeWriter writer;
5394
1.31M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
5395
1.31M
    if (maxchr <= 255) {
5396
1.18M
        memcpy(PyUnicode_1BYTE_DATA(u), s, pos);
5397
1.18M
        s += pos;
5398
1.18M
        writer.pos = pos;
5399
1.18M
    }
5400
5401
1.31M
    if (unicode_decode_utf8_impl(&writer, starts, s, end,
5402
1.31M
                                 error_handler, errors,
5403
1.31M
                                 consumed) < 0) {
5404
4.52k
        _PyUnicodeWriter_Dealloc(&writer);
5405
4.52k
        return NULL;
5406
4.52k
    }
5407
1.30M
    return _PyUnicodeWriter_Finish(&writer);
5408
1.31M
}
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
400k
{
5418
400k
    if (size == 0) {
5419
54.0k
        if (consumed) {
5420
0
            *consumed = 0;
5421
0
        }
5422
54.0k
        return 0;
5423
54.0k
    }
5424
5425
346k
    Py_ssize_t old_pos = writer->pos;
5426
346k
    Py_UCS4 old_maxchar = writer->maxchar;
5427
5428
    // fast path: try ASCII string.
5429
346k
    if (_PyUnicodeWriter_Prepare(writer, size, 127) < 0) {
5430
0
        goto error;
5431
0
    }
5432
346k
    assert(_PyUnicodeWriter_CanWrite(writer));
5433
5434
346k
    const char *starts = s;
5435
346k
    const char *end = s + size;
5436
346k
    if (writer->kind == PyUnicode_1BYTE_KIND) {
5437
335k
        Py_UCS1 *dest = (Py_UCS1*)writer->data + writer->pos * writer->kind;
5438
335k
        Py_ssize_t decoded = ascii_decode(s, end, dest);
5439
335k
        writer->pos += decoded;
5440
5441
335k
        if (decoded == size) {
5442
333k
            if (consumed) {
5443
1.08k
                *consumed = size;
5444
1.08k
            }
5445
333k
            return 0;
5446
333k
        }
5447
1.95k
        s += decoded;
5448
1.95k
    }
5449
5450
13.6k
    int res = unicode_decode_utf8_impl(writer, starts, s, end,
5451
13.6k
                                       error_handler, errors, consumed);
5452
13.6k
    if (res < 0) {
5453
0
        goto error;
5454
0
    }
5455
13.6k
    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
13.6k
}
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
64.5M
{
5477
64.5M
    return unicode_decode_utf8(s, size,
5478
64.5M
                               errors ? _Py_ERROR_UNKNOWN : _Py_ERROR_STRICT,
5479
64.5M
                               errors, consumed);
5480
64.5M
}
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
7.26k
{
5505
7.26k
    assert(0 <= size);
5506
7.26k
    assert(s != NULL);
5507
7.26k
    assert(wstr != NULL);
5508
5509
7.26k
    int surrogateescape = 0;
5510
7.26k
    int surrogatepass = 0;
5511
7.26k
    switch (errors)
5512
7.26k
    {
5513
0
    case _Py_ERROR_STRICT:
5514
0
        break;
5515
7.26k
    case _Py_ERROR_SURROGATEESCAPE:
5516
7.26k
        surrogateescape = 1;
5517
7.26k
        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
7.26k
    }
5524
5525
    /* Note: size will always be longer than the resulting Unicode
5526
       character count */
5527
7.26k
    if ((size_t)PY_SSIZE_T_MAX / sizeof(wchar_t) - 1 < (size_t)size) {
5528
0
        return _Py_CODEC_MEMORY_ERROR;
5529
0
    }
5530
7.26k
    wchar_t *unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
5531
7.26k
    if (!unicode) {
5532
0
        return _Py_CODEC_MEMORY_ERROR;
5533
0
    }
5534
5535
    /* Unpack UTF-8 encoded data */
5536
7.26k
    const char *orig_s = s;
5537
7.26k
    const char *e = s + size;
5538
7.26k
    Py_ssize_t outpos = 0;
5539
7.26k
    while (s < e) {
5540
7.26k
        Py_UCS4 ch;
5541
7.26k
#if SIZEOF_WCHAR_T == 4
5542
7.26k
        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
7.26k
        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
7.26k
        else {
5557
7.26k
            if (!ch && s == e) {
5558
7.26k
                break;
5559
7.26k
            }
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
7.26k
    }
5586
7.26k
    unicode[outpos] = L'\0';
5587
7.26k
    if (wlen) {
5588
7.26k
        *wlen = outpos;
5589
7.26k
    }
5590
7.26k
    *wstr = unicode;
5591
7.26k
    return 0;
5592
7.26k
}
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.10k
{
5635
1.10k
    assert(str != NULL);
5636
1.10k
    assert(output_length != NULL);
5637
5638
    // U+10ffff encoded to UTF-8 takes 4 bytes
5639
1.10k
    const size_t max_char_size = 4;
5640
1.10k
    size_t len = wcslen(text);
5641
5642
1.10k
    int surrogateescape = 0;
5643
1.10k
    int surrogatepass = 0;
5644
1.10k
    switch (errors)
5645
1.10k
    {
5646
88
    case _Py_ERROR_STRICT:
5647
88
        break;
5648
1.01k
    case _Py_ERROR_SURROGATEESCAPE:
5649
1.01k
        surrogateescape = 1;
5650
1.01k
        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.10k
    }
5657
5658
1.10k
    if (len > (size_t)PY_SSIZE_T_MAX / max_char_size - 1) {
5659
0
        return _Py_CODEC_MEMORY_ERROR;
5660
0
    }
5661
1.10k
    char *bytes;
5662
1.10k
    if (raw_malloc) {
5663
1.10k
        bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5664
1.10k
    }
5665
0
    else {
5666
0
        bytes = PyMem_Malloc((len + 1) * max_char_size);
5667
0
    }
5668
1.10k
    if (bytes == NULL) {
5669
0
        return _Py_CODEC_MEMORY_ERROR;
5670
0
    }
5671
5672
1.10k
    char *p = bytes;
5673
71.1k
    for (size_t i = 0; i < len; ) {
5674
70.0k
        Py_ssize_t ch_pos = i;
5675
70.0k
        Py_UCS4 ch = text[i];
5676
70.0k
        i++;
5677
70.0k
        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
70.0k
        if (ch < 0x80) {
5687
            /* Encode ASCII */
5688
70.0k
            *p++ = (char) ch;
5689
70.0k
        }
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
70.0k
    }
5725
5726
1.10k
    *p++ = '\0';  // trailing NUL byte
5727
1.10k
    size_t final_size = (p - bytes);
5728
1.10k
    assert(final_size >= 1);
5729
1.10k
    *output_length = final_size - 1;  // -1 for the trailing NUL byte
5730
5731
1.10k
    char *result;
5732
1.10k
    if (raw_malloc) {
5733
1.10k
        result = PyMem_RawRealloc(bytes, final_size);
5734
1.10k
    }
5735
0
    else {
5736
0
        result = PyMem_Realloc(bytes, final_size);
5737
0
    }
5738
1.10k
    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.10k
    *str = result;
5748
1.10k
    return 0;
5749
1.10k
}
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
8.24k
{
5763
8.24k
    if (!PyUnicode_Check(unicode)) {
5764
0
        PyErr_BadArgument();
5765
0
        return NULL;
5766
0
    }
5767
5768
8.24k
    if (PyUnicode_UTF8(unicode))
5769
8.03k
        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5770
8.03k
                                         PyUnicode_UTF8_LENGTH(unicode));
5771
5772
208
    int kind = PyUnicode_KIND(unicode);
5773
208
    const void *data = PyUnicode_DATA(unicode);
5774
208
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5775
5776
208
    PyBytesWriter *writer;
5777
208
    char *end;
5778
5779
208
    switch (kind) {
5780
0
    default:
5781
0
        Py_UNREACHABLE();
5782
26
    case PyUnicode_1BYTE_KIND:
5783
        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5784
26
        assert(!PyUnicode_IS_ASCII(unicode));
5785
26
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5786
26
                                      error_handler, errors, &end);
5787
26
        break;
5788
114
    case PyUnicode_2BYTE_KIND:
5789
114
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5790
114
                                      error_handler, errors, &end);
5791
114
        break;
5792
68
    case PyUnicode_4BYTE_KIND:
5793
68
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5794
68
                                      error_handler, errors, &end);
5795
68
        break;
5796
208
    }
5797
5798
208
    if (writer == NULL) {
5799
0
        PyBytesWriter_Discard(writer);
5800
0
        return NULL;
5801
0
    }
5802
208
    return PyBytesWriter_FinishWithPointer(writer, end);
5803
208
}
5804
5805
static int
5806
unicode_fill_utf8(PyObject *unicode)
5807
12.2k
{
5808
12.2k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(unicode);
5809
    /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5810
12.2k
    assert(!PyUnicode_IS_ASCII(unicode));
5811
5812
12.2k
    int kind = PyUnicode_KIND(unicode);
5813
12.2k
    const void *data = PyUnicode_DATA(unicode);
5814
12.2k
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5815
5816
12.2k
    PyBytesWriter *writer;
5817
12.2k
    char *end;
5818
5819
12.2k
    switch (kind) {
5820
0
    default:
5821
0
        Py_UNREACHABLE();
5822
5.34k
    case PyUnicode_1BYTE_KIND:
5823
5.34k
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5824
5.34k
                                      _Py_ERROR_STRICT, NULL, &end);
5825
5.34k
        break;
5826
5.06k
    case PyUnicode_2BYTE_KIND:
5827
5.06k
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5828
5.06k
                                      _Py_ERROR_STRICT, NULL, &end);
5829
5.06k
        break;
5830
1.80k
    case PyUnicode_4BYTE_KIND:
5831
1.80k
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5832
1.80k
                                      _Py_ERROR_STRICT, NULL, &end);
5833
1.80k
        break;
5834
12.2k
    }
5835
12.2k
    if (writer == NULL) {
5836
38
        return -1;
5837
38
    }
5838
5839
12.1k
    const char *start = PyBytesWriter_GetData(writer);
5840
12.1k
    Py_ssize_t len = end - start;
5841
5842
12.1k
    char *cache = PyMem_Malloc(len + 1);
5843
12.1k
    if (cache == NULL) {
5844
0
        PyBytesWriter_Discard(writer);
5845
0
        PyErr_NoMemory();
5846
0
        return -1;
5847
0
    }
5848
12.1k
    memcpy(cache, start, len);
5849
12.1k
    cache[len] = '\0';
5850
12.1k
    PyUnicode_SET_UTF8_LENGTH(unicode, len);
5851
12.1k
    PyUnicode_SET_UTF8(unicode, cache);
5852
12.1k
    PyBytesWriter_Discard(writer);
5853
12.1k
    return 0;
5854
12.1k
}
5855
5856
PyObject *
5857
_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5858
319
{
5859
319
    return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5860
319
}
5861
5862
5863
PyObject *
5864
PyUnicode_AsUTF8String(PyObject *unicode)
5865
249
{
5866
249
    return _PyUnicode_AsUTF8String(unicode, NULL);
5867
249
}
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
22
{
5877
22
    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5878
22
}
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
366
{
5887
366
    const char *starts = s;
5888
366
    Py_ssize_t startinpos;
5889
366
    Py_ssize_t endinpos;
5890
366
    _PyUnicodeWriter writer;
5891
366
    const unsigned char *q, *e;
5892
366
    int le, bo = 0;       /* assume native ordering by default */
5893
366
    const char *encoding;
5894
366
    const char *errmsg = "";
5895
366
    PyObject *errorHandler = NULL;
5896
366
    PyObject *exc = NULL;
5897
5898
366
    q = (const unsigned char *)s;
5899
366
    e = q + size;
5900
5901
366
    if (byteorder)
5902
344
        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
366
    if (bo == 0 && size >= 4) {
5909
39
        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5910
39
        if (bom == 0x0000FEFF) {
5911
3
            bo = -1;
5912
3
            q += 4;
5913
3
        }
5914
36
        else if (bom == 0xFFFE0000) {
5915
11
            bo = 1;
5916
11
            q += 4;
5917
11
        }
5918
39
        if (byteorder)
5919
17
            *byteorder = bo;
5920
39
    }
5921
5922
366
    if (q == e) {
5923
2
        if (consumed)
5924
0
            *consumed = size;
5925
2
        _Py_RETURN_UNICODE_EMPTY();
5926
2
    }
5927
5928
#ifdef WORDS_BIGENDIAN
5929
    le = bo < 0;
5930
#else
5931
364
    le = bo <= 0;
5932
364
#endif
5933
364
    encoding = le ? "utf-32-le" : "utf-32-be";
5934
5935
364
    _PyUnicodeWriter_Init(&writer);
5936
364
    writer.min_length = (e - q + 3) / 4;
5937
364
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
5938
0
        goto onError;
5939
5940
1.88k
    while (1) {
5941
1.88k
        Py_UCS4 ch = 0;
5942
1.88k
        Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
5943
5944
1.88k
        if (e - q >= 4) {
5945
1.78k
            int kind = writer.kind;
5946
1.78k
            void *data = writer.data;
5947
1.78k
            const unsigned char *last = e - 4;
5948
1.78k
            Py_ssize_t pos = writer.pos;
5949
1.78k
            if (le) {
5950
12.1k
                do {
5951
12.1k
                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5952
12.1k
                    if (ch > maxch)
5953
232
                        break;
5954
11.8k
                    if (kind != PyUnicode_1BYTE_KIND &&
5955
8.62k
                        Py_UNICODE_IS_SURROGATE(ch))
5956
315
                        break;
5957
11.5k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5958
11.5k
                    q += 4;
5959
11.5k
                } while (q <= last);
5960
594
            }
5961
1.18k
            else {
5962
227k
                do {
5963
227k
                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5964
227k
                    if (ch > maxch)
5965
275
                        break;
5966
227k
                    if (kind != PyUnicode_1BYTE_KIND &&
5967
185k
                        Py_UNICODE_IS_SURROGATE(ch))
5968
858
                        break;
5969
226k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5970
226k
                    q += 4;
5971
226k
                } while (q <= last);
5972
1.18k
            }
5973
1.78k
            writer.pos = pos;
5974
1.78k
        }
5975
5976
1.88k
        if (Py_UNICODE_IS_SURROGATE(ch)) {
5977
1.21k
            errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
5978
1.21k
            startinpos = ((const char *)q) - starts;
5979
1.21k
            endinpos = startinpos + 4;
5980
1.21k
        }
5981
669
        else if (ch <= maxch) {
5982
207
            if (q == e || consumed)
5983
183
                break;
5984
            /* remaining bytes at the end? (size should be divisible by 4) */
5985
24
            errmsg = "truncated data";
5986
24
            startinpos = ((const char *)q) - starts;
5987
24
            endinpos = ((const char *)e) - starts;
5988
24
        }
5989
462
        else {
5990
462
            if (ch < 0x110000) {
5991
305
                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
5992
0
                    goto onError;
5993
305
                q += 4;
5994
305
                continue;
5995
305
            }
5996
157
            errmsg = "code point not in range(0x110000)";
5997
157
            startinpos = ((const char *)q) - starts;
5998
157
            endinpos = startinpos + 4;
5999
157
        }
6000
6001
        /* The remaining input chars are ignored if the callback
6002
           chooses to skip the input */
6003
1.39k
        if (unicode_decode_call_errorhandler_writer(
6004
1.39k
                errors, &errorHandler,
6005
1.39k
                encoding, errmsg,
6006
1.39k
                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
6007
1.39k
                &writer))
6008
181
            goto onError;
6009
1.39k
    }
6010
6011
183
    if (consumed)
6012
0
        *consumed = (const char *)q-starts;
6013
6014
183
    Py_XDECREF(errorHandler);
6015
183
    Py_XDECREF(exc);
6016
183
    return _PyUnicodeWriter_Finish(&writer);
6017
6018
181
  onError:
6019
181
    _PyUnicodeWriter_Dealloc(&writer);
6020
181
    Py_XDECREF(errorHandler);
6021
181
    Py_XDECREF(exc);
6022
181
    return NULL;
6023
364
}
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
109
{
6193
109
    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
6194
109
}
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
8.86k
{
6203
8.86k
    const char *starts = s;
6204
8.86k
    Py_ssize_t startinpos;
6205
8.86k
    Py_ssize_t endinpos;
6206
8.86k
    _PyUnicodeWriter writer;
6207
8.86k
    const unsigned char *q, *e;
6208
8.86k
    int bo = 0;       /* assume native ordering by default */
6209
8.86k
    int native_ordering;
6210
8.86k
    const char *errmsg = "";
6211
8.86k
    PyObject *errorHandler = NULL;
6212
8.86k
    PyObject *exc = NULL;
6213
8.86k
    const char *encoding;
6214
6215
8.86k
    q = (const unsigned char *)s;
6216
8.86k
    e = q + size;
6217
6218
8.86k
    if (byteorder)
6219
8.75k
        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
8.86k
    if (bo == 0 && size >= 2) {
6226
150
        const Py_UCS4 bom = (q[1] << 8) | q[0];
6227
150
        if (bom == 0xFEFF) {
6228
18
            q += 2;
6229
18
            bo = -1;
6230
18
        }
6231
132
        else if (bom == 0xFFFE) {
6232
27
            q += 2;
6233
27
            bo = 1;
6234
27
        }
6235
150
        if (byteorder)
6236
41
            *byteorder = bo;
6237
150
    }
6238
6239
8.86k
    if (q == e) {
6240
2
        if (consumed)
6241
0
            *consumed = size;
6242
2
        _Py_RETURN_UNICODE_EMPTY();
6243
2
    }
6244
6245
8.85k
#if PY_LITTLE_ENDIAN
6246
8.85k
    native_ordering = bo <= 0;
6247
8.85k
    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
8.85k
    _PyUnicodeWriter_Init(&writer);
6257
8.85k
    writer.min_length = (e - q + 1) / 2;
6258
8.85k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
6259
0
        goto onError;
6260
6261
321k
    while (1) {
6262
321k
        Py_UCS4 ch = 0;
6263
321k
        if (e - q >= 2) {
6264
316k
            int kind = writer.kind;
6265
316k
            if (kind == PyUnicode_1BYTE_KIND) {
6266
11.8k
                if (PyUnicode_IS_ASCII(writer.buffer))
6267
8.85k
                    ch = asciilib_utf16_decode(&q, e,
6268
8.85k
                            (Py_UCS1*)writer.data, &writer.pos,
6269
8.85k
                            native_ordering);
6270
3.00k
                else
6271
3.00k
                    ch = ucs1lib_utf16_decode(&q, e,
6272
3.00k
                            (Py_UCS1*)writer.data, &writer.pos,
6273
3.00k
                            native_ordering);
6274
304k
            } else if (kind == PyUnicode_2BYTE_KIND) {
6275
253k
                ch = ucs2lib_utf16_decode(&q, e,
6276
253k
                        (Py_UCS2*)writer.data, &writer.pos,
6277
253k
                        native_ordering);
6278
253k
            } else {
6279
50.3k
                assert(kind == PyUnicode_4BYTE_KIND);
6280
50.3k
                ch = ucs4lib_utf16_decode(&q, e,
6281
50.3k
                        (Py_UCS4*)writer.data, &writer.pos,
6282
50.3k
                        native_ordering);
6283
50.3k
            }
6284
316k
        }
6285
6286
321k
        switch (ch)
6287
321k
        {
6288
8.83k
        case 0:
6289
            /* remaining byte at the end? (size should be even) */
6290
8.83k
            if (q == e || consumed)
6291
8.54k
                goto End;
6292
298
            errmsg = "truncated data";
6293
298
            startinpos = ((const char *)q) - starts;
6294
298
            endinpos = ((const char *)e) - starts;
6295
298
            break;
6296
            /* The remaining input chars are ignored if the callback
6297
               chooses to skip the input */
6298
146
        case 1:
6299
146
            q -= 2;
6300
146
            if (consumed)
6301
0
                goto End;
6302
146
            errmsg = "unexpected end of data";
6303
146
            startinpos = ((const char *)q) - starts;
6304
146
            endinpos = ((const char *)e) - starts;
6305
146
            break;
6306
281k
        case 2:
6307
281k
            errmsg = "illegal encoding";
6308
281k
            startinpos = ((const char *)q) - 2 - starts;
6309
281k
            endinpos = startinpos + 2;
6310
281k
            break;
6311
20.1k
        case 3:
6312
20.1k
            errmsg = "illegal UTF-16 surrogate";
6313
20.1k
            startinpos = ((const char *)q) - 4 - starts;
6314
20.1k
            endinpos = startinpos + 2;
6315
20.1k
            break;
6316
10.7k
        default:
6317
10.7k
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
6318
0
                goto onError;
6319
10.7k
            continue;
6320
321k
        }
6321
6322
302k
        if (unicode_decode_call_errorhandler_writer(
6323
302k
                errors,
6324
302k
                &errorHandler,
6325
302k
                encoding, errmsg,
6326
302k
                &starts,
6327
302k
                (const char **)&e,
6328
302k
                &startinpos,
6329
302k
                &endinpos,
6330
302k
                &exc,
6331
302k
                (const char **)&q,
6332
302k
                &writer))
6333
319
            goto onError;
6334
302k
    }
6335
6336
8.54k
End:
6337
8.54k
    if (consumed)
6338
0
        *consumed = (const char *)q-starts;
6339
6340
8.54k
    Py_XDECREF(errorHandler);
6341
8.54k
    Py_XDECREF(exc);
6342
8.54k
    return _PyUnicodeWriter_Finish(&writer);
6343
6344
319
  onError:
6345
319
    _PyUnicodeWriter_Dealloc(&writer);
6346
319
    Py_XDECREF(errorHandler);
6347
319
    Py_XDECREF(exc);
6348
319
    return NULL;
6349
8.85k
}
6350
6351
PyObject *
6352
_PyUnicode_EncodeUTF16(PyObject *str,
6353
                       const char *errors,
6354
                       int byteorder)
6355
0
{
6356
0
    if (!PyUnicode_Check(str)) {
6357
0
        PyErr_BadArgument();
6358
0
        return NULL;
6359
0
    }
6360
0
    int kind = PyUnicode_KIND(str);
6361
0
    const void *data = PyUnicode_DATA(str);
6362
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6363
6364
0
    Py_ssize_t pairs = 0;
6365
0
    if (kind == PyUnicode_4BYTE_KIND) {
6366
0
        const Py_UCS4 *in = (const Py_UCS4 *)data;
6367
0
        const Py_UCS4 *end = in + len;
6368
0
        while (in < end) {
6369
0
            if (*in++ >= 0x10000) {
6370
0
                pairs++;
6371
0
            }
6372
0
        }
6373
0
    }
6374
0
    if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
6375
0
        return PyErr_NoMemory();
6376
0
    }
6377
0
    Py_ssize_t nsize = len + pairs + (byteorder == 0);
6378
6379
#if PY_BIG_ENDIAN
6380
    int native_ordering = byteorder >= 0;
6381
#else
6382
0
    int native_ordering = byteorder <= 0;
6383
0
#endif
6384
6385
0
    if (kind == PyUnicode_1BYTE_KIND) {
6386
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6387
        // on short strings
6388
0
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 2);
6389
0
        if (v == NULL) {
6390
0
            return NULL;
6391
0
        }
6392
6393
        /* output buffer is 2-bytes aligned */
6394
0
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
6395
0
        unsigned short *out = (unsigned short *)PyBytes_AS_STRING(v);
6396
0
        if (byteorder == 0) {
6397
0
            *out++ = 0xFEFF;
6398
0
        }
6399
0
        if (len > 0) {
6400
0
            ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
6401
0
        }
6402
0
        return v;
6403
0
    }
6404
6405
0
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 2);
6406
0
    if (writer == NULL) {
6407
0
        return NULL;
6408
0
    }
6409
6410
    /* output buffer is 2-bytes aligned */
6411
0
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 2));
6412
0
    unsigned short *out = PyBytesWriter_GetData(writer);
6413
0
    if (byteorder == 0) {
6414
0
        *out++ = 0xFEFF;
6415
0
    }
6416
0
    if (len == 0) {
6417
0
        return PyBytesWriter_Finish(writer);
6418
0
    }
6419
6420
0
    const char *encoding;
6421
0
    if (byteorder < 0) {
6422
0
        encoding = "utf-16-le";
6423
0
    }
6424
0
    else if (byteorder > 0) {
6425
0
        encoding = "utf-16-be";
6426
0
    }
6427
0
    else {
6428
0
        encoding = "utf-16";
6429
0
    }
6430
6431
0
    PyObject *errorHandler = NULL;
6432
0
    PyObject *exc = NULL;
6433
0
    PyObject *rep = NULL;
6434
6435
0
    for (Py_ssize_t pos = 0; pos < len; ) {
6436
0
        if (kind == PyUnicode_2BYTE_KIND) {
6437
0
            pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
6438
0
                                        &out, native_ordering);
6439
0
        }
6440
0
        else {
6441
0
            assert(kind == PyUnicode_4BYTE_KIND);
6442
0
            pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
6443
0
                                        &out, native_ordering);
6444
0
        }
6445
0
        if (pos == len)
6446
0
            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
0
    Py_XDECREF(errorHandler);
6502
0
    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
0
    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
0
}
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
3.13k
{
6526
3.13k
    PyInterpreterState *interp = _PyInterpreterState_GET();
6527
3.13k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6528
6529
3.13k
    ucnhash_capi = _Py_atomic_load_ptr(&interp->unicode.ucnhash_capi);
6530
3.13k
    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
3.13k
    return ucnhash_capi;
6538
3.13k
}
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
33.0k
{
6550
33.0k
    const char *starts = s;
6551
33.0k
    const char *initial_starts = starts;
6552
33.0k
    _PyUnicodeWriter writer;
6553
33.0k
    const char *end;
6554
33.0k
    PyObject *errorHandler = NULL;
6555
33.0k
    PyObject *exc = NULL;
6556
33.0k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6557
6558
    // so we can remember if we've seen an invalid escape char or not
6559
33.0k
    *first_invalid_escape_char = -1;
6560
33.0k
    *first_invalid_escape_ptr = NULL;
6561
6562
33.0k
    if (size == 0) {
6563
3.52k
        if (consumed) {
6564
1
            *consumed = 0;
6565
1
        }
6566
3.52k
        _Py_RETURN_UNICODE_EMPTY();
6567
3.52k
    }
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.5k
    _PyUnicodeWriter_Init(&writer);
6574
29.5k
    writer.min_length = size;
6575
29.5k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6576
0
        goto onError;
6577
0
    }
6578
6579
29.5k
    end = s + size;
6580
21.0M
    while (s < end) {
6581
21.0M
        unsigned char c = (unsigned char) *s++;
6582
21.0M
        Py_UCS4 ch;
6583
21.0M
        int count;
6584
21.0M
        const char *message;
6585
6586
21.0M
#define WRITE_ASCII_CHAR(ch)                                                  \
6587
21.0M
            do {                                                              \
6588
3.91M
                assert(ch <= 127);                                            \
6589
3.91M
                assert(writer.pos < writer.size);                             \
6590
3.91M
                PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch);  \
6591
3.91M
            } while(0)
6592
6593
21.0M
#define WRITE_CHAR(ch)                                                        \
6594
21.0M
            do {                                                              \
6595
17.6M
                if (ch <= writer.maxchar) {                                   \
6596
17.6M
                    assert(writer.pos < writer.size);                         \
6597
17.6M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6598
17.6M
                }                                                             \
6599
17.6M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6600
0
                    goto onError;                                             \
6601
0
                }                                                             \
6602
17.6M
            } while(0)
6603
6604
        /* Non-escape characters are interpreted as Unicode ordinals */
6605
21.0M
        if (c != '\\') {
6606
16.0M
            WRITE_CHAR(c);
6607
16.0M
            continue;
6608
16.0M
        }
6609
6610
4.98M
        Py_ssize_t startinpos = s - starts - 1;
6611
        /* \ - Escapes */
6612
4.98M
        if (s >= end) {
6613
0
            message = "\\ at end of string";
6614
0
            goto incomplete;
6615
0
        }
6616
4.98M
        c = (unsigned char) *s++;
6617
6618
4.98M
        assert(writer.pos < writer.size);
6619
4.98M
        switch (c) {
6620
6621
            /* \x escapes */
6622
2.08k
        case '\n': continue;
6623
367k
        case '\\': WRITE_ASCII_CHAR('\\'); continue;
6624
367k
        case '\'': WRITE_ASCII_CHAR('\''); continue;
6625
422k
        case '\"': WRITE_ASCII_CHAR('\"'); continue;
6626
422k
        case 'b': WRITE_ASCII_CHAR('\b'); continue;
6627
        /* FF */
6628
602k
        case 'f': WRITE_ASCII_CHAR('\014'); continue;
6629
602k
        case 't': WRITE_ASCII_CHAR('\t'); continue;
6630
1.01M
        case 'n': WRITE_ASCII_CHAR('\n'); continue;
6631
1.01M
        case 'r': WRITE_ASCII_CHAR('\r'); continue;
6632
        /* VT */
6633
576k
        case 'v': WRITE_ASCII_CHAR('\013'); continue;
6634
        /* BEL, not classic C */
6635
48.6k
        case 'a': WRITE_ASCII_CHAR('\007'); continue;
6636
6637
            /* \OOO (octal) escapes */
6638
99.8k
        case '0': case '1': case '2': case '3':
6639
119k
        case '4': case '5': case '6': case '7':
6640
119k
            ch = c - '0';
6641
119k
            if (s < end && '0' <= *s && *s <= '7') {
6642
3.75k
                ch = (ch<<3) + *s++ - '0';
6643
3.75k
                if (s < end && '0' <= *s && *s <= '7') {
6644
1.12k
                    ch = (ch<<3) + *s++ - '0';
6645
1.12k
                }
6646
3.75k
            }
6647
119k
            if (ch > 0377) {
6648
933
                if (*first_invalid_escape_char == -1) {
6649
531
                    *first_invalid_escape_char = ch;
6650
531
                    if (starts == initial_starts) {
6651
                        /* Back up 3 chars, since we've already incremented s. */
6652
531
                        *first_invalid_escape_ptr = s - 3;
6653
531
                    }
6654
531
                }
6655
933
            }
6656
119k
            WRITE_CHAR(ch);
6657
119k
            continue;
6658
6659
            /* hex escapes */
6660
            /* \xXX */
6661
119k
        case 'x':
6662
163
            count = 2;
6663
163
            message = "truncated \\xXX escape";
6664
163
            goto hexescape;
6665
6666
            /* \uXXXX */
6667
6.35k
        case 'u':
6668
6.35k
            count = 4;
6669
6.35k
            message = "truncated \\uXXXX escape";
6670
6.35k
            goto hexescape;
6671
6672
            /* \UXXXXXXXX */
6673
933k
        case 'U':
6674
933k
            count = 8;
6675
933k
            message = "truncated \\UXXXXXXXX escape";
6676
940k
        hexescape:
6677
8.43M
            for (ch = 0; count; ++s, --count) {
6678
7.49M
                if (s >= end) {
6679
2
                    goto incomplete;
6680
2
                }
6681
7.49M
                c = (unsigned char)*s;
6682
7.49M
                ch <<= 4;
6683
7.49M
                if (c >= '0' && c <= '9') {
6684
5.61M
                    ch += c - '0';
6685
5.61M
                }
6686
1.87M
                else if (c >= 'a' && c <= 'f') {
6687
1.87M
                    ch += c - ('a' - 10);
6688
1.87M
                }
6689
389
                else if (c >= 'A' && c <= 'F') {
6690
381
                    ch += c - ('A' - 10);
6691
381
                }
6692
8
                else {
6693
8
                    goto error;
6694
8
                }
6695
7.49M
            }
6696
6697
            /* when we get here, ch is a 32-bit unicode character */
6698
940k
            if (ch > MAX_UNICODE) {
6699
1
                message = "illegal Unicode character";
6700
1
                goto error;
6701
1
            }
6702
6703
940k
            WRITE_CHAR(ch);
6704
940k
            continue;
6705
6706
            /* \N{name} */
6707
940k
        case 'N':
6708
3.13k
            ucnhash_capi = _PyUnicode_GetNameCAPI();
6709
3.13k
            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
3.13k
            message = "malformed \\N character escape";
6718
3.13k
            if (s >= end) {
6719
4
                goto incomplete;
6720
4
            }
6721
3.13k
            if (*s == '{') {
6722
3.13k
                const char *start = ++s;
6723
3.13k
                size_t namelen;
6724
                /* look for the closing brace */
6725
2.14M
                while (s < end && *s != '}')
6726
2.14M
                    s++;
6727
3.13k
                if (s >= end) {
6728
14
                    goto incomplete;
6729
14
                }
6730
3.11k
                namelen = s - start;
6731
3.11k
                if (namelen) {
6732
                    /* found a name.  look it up in the unicode database */
6733
3.11k
                    s++;
6734
3.11k
                    ch = 0xffffffff; /* in case 'getcode' messes up */
6735
3.11k
                    if (namelen <= INT_MAX &&
6736
3.11k
                        ucnhash_capi->getcode(start, (int)namelen,
6737
3.11k
                                              &ch, 0)) {
6738
3.05k
                        assert(ch <= MAX_UNICODE);
6739
3.05k
                        WRITE_CHAR(ch);
6740
3.05k
                        continue;
6741
3.05k
                    }
6742
57
                    message = "unknown Unicode character name";
6743
57
                }
6744
3.11k
            }
6745
62
            goto error;
6746
6747
567k
        default:
6748
567k
            if (*first_invalid_escape_char == -1) {
6749
12.1k
                *first_invalid_escape_char = c;
6750
12.1k
                if (starts == initial_starts) {
6751
                    /* Back up one char, since we've already incremented s. */
6752
12.1k
                    *first_invalid_escape_ptr = s - 1;
6753
12.1k
                }
6754
12.1k
            }
6755
567k
            WRITE_ASCII_CHAR('\\');
6756
567k
            WRITE_CHAR(c);
6757
567k
            continue;
6758
4.98M
        }
6759
6760
20
      incomplete:
6761
20
        if (consumed) {
6762
3
            *consumed = startinpos;
6763
3
            break;
6764
3
        }
6765
88
      error:;
6766
88
        Py_ssize_t endinpos = s-starts;
6767
88
        writer.min_length = end - s + writer.pos;
6768
88
        if (unicode_decode_call_errorhandler_writer(
6769
88
                errors, &errorHandler,
6770
88
                "unicodeescape", message,
6771
88
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6772
88
                &writer)) {
6773
88
            goto onError;
6774
88
        }
6775
88
        assert(end - s <= writer.size - writer.pos);
6776
6777
0
#undef WRITE_ASCII_CHAR
6778
0
#undef WRITE_CHAR
6779
0
    }
6780
6781
29.4k
    Py_XDECREF(errorHandler);
6782
29.4k
    Py_XDECREF(exc);
6783
29.4k
    return _PyUnicodeWriter_Finish(&writer);
6784
6785
88
  onError:
6786
88
    _PyUnicodeWriter_Dealloc(&writer);
6787
88
    Py_XDECREF(errorHandler);
6788
88
    Py_XDECREF(exc);
6789
88
    return NULL;
6790
29.5k
}
6791
6792
PyObject *
6793
_PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
6794
                              Py_ssize_t size,
6795
                              const char *errors,
6796
                              Py_ssize_t *consumed)
6797
0
{
6798
0
    int first_invalid_escape_char;
6799
0
    const char *first_invalid_escape_ptr;
6800
0
    PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal2(s, size, errors,
6801
0
                                                      consumed,
6802
0
                                                      &first_invalid_escape_char,
6803
0
                                                      &first_invalid_escape_ptr);
6804
0
    if (result == NULL)
6805
0
        return NULL;
6806
0
    if (first_invalid_escape_char != -1) {
6807
0
        if (first_invalid_escape_char > 0xff) {
6808
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6809
0
                                 "\"\\%o\" is an invalid octal escape sequence. "
6810
0
                                 "Such sequences will not work in the future. ",
6811
0
                                 first_invalid_escape_char) < 0)
6812
0
            {
6813
0
                Py_DECREF(result);
6814
0
                return NULL;
6815
0
            }
6816
0
        }
6817
0
        else {
6818
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6819
0
                                 "\"\\%c\" is an invalid escape sequence. "
6820
0
                                 "Such sequences will not work in the future. ",
6821
0
                                 first_invalid_escape_char) < 0)
6822
0
            {
6823
0
                Py_DECREF(result);
6824
0
                return NULL;
6825
0
            }
6826
0
        }
6827
0
    }
6828
0
    return result;
6829
0
}
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
0
{
6844
0
    if (!PyUnicode_Check(unicode)) {
6845
0
        PyErr_BadArgument();
6846
0
        return NULL;
6847
0
    }
6848
6849
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
6850
0
    if (len == 0) {
6851
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
6852
0
    }
6853
0
    int kind = PyUnicode_KIND(unicode);
6854
0
    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
0
    Py_ssize_t expandsize = kind * 2 + 2;
6863
0
    if (len > PY_SSIZE_T_MAX / expandsize) {
6864
0
        return PyErr_NoMemory();
6865
0
    }
6866
6867
0
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
6868
0
    if (writer == NULL) {
6869
0
        return NULL;
6870
0
    }
6871
0
    char *p = PyBytesWriter_GetData(writer);
6872
6873
0
    for (Py_ssize_t i = 0; i < len; i++) {
6874
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6875
6876
        /* U+0000-U+00ff range */
6877
0
        if (ch < 0x100) {
6878
0
            if (ch >= ' ' && ch < 127) {
6879
0
                if (ch != '\\') {
6880
                    /* Copy printable US ASCII as-is */
6881
0
                    *p++ = (char) ch;
6882
0
                }
6883
                /* Escape backslashes */
6884
0
                else {
6885
0
                    *p++ = '\\';
6886
0
                    *p++ = '\\';
6887
0
                }
6888
0
            }
6889
6890
            /* Map special whitespace to '\t', \n', '\r' */
6891
0
            else if (ch == '\t') {
6892
0
                *p++ = '\\';
6893
0
                *p++ = 't';
6894
0
            }
6895
0
            else if (ch == '\n') {
6896
0
                *p++ = '\\';
6897
0
                *p++ = 'n';
6898
0
            }
6899
0
            else if (ch == '\r') {
6900
0
                *p++ = '\\';
6901
0
                *p++ = 'r';
6902
0
            }
6903
6904
            /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6905
0
            else {
6906
0
                *p++ = '\\';
6907
0
                *p++ = 'x';
6908
0
                *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6909
0
                *p++ = Py_hexdigits[ch & 0x000F];
6910
0
            }
6911
0
        }
6912
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
6913
0
        else if (ch < 0x10000) {
6914
0
            *p++ = '\\';
6915
0
            *p++ = 'u';
6916
0
            *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6917
0
            *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6918
0
            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6919
0
            *p++ = Py_hexdigits[ch & 0x000F];
6920
0
        }
6921
        /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6922
0
        else {
6923
6924
            /* Make sure that the first two digits are zero */
6925
0
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6926
0
            *p++ = '\\';
6927
0
            *p++ = 'U';
6928
0
            *p++ = '0';
6929
0
            *p++ = '0';
6930
0
            *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6931
0
            *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6932
0
            *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6933
0
            *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6934
0
            *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6935
0
            *p++ = Py_hexdigits[ch & 0x0000000F];
6936
0
        }
6937
0
    }
6938
6939
0
    return PyBytesWriter_FinishWithPointer(writer, p);
6940
0
}
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
0
{
6950
0
    const char *starts = s;
6951
0
    _PyUnicodeWriter writer;
6952
0
    const char *end;
6953
0
    PyObject *errorHandler = NULL;
6954
0
    PyObject *exc = NULL;
6955
6956
0
    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
0
    _PyUnicodeWriter_Init(&writer);
6968
0
    writer.min_length = size;
6969
0
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6970
0
        goto onError;
6971
0
    }
6972
6973
0
    end = s + size;
6974
0
    while (s < end) {
6975
0
        unsigned char c = (unsigned char) *s++;
6976
0
        Py_UCS4 ch;
6977
0
        int count;
6978
0
        const char *message;
6979
6980
0
#define WRITE_CHAR(ch)                                                        \
6981
0
            do {                                                              \
6982
0
                if (ch <= writer.maxchar) {                                   \
6983
0
                    assert(writer.pos < writer.size);                         \
6984
0
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6985
0
                }                                                             \
6986
0
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6987
0
                    goto onError;                                             \
6988
0
                }                                                             \
6989
0
            } while(0)
6990
6991
        /* Non-escape characters are interpreted as Unicode ordinals */
6992
0
        if (c != '\\' || (s >= end && !consumed)) {
6993
0
            WRITE_CHAR(c);
6994
0
            continue;
6995
0
        }
6996
6997
0
        Py_ssize_t startinpos = s - starts - 1;
6998
        /* \ - Escapes */
6999
0
        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
0
        c = (unsigned char) *s++;
7008
0
        if (c == 'u') {
7009
0
            count = 4;
7010
0
            message = "truncated \\uXXXX escape";
7011
0
        }
7012
0
        else if (c == 'U') {
7013
0
            count = 8;
7014
0
            message = "truncated \\UXXXXXXXX escape";
7015
0
        }
7016
0
        else {
7017
0
            assert(writer.pos < writer.size);
7018
0
            PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
7019
0
            WRITE_CHAR(c);
7020
0
            continue;
7021
0
        }
7022
7023
        /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
7024
0
        for (ch = 0; count; ++s, --count) {
7025
0
            if (s >= end) {
7026
0
                goto incomplete;
7027
0
            }
7028
0
            c = (unsigned char)*s;
7029
0
            ch <<= 4;
7030
0
            if (c >= '0' && c <= '9') {
7031
0
                ch += c - '0';
7032
0
            }
7033
0
            else if (c >= 'a' && c <= 'f') {
7034
0
                ch += c - ('a' - 10);
7035
0
            }
7036
0
            else if (c >= 'A' && c <= 'F') {
7037
0
                ch += c - ('A' - 10);
7038
0
            }
7039
0
            else {
7040
0
                goto error;
7041
0
            }
7042
0
        }
7043
0
        if (ch > MAX_UNICODE) {
7044
0
            message = "\\Uxxxxxxxx out of range";
7045
0
            goto error;
7046
0
        }
7047
0
        WRITE_CHAR(ch);
7048
0
        continue;
7049
7050
0
      incomplete:
7051
0
        if (consumed) {
7052
0
            *consumed = startinpos;
7053
0
            break;
7054
0
        }
7055
0
      error:;
7056
0
        Py_ssize_t endinpos = s-starts;
7057
0
        writer.min_length = end - s + writer.pos;
7058
0
        if (unicode_decode_call_errorhandler_writer(
7059
0
                errors, &errorHandler,
7060
0
                "rawunicodeescape", message,
7061
0
                &starts, &end, &startinpos, &endinpos, &exc, &s,
7062
0
                &writer)) {
7063
0
            goto onError;
7064
0
        }
7065
0
        assert(end - s <= writer.size - writer.pos);
7066
7067
0
#undef WRITE_CHAR
7068
0
    }
7069
0
    Py_XDECREF(errorHandler);
7070
0
    Py_XDECREF(exc);
7071
0
    return _PyUnicodeWriter_Finish(&writer);
7072
7073
0
  onError:
7074
0
    _PyUnicodeWriter_Dealloc(&writer);
7075
0
    Py_XDECREF(errorHandler);
7076
0
    Py_XDECREF(exc);
7077
0
    return NULL;
7078
0
}
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
0
{
7092
0
    if (!PyUnicode_Check(unicode)) {
7093
0
        PyErr_BadArgument();
7094
0
        return NULL;
7095
0
    }
7096
0
    int kind = PyUnicode_KIND(unicode);
7097
0
    const void *data = PyUnicode_DATA(unicode);
7098
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
7099
0
    if (len == 0) {
7100
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7101
0
    }
7102
0
    if (kind == PyUnicode_1BYTE_KIND) {
7103
0
        return PyBytes_FromStringAndSize(data, len);
7104
0
    }
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
0
    Py_ssize_t expandsize = kind * 2 + 2;
7109
0
    if (len > PY_SSIZE_T_MAX / expandsize) {
7110
0
        return PyErr_NoMemory();
7111
0
    }
7112
7113
0
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
7114
0
    if (writer == NULL) {
7115
0
        return NULL;
7116
0
    }
7117
0
    char *p = PyBytesWriter_GetData(writer);
7118
7119
0
    for (Py_ssize_t pos = 0; pos < len; pos++) {
7120
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7121
7122
        /* U+0000-U+00ff range: Copy 8-bit characters as-is */
7123
0
        if (ch < 0x100) {
7124
0
            *p++ = (char) ch;
7125
0
        }
7126
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
7127
0
        else if (ch < 0x10000) {
7128
0
            *p++ = '\\';
7129
0
            *p++ = 'u';
7130
0
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7131
0
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7132
0
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7133
0
            *p++ = Py_hexdigits[ch & 15];
7134
0
        }
7135
        /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
7136
0
        else {
7137
0
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
7138
0
            *p++ = '\\';
7139
0
            *p++ = 'U';
7140
0
            *p++ = '0';
7141
0
            *p++ = '0';
7142
0
            *p++ = Py_hexdigits[(ch >> 20) & 0xf];
7143
0
            *p++ = Py_hexdigits[(ch >> 16) & 0xf];
7144
0
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7145
0
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7146
0
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7147
0
            *p++ = Py_hexdigits[ch & 15];
7148
0
        }
7149
0
    }
7150
7151
0
    return PyBytesWriter_FinishWithPointer(writer, p);
7152
0
}
7153
7154
/* --- Latin-1 Codec ------------------------------------------------------ */
7155
7156
PyObject *
7157
PyUnicode_DecodeLatin1(const char *s,
7158
                       Py_ssize_t size,
7159
                       const char *errors)
7160
6.31k
{
7161
    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
7162
6.31k
    return _PyUnicode_FromUCS1((const unsigned char*)s, size);
7163
6.31k
}
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
29.6k
{
7173
29.6k
    if (*exceptionObject == NULL) {
7174
29.6k
        *exceptionObject = PyObject_CallFunction(
7175
29.6k
            PyExc_UnicodeEncodeError, "sOnns",
7176
29.6k
            encoding, unicode, startpos, endpos, reason);
7177
29.6k
    }
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
29.6k
}
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
29.6k
{
7199
29.6k
    make_encode_exception(exceptionObject,
7200
29.6k
                          encoding, unicode, startpos, endpos, reason);
7201
29.6k
    if (*exceptionObject != NULL)
7202
29.6k
        PyCodec_StrictErrors(*exceptionObject);
7203
29.6k
}
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
38
{
7217
38
    static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
7218
38
    Py_ssize_t len;
7219
38
    PyObject *restuple;
7220
38
    PyObject *resunicode;
7221
7222
38
    if (*errorHandler == NULL) {
7223
38
        *errorHandler = PyCodec_LookupError(errors);
7224
38
        if (*errorHandler == NULL)
7225
0
            return NULL;
7226
38
    }
7227
7228
38
    len = PyUnicode_GET_LENGTH(unicode);
7229
7230
38
    make_encode_exception(exceptionObject,
7231
38
                          encoding, unicode, startpos, endpos, reason);
7232
38
    if (*exceptionObject == NULL)
7233
0
        return NULL;
7234
7235
38
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
7236
38
    if (restuple == NULL)
7237
38
        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
29.8k
{
7270
    /* input state */
7271
29.8k
    Py_ssize_t pos=0, size;
7272
29.8k
    int kind;
7273
29.8k
    const void *data;
7274
29.8k
    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
7275
29.8k
    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
7276
29.8k
    PyObject *error_handler_obj = NULL;
7277
29.8k
    PyObject *exc = NULL;
7278
29.8k
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7279
29.8k
    PyObject *rep = NULL;
7280
7281
29.8k
    size = PyUnicode_GET_LENGTH(unicode);
7282
29.8k
    kind = PyUnicode_KIND(unicode);
7283
29.8k
    data = PyUnicode_DATA(unicode);
7284
    /* allocate enough for a simple encoding without
7285
       replacements, if we need more, we'll resize */
7286
29.8k
    if (size == 0)
7287
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7288
7289
    /* output object */
7290
29.8k
    PyBytesWriter *writer = PyBytesWriter_Create(size);
7291
29.8k
    if (writer == NULL) {
7292
0
        return NULL;
7293
0
    }
7294
    /* pointer into the output */
7295
29.8k
    char *str = PyBytesWriter_GetData(writer);
7296
7297
3.10M
    while (pos < size) {
7298
3.10M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7299
7300
        /* can we encode this? */
7301
3.10M
        if (ch < limit) {
7302
            /* no overflow check, because we know that the space is enough */
7303
3.06M
            *str++ = (char)ch;
7304
3.06M
            ++pos;
7305
3.06M
        }
7306
39.9k
        else {
7307
39.9k
            Py_ssize_t newpos, i;
7308
            /* startpos for collecting unencodable chars */
7309
39.9k
            Py_ssize_t collstart = pos;
7310
39.9k
            Py_ssize_t collend = collstart + 1;
7311
            /* find all unecodable characters */
7312
7313
427k
            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
7314
387k
                ++collend;
7315
7316
            /* Only overallocate the buffer if it's not the last write */
7317
39.9k
            writer->overallocate = (collend < size);
7318
7319
            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
7320
39.9k
            if (error_handler == _Py_ERROR_UNKNOWN)
7321
29.8k
                error_handler = _Py_GetErrorHandler(errors);
7322
7323
39.9k
            switch (error_handler) {
7324
29.6k
            case _Py_ERROR_STRICT:
7325
29.6k
                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
7326
29.6k
                goto onError;
7327
7328
0
            case _Py_ERROR_REPLACE:
7329
0
                memset(str, '?', collend - collstart);
7330
0
                str += (collend - collstart);
7331
0
                _Py_FALLTHROUGH;
7332
0
            case _Py_ERROR_IGNORE:
7333
0
                pos = collend;
7334
0
                break;
7335
7336
10.3k
            case _Py_ERROR_BACKSLASHREPLACE:
7337
10.3k
                str = backslashreplace(writer, str,
7338
10.3k
                                       unicode, collstart, collend);
7339
10.3k
                if (str == NULL)
7340
0
                    goto onError;
7341
10.3k
                pos = collend;
7342
10.3k
                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
0
            case _Py_ERROR_SURROGATEESCAPE:
7353
0
                for (i = collstart; i < collend; ++i) {
7354
0
                    ch = PyUnicode_READ(kind, data, i);
7355
0
                    if (ch < 0xdc80 || 0xdcff < ch) {
7356
                        /* Not a UTF-8b surrogate */
7357
0
                        break;
7358
0
                    }
7359
0
                    *str++ = (char)(ch - 0xdc00);
7360
0
                    ++pos;
7361
0
                }
7362
0
                if (i >= collend)
7363
0
                    break;
7364
0
                collstart = pos;
7365
0
                assert(collstart != collend);
7366
0
                _Py_FALLTHROUGH;
7367
7368
0
            default:
7369
0
                rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
7370
0
                                                       encoding, reason, unicode, &exc,
7371
0
                                                       collstart, collend, &newpos);
7372
0
                if (rep == NULL)
7373
0
                    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
39.9k
            }
7428
7429
            /* If overallocation was disabled, ensure that it was the last
7430
               write. Otherwise, we missed an optimization */
7431
39.9k
            assert(writer->overallocate || pos == size);
7432
10.3k
        }
7433
3.10M
    }
7434
7435
279
    Py_XDECREF(error_handler_obj);
7436
279
    Py_XDECREF(exc);
7437
279
    return PyBytesWriter_FinishWithPointer(writer, str);
7438
7439
29.6k
  onError:
7440
29.6k
    Py_XDECREF(rep);
7441
29.6k
    PyBytesWriter_Discard(writer);
7442
29.6k
    Py_XDECREF(error_handler_obj);
7443
29.6k
    Py_XDECREF(exc);
7444
29.6k
    return NULL;
7445
29.8k
}
7446
7447
PyObject *
7448
_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
7449
0
{
7450
0
    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
0
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7457
0
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7458
0
                                         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
0
}
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
65.9k
{
7477
65.9k
    const char *starts = s;
7478
65.9k
    const char *e = s + size;
7479
65.9k
    PyObject *error_handler_obj = NULL;
7480
65.9k
    PyObject *exc = NULL;
7481
65.9k
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7482
7483
65.9k
    if (size == 0)
7484
24
        _Py_RETURN_UNICODE_EMPTY();
7485
7486
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
7487
65.8k
    if (size == 1 && (unsigned char)s[0] < 128) {
7488
3.77k
        return get_latin1_char((unsigned char)s[0]);
7489
3.77k
    }
7490
7491
    // Shortcut for simple case
7492
62.1k
    PyObject *u = PyUnicode_New(size, 127);
7493
62.1k
    if (u == NULL) {
7494
0
        return NULL;
7495
0
    }
7496
62.1k
    Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
7497
62.1k
    if (outpos == size) {
7498
61.7k
        return u;
7499
61.7k
    }
7500
7501
387
    _PyUnicodeWriter writer;
7502
387
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
7503
387
    writer.pos = outpos;
7504
7505
387
    s += outpos;
7506
387
    int kind = writer.kind;
7507
387
    void *data = writer.data;
7508
387
    Py_ssize_t startinpos, endinpos;
7509
7510
9.83M
    while (s < e) {
7511
9.83M
        unsigned char c = (unsigned char)*s;
7512
9.83M
        if (c < 128) {
7513
9.78M
            PyUnicode_WRITE(kind, data, writer.pos, c);
7514
9.78M
            writer.pos++;
7515
9.78M
            ++s;
7516
9.78M
            continue;
7517
9.78M
        }
7518
7519
        /* byte outsize range 0x00..0x7f: call the error handler */
7520
7521
53.7k
        if (error_handler == _Py_ERROR_UNKNOWN)
7522
387
            error_handler = _Py_GetErrorHandler(errors);
7523
7524
53.7k
        switch (error_handler)
7525
53.7k
        {
7526
768
        case _Py_ERROR_REPLACE:
7527
53.5k
        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
53.5k
            if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7531
0
                goto onError;
7532
53.5k
            assert(_PyUnicodeWriter_CanWrite(&writer));
7533
53.5k
            kind = writer.kind;
7534
53.5k
            data = writer.data;
7535
7536
53.5k
            if (error_handler == _Py_ERROR_REPLACE)
7537
768
                PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7538
52.7k
            else
7539
52.7k
                PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7540
53.5k
            writer.pos++;
7541
53.5k
            ++s;
7542
53.5k
            break;
7543
7544
0
        case _Py_ERROR_IGNORE:
7545
0
            ++s;
7546
0
            break;
7547
7548
209
        default:
7549
209
            startinpos = s-starts;
7550
209
            endinpos = startinpos + 1;
7551
209
            if (unicode_decode_call_errorhandler_writer(
7552
209
                    errors, &error_handler_obj,
7553
209
                    "ascii", "ordinal not in range(128)",
7554
209
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
7555
209
                    &writer))
7556
209
                goto onError;
7557
0
            kind = writer.kind;
7558
0
            data = writer.data;
7559
53.7k
        }
7560
53.7k
    }
7561
178
    Py_XDECREF(error_handler_obj);
7562
178
    Py_XDECREF(exc);
7563
178
    return _PyUnicodeWriter_Finish(&writer);
7564
7565
209
  onError:
7566
209
    _PyUnicodeWriter_Dealloc(&writer);
7567
209
    Py_XDECREF(error_handler_obj);
7568
209
    Py_XDECREF(exc);
7569
209
    return NULL;
7570
387
}
7571
7572
PyObject *
7573
_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
7574
32.4k
{
7575
32.4k
    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
32.4k
    if (PyUnicode_IS_ASCII(unicode))
7582
2.54k
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7583
2.54k
                                         PyUnicode_GET_LENGTH(unicode));
7584
29.8k
    return unicode_encode_ucs1(unicode, errors, 128);
7585
32.4k
}
7586
7587
PyObject *
7588
PyUnicode_AsASCIIString(PyObject *unicode)
7589
350
{
7590
350
    return _PyUnicode_AsASCIIString(unicode, NULL);
7591
350
}
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
348
#  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
1.01k
{
8308
1.01k
    iconv_t cd = iconv_open(tocode, fromcode);
8309
1.01k
    if (cd == (iconv_t)-1) {
8310
578
        if (errno == EINVAL) {
8311
578
            PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding);
8312
578
        }
8313
0
        else {
8314
0
            PyErr_SetFromErrno(PyExc_OSError);
8315
0
        }
8316
578
    }
8317
1.01k
    return cd;
8318
1.01k
}
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
348
{
8332
348
    if (size < 0) {
8333
0
        PyErr_BadInternalCall();
8334
0
        return NULL;
8335
0
    }
8336
8337
348
    iconv_t cd = iconv_open_or_set_error(ICONV_PIVOT, encoding, encoding);
8338
348
    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
348
    Py_UCS4 chunk[1024];
8344
348
    const char *starts = s;
8345
348
    const char *in = s;
8346
348
    const char *inend = s + size;
8347
348
    _PyUnicodeWriter writer;
8348
348
    PyObject *errorHandler = NULL;
8349
348
    PyObject *exc = NULL;
8350
8351
348
    _PyUnicodeWriter_Init(&writer);
8352
348
    writer.min_length = size;
8353
8354
6.58k
    while (in < inend) {
8355
6.54k
        char *inptr = (char *)in;
8356
6.54k
        size_t inleft = (size_t)(inend - in);
8357
6.54k
        char *outptr = (char *)chunk;
8358
6.54k
        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
6.54k
        size_t ret = iconv(cd, (void *)&inptr, &inleft, &outptr, &outleft);
8364
6.54k
        int err = errno;
8365
6.54k
        in = inptr;
8366
8367
        /* Append whatever code points this call produced. */
8368
6.54k
        Py_ssize_t nch = (Py_UCS4 *)outptr - chunk;
8369
6.54k
        if (nch > 0 && PyUnicodeWriter_WriteUCS4((PyUnicodeWriter *)&writer,
8370
2.68k
                                                 chunk, nch) < 0) {
8371
0
            goto error;
8372
0
        }
8373
8374
6.54k
        if (ret != (size_t)-1) {
8375
295
            assert(in == inend);
8376
295
            break;
8377
295
        }
8378
8379
6.25k
        if (err == E2BIG) {
8380
            /* The scratch buffer filled up; drain it and continue. */
8381
2.09k
            continue;
8382
2.09k
        }
8383
8384
4.16k
        const char *reason;
8385
4.16k
        if (err == EINVAL) {
8386
            /* Incomplete multibyte sequence at the end of the input. */
8387
22
            if (consumed != NULL) {
8388
                /* Stateful decoding: stop and report the consumed bytes. */
8389
0
                break;
8390
0
            }
8391
22
            reason = "incomplete multibyte sequence";
8392
22
        }
8393
4.14k
        else if (err == EILSEQ) {
8394
4.14k
            reason = "invalid multibyte sequence";
8395
4.14k
        }
8396
0
        else {
8397
0
            errno = err;
8398
0
            PyErr_SetFromErrno(PyExc_OSError);
8399
0
            goto error;
8400
0
        }
8401
8402
4.16k
        Py_ssize_t startinpos = in - starts;
8403
4.16k
        Py_ssize_t endinpos = startinpos + 1;
8404
4.16k
        if (unicode_decode_call_errorhandler_writer(
8405
4.16k
                errors, &errorHandler, encoding, reason,
8406
4.16k
                &starts, &inend, &startinpos, &endinpos, &exc, &in,
8407
4.16k
                &writer)) {
8408
22
            goto error;
8409
22
        }
8410
        /* The error handler may have skipped bytes; reset the conversion
8411
           descriptor to the initial shift state before continuing. */
8412
4.14k
        iconv(cd, NULL, NULL, NULL, NULL);
8413
4.14k
    }
8414
8415
326
    if (consumed != NULL) {
8416
0
        *consumed = in - starts;
8417
0
    }
8418
326
    iconv_close(cd);
8419
326
    Py_XDECREF(errorHandler);
8420
326
    Py_XDECREF(exc);
8421
326
    return _PyUnicodeWriter_Finish(&writer);
8422
8423
22
error:
8424
22
    iconv_close(cd);
8425
22
    _PyUnicodeWriter_Dealloc(&writer);
8426
22
    Py_XDECREF(errorHandler);
8427
22
    Py_XDECREF(exc);
8428
22
    return NULL;
8429
348
}
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
663
{
8462
663
    if (!PyUnicode_Check(unicode)) {
8463
0
        PyErr_BadArgument();
8464
0
        return NULL;
8465
0
    }
8466
8467
663
    Py_ssize_t ulen = PyUnicode_GET_LENGTH(unicode);
8468
663
    const char *source;         /* iconv source encoding for this kind */
8469
663
    const char *data;           /* the units to encode */
8470
663
    Py_ssize_t unit;            /* bytes per code point in *data */
8471
663
    Py_UCS4 *widened = NULL;    /* owned UTF-32 copy of a 2-byte string */
8472
663
    int kind = PyUnicode_KIND(unicode);
8473
663
    if (kind == PyUnicode_1BYTE_KIND) {
8474
663
        source = "ISO-8859-1";
8475
663
        data = (const char *)PyUnicode_1BYTE_DATA(unicode);
8476
663
        unit = 1;
8477
663
    }
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
663
    iconv_t cd = iconv_open_or_set_error(encoding, source, encoding);
8502
663
    if (cd == (iconv_t)-1) {
8503
578
        PyMem_Free(widened);
8504
578
        return NULL;
8505
578
    }
8506
8507
85
    PyBytesWriter *writer = NULL;
8508
85
    PyObject *errorHandler = NULL;
8509
85
    PyObject *exc = NULL;
8510
85
    PyObject *result = NULL;
8511
85
    const char *ustart = data;
8512
85
    const char *up = data;
8513
85
    const char *uend = data + (size_t)ulen * unit;
8514
85
    int flushing = 0;
8515
85
    int careful = 0;            /* feed one code point per iconv() call */
8516
8517
    /* A generous initial estimate for the output size. */
8518
85
    writer = PyBytesWriter_Create(ulen + (ulen >> 1) + 16);
8519
85
    if (writer == NULL) {
8520
0
        goto done;
8521
0
    }
8522
85
    char *out = PyBytesWriter_GetData(writer);
8523
85
    char *outend = out + PyBytesWriter_GetSize(writer);
8524
8525
170
    for (;;) {
8526
170
        char *inptr = (char *)up;
8527
170
        size_t inleft = (size_t)(uend - up);
8528
        /* One code point at a time, to pin a substitution to its position. */
8529
170
        if (careful && inleft > (size_t)unit) {
8530
0
            inleft = (size_t)unit;
8531
0
        }
8532
170
        char *out_before = out;
8533
170
        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
170
        size_t ret = iconv(cd, flushing ? NULL : (void *)&inptr, &inleft, &out, &outleft);
8538
170
        if (!flushing) {
8539
85
            up = inptr;
8540
85
        }
8541
8542
170
        if (ret != (size_t)-1) {
8543
170
            if (flushing) {
8544
85
                break;
8545
85
            }
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
85
            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
85
            else if (careful && up < uend) {
8564
0
                continue;
8565
0
            }
8566
85
            else {
8567
                /* All input consumed; switch to flushing the shift state. */
8568
85
                flushing = 1;
8569
85
                continue;
8570
85
            }
8571
85
        }
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
85
    result = PyBytesWriter_FinishWithPointer(writer, out);
8645
85
    writer = NULL;
8646
8647
85
done:
8648
85
    if (writer != NULL) {
8649
0
        PyBytesWriter_Discard(writer);
8650
0
    }
8651
85
    iconv_close(cd);
8652
85
    PyMem_Free(widened);
8653
85
    Py_XDECREF(errorHandler);
8654
85
    Py_XDECREF(exc);
8655
85
    return result;
8656
85
}
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
1.42k
{
8669
1.42k
    const char *starts = s;
8670
1.42k
    const char *e;
8671
1.42k
    Py_ssize_t startinpos, endinpos;
8672
1.42k
    PyObject *errorHandler = NULL, *exc = NULL;
8673
1.42k
    Py_ssize_t maplen;
8674
1.42k
    int mapkind;
8675
1.42k
    const void *mapdata;
8676
1.42k
    Py_UCS4 x;
8677
1.42k
    unsigned char ch;
8678
8679
1.42k
    maplen = PyUnicode_GET_LENGTH(mapping);
8680
1.42k
    mapdata = PyUnicode_DATA(mapping);
8681
1.42k
    mapkind = PyUnicode_KIND(mapping);
8682
8683
0
    e = s + size;
8684
8685
1.42k
    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
18
        const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
8690
18
        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8691
18
        Py_UCS4 maxchar = writer->maxchar;
8692
8693
18
        assert (writer->kind == PyUnicode_1BYTE_KIND);
8694
2.05k
        while (s < e) {
8695
2.03k
            ch = *s;
8696
2.03k
            x = mapdata_ucs1[ch];
8697
2.03k
            if (x > maxchar) {
8698
18
                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8699
0
                    goto onError;
8700
18
                maxchar = writer->maxchar;
8701
18
                outdata = (Py_UCS1 *)writer->data;
8702
18
            }
8703
2.03k
            outdata[writer->pos] = x;
8704
2.03k
            writer->pos++;
8705
2.03k
            ++s;
8706
2.03k
        }
8707
18
        return 0;
8708
18
    }
8709
8710
4.12k
    while (s < e) {
8711
4.09k
        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8712
4.09k
            int outkind = writer->kind;
8713
4.09k
            const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
8714
4.09k
            if (outkind == PyUnicode_1BYTE_KIND) {
8715
2.36k
                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8716
2.36k
                Py_UCS4 maxchar = writer->maxchar;
8717
299k
                while (s < e) {
8718
298k
                    ch = *s;
8719
298k
                    x = mapdata_ucs2[ch];
8720
298k
                    if (x > maxchar)
8721
2.18k
                        goto Error;
8722
296k
                    outdata[writer->pos] = x;
8723
296k
                    writer->pos++;
8724
296k
                    ++s;
8725
296k
                }
8726
178
                break;
8727
2.36k
            }
8728
1.73k
            else if (outkind == PyUnicode_2BYTE_KIND) {
8729
1.73k
                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8730
2.59M
                while (s < e) {
8731
2.59M
                    ch = *s;
8732
2.59M
                    x = mapdata_ucs2[ch];
8733
2.59M
                    if (x == 0xFFFE)
8734
549
                        goto Error;
8735
2.59M
                    outdata[writer->pos] = x;
8736
2.59M
                    writer->pos++;
8737
2.59M
                    ++s;
8738
2.59M
                }
8739
1.18k
                break;
8740
1.73k
            }
8741
4.09k
        }
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
2.73k
Error:
8749
2.73k
        if (x == 0xfffe)
8750
557
        {
8751
            /* undefined mapping */
8752
557
            startinpos = s-starts;
8753
557
            endinpos = startinpos+1;
8754
557
            if (unicode_decode_call_errorhandler_writer(
8755
557
                    errors, &errorHandler,
8756
557
                    "charmap", "character maps to <undefined>",
8757
557
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
8758
557
                    writer)) {
8759
20
                goto onError;
8760
20
            }
8761
537
            continue;
8762
557
        }
8763
8764
2.17k
        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8765
0
            goto onError;
8766
2.17k
        ++s;
8767
2.17k
    }
8768
1.39k
    Py_XDECREF(errorHandler);
8769
1.39k
    Py_XDECREF(exc);
8770
1.39k
    return 0;
8771
8772
20
onError:
8773
20
    Py_XDECREF(errorHandler);
8774
20
    Py_XDECREF(exc);
8775
20
    return -1;
8776
1.41k
}
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
1.42k
{
8888
1.42k
    _PyUnicodeWriter writer;
8889
8890
    /* Default to Latin-1 */
8891
1.42k
    if (mapping == NULL)
8892
0
        return PyUnicode_DecodeLatin1(s, size, errors);
8893
8894
1.42k
    if (size == 0)
8895
0
        _Py_RETURN_UNICODE_EMPTY();
8896
1.42k
    _PyUnicodeWriter_Init(&writer);
8897
1.42k
    writer.min_length = size;
8898
1.42k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
8899
0
        goto onError;
8900
8901
1.42k
    if (PyUnicode_CheckExact(mapping)) {
8902
1.42k
        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8903
20
            goto onError;
8904
1.42k
    }
8905
0
    else {
8906
0
        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8907
0
            goto onError;
8908
0
    }
8909
1.40k
    return _PyUnicodeWriter_Finish(&writer);
8910
8911
20
  onError:
8912
20
    _PyUnicodeWriter_Dealloc(&writer);
8913
20
    return NULL;
8914
1.42k
}
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
56
{
8961
56
    PyObject *result;
8962
56
    struct encoding_map *mresult;
8963
56
    int i;
8964
56
    int need_dict = 0;
8965
56
    unsigned char level1[32];
8966
56
    unsigned char level2[512];
8967
56
    unsigned char *mlevel1, *mlevel2, *mlevel3;
8968
56
    int count2 = 0, count3 = 0;
8969
56
    int kind;
8970
56
    const void *data;
8971
56
    int length;
8972
56
    Py_UCS4 ch;
8973
8974
56
    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
8975
0
        PyErr_BadArgument();
8976
0
        return NULL;
8977
0
    }
8978
56
    kind = PyUnicode_KIND(string);
8979
56
    data = PyUnicode_DATA(string);
8980
56
    length = (int)Py_MIN(PyUnicode_GET_LENGTH(string), 256);
8981
56
    memset(level1, 0xFF, sizeof level1);
8982
56
    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
56
    if (PyUnicode_READ(kind, data, 0) != 0)
8988
0
        need_dict = 1;
8989
14.3k
    for (i = 1; i < length; i++) {
8990
14.2k
        int l1, l2;
8991
14.2k
        ch = PyUnicode_READ(kind, data, i);
8992
14.2k
        if (ch == 0 || ch > 0xFFFF) {
8993
0
            need_dict = 1;
8994
0
            break;
8995
0
        }
8996
14.2k
        if (ch == 0xFFFE)
8997
            /* unmapped character */
8998
440
            continue;
8999
13.8k
        l1 = ch >> 11;
9000
13.8k
        l2 = ch >> 7;
9001
13.8k
        if (level1[l1] == 0xFF)
9002
101
            level1[l1] = count2++;
9003
13.8k
        if (level2[l2] == 0xFF)
9004
280
            level2[l2] = count3++;
9005
13.8k
    }
9006
9007
56
    if (count2 >= 0xFF || count3 >= 0xFF)
9008
0
        need_dict = 1;
9009
9010
56
    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
56
    result = PyObject_Malloc(sizeof(struct encoding_map) +
9040
56
                             16*count2 + 128*count3 - 1);
9041
56
    if (!result) {
9042
0
        return PyErr_NoMemory();
9043
0
    }
9044
9045
56
    _PyObject_Init(result, &EncodingMapType);
9046
56
    mresult = (struct encoding_map*)result;
9047
56
    mresult->count2 = count2;
9048
56
    mresult->count3 = count3;
9049
56
    mlevel1 = mresult->level1;
9050
56
    mlevel2 = mresult->level23;
9051
56
    mlevel3 = mresult->level23 + 16*count2;
9052
56
    memcpy(mlevel1, level1, 32);
9053
56
    memset(mlevel2, 0xFF, 16*count2);
9054
56
    memset(mlevel3, 0, 128*count3);
9055
56
    count3 = 0;
9056
14.3k
    for (i = 1; i < length; i++) {
9057
14.2k
        int o1, o2, o3, i2, i3;
9058
14.2k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9059
14.2k
        if (ch == 0xFFFE)
9060
            /* unmapped character */
9061
440
            continue;
9062
13.8k
        o1 = ch>>11;
9063
13.8k
        o2 = (ch>>7) & 0xF;
9064
13.8k
        i2 = 16*mlevel1[o1] + o2;
9065
13.8k
        if (mlevel2[i2] == 0xFF)
9066
280
            mlevel2[i2] = count3++;
9067
13.8k
        o3 = ch & 0x7F;
9068
13.8k
        i3 = 128*mlevel2[i2] + o3;
9069
13.8k
        mlevel3[i3] = i;
9070
13.8k
    }
9071
56
    return result;
9072
56
}
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
0
{
9113
0
    PyObject *w = PyLong_FromLong((long)c);
9114
0
    PyObject *x;
9115
9116
0
    if (w == NULL)
9117
0
        return NULL;
9118
0
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9119
0
    Py_DECREF(w);
9120
0
    if (rc == 0) {
9121
        /* No mapping found means: mapping is undefined. */
9122
0
        Py_RETURN_NONE;
9123
0
    }
9124
0
    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
0
    else if (x == Py_None)
9133
0
        return x;
9134
0
    else if (PyLong_Check(x)) {
9135
0
        long value = PyLong_AsLong(x);
9136
0
        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
0
        *replace = (unsigned char)value;
9143
0
        return x;
9144
0
    }
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
0
}
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
0
{
9180
0
    PyObject *rep;
9181
0
    unsigned char replace;
9182
0
    char *outstart;
9183
0
    Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9184
9185
0
    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
0
    rep = charmapencode_lookup(c, mapping, &replace);
9203
0
    if (rep==NULL)
9204
0
        return enc_EXCEPTION;
9205
0
    else if (rep==Py_None) {
9206
0
        Py_DECREF(rep);
9207
0
        return enc_FAILED;
9208
0
    } else {
9209
0
        if (PyLong_Check(rep)) {
9210
0
            Py_ssize_t requiredsize = *outpos+1;
9211
0
            if (outsize<requiredsize)
9212
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9213
0
                    Py_DECREF(rep);
9214
0
                    return enc_EXCEPTION;
9215
0
                }
9216
0
            outstart = _PyBytesWriter_GetData(writer);
9217
0
            outstart[(*outpos)++] = (char)replace;
9218
0
        }
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
0
    }
9233
0
    Py_DECREF(rep);
9234
0
    return enc_SUCCESS;
9235
0
}
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
0
{
9385
    /* Default to Latin-1 */
9386
0
    if (mapping == NULL) {
9387
0
        return unicode_encode_ucs1(unicode, errors, 256);
9388
0
    }
9389
9390
0
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
9391
0
    if (size == 0) {
9392
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
9393
0
    }
9394
0
    const void *data = PyUnicode_DATA(unicode);
9395
0
    int kind = PyUnicode_KIND(unicode);
9396
9397
0
    PyObject *error_handler_obj = NULL;
9398
0
    PyObject *exc = NULL;
9399
9400
    /* output object */
9401
0
    PyBytesWriter *writer;
9402
    /* allocate enough for a simple encoding without
9403
       replacements, if we need more, we'll resize */
9404
0
    writer = PyBytesWriter_Create(size);
9405
0
    if (writer == NULL) {
9406
0
        goto onError;
9407
0
    }
9408
9409
    /* current input position */
9410
0
    Py_ssize_t inpos = 0;
9411
    /* current output position */
9412
0
    Py_ssize_t respos = 0;
9413
0
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
9414
9415
0
    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
0
    else {
9454
0
        while (inpos<size) {
9455
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9456
            /* try to encode it */
9457
0
            charmapencode_result x = charmapencode_output(ch, mapping, writer, &respos);
9458
0
            if (x==enc_EXCEPTION) { /* error */
9459
0
                goto onError;
9460
0
            }
9461
0
            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
0
            else {
9470
                /* done with this character => adjust input position */
9471
0
                ++inpos;
9472
0
            }
9473
0
        }
9474
0
    }
9475
9476
0
    Py_XDECREF(exc);
9477
0
    Py_XDECREF(error_handler_obj);
9478
9479
    /* Resize if we allocated too much */
9480
0
    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
0
}
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
282
{
9588
282
    PyObject *w = PyLong_FromLong((long)c);
9589
282
    PyObject *x;
9590
9591
282
    if (w == NULL)
9592
0
        return -1;
9593
282
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9594
282
    Py_DECREF(w);
9595
282
    if (rc == 0) {
9596
        /* No mapping found means: use 1:1 mapping. */
9597
126
        *result = NULL;
9598
126
        return 0;
9599
126
    }
9600
156
    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
156
    else if (x == Py_None) {
9610
0
        *result = x;
9611
0
        return 0;
9612
0
    }
9613
156
    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
156
    else if (PyUnicode_Check(x)) {
9627
156
        *result = x;
9628
156
        return 0;
9629
156
    }
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
156
}
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
108
{
9646
108
    PyObject *item;
9647
108
    Py_UCS4 replace;
9648
9649
108
    if (charmaptranslate_lookup(ch, mapping, &item, &replace))
9650
0
        return -1;
9651
9652
108
    if (item == NULL) {
9653
        /* not found => default to 1:1 mapping */
9654
24
        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
9655
0
            return -1;
9656
0
        }
9657
24
        return 1;
9658
24
    }
9659
9660
84
    if (item == Py_None) {
9661
0
        Py_DECREF(item);
9662
0
        return 0;
9663
0
    }
9664
9665
84
    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
84
    if (!PyUnicode_Check(item)) {
9675
0
        Py_DECREF(item);
9676
0
        return -1;
9677
0
    }
9678
9679
84
    if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
9680
0
        Py_DECREF(item);
9681
0
        return -1;
9682
0
    }
9683
9684
84
    Py_DECREF(item);
9685
84
    return 1;
9686
84
}
9687
9688
static int
9689
unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
9690
                              Py_UCS1 *translate)
9691
174
{
9692
174
    PyObject *item = NULL;
9693
174
    Py_UCS4 replace;
9694
174
    int ret = 0;
9695
9696
174
    if (charmaptranslate_lookup(ch, mapping, &item, &replace)) {
9697
0
        return -1;
9698
0
    }
9699
9700
174
    if (item == Py_None) {
9701
        /* deletion */
9702
0
        translate[ch] = 0xfe;
9703
0
    }
9704
174
    else if (item == NULL) {
9705
        /* not found => default to 1:1 mapping */
9706
102
        translate[ch] = ch;
9707
102
        return 1;
9708
102
    }
9709
72
    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
72
    else if (PyUnicode_Check(item)) {
9718
72
        if (PyUnicode_GET_LENGTH(item) != 1)
9719
72
            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
72
  exit:
9733
72
    Py_DECREF(item);
9734
72
    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
144
{
9745
144
    Py_UCS1 ascii_table[128], ch, ch2;
9746
144
    Py_ssize_t len;
9747
144
    const Py_UCS1 *in, *end;
9748
144
    Py_UCS1 *out;
9749
144
    int res = 0;
9750
9751
144
    len = PyUnicode_GET_LENGTH(input);
9752
9753
144
    memset(ascii_table, 0xff, 128);
9754
9755
144
    in = PyUnicode_1BYTE_DATA(input);
9756
144
    end = in + len;
9757
9758
144
    assert(PyUnicode_IS_ASCII(writer->buffer));
9759
144
    assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9760
144
    out = PyUnicode_1BYTE_DATA(writer->buffer);
9761
9762
267
    for (; in < end; in++) {
9763
195
        ch = *in;
9764
195
        ch2 = ascii_table[ch];
9765
195
        if (ch2 == 0xff) {
9766
174
            int translate = unicode_fast_translate_lookup(mapping, ch,
9767
174
                                                          ascii_table);
9768
174
            if (translate < 0)
9769
0
                return -1;
9770
174
            if (translate == 0)
9771
72
                goto exit;
9772
102
            ch2 = ascii_table[ch];
9773
102
        }
9774
123
        if (ch2 == 0xfe) {
9775
0
            if (ignore)
9776
0
                continue;
9777
0
            goto exit;
9778
0
        }
9779
123
        assert(ch2 < 128);
9780
123
        *out = ch2;
9781
123
        out++;
9782
123
    }
9783
72
    res = 1;
9784
9785
144
exit:
9786
144
    writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
9787
144
    *input_pos = in - PyUnicode_1BYTE_DATA(input);
9788
144
    return res;
9789
72
}
9790
9791
static PyObject *
9792
_PyUnicode_TranslateCharmap(PyObject *input,
9793
                            PyObject *mapping,
9794
                            const char *errors)
9795
144
{
9796
    /* input object */
9797
144
    const void *data;
9798
144
    Py_ssize_t size, i;
9799
144
    int kind;
9800
    /* output buffer */
9801
144
    _PyUnicodeWriter writer;
9802
    /* error handler */
9803
144
    const char *reason = "character maps to <undefined>";
9804
144
    PyObject *errorHandler = NULL;
9805
144
    PyObject *exc = NULL;
9806
144
    int ignore;
9807
144
    int res;
9808
9809
144
    if (mapping == NULL) {
9810
0
        PyErr_BadArgument();
9811
0
        return NULL;
9812
0
    }
9813
9814
144
    data = PyUnicode_DATA(input);
9815
144
    kind = PyUnicode_KIND(input);
9816
144
    size = PyUnicode_GET_LENGTH(input);
9817
9818
144
    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
144
    _PyUnicodeWriter_Init(&writer);
9824
144
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
9825
0
        goto onError;
9826
9827
144
    ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9828
9829
144
    if (PyUnicode_IS_ASCII(input)) {
9830
144
        res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9831
144
        if (res < 0) {
9832
0
            _PyUnicodeWriter_Dealloc(&writer);
9833
0
            return NULL;
9834
0
        }
9835
144
        if (res == 1)
9836
72
            return _PyUnicodeWriter_Finish(&writer);
9837
144
    }
9838
0
    else {
9839
0
        i = 0;
9840
0
    }
9841
9842
180
    while (i<size) {
9843
        /* try to encode it */
9844
108
        int translate;
9845
108
        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9846
108
        Py_ssize_t newpos;
9847
        /* startpos for collecting untranslatable chars */
9848
108
        Py_ssize_t collstart;
9849
108
        Py_ssize_t collend;
9850
108
        Py_UCS4 ch;
9851
9852
108
        ch = PyUnicode_READ(kind, data, i);
9853
108
        translate = charmaptranslate_output(ch, mapping, &writer);
9854
108
        if (translate < 0)
9855
0
            goto onError;
9856
9857
108
        if (translate != 0) {
9858
            /* it worked => adjust input pointer */
9859
108
            ++i;
9860
108
            continue;
9861
108
        }
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
72
    Py_XDECREF(exc);
9898
72
    Py_XDECREF(errorHandler);
9899
72
    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
72
}
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
206k
{
9921
206k
    if (!PyUnicode_Check(unicode)) {
9922
0
        PyErr_BadInternalCall();
9923
0
        return NULL;
9924
0
    }
9925
206k
    if (PyUnicode_IS_ASCII(unicode)) {
9926
        /* If the string is already ASCII, just return the same string */
9927
205k
        return Py_NewRef(unicode);
9928
205k
    }
9929
9930
1.68k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9931
1.68k
    PyObject *result = PyUnicode_New(len, 127);
9932
1.68k
    if (result == NULL) {
9933
0
        return NULL;
9934
0
    }
9935
9936
1.68k
    Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9937
1.68k
    int kind = PyUnicode_KIND(unicode);
9938
1.68k
    const void *data = PyUnicode_DATA(unicode);
9939
1.68k
    Py_ssize_t i;
9940
945k
    for (i = 0; i < len; ++i) {
9941
945k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9942
945k
        if (ch < 127) {
9943
937k
            out[i] = ch;
9944
937k
        }
9945
8.47k
        else if (Py_UNICODE_ISSPACE(ch)) {
9946
6.59k
            out[i] = ' ';
9947
6.59k
        }
9948
1.87k
        else {
9949
1.87k
            int decimal = Py_UNICODE_TODECIMAL(ch);
9950
1.87k
            if (decimal < 0) {
9951
1.41k
                out[i] = '?';
9952
1.41k
                out[i+1] = '\0';
9953
1.41k
                _PyUnicode_LENGTH(result) = i + 1;
9954
0
                break;
9955
1.41k
            }
9956
462
            out[i] = '0' + decimal;
9957
462
        }
9958
945k
    }
9959
9960
1.68k
    assert(_PyUnicode_CheckConsistency(result, 1));
9961
1.68k
    return result;
9962
1.68k
}
9963
9964
/* --- Helpers ------------------------------------------------------------ */
9965
9966
/* helper macro to fixup start/end slice values */
9967
#define ADJUST_INDICES(start, end, len) \
9968
3.05M
    do {                                \
9969
3.05M
        if (end > len) {                \
9970
411k
            end = len;                  \
9971
411k
        }                               \
9972
3.05M
        else if (end < 0) {             \
9973
0
            end += len;                 \
9974
0
            if (end < 0) {              \
9975
0
                end = 0;                \
9976
0
            }                           \
9977
0
        }                               \
9978
3.05M
        if (start < 0) {                \
9979
0
            start += len;               \
9980
0
            if (start < 0) {            \
9981
0
                start = 0;              \
9982
0
            }                           \
9983
0
        }                               \
9984
3.05M
    } 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
11.4k
{
9992
11.4k
    int kind1, kind2;
9993
11.4k
    const void *buf1, *buf2;
9994
11.4k
    Py_ssize_t len1, len2, result;
9995
9996
11.4k
    kind1 = PyUnicode_KIND(s1);
9997
11.4k
    kind2 = PyUnicode_KIND(s2);
9998
11.4k
    if (kind1 < kind2)
9999
0
        return -1;
10000
10001
11.4k
    len1 = PyUnicode_GET_LENGTH(s1);
10002
11.4k
    len2 = PyUnicode_GET_LENGTH(s2);
10003
11.4k
    ADJUST_INDICES(start, end, len1);
10004
11.4k
    if (end - start < len2)
10005
1.25k
        return -1;
10006
10007
10.1k
    buf1 = PyUnicode_DATA(s1);
10008
10.1k
    buf2 = PyUnicode_DATA(s2);
10009
10.1k
    if (len2 == 1) {
10010
10.1k
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10011
10.1k
        result = findchar((const char *)buf1 + kind1*start,
10012
10.1k
                          kind1, end - start, ch, direction);
10013
10.1k
        if (result == -1)
10014
8.85k
            return -1;
10015
1.31k
        else
10016
1.31k
            return start + result;
10017
10.1k
    }
10018
10019
0
    if (kind2 != kind1) {
10020
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10021
0
        if (!buf2)
10022
0
            return -2;
10023
0
    }
10024
10025
0
    if (direction > 0) {
10026
0
        switch (kind1) {
10027
0
        case PyUnicode_1BYTE_KIND:
10028
0
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
10029
0
                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
10030
0
            else
10031
0
                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
10032
0
            break;
10033
0
        case PyUnicode_2BYTE_KIND:
10034
0
            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
10035
0
            break;
10036
0
        case PyUnicode_4BYTE_KIND:
10037
0
            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
10038
0
            break;
10039
0
        default:
10040
0
            Py_UNREACHABLE();
10041
0
        }
10042
0
    }
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
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
10063
0
    if (kind2 != kind1)
10064
0
        PyMem_Free((void *)buf2);
10065
10066
0
    return result;
10067
0
}
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
4.70k
{
10089
4.70k
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10090
0
        return -2;
10091
10092
4.70k
    return any_find_slice(str, substr, start, end, direction);
10093
4.70k
}
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
2.62M
{
10100
2.62M
    int kind;
10101
2.62M
    Py_ssize_t len, result;
10102
2.62M
    len = PyUnicode_GET_LENGTH(str);
10103
2.62M
    ADJUST_INDICES(start, end, len);
10104
2.62M
    if (end - start < 1)
10105
0
        return -1;
10106
2.62M
    kind = PyUnicode_KIND(str);
10107
2.62M
    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
10108
2.62M
                      kind, end-start, ch, direction);
10109
2.62M
    if (result == -1)
10110
2.45M
        return -1;
10111
162k
    else
10112
162k
        return start + result;
10113
2.62M
}
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
411k
{
10122
411k
    int kind_self;
10123
411k
    int kind_sub;
10124
411k
    const void *data_self;
10125
411k
    const void *data_sub;
10126
411k
    Py_ssize_t offset;
10127
411k
    Py_ssize_t i;
10128
411k
    Py_ssize_t end_sub;
10129
10130
411k
    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
10131
411k
    end -= PyUnicode_GET_LENGTH(substring);
10132
411k
    if (end < start)
10133
93.0k
        return 0;
10134
10135
318k
    if (PyUnicode_GET_LENGTH(substring) == 0)
10136
0
        return 1;
10137
10138
318k
    kind_self = PyUnicode_KIND(self);
10139
318k
    data_self = PyUnicode_DATA(self);
10140
318k
    kind_sub = PyUnicode_KIND(substring);
10141
318k
    data_sub = PyUnicode_DATA(substring);
10142
318k
    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
10143
10144
318k
    if (direction > 0)
10145
131k
        offset = end;
10146
187k
    else
10147
187k
        offset = start;
10148
10149
318k
    if (PyUnicode_READ(kind_self, data_self, offset) ==
10150
318k
        PyUnicode_READ(kind_sub, data_sub, 0) &&
10151
305k
        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
10152
305k
        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
10153
        /* If both are of the same kind, memcmp is sufficient */
10154
263k
        if (kind_self == kind_sub) {
10155
262k
            return ! memcmp((char *)data_self +
10156
262k
                                (offset * PyUnicode_KIND(substring)),
10157
0
                            data_sub,
10158
262k
                            PyUnicode_GET_LENGTH(substring) *
10159
262k
                                PyUnicode_KIND(substring));
10160
262k
        }
10161
        /* otherwise we have to compare each character by first accessing it */
10162
956
        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
1.70k
            for (i = 1; i < end_sub; ++i) {
10167
1.70k
                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
10168
1.70k
                    PyUnicode_READ(kind_sub, data_sub, i))
10169
954
                    return 0;
10170
1.70k
            }
10171
2
            return 1;
10172
956
        }
10173
263k
    }
10174
10175
54.7k
    return 0;
10176
318k
}
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
0
{
10185
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10186
0
        return -1;
10187
10188
0
    return tailmatch(str, substr, start, end, direction);
10189
0
}
10190
10191
static PyObject *
10192
ascii_upper_or_lower(PyObject *self, int lower)
10193
70.7k
{
10194
70.7k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
10195
70.7k
    const char *data = PyUnicode_DATA(self);
10196
70.7k
    char *resdata;
10197
70.7k
    PyObject *res;
10198
10199
70.7k
    res = PyUnicode_New(len, 127);
10200
70.7k
    if (res == NULL)
10201
0
        return NULL;
10202
70.7k
    resdata = PyUnicode_DATA(res);
10203
70.7k
    if (lower)
10204
70.5k
        _Py_bytes_lower(resdata, data, len);
10205
153
    else
10206
153
        _Py_bytes_upper(resdata, data, len);
10207
70.7k
    return res;
10208
70.7k
}
10209
10210
static Py_UCS4
10211
handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
10212
35
{
10213
35
    Py_ssize_t j;
10214
35
    int final_sigma;
10215
35
    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
35
    for (j = i - 1; j >= 0; j--) {
10223
0
        c = PyUnicode_READ(kind, data, j);
10224
0
        if (!_PyUnicode_IsCaseIgnorable(c))
10225
0
            break;
10226
0
    }
10227
35
    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
10228
35
    if (final_sigma) {
10229
0
        for (j = i + 1; j < length; j++) {
10230
0
            c = PyUnicode_READ(kind, data, j);
10231
0
            if (!_PyUnicode_IsCaseIgnorable(c))
10232
0
                break;
10233
0
        }
10234
0
        final_sigma = j == length || !_PyUnicode_IsCased(c);
10235
0
    }
10236
35
    return (final_sigma) ? 0x3C2 : 0x3C3;
10237
35
}
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
536k
{
10243
    /* Obscure special case. */
10244
536k
    if (c == 0x3A3) {
10245
35
        mapped[0] = handle_capital_sigma(kind, data, length, i);
10246
35
        return 1;
10247
35
    }
10248
536k
    return _PyUnicode_ToLowerFull(c, mapped);
10249
536k
}
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
352k
{
10304
352k
    Py_ssize_t i, k = 0;
10305
10306
889k
    for (i = 0; i < length; i++) {
10307
536k
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10308
536k
        int n_res, j;
10309
536k
        if (lower)
10310
536k
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10311
0
        else
10312
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10313
1.07M
        for (j = 0; j < n_res; j++) {
10314
536k
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10315
536k
            res[k++] = mapped[j];
10316
536k
        }
10317
536k
    }
10318
352k
    return k;
10319
352k
}
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
352k
{
10330
352k
    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
10331
352k
}
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
352k
{
10381
352k
    PyObject *res = NULL;
10382
352k
    Py_ssize_t length, newlength = 0;
10383
352k
    int kind, outkind;
10384
352k
    const void *data;
10385
352k
    void *outdata;
10386
352k
    Py_UCS4 maxchar = 0, *tmp, *tmpend;
10387
10388
352k
    kind = PyUnicode_KIND(self);
10389
352k
    data = PyUnicode_DATA(self);
10390
352k
    length = PyUnicode_GET_LENGTH(self);
10391
352k
    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
352k
    tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
10396
352k
    if (tmp == NULL)
10397
0
        return PyErr_NoMemory();
10398
352k
    newlength = perform(kind, data, length, tmp, &maxchar);
10399
352k
    res = PyUnicode_New(newlength, maxchar);
10400
352k
    if (res == NULL)
10401
0
        goto leave;
10402
352k
    tmpend = tmp + newlength;
10403
352k
    outdata = PyUnicode_DATA(res);
10404
352k
    outkind = PyUnicode_KIND(res);
10405
0
    switch (outkind) {
10406
33.0k
    case PyUnicode_1BYTE_KIND:
10407
33.0k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10408
33.0k
        break;
10409
291k
    case PyUnicode_2BYTE_KIND:
10410
291k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10411
291k
        break;
10412
28.8k
    case PyUnicode_4BYTE_KIND:
10413
28.8k
        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10414
28.8k
        break;
10415
0
    default:
10416
0
        Py_UNREACHABLE();
10417
352k
    }
10418
352k
  leave:
10419
352k
    PyMem_Free(tmp);
10420
352k
    return res;
10421
352k
}
10422
10423
PyObject *
10424
PyUnicode_Join(PyObject *separator, PyObject *seq)
10425
256k
{
10426
256k
    PyObject *res;
10427
256k
    PyObject *fseq;
10428
256k
    Py_ssize_t seqlen;
10429
256k
    PyObject **items;
10430
10431
256k
    fseq = PySequence_Fast(seq, "can only join an iterable");
10432
256k
    if (fseq == NULL) {
10433
0
        return NULL;
10434
0
    }
10435
10436
256k
    Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(seq);
10437
10438
256k
    items = PySequence_Fast_ITEMS(fseq);
10439
256k
    seqlen = PySequence_Fast_GET_SIZE(fseq);
10440
256k
    res = _PyUnicode_JoinArray(separator, items, seqlen);
10441
10442
256k
    Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
10443
10444
256k
    Py_DECREF(fseq);
10445
256k
    return res;
10446
256k
}
10447
10448
PyObject *
10449
_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
10450
412k
{
10451
412k
    PyObject *res = NULL; /* the result */
10452
412k
    PyObject *sep = NULL;
10453
412k
    Py_ssize_t seplen;
10454
412k
    PyObject *item;
10455
412k
    Py_ssize_t sz, i, res_offset;
10456
412k
    Py_UCS4 maxchar;
10457
412k
    Py_UCS4 item_maxchar;
10458
412k
    int use_memcpy;
10459
412k
    unsigned char *res_data = NULL, *sep_data = NULL;
10460
412k
    PyObject *last_obj;
10461
412k
    int kind = 0;
10462
10463
    /* If empty sequence, return u"". */
10464
412k
    if (seqlen == 0) {
10465
1
        _Py_RETURN_UNICODE_EMPTY();
10466
1
    }
10467
10468
    /* If singleton sequence with an exact Unicode, return that. */
10469
412k
    last_obj = NULL;
10470
412k
    if (seqlen == 1) {
10471
203k
        if (PyUnicode_CheckExact(items[0])) {
10472
203k
            res = items[0];
10473
203k
            return Py_NewRef(res);
10474
203k
        }
10475
0
        seplen = 0;
10476
0
        maxchar = 0;
10477
0
    }
10478
208k
    else {
10479
        /* Set up sep and seplen */
10480
208k
        if (separator == NULL) {
10481
            /* fall back to a blank space separator */
10482
0
            sep = PyUnicode_FromOrdinal(' ');
10483
0
            if (!sep)
10484
0
                goto onError;
10485
0
            seplen = 1;
10486
0
            maxchar = 32;
10487
0
        }
10488
208k
        else {
10489
208k
            if (!PyUnicode_Check(separator)) {
10490
0
                PyErr_Format(PyExc_TypeError,
10491
0
                             "separator: expected str instance,"
10492
0
                             " %.80s found",
10493
0
                             Py_TYPE(separator)->tp_name);
10494
0
                goto onError;
10495
0
            }
10496
208k
            sep = separator;
10497
208k
            seplen = PyUnicode_GET_LENGTH(separator);
10498
208k
            maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10499
            /* inc refcount to keep this code path symmetric with the
10500
               above case of a blank separator */
10501
208k
            Py_INCREF(sep);
10502
208k
        }
10503
208k
        last_obj = sep;
10504
208k
    }
10505
10506
    /* There are at least two things to join, or else we have a subclass
10507
     * of str in the sequence.
10508
     * Do a pre-pass to figure out the total amount of space we'll
10509
     * need (sz), and see whether all argument are strings.
10510
     */
10511
208k
    sz = 0;
10512
#ifdef Py_DEBUG
10513
    use_memcpy = 0;
10514
#else
10515
208k
    use_memcpy = 1;
10516
208k
#endif
10517
26.7M
    for (i = 0; i < seqlen; i++) {
10518
26.5M
        size_t add_sz;
10519
26.5M
        item = items[i];
10520
26.5M
        if (!PyUnicode_Check(item)) {
10521
0
            PyErr_Format(PyExc_TypeError,
10522
0
                         "sequence item %zd: expected str instance,"
10523
0
                         " %.80s found",
10524
0
                         i, Py_TYPE(item)->tp_name);
10525
0
            goto onError;
10526
0
        }
10527
26.5M
        add_sz = PyUnicode_GET_LENGTH(item);
10528
26.5M
        item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
10529
26.5M
        maxchar = Py_MAX(maxchar, item_maxchar);
10530
26.5M
        if (i != 0) {
10531
26.2M
            add_sz += seplen;
10532
26.2M
        }
10533
26.5M
        if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
10534
0
            PyErr_SetString(PyExc_OverflowError,
10535
0
                            "join() result is too long for a Python string");
10536
0
            goto onError;
10537
0
        }
10538
26.5M
        sz += add_sz;
10539
26.5M
        if (use_memcpy && last_obj != NULL) {
10540
3.87M
            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10541
27.5k
                use_memcpy = 0;
10542
1.93M
        }
10543
0
        last_obj = item;
10544
26.5M
    }
10545
10546
208k
    res = PyUnicode_New(sz, maxchar);
10547
208k
    if (res == NULL)
10548
0
        goto onError;
10549
10550
    /* Catenate everything. */
10551
#ifdef Py_DEBUG
10552
    use_memcpy = 0;
10553
#else
10554
208k
    if (use_memcpy) {
10555
181k
        res_data = PyUnicode_1BYTE_DATA(res);
10556
181k
        kind = PyUnicode_KIND(res);
10557
181k
        if (seplen != 0)
10558
8.95k
            sep_data = PyUnicode_1BYTE_DATA(sep);
10559
181k
    }
10560
208k
#endif
10561
208k
    if (use_memcpy) {
10562
2.02M
        for (i = 0; i < seqlen; ++i) {
10563
1.84M
            Py_ssize_t itemlen;
10564
1.84M
            item = items[i];
10565
10566
            /* Copy item, and maybe the separator. */
10567
1.84M
            if (i && seplen != 0) {
10568
45.9k
                memcpy(res_data,
10569
45.9k
                          sep_data,
10570
45.9k
                          kind * seplen);
10571
45.9k
                res_data += kind * seplen;
10572
45.9k
            }
10573
10574
1.84M
            itemlen = PyUnicode_GET_LENGTH(item);
10575
1.84M
            if (itemlen != 0) {
10576
1.80M
                memcpy(res_data,
10577
1.80M
                          PyUnicode_DATA(item),
10578
1.80M
                          kind * itemlen);
10579
1.80M
                res_data += kind * itemlen;
10580
1.80M
            }
10581
1.84M
        }
10582
181k
        assert(res_data == PyUnicode_1BYTE_DATA(res)
10583
181k
                           + kind * PyUnicode_GET_LENGTH(res));
10584
181k
    }
10585
27.5k
    else {
10586
24.6M
        for (i = 0, res_offset = 0; i < seqlen; ++i) {
10587
24.6M
            Py_ssize_t itemlen;
10588
24.6M
            item = items[i];
10589
10590
            /* Copy item, and maybe the separator. */
10591
24.6M
            if (i && seplen != 0) {
10592
49.5k
                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10593
49.5k
                res_offset += seplen;
10594
49.5k
            }
10595
10596
24.6M
            itemlen = PyUnicode_GET_LENGTH(item);
10597
24.6M
            if (itemlen != 0) {
10598
24.6M
                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
10599
24.6M
                res_offset += itemlen;
10600
24.6M
            }
10601
24.6M
        }
10602
27.5k
        assert(res_offset == PyUnicode_GET_LENGTH(res));
10603
27.5k
    }
10604
10605
208k
    Py_XDECREF(sep);
10606
208k
    assert(_PyUnicode_CheckConsistency(res, 1));
10607
208k
    return res;
10608
10609
0
  onError:
10610
0
    Py_XDECREF(sep);
10611
0
    Py_XDECREF(res);
10612
0
    return NULL;
10613
208k
}
10614
10615
void
10616
_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10617
                    Py_UCS4 fill_char)
10618
555
{
10619
555
    const int kind = PyUnicode_KIND(unicode);
10620
555
    void *data = PyUnicode_DATA(unicode);
10621
555
    assert(_PyUnicode_IsModifiable(unicode));
10622
555
    assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10623
555
    assert(start >= 0);
10624
555
    assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10625
555
    _PyUnicode_Fill(kind, data, fill_char, start, length);
10626
555
}
10627
10628
Py_ssize_t
10629
PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10630
               Py_UCS4 fill_char)
10631
555
{
10632
555
    Py_ssize_t maxlen;
10633
10634
555
    if (!PyUnicode_Check(unicode)) {
10635
0
        PyErr_BadInternalCall();
10636
0
        return -1;
10637
0
    }
10638
555
    if (unicode_check_modifiable(unicode))
10639
0
        return -1;
10640
10641
555
    if (start < 0) {
10642
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
10643
0
        return -1;
10644
0
    }
10645
555
    if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10646
0
        PyErr_SetString(PyExc_ValueError,
10647
0
                         "fill character is bigger than "
10648
0
                         "the string maximum character");
10649
0
        return -1;
10650
0
    }
10651
10652
555
    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10653
555
    length = Py_MIN(maxlen, length);
10654
555
    if (length <= 0)
10655
0
        return 0;
10656
10657
555
    _PyUnicode_FastFill(unicode, start, length, fill_char);
10658
555
    return length;
10659
555
}
10660
10661
static PyObject *
10662
pad(PyObject *self,
10663
    Py_ssize_t left,
10664
    Py_ssize_t right,
10665
    Py_UCS4 fill)
10666
0
{
10667
0
    PyObject *u;
10668
0
    Py_UCS4 maxchar;
10669
0
    int kind;
10670
0
    void *data;
10671
10672
0
    if (left < 0)
10673
0
        left = 0;
10674
0
    if (right < 0)
10675
0
        right = 0;
10676
10677
0
    if (left == 0 && right == 0)
10678
0
        return unicode_result_unchanged(self);
10679
10680
0
    if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10681
0
        right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
10682
0
        PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10683
0
        return NULL;
10684
0
    }
10685
0
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10686
0
    maxchar = Py_MAX(maxchar, fill);
10687
0
    u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
10688
0
    if (!u)
10689
0
        return NULL;
10690
10691
0
    kind = PyUnicode_KIND(u);
10692
0
    data = PyUnicode_DATA(u);
10693
0
    if (left)
10694
0
        _PyUnicode_Fill(kind, data, fill, 0, left);
10695
0
    if (right)
10696
0
        _PyUnicode_Fill(kind, data, fill,
10697
0
                        left + _PyUnicode_LENGTH(self), right);
10698
0
    _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
10699
0
    assert(_PyUnicode_CheckConsistency(u, 1));
10700
0
    return u;
10701
0
}
10702
10703
PyObject *
10704
PyUnicode_Splitlines(PyObject *string, int keepends)
10705
0
{
10706
0
    PyObject *list;
10707
10708
0
    if (ensure_unicode(string) < 0)
10709
0
        return NULL;
10710
10711
0
    switch (PyUnicode_KIND(string)) {
10712
0
    case PyUnicode_1BYTE_KIND:
10713
0
        if (PyUnicode_IS_ASCII(string))
10714
0
            list = asciilib_splitlines(
10715
0
                string, PyUnicode_1BYTE_DATA(string),
10716
0
                PyUnicode_GET_LENGTH(string), keepends);
10717
0
        else
10718
0
            list = ucs1lib_splitlines(
10719
0
                string, PyUnicode_1BYTE_DATA(string),
10720
0
                PyUnicode_GET_LENGTH(string), keepends);
10721
0
        break;
10722
0
    case PyUnicode_2BYTE_KIND:
10723
0
        list = ucs2lib_splitlines(
10724
0
            string, PyUnicode_2BYTE_DATA(string),
10725
0
            PyUnicode_GET_LENGTH(string), keepends);
10726
0
        break;
10727
0
    case PyUnicode_4BYTE_KIND:
10728
0
        list = ucs4lib_splitlines(
10729
0
            string, PyUnicode_4BYTE_DATA(string),
10730
0
            PyUnicode_GET_LENGTH(string), keepends);
10731
0
        break;
10732
0
    default:
10733
0
        Py_UNREACHABLE();
10734
0
    }
10735
0
    return list;
10736
0
}
10737
10738
static PyObject *
10739
split(PyObject *self,
10740
      PyObject *substring,
10741
      Py_ssize_t maxcount)
10742
3.34k
{
10743
3.34k
    int kind1, kind2;
10744
3.34k
    const void *buf1, *buf2;
10745
3.34k
    Py_ssize_t len1, len2;
10746
3.34k
    PyObject* out;
10747
3.34k
    len1 = PyUnicode_GET_LENGTH(self);
10748
3.34k
    kind1 = PyUnicode_KIND(self);
10749
10750
3.34k
    if (substring == NULL) {
10751
7
        if (maxcount < 0) {
10752
7
            maxcount = (len1 - 1) / 2 + 1;
10753
7
        }
10754
7
        switch (kind1) {
10755
7
        case PyUnicode_1BYTE_KIND:
10756
7
            if (PyUnicode_IS_ASCII(self))
10757
7
                return asciilib_split_whitespace(
10758
7
                    self,  PyUnicode_1BYTE_DATA(self),
10759
7
                    len1, maxcount
10760
7
                    );
10761
0
            else
10762
0
                return ucs1lib_split_whitespace(
10763
0
                    self,  PyUnicode_1BYTE_DATA(self),
10764
0
                    len1, maxcount
10765
0
                    );
10766
0
        case PyUnicode_2BYTE_KIND:
10767
0
            return ucs2lib_split_whitespace(
10768
0
                self,  PyUnicode_2BYTE_DATA(self),
10769
0
                len1, maxcount
10770
0
                );
10771
0
        case PyUnicode_4BYTE_KIND:
10772
0
            return ucs4lib_split_whitespace(
10773
0
                self,  PyUnicode_4BYTE_DATA(self),
10774
0
                len1, maxcount
10775
0
                );
10776
0
        default:
10777
0
            Py_UNREACHABLE();
10778
7
        }
10779
7
    }
10780
10781
3.34k
    kind2 = PyUnicode_KIND(substring);
10782
3.34k
    len2 = PyUnicode_GET_LENGTH(substring);
10783
3.34k
    if (maxcount < 0) {
10784
        // if len2 == 0, it will raise ValueError.
10785
3.34k
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10786
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10787
3.34k
        maxcount = maxcount < 0 ? len1 : maxcount;
10788
3.34k
    }
10789
3.34k
    if (kind1 < kind2 || len1 < len2) {
10790
2
        out = PyList_New(1);
10791
2
        if (out == NULL)
10792
0
            return NULL;
10793
2
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10794
2
        return out;
10795
2
    }
10796
3.33k
    buf1 = PyUnicode_DATA(self);
10797
3.33k
    buf2 = PyUnicode_DATA(substring);
10798
3.33k
    if (kind2 != kind1) {
10799
1.13k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10800
1.13k
        if (!buf2)
10801
0
            return NULL;
10802
1.13k
    }
10803
10804
3.33k
    switch (kind1) {
10805
2.20k
    case PyUnicode_1BYTE_KIND:
10806
2.20k
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10807
1.89k
            out = asciilib_split(
10808
1.89k
                self,  buf1, len1, buf2, len2, maxcount);
10809
310
        else
10810
310
            out = ucs1lib_split(
10811
310
                self,  buf1, len1, buf2, len2, maxcount);
10812
2.20k
        break;
10813
615
    case PyUnicode_2BYTE_KIND:
10814
615
        out = ucs2lib_split(
10815
615
            self,  buf1, len1, buf2, len2, maxcount);
10816
615
        break;
10817
523
    case PyUnicode_4BYTE_KIND:
10818
523
        out = ucs4lib_split(
10819
523
            self,  buf1, len1, buf2, len2, maxcount);
10820
523
        break;
10821
0
    default:
10822
0
        out = NULL;
10823
3.33k
    }
10824
3.33k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10825
3.33k
    if (kind2 != kind1)
10826
1.13k
        PyMem_Free((void *)buf2);
10827
3.33k
    return out;
10828
3.33k
}
10829
10830
static PyObject *
10831
rsplit(PyObject *self,
10832
       PyObject *substring,
10833
       Py_ssize_t maxcount)
10834
0
{
10835
0
    int kind1, kind2;
10836
0
    const void *buf1, *buf2;
10837
0
    Py_ssize_t len1, len2;
10838
0
    PyObject* out;
10839
10840
0
    len1 = PyUnicode_GET_LENGTH(self);
10841
0
    kind1 = PyUnicode_KIND(self);
10842
10843
0
    if (substring == NULL) {
10844
0
        if (maxcount < 0) {
10845
0
            maxcount = (len1 - 1) / 2 + 1;
10846
0
        }
10847
0
        switch (kind1) {
10848
0
        case PyUnicode_1BYTE_KIND:
10849
0
            if (PyUnicode_IS_ASCII(self))
10850
0
                return asciilib_rsplit_whitespace(
10851
0
                    self,  PyUnicode_1BYTE_DATA(self),
10852
0
                    len1, maxcount
10853
0
                    );
10854
0
            else
10855
0
                return ucs1lib_rsplit_whitespace(
10856
0
                    self,  PyUnicode_1BYTE_DATA(self),
10857
0
                    len1, maxcount
10858
0
                    );
10859
0
        case PyUnicode_2BYTE_KIND:
10860
0
            return ucs2lib_rsplit_whitespace(
10861
0
                self,  PyUnicode_2BYTE_DATA(self),
10862
0
                len1, maxcount
10863
0
                );
10864
0
        case PyUnicode_4BYTE_KIND:
10865
0
            return ucs4lib_rsplit_whitespace(
10866
0
                self,  PyUnicode_4BYTE_DATA(self),
10867
0
                len1, maxcount
10868
0
                );
10869
0
        default:
10870
0
            Py_UNREACHABLE();
10871
0
        }
10872
0
    }
10873
0
    kind2 = PyUnicode_KIND(substring);
10874
0
    len2 = PyUnicode_GET_LENGTH(substring);
10875
0
    if (maxcount < 0) {
10876
        // if len2 == 0, it will raise ValueError.
10877
0
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10878
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10879
0
        maxcount = maxcount < 0 ? len1 : maxcount;
10880
0
    }
10881
0
    if (kind1 < kind2 || len1 < len2) {
10882
0
        out = PyList_New(1);
10883
0
        if (out == NULL)
10884
0
            return NULL;
10885
0
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10886
0
        return out;
10887
0
    }
10888
0
    buf1 = PyUnicode_DATA(self);
10889
0
    buf2 = PyUnicode_DATA(substring);
10890
0
    if (kind2 != kind1) {
10891
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10892
0
        if (!buf2)
10893
0
            return NULL;
10894
0
    }
10895
10896
0
    switch (kind1) {
10897
0
    case PyUnicode_1BYTE_KIND:
10898
0
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10899
0
            out = asciilib_rsplit(
10900
0
                self,  buf1, len1, buf2, len2, maxcount);
10901
0
        else
10902
0
            out = ucs1lib_rsplit(
10903
0
                self,  buf1, len1, buf2, len2, maxcount);
10904
0
        break;
10905
0
    case PyUnicode_2BYTE_KIND:
10906
0
        out = ucs2lib_rsplit(
10907
0
            self,  buf1, len1, buf2, len2, maxcount);
10908
0
        break;
10909
0
    case PyUnicode_4BYTE_KIND:
10910
0
        out = ucs4lib_rsplit(
10911
0
            self,  buf1, len1, buf2, len2, maxcount);
10912
0
        break;
10913
0
    default:
10914
0
        out = NULL;
10915
0
    }
10916
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10917
0
    if (kind2 != kind1)
10918
0
        PyMem_Free((void *)buf2);
10919
0
    return out;
10920
0
}
10921
10922
static Py_ssize_t
10923
anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
10924
            PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
10925
36.3k
{
10926
36.3k
    switch (kind) {
10927
19.5k
    case PyUnicode_1BYTE_KIND:
10928
19.5k
        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10929
14.7k
            return asciilib_find(buf1, len1, buf2, len2, offset);
10930
4.77k
        else
10931
4.77k
            return ucs1lib_find(buf1, len1, buf2, len2, offset);
10932
7.58k
    case PyUnicode_2BYTE_KIND:
10933
7.58k
        return ucs2lib_find(buf1, len1, buf2, len2, offset);
10934
9.29k
    case PyUnicode_4BYTE_KIND:
10935
9.29k
        return ucs4lib_find(buf1, len1, buf2, len2, offset);
10936
36.3k
    }
10937
36.3k
    Py_UNREACHABLE();
10938
36.3k
}
10939
10940
static Py_ssize_t
10941
anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
10942
             PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
10943
56.7k
{
10944
56.7k
    switch (kind) {
10945
52.5k
    case PyUnicode_1BYTE_KIND:
10946
52.5k
        return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10947
2.62k
    case PyUnicode_2BYTE_KIND:
10948
2.62k
        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10949
1.61k
    case PyUnicode_4BYTE_KIND:
10950
1.61k
        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10951
56.7k
    }
10952
56.7k
    Py_UNREACHABLE();
10953
56.7k
}
10954
10955
static void
10956
replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10957
                      Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10958
128
{
10959
128
    int kind = PyUnicode_KIND(u);
10960
128
    void *data = PyUnicode_DATA(u);
10961
128
    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10962
128
    if (kind == PyUnicode_1BYTE_KIND) {
10963
128
        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10964
128
                                      (Py_UCS1 *)data + len,
10965
128
                                      u1, u2, maxcount);
10966
128
    }
10967
0
    else if (kind == PyUnicode_2BYTE_KIND) {
10968
0
        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10969
0
                                      (Py_UCS2 *)data + len,
10970
0
                                      u1, u2, maxcount);
10971
0
    }
10972
0
    else {
10973
0
        assert(kind == PyUnicode_4BYTE_KIND);
10974
0
        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10975
0
                                      (Py_UCS4 *)data + len,
10976
0
                                      u1, u2, maxcount);
10977
0
    }
10978
128
}
10979
10980
static PyObject *
10981
replace(PyObject *self, PyObject *str1,
10982
        PyObject *str2, Py_ssize_t maxcount)
10983
61.1k
{
10984
61.1k
    PyObject *u;
10985
61.1k
    const char *sbuf = PyUnicode_DATA(self);
10986
61.1k
    const void *buf1 = PyUnicode_DATA(str1);
10987
61.1k
    const void *buf2 = PyUnicode_DATA(str2);
10988
61.1k
    int srelease = 0, release1 = 0, release2 = 0;
10989
61.1k
    int skind = PyUnicode_KIND(self);
10990
61.1k
    int kind1 = PyUnicode_KIND(str1);
10991
61.1k
    int kind2 = PyUnicode_KIND(str2);
10992
61.1k
    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10993
61.1k
    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10994
61.1k
    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
10995
61.1k
    int mayshrink;
10996
61.1k
    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
10997
10998
61.1k
    if (slen < len1)
10999
3.38k
        goto nothing;
11000
11001
57.8k
    if (maxcount < 0)
11002
57.8k
        maxcount = PY_SSIZE_T_MAX;
11003
0
    else if (maxcount == 0)
11004
0
        goto nothing;
11005
11006
57.8k
    if (str1 == str2)
11007
0
        goto nothing;
11008
11009
57.8k
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
11010
57.8k
    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
11011
57.8k
    if (maxchar < maxchar_str1)
11012
        /* substring too wide to be present */
11013
0
        goto nothing;
11014
57.8k
    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
11015
    /* Replacing str1 with str2 may cause a maxchar reduction in the
11016
       result string. */
11017
57.8k
    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
11018
57.8k
    maxchar = Py_MAX(maxchar, maxchar_str2);
11019
11020
57.8k
    if (len1 == len2) {
11021
        /* same length */
11022
1.03k
        if (len1 == 0)
11023
0
            goto nothing;
11024
1.03k
        if (len1 == 1) {
11025
            /* replace characters */
11026
1.03k
            Py_UCS4 u1, u2;
11027
1.03k
            Py_ssize_t pos;
11028
11029
1.03k
            u1 = PyUnicode_READ(kind1, buf1, 0);
11030
1.03k
            pos = findchar(sbuf, skind, slen, u1, 1);
11031
1.03k
            if (pos < 0)
11032
902
                goto nothing;
11033
128
            u2 = PyUnicode_READ(kind2, buf2, 0);
11034
128
            u = PyUnicode_New(slen, maxchar);
11035
128
            if (!u)
11036
0
                goto error;
11037
11038
128
            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
11039
128
            replace_1char_inplace(u, pos, u1, u2, maxcount);
11040
128
        }
11041
0
        else {
11042
0
            int rkind = skind;
11043
0
            char *res;
11044
0
            Py_ssize_t i;
11045
11046
0
            if (kind1 < rkind) {
11047
                /* widen substring */
11048
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
11049
0
                if (!buf1) goto error;
11050
0
                release1 = 1;
11051
0
            }
11052
0
            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
11053
0
            if (i < 0)
11054
0
                goto nothing;
11055
0
            if (rkind > kind2) {
11056
                /* widen replacement */
11057
0
                buf2 = unicode_askind(kind2, buf2, len2, rkind);
11058
0
                if (!buf2) goto error;
11059
0
                release2 = 1;
11060
0
            }
11061
0
            else if (rkind < kind2) {
11062
                /* widen self and buf1 */
11063
0
                rkind = kind2;
11064
0
                if (release1) {
11065
0
                    assert(buf1 != PyUnicode_DATA(str1));
11066
0
                    PyMem_Free((void *)buf1);
11067
0
                    buf1 = PyUnicode_DATA(str1);
11068
0
                    release1 = 0;
11069
0
                }
11070
0
                sbuf = unicode_askind(skind, sbuf, slen, rkind);
11071
0
                if (!sbuf) goto error;
11072
0
                srelease = 1;
11073
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
11074
0
                if (!buf1) goto error;
11075
0
                release1 = 1;
11076
0
            }
11077
0
            u = PyUnicode_New(slen, maxchar);
11078
0
            if (!u)
11079
0
                goto error;
11080
0
            assert(PyUnicode_KIND(u) == rkind);
11081
0
            res = PyUnicode_DATA(u);
11082
11083
0
            memcpy(res, sbuf, rkind * slen);
11084
            /* change everything in-place, starting with this one */
11085
0
            memcpy(res + rkind * i,
11086
0
                   buf2,
11087
0
                   rkind * len2);
11088
0
            i += len1;
11089
11090
0
            while ( --maxcount > 0) {
11091
0
                i = anylib_find(rkind, self,
11092
0
                                sbuf+rkind*i, slen-i,
11093
0
                                str1, buf1, len1, i);
11094
0
                if (i == -1)
11095
0
                    break;
11096
0
                memcpy(res + rkind * i,
11097
0
                       buf2,
11098
0
                       rkind * len2);
11099
0
                i += len1;
11100
0
            }
11101
0
        }
11102
1.03k
    }
11103
56.7k
    else {
11104
56.7k
        Py_ssize_t n, i, j, ires;
11105
56.7k
        Py_ssize_t new_size;
11106
56.7k
        int rkind = skind;
11107
56.7k
        char *res;
11108
11109
56.7k
        if (kind1 < rkind) {
11110
            /* widen substring */
11111
4.23k
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11112
4.23k
            if (!buf1) goto error;
11113
4.23k
            release1 = 1;
11114
4.23k
        }
11115
56.7k
        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
11116
56.7k
        if (n == 0)
11117
47.0k
            goto nothing;
11118
9.70k
        if (kind2 < rkind) {
11119
            /* widen replacement */
11120
2.72k
            buf2 = unicode_askind(kind2, buf2, len2, rkind);
11121
2.72k
            if (!buf2) goto error;
11122
2.72k
            release2 = 1;
11123
2.72k
        }
11124
6.98k
        else if (kind2 > rkind) {
11125
            /* widen self and buf1 */
11126
0
            rkind = kind2;
11127
0
            sbuf = unicode_askind(skind, sbuf, slen, rkind);
11128
0
            if (!sbuf) goto error;
11129
0
            srelease = 1;
11130
0
            if (release1) {
11131
0
                assert(buf1 != PyUnicode_DATA(str1));
11132
0
                PyMem_Free((void *)buf1);
11133
0
                buf1 = PyUnicode_DATA(str1);
11134
0
                release1 = 0;
11135
0
            }
11136
0
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11137
0
            if (!buf1) goto error;
11138
0
            release1 = 1;
11139
0
        }
11140
        /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
11141
           PyUnicode_GET_LENGTH(str1)); */
11142
9.70k
        if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
11143
0
                PyErr_SetString(PyExc_OverflowError,
11144
0
                                "replace string is too long");
11145
0
                goto error;
11146
0
        }
11147
9.70k
        new_size = slen + n * (len2 - len1);
11148
9.70k
        if (new_size == 0) {
11149
0
            u = _PyUnicode_GetEmpty();
11150
0
            goto done;
11151
0
        }
11152
9.70k
        if (new_size > (PY_SSIZE_T_MAX / rkind)) {
11153
0
            PyErr_SetString(PyExc_OverflowError,
11154
0
                            "replace string is too long");
11155
0
            goto error;
11156
0
        }
11157
9.70k
        u = PyUnicode_New(new_size, maxchar);
11158
9.70k
        if (!u)
11159
0
            goto error;
11160
9.70k
        assert(PyUnicode_KIND(u) == rkind);
11161
9.70k
        res = PyUnicode_DATA(u);
11162
9.70k
        ires = i = 0;
11163
9.70k
        if (len1 > 0) {
11164
46.0k
            while (n-- > 0) {
11165
                /* look for next match */
11166
36.3k
                j = anylib_find(rkind, self,
11167
36.3k
                                sbuf + rkind * i, slen-i,
11168
36.3k
                                str1, buf1, len1, i);
11169
36.3k
                if (j == -1)
11170
0
                    break;
11171
36.3k
                else if (j > i) {
11172
                    /* copy unchanged part [i:j] */
11173
14.6k
                    memcpy(res + rkind * ires,
11174
14.6k
                           sbuf + rkind * i,
11175
14.6k
                           rkind * (j-i));
11176
14.6k
                    ires += j - i;
11177
14.6k
                }
11178
                /* copy substitution string */
11179
36.3k
                if (len2 > 0) {
11180
33.9k
                    memcpy(res + rkind * ires,
11181
33.9k
                           buf2,
11182
33.9k
                           rkind * len2);
11183
33.9k
                    ires += len2;
11184
33.9k
                }
11185
36.3k
                i = j + len1;
11186
36.3k
            }
11187
9.70k
            if (i < slen)
11188
                /* copy tail [i:] */
11189
7.40k
                memcpy(res + rkind * ires,
11190
7.40k
                       sbuf + rkind * i,
11191
7.40k
                       rkind * (slen-i));
11192
9.70k
        }
11193
0
        else {
11194
            /* interleave */
11195
0
            while (n > 0) {
11196
0
                memcpy(res + rkind * ires,
11197
0
                       buf2,
11198
0
                       rkind * len2);
11199
0
                ires += len2;
11200
0
                if (--n <= 0)
11201
0
                    break;
11202
0
                memcpy(res + rkind * ires,
11203
0
                       sbuf + rkind * i,
11204
0
                       rkind);
11205
0
                ires++;
11206
0
                i++;
11207
0
            }
11208
0
            memcpy(res + rkind * ires,
11209
0
                   sbuf + rkind * i,
11210
0
                   rkind * (slen-i));
11211
0
        }
11212
9.70k
    }
11213
11214
9.83k
    if (mayshrink) {
11215
0
        unicode_adjust_maxchar(&u);
11216
0
        if (u == NULL)
11217
0
            goto error;
11218
0
    }
11219
11220
9.83k
  done:
11221
9.83k
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11222
9.83k
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11223
9.83k
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11224
9.83k
    if (srelease)
11225
0
        PyMem_Free((void *)sbuf);
11226
9.83k
    if (release1)
11227
2.72k
        PyMem_Free((void *)buf1);
11228
9.83k
    if (release2)
11229
2.72k
        PyMem_Free((void *)buf2);
11230
9.83k
    assert(_PyUnicode_CheckConsistency(u, 1));
11231
9.83k
    return u;
11232
11233
51.3k
  nothing:
11234
    /* nothing to replace; return original string (when possible) */
11235
51.3k
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11236
51.3k
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11237
51.3k
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11238
51.3k
    if (srelease)
11239
0
        PyMem_Free((void *)sbuf);
11240
51.3k
    if (release1)
11241
1.51k
        PyMem_Free((void *)buf1);
11242
51.3k
    if (release2)
11243
0
        PyMem_Free((void *)buf2);
11244
51.3k
    return unicode_result_unchanged(self);
11245
11246
0
  error:
11247
0
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11248
0
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11249
0
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11250
0
    if (srelease)
11251
0
        PyMem_Free((void *)sbuf);
11252
0
    if (release1)
11253
0
        PyMem_Free((void *)buf1);
11254
0
    if (release2)
11255
0
        PyMem_Free((void *)buf2);
11256
0
    return NULL;
11257
0
}
11258
11259
/* --- Unicode Object Methods --------------------------------------------- */
11260
11261
/*[clinic input]
11262
str.title as unicode_title
11263
11264
Return a version of the string where each word is titlecased.
11265
11266
More specifically, words start with uppercased characters and all
11267
remaining cased characters have lower case.
11268
[clinic start generated code]*/
11269
11270
static PyObject *
11271
unicode_title_impl(PyObject *self)
11272
/*[clinic end generated code: output=c75ae03809574902 input=2a07e2c7df94627a]*/
11273
0
{
11274
0
    return case_operation(self, do_title);
11275
0
}
11276
11277
/*[clinic input]
11278
str.capitalize as unicode_capitalize
11279
11280
Return a capitalized version of the string.
11281
11282
More specifically, make the first character have upper case and the
11283
rest lower case.
11284
[clinic start generated code]*/
11285
11286
static PyObject *
11287
unicode_capitalize_impl(PyObject *self)
11288
/*[clinic end generated code: output=e49a4c333cdb7667 input=e50e50ed45a654cf]*/
11289
0
{
11290
0
    if (PyUnicode_GET_LENGTH(self) == 0)
11291
0
        return unicode_result_unchanged(self);
11292
0
    return case_operation(self, do_capitalize);
11293
0
}
11294
11295
/*[clinic input]
11296
str.casefold as unicode_casefold
11297
11298
Return a version of the string suitable for caseless comparisons.
11299
[clinic start generated code]*/
11300
11301
static PyObject *
11302
unicode_casefold_impl(PyObject *self)
11303
/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
11304
0
{
11305
0
    if (PyUnicode_IS_ASCII(self))
11306
0
        return ascii_upper_or_lower(self, 1);
11307
0
    return case_operation(self, do_casefold);
11308
0
}
11309
11310
11311
/* Argument converter. Accepts a single Unicode character. */
11312
11313
static int
11314
convert_uc(PyObject *obj, void *addr)
11315
0
{
11316
0
    Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
11317
11318
0
    if (!PyUnicode_Check(obj)) {
11319
0
        PyErr_Format(PyExc_TypeError,
11320
0
                     "The fill character must be a unicode character, "
11321
0
                     "not %.100s", Py_TYPE(obj)->tp_name);
11322
0
        return 0;
11323
0
    }
11324
0
    if (PyUnicode_GET_LENGTH(obj) != 1) {
11325
0
        PyErr_SetString(PyExc_TypeError,
11326
0
                        "The fill character must be exactly one character long");
11327
0
        return 0;
11328
0
    }
11329
0
    *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
11330
0
    return 1;
11331
0
}
11332
11333
/*[clinic input]
11334
str.center as unicode_center
11335
11336
    width: Py_ssize_t
11337
    fillchar: Py_UCS4 = ' '
11338
    /
11339
11340
Return a centered string of length width.
11341
11342
Padding is done using the specified fill character (default is
11343
a space).
11344
[clinic start generated code]*/
11345
11346
static PyObject *
11347
unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
11348
/*[clinic end generated code: output=420c8859effc7c0c input=df91017dfd186a78]*/
11349
0
{
11350
0
    Py_ssize_t marg, left;
11351
11352
0
    if (PyUnicode_GET_LENGTH(self) >= width)
11353
0
        return unicode_result_unchanged(self);
11354
11355
0
    marg = width - PyUnicode_GET_LENGTH(self);
11356
0
    left = marg / 2 + (marg & width & 1);
11357
11358
0
    return pad(self, left, marg - left, fillchar);
11359
0
}
11360
11361
/* This function assumes that str1 and str2 are readied by the caller. */
11362
11363
static int
11364
unicode_compare(PyObject *str1, PyObject *str2)
11365
3.79M
{
11366
3.79M
#define COMPARE(TYPE1, TYPE2) \
11367
3.79M
    do { \
11368
2.72M
        TYPE1* p1 = (TYPE1 *)data1; \
11369
2.72M
        TYPE2* p2 = (TYPE2 *)data2; \
11370
2.72M
        TYPE1* end = p1 + len; \
11371
2.72M
        Py_UCS4 c1, c2; \
11372
2.87M
        for (; p1 != end; p1++, p2++) { \
11373
2.87M
            c1 = *p1; \
11374
2.87M
            c2 = *p2; \
11375
2.87M
            if (c1 != c2) \
11376
2.87M
                return (c1 < c2) ? -1 : 1; \
11377
2.87M
        } \
11378
2.72M
    } \
11379
2.72M
    while (0)
11380
11381
3.79M
    int kind1, kind2;
11382
3.79M
    const void *data1, *data2;
11383
3.79M
    Py_ssize_t len1, len2, len;
11384
11385
3.79M
    kind1 = PyUnicode_KIND(str1);
11386
3.79M
    kind2 = PyUnicode_KIND(str2);
11387
3.79M
    data1 = PyUnicode_DATA(str1);
11388
3.79M
    data2 = PyUnicode_DATA(str2);
11389
3.79M
    len1 = PyUnicode_GET_LENGTH(str1);
11390
3.79M
    len2 = PyUnicode_GET_LENGTH(str2);
11391
3.79M
    len = Py_MIN(len1, len2);
11392
11393
3.79M
    switch(kind1) {
11394
1.05M
    case PyUnicode_1BYTE_KIND:
11395
1.05M
    {
11396
1.05M
        switch(kind2) {
11397
945k
        case PyUnicode_1BYTE_KIND:
11398
945k
        {
11399
945k
            int cmp = memcmp(data1, data2, len);
11400
            /* normalize result of memcmp() into the range [-1; 1] */
11401
945k
            if (cmp < 0)
11402
513k
                return -1;
11403
431k
            if (cmp > 0)
11404
373k
                return 1;
11405
58.0k
            break;
11406
431k
        }
11407
90.9k
        case PyUnicode_2BYTE_KIND:
11408
90.9k
            COMPARE(Py_UCS1, Py_UCS2);
11409
1.40k
            break;
11410
14.0k
        case PyUnicode_4BYTE_KIND:
11411
14.0k
            COMPARE(Py_UCS1, Py_UCS4);
11412
67
            break;
11413
67
        default:
11414
0
            Py_UNREACHABLE();
11415
1.05M
        }
11416
59.4k
        break;
11417
1.05M
    }
11418
2.60M
    case PyUnicode_2BYTE_KIND:
11419
2.60M
    {
11420
2.60M
        switch(kind2) {
11421
13.3k
        case PyUnicode_1BYTE_KIND:
11422
13.3k
            COMPARE(Py_UCS2, Py_UCS1);
11423
1.06k
            break;
11424
2.57M
        case PyUnicode_2BYTE_KIND:
11425
2.57M
        {
11426
2.57M
            COMPARE(Py_UCS2, Py_UCS2);
11427
3.63k
            break;
11428
2.57M
        }
11429
12.0k
        case PyUnicode_4BYTE_KIND:
11430
12.0k
            COMPARE(Py_UCS2, Py_UCS4);
11431
24
            break;
11432
24
        default:
11433
0
            Py_UNREACHABLE();
11434
2.60M
        }
11435
4.72k
        break;
11436
2.60M
    }
11437
138k
    case PyUnicode_4BYTE_KIND:
11438
138k
    {
11439
138k
        switch(kind2) {
11440
611
        case PyUnicode_1BYTE_KIND:
11441
611
            COMPARE(Py_UCS4, Py_UCS1);
11442
45
            break;
11443
12.3k
        case PyUnicode_2BYTE_KIND:
11444
12.3k
            COMPARE(Py_UCS4, Py_UCS2);
11445
7
            break;
11446
125k
        case PyUnicode_4BYTE_KIND:
11447
125k
        {
11448
125k
#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11449
125k
            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11450
            /* normalize result of wmemcmp() into the range [-1; 1] */
11451
125k
            if (cmp < 0)
11452
60.6k
                return -1;
11453
65.3k
            if (cmp > 0)
11454
65.2k
                return 1;
11455
#else
11456
            COMPARE(Py_UCS4, Py_UCS4);
11457
#endif
11458
70
            break;
11459
65.3k
        }
11460
70
        default:
11461
0
            Py_UNREACHABLE();
11462
138k
        }
11463
122
        break;
11464
138k
    }
11465
122
    default:
11466
0
        Py_UNREACHABLE();
11467
3.79M
    }
11468
11469
64.3k
    if (len1 == len2)
11470
377
        return 0;
11471
63.9k
    if (len1 < len2)
11472
33.3k
        return -1;
11473
30.6k
    else
11474
30.6k
        return 1;
11475
11476
63.9k
#undef COMPARE
11477
63.9k
}
11478
11479
11480
int
11481
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
11482
84.8M
{
11483
84.8M
    assert(PyUnicode_Check(str1));
11484
84.8M
    assert(PyUnicode_Check(str2));
11485
84.8M
    if (str1 == str2) {
11486
12.9M
        return 1;
11487
12.9M
    }
11488
71.8M
    return unicode_eq(str1, str2);
11489
84.8M
}
11490
11491
11492
int
11493
PyUnicode_Equal(PyObject *str1, PyObject *str2)
11494
0
{
11495
0
    if (!PyUnicode_Check(str1)) {
11496
0
        PyErr_Format(PyExc_TypeError,
11497
0
                     "first argument must be str, not %T", str1);
11498
0
        return -1;
11499
0
    }
11500
0
    if (!PyUnicode_Check(str2)) {
11501
0
        PyErr_Format(PyExc_TypeError,
11502
0
                     "second argument must be str, not %T", str2);
11503
0
        return -1;
11504
0
    }
11505
11506
0
    return _PyUnicode_Equal(str1, str2);
11507
0
}
11508
11509
11510
int
11511
PyUnicode_Compare(PyObject *left, PyObject *right)
11512
141k
{
11513
141k
    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11514
        /* a string is equal to itself */
11515
141k
        if (left == right)
11516
49
            return 0;
11517
11518
141k
        return unicode_compare(left, right);
11519
141k
    }
11520
0
    PyErr_Format(PyExc_TypeError,
11521
0
                 "Can't compare %.100s and %.100s",
11522
0
                 Py_TYPE(left)->tp_name,
11523
0
                 Py_TYPE(right)->tp_name);
11524
0
    return -1;
11525
141k
}
11526
11527
int
11528
PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11529
880k
{
11530
880k
    Py_ssize_t i;
11531
880k
    int kind;
11532
880k
    Py_UCS4 chr;
11533
11534
880k
    assert(_PyUnicode_CHECK(uni));
11535
880k
    kind = PyUnicode_KIND(uni);
11536
880k
    if (kind == PyUnicode_1BYTE_KIND) {
11537
878k
        const void *data = PyUnicode_1BYTE_DATA(uni);
11538
878k
        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
11539
878k
        size_t len, len2 = strlen(str);
11540
878k
        int cmp;
11541
11542
878k
        len = Py_MIN(len1, len2);
11543
878k
        cmp = memcmp(data, str, len);
11544
878k
        if (cmp != 0) {
11545
451k
            if (cmp < 0)
11546
16.7k
                return -1;
11547
435k
            else
11548
435k
                return 1;
11549
451k
        }
11550
426k
        if (len1 > len2)
11551
409
            return 1; /* uni is longer */
11552
425k
        if (len1 < len2)
11553
5.55k
            return -1; /* str is longer */
11554
420k
        return 0;
11555
425k
    }
11556
2.82k
    else {
11557
2.82k
        const void *data = PyUnicode_DATA(uni);
11558
        /* Compare Unicode string and source character set string */
11559
6.63k
        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
11560
5.73k
            if (chr != (unsigned char)str[i])
11561
1.92k
                return (chr < (unsigned char)(str[i])) ? -1 : 1;
11562
        /* This check keeps Python strings that end in '\0' from comparing equal
11563
         to C strings identical up to that point. */
11564
904
        if (PyUnicode_GET_LENGTH(uni) != i || chr)
11565
904
            return 1; /* uni is longer */
11566
0
        if (str[i])
11567
0
            return -1; /* str is longer */
11568
0
        return 0;
11569
0
    }
11570
880k
}
11571
11572
int
11573
PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
11574
2
{
11575
2
    return PyUnicode_EqualToUTF8AndSize(unicode, str, strlen(str));
11576
2
}
11577
11578
int
11579
PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t size)
11580
2
{
11581
2
    assert(_PyUnicode_CHECK(unicode));
11582
2
    assert(str);
11583
11584
2
    if (PyUnicode_IS_ASCII(unicode)) {
11585
2
        Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11586
2
        return size == len &&
11587
0
            memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11588
2
    }
11589
0
    if (PyUnicode_UTF8(unicode) != NULL) {
11590
0
        Py_ssize_t len = PyUnicode_UTF8_LENGTH(unicode);
11591
0
        return size == len &&
11592
0
            memcmp(PyUnicode_UTF8(unicode), str, len) == 0;
11593
0
    }
11594
11595
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11596
0
    if ((size_t)len >= (size_t)size || (size_t)len < (size_t)size / 4) {
11597
0
        return 0;
11598
0
    }
11599
0
    const unsigned char *s = (const unsigned char *)str;
11600
0
    const unsigned char *ends = s + (size_t)size;
11601
0
    int kind = PyUnicode_KIND(unicode);
11602
0
    const void *data = PyUnicode_DATA(unicode);
11603
    /* Compare Unicode string and UTF-8 string */
11604
0
    for (Py_ssize_t i = 0; i < len; i++) {
11605
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11606
0
        if (ch < 0x80) {
11607
0
            if (ends == s || s[0] != ch) {
11608
0
                return 0;
11609
0
            }
11610
0
            s += 1;
11611
0
        }
11612
0
        else if (ch < 0x800) {
11613
0
            if ((ends - s) < 2 ||
11614
0
                s[0] != (0xc0 | (ch >> 6)) ||
11615
0
                s[1] != (0x80 | (ch & 0x3f)))
11616
0
            {
11617
0
                return 0;
11618
0
            }
11619
0
            s += 2;
11620
0
        }
11621
0
        else if (ch < 0x10000) {
11622
0
            if (Py_UNICODE_IS_SURROGATE(ch) ||
11623
0
                (ends - s) < 3 ||
11624
0
                s[0] != (0xe0 | (ch >> 12)) ||
11625
0
                s[1] != (0x80 | ((ch >> 6) & 0x3f)) ||
11626
0
                s[2] != (0x80 | (ch & 0x3f)))
11627
0
            {
11628
0
                return 0;
11629
0
            }
11630
0
            s += 3;
11631
0
        }
11632
0
        else {
11633
0
            assert(ch <= MAX_UNICODE);
11634
0
            if ((ends - s) < 4 ||
11635
0
                s[0] != (0xf0 | (ch >> 18)) ||
11636
0
                s[1] != (0x80 | ((ch >> 12) & 0x3f)) ||
11637
0
                s[2] != (0x80 | ((ch >> 6) & 0x3f)) ||
11638
0
                s[3] != (0x80 | (ch & 0x3f)))
11639
0
            {
11640
0
                return 0;
11641
0
            }
11642
0
            s += 4;
11643
0
        }
11644
0
    }
11645
0
    return s == ends;
11646
0
}
11647
11648
int
11649
_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11650
4.11M
{
11651
4.11M
    size_t len;
11652
4.11M
    assert(_PyUnicode_CHECK(unicode));
11653
4.11M
    assert(str);
11654
4.11M
#ifndef NDEBUG
11655
26.0M
    for (const char *p = str; *p; p++) {
11656
21.9M
        assert((unsigned char)*p < 128);
11657
21.9M
    }
11658
4.11M
#endif
11659
4.11M
    if (!PyUnicode_IS_ASCII(unicode))
11660
190k
        return 0;
11661
3.92M
    len = (size_t)PyUnicode_GET_LENGTH(unicode);
11662
3.92M
    return strlen(str) == len &&
11663
349k
           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11664
4.11M
}
11665
11666
PyObject *
11667
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
11668
5.60M
{
11669
5.60M
    int result;
11670
11671
5.60M
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11672
11.8k
        Py_RETURN_NOTIMPLEMENTED;
11673
11674
5.59M
    if (left == right) {
11675
442
        switch (op) {
11676
365
        case Py_EQ:
11677
365
        case Py_LE:
11678
365
        case Py_GE:
11679
            /* a string is equal to itself */
11680
365
            Py_RETURN_TRUE;
11681
77
        case Py_NE:
11682
77
        case Py_LT:
11683
77
        case Py_GT:
11684
77
            Py_RETURN_FALSE;
11685
0
        default:
11686
0
            PyErr_BadArgument();
11687
0
            return NULL;
11688
442
        }
11689
442
    }
11690
5.59M
    else if (op == Py_EQ || op == Py_NE) {
11691
1.94M
        result = unicode_eq(left, right);
11692
1.94M
        result ^= (op == Py_NE);
11693
1.94M
        return PyBool_FromLong(result);
11694
1.94M
    }
11695
3.64M
    else {
11696
3.64M
        result = unicode_compare(left, right);
11697
3.64M
        Py_RETURN_RICHCOMPARE(result, 0, op);
11698
3.64M
    }
11699
5.59M
}
11700
11701
int
11702
PyUnicode_Contains(PyObject *str, PyObject *substr)
11703
348M
{
11704
348M
    int kind1, kind2;
11705
348M
    const void *buf1, *buf2;
11706
348M
    Py_ssize_t len1, len2;
11707
348M
    int result;
11708
11709
348M
    if (!PyUnicode_Check(substr)) {
11710
0
        PyErr_Format(PyExc_TypeError,
11711
0
                     "'in <string>' requires string as left operand, not %.100s",
11712
0
                     Py_TYPE(substr)->tp_name);
11713
0
        return -1;
11714
0
    }
11715
348M
    if (ensure_unicode(str) < 0)
11716
0
        return -1;
11717
11718
348M
    kind1 = PyUnicode_KIND(str);
11719
348M
    kind2 = PyUnicode_KIND(substr);
11720
348M
    if (kind1 < kind2)
11721
3
        return 0;
11722
348M
    len1 = PyUnicode_GET_LENGTH(str);
11723
348M
    len2 = PyUnicode_GET_LENGTH(substr);
11724
348M
    if (len1 < len2)
11725
44
        return 0;
11726
348M
    buf1 = PyUnicode_DATA(str);
11727
348M
    buf2 = PyUnicode_DATA(substr);
11728
348M
    if (len2 == 1) {
11729
27.7M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11730
27.7M
        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11731
27.7M
        return result;
11732
27.7M
    }
11733
320M
    if (kind2 != kind1) {
11734
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11735
0
        if (!buf2)
11736
0
            return -1;
11737
0
    }
11738
11739
320M
    switch (kind1) {
11740
320M
    case PyUnicode_1BYTE_KIND:
11741
320M
        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11742
320M
        break;
11743
0
    case PyUnicode_2BYTE_KIND:
11744
0
        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11745
0
        break;
11746
0
    case PyUnicode_4BYTE_KIND:
11747
0
        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11748
0
        break;
11749
0
    default:
11750
0
        Py_UNREACHABLE();
11751
320M
    }
11752
11753
320M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
11754
320M
    if (kind2 != kind1)
11755
0
        PyMem_Free((void *)buf2);
11756
11757
320M
    return result;
11758
320M
}
11759
11760
/* Concat to string or Unicode object giving a new Unicode object. */
11761
11762
PyObject *
11763
PyUnicode_Concat(PyObject *left, PyObject *right)
11764
1.46M
{
11765
1.46M
    PyObject *result;
11766
1.46M
    Py_UCS4 maxchar, maxchar2;
11767
1.46M
    Py_ssize_t left_len, right_len, new_len;
11768
11769
1.46M
    if (ensure_unicode(left) < 0)
11770
0
        return NULL;
11771
11772
1.46M
    if (!PyUnicode_Check(right)) {
11773
508
        PyErr_Format(PyExc_TypeError,
11774
508
            "can only concatenate str (not \"%.200s\") to str",
11775
508
            Py_TYPE(right)->tp_name);
11776
508
        return NULL;
11777
508
    }
11778
11779
    /* Shortcuts */
11780
1.46M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11781
1.46M
    if (left == empty) {
11782
35.7k
        return PyUnicode_FromObject(right);
11783
35.7k
    }
11784
1.42M
    if (right == empty) {
11785
44.1k
        return PyUnicode_FromObject(left);
11786
44.1k
    }
11787
11788
1.38M
    left_len = PyUnicode_GET_LENGTH(left);
11789
1.38M
    right_len = PyUnicode_GET_LENGTH(right);
11790
1.38M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11791
0
        PyErr_SetString(PyExc_OverflowError,
11792
0
                        "strings are too large to concat");
11793
0
        return NULL;
11794
0
    }
11795
1.38M
    new_len = left_len + right_len;
11796
11797
1.38M
    maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11798
1.38M
    maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11799
1.38M
    maxchar = Py_MAX(maxchar, maxchar2);
11800
11801
    /* Concat the two Unicode strings */
11802
1.38M
    result = PyUnicode_New(new_len, maxchar);
11803
1.38M
    if (result == NULL)
11804
0
        return NULL;
11805
1.38M
    _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11806
1.38M
    _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11807
1.38M
    assert(_PyUnicode_CheckConsistency(result, 1));
11808
1.38M
    return result;
11809
1.38M
}
11810
11811
void
11812
PyUnicode_Append(PyObject **p_left, PyObject *right)
11813
7.04M
{
11814
7.04M
    PyObject *left, *res;
11815
7.04M
    Py_UCS4 maxchar, maxchar2;
11816
7.04M
    Py_ssize_t left_len, right_len, new_len;
11817
11818
7.04M
    if (p_left == NULL) {
11819
0
        if (!PyErr_Occurred())
11820
0
            PyErr_BadInternalCall();
11821
0
        return;
11822
0
    }
11823
7.04M
    left = *p_left;
11824
7.04M
    if (right == NULL || left == NULL
11825
7.04M
        || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
11826
0
        if (!PyErr_Occurred())
11827
0
            PyErr_BadInternalCall();
11828
0
        goto error;
11829
0
    }
11830
11831
    /* Shortcuts */
11832
7.04M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11833
7.04M
    if (left == empty) {
11834
65.9k
        Py_DECREF(left);
11835
65.9k
        *p_left = Py_NewRef(right);
11836
65.9k
        return;
11837
65.9k
    }
11838
6.97M
    if (right == empty) {
11839
3.27k
        return;
11840
3.27k
    }
11841
11842
6.97M
    left_len = PyUnicode_GET_LENGTH(left);
11843
6.97M
    right_len = PyUnicode_GET_LENGTH(right);
11844
6.97M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11845
0
        PyErr_SetString(PyExc_OverflowError,
11846
0
                        "strings are too large to concat");
11847
0
        goto error;
11848
0
    }
11849
6.97M
    new_len = left_len + right_len;
11850
11851
6.97M
    if (_PyUnicode_IsModifiable(left)
11852
6.97M
        && PyUnicode_CheckExact(right)
11853
12.6M
        && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
11854
        /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11855
           to change the structure size, but characters are stored just after
11856
           the structure, and so it requires to move all characters which is
11857
           not so different than duplicating the string. */
11858
6.32M
        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11859
6.32M
    {
11860
        /* append inplace */
11861
6.32M
        if (unicode_resize(p_left, new_len) != 0)
11862
0
            goto error;
11863
11864
        /* copy 'right' into the newly allocated area of 'left' */
11865
6.32M
        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
11866
6.32M
    }
11867
646k
    else {
11868
646k
        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11869
646k
        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11870
646k
        maxchar = Py_MAX(maxchar, maxchar2);
11871
11872
        /* Concat the two Unicode strings */
11873
646k
        res = PyUnicode_New(new_len, maxchar);
11874
646k
        if (res == NULL)
11875
0
            goto error;
11876
646k
        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11877
646k
        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
11878
646k
        Py_DECREF(left);
11879
646k
        *p_left = res;
11880
646k
    }
11881
6.97M
    assert(_PyUnicode_CheckConsistency(*p_left, 1));
11882
6.97M
    return;
11883
11884
6.97M
error:
11885
0
    Py_CLEAR(*p_left);
11886
0
}
11887
11888
void
11889
PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11890
0
{
11891
0
    PyUnicode_Append(pleft, right);
11892
0
    Py_XDECREF(right);
11893
0
}
11894
11895
/*[clinic input]
11896
@permit_long_summary
11897
@text_signature "($self, sub[, start[, end]], /)"
11898
str.count as unicode_count -> Py_ssize_t
11899
11900
    self as str: self
11901
    sub as substr: unicode
11902
    start: slice_index(accept={int, NoneType}, c_default='0') = None
11903
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
11904
    /
11905
11906
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
11907
11908
Optional arguments start and end are interpreted as in slice
11909
notation.
11910
[clinic start generated code]*/
11911
11912
static Py_ssize_t
11913
unicode_count_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
11914
                   Py_ssize_t end)
11915
/*[clinic end generated code: output=8fcc3aef0b18edbf input=c9209e05438cc352]*/
11916
6.25k
{
11917
6.25k
    assert(PyUnicode_Check(str));
11918
6.25k
    assert(PyUnicode_Check(substr));
11919
11920
6.25k
    Py_ssize_t result;
11921
6.25k
    int kind1, kind2;
11922
6.25k
    const void *buf1 = NULL, *buf2 = NULL;
11923
6.25k
    Py_ssize_t len1, len2;
11924
11925
6.25k
    kind1 = PyUnicode_KIND(str);
11926
6.25k
    kind2 = PyUnicode_KIND(substr);
11927
6.25k
    if (kind1 < kind2)
11928
0
        return 0;
11929
11930
6.25k
    len1 = PyUnicode_GET_LENGTH(str);
11931
6.25k
    len2 = PyUnicode_GET_LENGTH(substr);
11932
6.25k
    ADJUST_INDICES(start, end, len1);
11933
6.25k
    if (end - start < len2)
11934
1.25k
        return 0;
11935
11936
4.99k
    buf1 = PyUnicode_DATA(str);
11937
4.99k
    buf2 = PyUnicode_DATA(substr);
11938
4.99k
    if (kind2 != kind1) {
11939
2.18k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11940
2.18k
        if (!buf2)
11941
0
            goto onError;
11942
2.18k
    }
11943
11944
    // We don't reuse `anylib_count` here because of the explicit casts.
11945
4.99k
    switch (kind1) {
11946
2.81k
    case PyUnicode_1BYTE_KIND:
11947
2.81k
        result = ucs1lib_count(
11948
2.81k
            ((const Py_UCS1*)buf1) + start, end - start,
11949
2.81k
            buf2, len2, PY_SSIZE_T_MAX
11950
2.81k
            );
11951
2.81k
        break;
11952
933
    case PyUnicode_2BYTE_KIND:
11953
933
        result = ucs2lib_count(
11954
933
            ((const Py_UCS2*)buf1) + start, end - start,
11955
933
            buf2, len2, PY_SSIZE_T_MAX
11956
933
            );
11957
933
        break;
11958
1.25k
    case PyUnicode_4BYTE_KIND:
11959
1.25k
        result = ucs4lib_count(
11960
1.25k
            ((const Py_UCS4*)buf1) + start, end - start,
11961
1.25k
            buf2, len2, PY_SSIZE_T_MAX
11962
1.25k
            );
11963
1.25k
        break;
11964
0
    default:
11965
0
        Py_UNREACHABLE();
11966
4.99k
    }
11967
11968
4.99k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11969
4.99k
    if (kind2 != kind1)
11970
2.18k
        PyMem_Free((void *)buf2);
11971
11972
4.99k
    return result;
11973
0
  onError:
11974
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11975
0
    if (kind2 != kind1)
11976
0
        PyMem_Free((void *)buf2);
11977
0
    return -1;
11978
0
}
11979
11980
/*[clinic input]
11981
str.encode as unicode_encode
11982
11983
    encoding: str(c_default="NULL") = 'utf-8'
11984
        The encoding in which to encode the string.
11985
    errors: str(c_default="NULL") = 'strict'
11986
        The error handling scheme to use for encoding errors.
11987
        The default is 'strict' meaning that encoding errors raise a
11988
        UnicodeEncodeError.  Other possible values are 'ignore', 'replace'
11989
        and 'xmlcharrefreplace' as well as any other name registered with
11990
        codecs.register_error that can handle UnicodeEncodeErrors.
11991
11992
Encode the string using the codec registered for encoding.
11993
[clinic start generated code]*/
11994
11995
static PyObject *
11996
unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
11997
/*[clinic end generated code: output=bf78b6e2a9470e3c input=b85a9645cb33b729]*/
11998
46.6k
{
11999
46.6k
    return PyUnicode_AsEncodedString(self, encoding, errors);
12000
46.6k
}
12001
12002
/*[clinic input]
12003
str.expandtabs as unicode_expandtabs
12004
12005
    tabsize: int = 8
12006
12007
Return a copy where all tab characters are expanded using spaces.
12008
12009
If tabsize is not given, a tab size of 8 characters is assumed.
12010
[clinic start generated code]*/
12011
12012
static PyObject *
12013
unicode_expandtabs_impl(PyObject *self, int tabsize)
12014
/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
12015
2.91k
{
12016
2.91k
    Py_ssize_t i, j, line_pos, src_len, incr;
12017
2.91k
    Py_UCS4 ch;
12018
2.91k
    PyObject *u;
12019
2.91k
    const void *src_data;
12020
2.91k
    void *dest_data;
12021
2.91k
    int kind;
12022
2.91k
    int found;
12023
12024
    /* First pass: determine size of output string */
12025
2.91k
    src_len = PyUnicode_GET_LENGTH(self);
12026
2.91k
    i = j = line_pos = 0;
12027
2.91k
    kind = PyUnicode_KIND(self);
12028
2.91k
    src_data = PyUnicode_DATA(self);
12029
2.91k
    found = 0;
12030
152k
    for (; i < src_len; i++) {
12031
149k
        ch = PyUnicode_READ(kind, src_data, i);
12032
149k
        if (ch == '\t') {
12033
7.77k
            found = 1;
12034
7.77k
            if (tabsize > 0) {
12035
7.77k
                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
12036
7.77k
                if (j > PY_SSIZE_T_MAX - incr)
12037
0
                    goto overflow;
12038
7.77k
                line_pos += incr;
12039
7.77k
                j += incr;
12040
7.77k
            }
12041
7.77k
        }
12042
141k
        else {
12043
141k
            if (j > PY_SSIZE_T_MAX - 1)
12044
0
                goto overflow;
12045
141k
            line_pos++;
12046
141k
            j++;
12047
141k
            if (ch == '\n' || ch == '\r')
12048
32.4k
                line_pos = 0;
12049
141k
        }
12050
149k
    }
12051
2.91k
    if (!found)
12052
1.92k
        return unicode_result_unchanged(self);
12053
12054
    /* Second pass: create output string and fill it */
12055
988
    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
12056
988
    if (!u)
12057
0
        return NULL;
12058
988
    dest_data = PyUnicode_DATA(u);
12059
12060
988
    i = j = line_pos = 0;
12061
12062
131k
    for (; i < src_len; i++) {
12063
130k
        ch = PyUnicode_READ(kind, src_data, i);
12064
130k
        if (ch == '\t') {
12065
7.77k
            if (tabsize > 0) {
12066
7.77k
                incr = tabsize - (line_pos % tabsize);
12067
7.77k
                line_pos += incr;
12068
7.77k
                _PyUnicode_Fill(kind, dest_data, ' ', j, incr);
12069
7.77k
                j += incr;
12070
7.77k
            }
12071
7.77k
        }
12072
122k
        else {
12073
122k
            line_pos++;
12074
122k
            PyUnicode_WRITE(kind, dest_data, j, ch);
12075
122k
            j++;
12076
122k
            if (ch == '\n' || ch == '\r')
12077
28.5k
                line_pos = 0;
12078
122k
        }
12079
130k
    }
12080
988
    assert (j == PyUnicode_GET_LENGTH(u));
12081
988
    return unicode_result(u);
12082
12083
0
  overflow:
12084
0
    PyErr_SetString(PyExc_OverflowError, "new string is too long");
12085
0
    return NULL;
12086
988
}
12087
12088
/*[clinic input]
12089
@permit_long_summary
12090
str.find as unicode_find = str.count
12091
12092
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12093
12094
Optional arguments start and end are interpreted as in slice
12095
notation.  Return -1 on failure.
12096
[clinic start generated code]*/
12097
12098
static Py_ssize_t
12099
unicode_find_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12100
                  Py_ssize_t end)
12101
/*[clinic end generated code: output=51dbe6255712e278 input=f57e93c59d1ee927]*/
12102
22
{
12103
22
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12104
22
    if (result < 0) {
12105
0
        return -1;
12106
0
    }
12107
22
    return result;
12108
22
}
12109
12110
static PyObject *
12111
unicode_getitem(PyObject *self, Py_ssize_t index)
12112
6.32M
{
12113
6.32M
    const void *data;
12114
6.32M
    int kind;
12115
6.32M
    Py_UCS4 ch;
12116
12117
6.32M
    if (!PyUnicode_Check(self)) {
12118
0
        PyErr_BadArgument();
12119
0
        return NULL;
12120
0
    }
12121
6.32M
    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
12122
7.22k
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12123
7.22k
        return NULL;
12124
7.22k
    }
12125
6.32M
    kind = PyUnicode_KIND(self);
12126
6.32M
    data = PyUnicode_DATA(self);
12127
6.32M
    ch = PyUnicode_READ(kind, data, index);
12128
6.32M
    return unicode_char(ch);
12129
6.32M
}
12130
12131
/* Believe it or not, this produces the same value for ASCII strings
12132
   as bytes_hash(). */
12133
static Py_hash_t
12134
unicode_hash(PyObject *self)
12135
15.3M
{
12136
15.3M
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
12137
12138
#ifdef Py_DEBUG
12139
    assert(_Py_HashSecret_Initialized);
12140
#endif
12141
15.3M
    Py_hash_t hash = PyUnicode_HASH(self);
12142
15.3M
    if (hash != -1) {
12143
9.88M
        return hash;
12144
9.88M
    }
12145
5.50M
    x = Py_HashBuffer(PyUnicode_DATA(self),
12146
5.50M
                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
12147
12148
0
    PyUnicode_SET_HASH(self, x);
12149
5.50M
    return x;
12150
5.50M
}
12151
12152
/*[clinic input]
12153
@permit_long_summary
12154
str.index as unicode_index = str.count
12155
12156
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12157
12158
Optional arguments start and end are interpreted as in slice
12159
notation.  Raises ValueError when the substring is not found.
12160
[clinic start generated code]*/
12161
12162
static Py_ssize_t
12163
unicode_index_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12164
                   Py_ssize_t end)
12165
/*[clinic end generated code: output=77558288837cdf40 input=5900ab84de55e628]*/
12166
0
{
12167
0
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12168
0
    if (result == -1) {
12169
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
12170
0
    }
12171
0
    else if (result < 0) {
12172
0
        return -1;
12173
0
    }
12174
0
    return result;
12175
0
}
12176
12177
/*[clinic input]
12178
@permit_long_summary
12179
str.isascii as unicode_isascii
12180
12181
Return True if all characters in the string are ASCII, False otherwise.
12182
12183
ASCII characters have code points in the range U+0000-U+007F.
12184
Empty string is ASCII too.
12185
[clinic start generated code]*/
12186
12187
static PyObject *
12188
unicode_isascii_impl(PyObject *self)
12189
/*[clinic end generated code: output=c5910d64b5a8003f input=dc74e1ced821159f]*/
12190
5.55k
{
12191
5.55k
    return PyBool_FromLong(PyUnicode_IS_ASCII(self));
12192
5.55k
}
12193
12194
/*[clinic input]
12195
str.islower as unicode_islower
12196
12197
Return True if the string is a lowercase string, False otherwise.
12198
12199
A string is lowercase if all cased characters in the string are
12200
lowercase and there is at least one cased character in the string.
12201
[clinic start generated code]*/
12202
12203
static PyObject *
12204
unicode_islower_impl(PyObject *self)
12205
/*[clinic end generated code: output=dbd41995bd005b81 input=1879b48dfc628366]*/
12206
0
{
12207
0
    Py_ssize_t i, length;
12208
0
    int kind;
12209
0
    const void *data;
12210
0
    int cased;
12211
12212
0
    length = PyUnicode_GET_LENGTH(self);
12213
0
    kind = PyUnicode_KIND(self);
12214
0
    data = PyUnicode_DATA(self);
12215
12216
    /* Shortcut for single character strings */
12217
0
    if (length == 1)
12218
0
        return PyBool_FromLong(
12219
0
            Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
12220
12221
    /* Special case for empty strings */
12222
0
    if (length == 0)
12223
0
        Py_RETURN_FALSE;
12224
12225
0
    cased = 0;
12226
0
    for (i = 0; i < length; i++) {
12227
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12228
12229
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
12230
0
            Py_RETURN_FALSE;
12231
0
        else if (!cased && Py_UNICODE_ISLOWER(ch))
12232
0
            cased = 1;
12233
0
    }
12234
0
    return PyBool_FromLong(cased);
12235
0
}
12236
12237
/*[clinic input]
12238
str.isupper as unicode_isupper
12239
12240
Return True if the string is an uppercase string, False otherwise.
12241
12242
A string is uppercase if all cased characters in the string are
12243
uppercase and there is at least one cased character in the string.
12244
[clinic start generated code]*/
12245
12246
static PyObject *
12247
unicode_isupper_impl(PyObject *self)
12248
/*[clinic end generated code: output=049209c8e7f15f59 input=77d29904aef0e3a0]*/
12249
0
{
12250
0
    Py_ssize_t i, length;
12251
0
    int kind;
12252
0
    const void *data;
12253
0
    int cased;
12254
12255
0
    length = PyUnicode_GET_LENGTH(self);
12256
0
    kind = PyUnicode_KIND(self);
12257
0
    data = PyUnicode_DATA(self);
12258
12259
    /* Shortcut for single character strings */
12260
0
    if (length == 1)
12261
0
        return PyBool_FromLong(
12262
0
            Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
12263
12264
    /* Special case for empty strings */
12265
0
    if (length == 0)
12266
0
        Py_RETURN_FALSE;
12267
12268
0
    cased = 0;
12269
0
    for (i = 0; i < length; i++) {
12270
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12271
12272
0
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
12273
0
            Py_RETURN_FALSE;
12274
0
        else if (!cased && Py_UNICODE_ISUPPER(ch))
12275
0
            cased = 1;
12276
0
    }
12277
0
    return PyBool_FromLong(cased);
12278
0
}
12279
12280
/*[clinic input]
12281
str.istitle as unicode_istitle
12282
12283
Return True if the string is a title-cased string, False otherwise.
12284
12285
In a title-cased string, upper- and title-case characters may only
12286
follow uncased characters and lowercase characters only cased ones.
12287
[clinic start generated code]*/
12288
12289
static PyObject *
12290
unicode_istitle_impl(PyObject *self)
12291
/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
12292
0
{
12293
0
    Py_ssize_t i, length;
12294
0
    int kind;
12295
0
    const void *data;
12296
0
    int cased, previous_is_cased;
12297
12298
0
    length = PyUnicode_GET_LENGTH(self);
12299
0
    kind = PyUnicode_KIND(self);
12300
0
    data = PyUnicode_DATA(self);
12301
12302
    /* Shortcut for single character strings */
12303
0
    if (length == 1) {
12304
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12305
0
        return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
12306
0
                               (Py_UNICODE_ISUPPER(ch) != 0));
12307
0
    }
12308
12309
    /* Special case for empty strings */
12310
0
    if (length == 0)
12311
0
        Py_RETURN_FALSE;
12312
12313
0
    cased = 0;
12314
0
    previous_is_cased = 0;
12315
0
    for (i = 0; i < length; i++) {
12316
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12317
12318
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
12319
0
            if (previous_is_cased)
12320
0
                Py_RETURN_FALSE;
12321
0
            previous_is_cased = 1;
12322
0
            cased = 1;
12323
0
        }
12324
0
        else if (Py_UNICODE_ISLOWER(ch)) {
12325
0
            if (!previous_is_cased)
12326
0
                Py_RETURN_FALSE;
12327
0
            previous_is_cased = 1;
12328
0
            cased = 1;
12329
0
        }
12330
0
        else
12331
0
            previous_is_cased = 0;
12332
0
    }
12333
0
    return PyBool_FromLong(cased);
12334
0
}
12335
12336
/*[clinic input]
12337
str.isspace as unicode_isspace
12338
12339
Return True if the string is a whitespace string, False otherwise.
12340
12341
A string is whitespace if all characters in the string are
12342
whitespace and there is at least one character in the string.
12343
[clinic start generated code]*/
12344
12345
static PyObject *
12346
unicode_isspace_impl(PyObject *self)
12347
/*[clinic end generated code: output=163a63bfa08ac2b9 input=29e09560fc23fbeb]*/
12348
0
{
12349
0
    Py_ssize_t i, length;
12350
0
    int kind;
12351
0
    const void *data;
12352
12353
0
    length = PyUnicode_GET_LENGTH(self);
12354
0
    kind = PyUnicode_KIND(self);
12355
0
    data = PyUnicode_DATA(self);
12356
12357
    /* Shortcut for single character strings */
12358
0
    if (length == 1)
12359
0
        return PyBool_FromLong(
12360
0
            Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
12361
12362
    /* Special case for empty strings */
12363
0
    if (length == 0)
12364
0
        Py_RETURN_FALSE;
12365
12366
0
    for (i = 0; i < length; i++) {
12367
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12368
0
        if (!Py_UNICODE_ISSPACE(ch))
12369
0
            Py_RETURN_FALSE;
12370
0
    }
12371
0
    Py_RETURN_TRUE;
12372
0
}
12373
12374
/*[clinic input]
12375
str.isalpha as unicode_isalpha
12376
12377
Return True if the string is an alphabetic string, False otherwise.
12378
12379
A string is alphabetic if all characters in the string are
12380
alphabetic and there is at least one character in the string.
12381
[clinic start generated code]*/
12382
12383
static PyObject *
12384
unicode_isalpha_impl(PyObject *self)
12385
/*[clinic end generated code: output=cc81b9ac3883ec4f input=9906a07f3e04892e]*/
12386
10
{
12387
10
    Py_ssize_t i, length;
12388
10
    int kind;
12389
10
    const void *data;
12390
12391
10
    length = PyUnicode_GET_LENGTH(self);
12392
10
    kind = PyUnicode_KIND(self);
12393
10
    data = PyUnicode_DATA(self);
12394
12395
    /* Shortcut for single character strings */
12396
10
    if (length == 1)
12397
7
        return PyBool_FromLong(
12398
7
            Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
12399
12400
    /* Special case for empty strings */
12401
3
    if (length == 0)
12402
0
        Py_RETURN_FALSE;
12403
12404
3
    for (i = 0; i < length; i++) {
12405
3
        if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
12406
3
            Py_RETURN_FALSE;
12407
3
    }
12408
3
    Py_RETURN_TRUE;
12409
3
}
12410
12411
/*[clinic input]
12412
@permit_long_summary
12413
str.isalnum as unicode_isalnum
12414
12415
Return True if the string is an alpha-numeric string, False otherwise.
12416
12417
A string is alpha-numeric if all characters in the string are
12418
alpha-numeric and there is at least one character in the string.
12419
[clinic start generated code]*/
12420
12421
static PyObject *
12422
unicode_isalnum_impl(PyObject *self)
12423
/*[clinic end generated code: output=a5a23490ffc3660c input=892f64ebc171fd4f]*/
12424
128
{
12425
128
    int kind;
12426
128
    const void *data;
12427
128
    Py_ssize_t len, i;
12428
12429
128
    kind = PyUnicode_KIND(self);
12430
128
    data = PyUnicode_DATA(self);
12431
128
    len = PyUnicode_GET_LENGTH(self);
12432
12433
    /* Shortcut for single character strings */
12434
128
    if (len == 1) {
12435
128
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12436
128
        return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12437
128
    }
12438
12439
    /* Special case for empty strings */
12440
0
    if (len == 0)
12441
0
        Py_RETURN_FALSE;
12442
12443
0
    for (i = 0; i < len; i++) {
12444
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12445
0
        if (!Py_UNICODE_ISALNUM(ch))
12446
0
            Py_RETURN_FALSE;
12447
0
    }
12448
0
    Py_RETURN_TRUE;
12449
0
}
12450
12451
/*[clinic input]
12452
str.isdecimal as unicode_isdecimal
12453
12454
Return True if the string is a decimal string, False otherwise.
12455
12456
A string is a decimal string if all characters in the string are
12457
decimal and there is at least one character in the string.
12458
[clinic start generated code]*/
12459
12460
static PyObject *
12461
unicode_isdecimal_impl(PyObject *self)
12462
/*[clinic end generated code: output=fb2dcdb62d3fc548 input=63b0453c48cad0af]*/
12463
4.13k
{
12464
4.13k
    Py_ssize_t i, length;
12465
4.13k
    int kind;
12466
4.13k
    const void *data;
12467
12468
4.13k
    length = PyUnicode_GET_LENGTH(self);
12469
4.13k
    kind = PyUnicode_KIND(self);
12470
4.13k
    data = PyUnicode_DATA(self);
12471
12472
    /* Shortcut for single character strings */
12473
4.13k
    if (length == 1)
12474
2.85k
        return PyBool_FromLong(
12475
2.85k
            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
12476
12477
    /* Special case for empty strings */
12478
1.28k
    if (length == 0)
12479
0
        Py_RETURN_FALSE;
12480
12481
828k
    for (i = 0; i < length; i++) {
12482
827k
        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
12483
360
            Py_RETURN_FALSE;
12484
827k
    }
12485
1.28k
    Py_RETURN_TRUE;
12486
1.28k
}
12487
12488
/*[clinic input]
12489
str.isdigit as unicode_isdigit
12490
12491
Return True if the string is a digit string, False otherwise.
12492
12493
A string is a digit string if all characters in the string are
12494
digits and there is at least one character in the string.
12495
[clinic start generated code]*/
12496
12497
static PyObject *
12498
unicode_isdigit_impl(PyObject *self)
12499
/*[clinic end generated code: output=10a6985311da6858 input=353b03747b062e4b]*/
12500
0
{
12501
0
    Py_ssize_t i, length;
12502
0
    int kind;
12503
0
    const void *data;
12504
12505
0
    length = PyUnicode_GET_LENGTH(self);
12506
0
    kind = PyUnicode_KIND(self);
12507
0
    data = PyUnicode_DATA(self);
12508
12509
    /* Shortcut for single character strings */
12510
0
    if (length == 1) {
12511
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12512
0
        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12513
0
    }
12514
12515
    /* Special case for empty strings */
12516
0
    if (length == 0)
12517
0
        Py_RETURN_FALSE;
12518
12519
0
    for (i = 0; i < length; i++) {
12520
0
        if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
12521
0
            Py_RETURN_FALSE;
12522
0
    }
12523
0
    Py_RETURN_TRUE;
12524
0
}
12525
12526
/*[clinic input]
12527
str.isnumeric as unicode_isnumeric
12528
12529
Return True if the string is a numeric string, False otherwise.
12530
12531
A string is numeric if all characters in the string are numeric and
12532
there is at least one character in the string.
12533
[clinic start generated code]*/
12534
12535
static PyObject *
12536
unicode_isnumeric_impl(PyObject *self)
12537
/*[clinic end generated code: output=9172a32d9013051a input=83b2a072ed7aff48]*/
12538
0
{
12539
0
    Py_ssize_t i, length;
12540
0
    int kind;
12541
0
    const void *data;
12542
12543
0
    length = PyUnicode_GET_LENGTH(self);
12544
0
    kind = PyUnicode_KIND(self);
12545
0
    data = PyUnicode_DATA(self);
12546
12547
    /* Shortcut for single character strings */
12548
0
    if (length == 1)
12549
0
        return PyBool_FromLong(
12550
0
            Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
12551
12552
    /* Special case for empty strings */
12553
0
    if (length == 0)
12554
0
        Py_RETURN_FALSE;
12555
12556
0
    for (i = 0; i < length; i++) {
12557
0
        if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
12558
0
            Py_RETURN_FALSE;
12559
0
    }
12560
0
    Py_RETURN_TRUE;
12561
0
}
12562
12563
Py_ssize_t
12564
_PyUnicode_ScanIdentifier(PyObject *self)
12565
65.8k
{
12566
65.8k
    Py_ssize_t i;
12567
65.8k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12568
65.8k
    if (len == 0) {
12569
        /* an empty string is not a valid identifier */
12570
0
        return 0;
12571
0
    }
12572
12573
65.8k
    int kind = PyUnicode_KIND(self);
12574
65.8k
    const void *data = PyUnicode_DATA(self);
12575
65.8k
    Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12576
    /* PEP 3131 says that the first character must be in
12577
       XID_Start and subsequent characters in XID_Continue,
12578
       and for the ASCII range, the 2.x rules apply (i.e
12579
       start with letters and underscore, continue with
12580
       letters, digits, underscore). However, given the current
12581
       definition of XID_Start and XID_Continue, it is sufficient
12582
       to check just for these, except that _ must be allowed
12583
       as starting an identifier.  */
12584
65.8k
    if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12585
310
        return 0;
12586
310
    }
12587
12588
3.95M
    for (i = 1; i < len; i++) {
12589
3.89M
        ch = PyUnicode_READ(kind, data, i);
12590
3.89M
        if (!_PyUnicode_IsXidContinue(ch)) {
12591
144
            return i;
12592
144
        }
12593
3.89M
    }
12594
65.3k
    return i;
12595
65.5k
}
12596
12597
int
12598
PyUnicode_IsIdentifier(PyObject *self)
12599
1.56k
{
12600
1.56k
    Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12601
1.56k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12602
    /* an empty string is not a valid identifier */
12603
1.56k
    return len && i == len;
12604
1.56k
}
12605
12606
/*[clinic input]
12607
@permit_long_summary
12608
str.isidentifier as unicode_isidentifier
12609
12610
Return True if the string is a valid Python identifier, False otherwise.
12611
12612
Call keyword.iskeyword(s) to test whether string s is a reserved
12613
identifier, such as "def" or "class".
12614
[clinic start generated code]*/
12615
12616
static PyObject *
12617
unicode_isidentifier_impl(PyObject *self)
12618
/*[clinic end generated code: output=fe585a9666572905 input=cabde62c20a3be6b]*/
12619
1.14k
{
12620
1.14k
    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12621
1.14k
}
12622
12623
/*[clinic input]
12624
@permit_long_summary
12625
str.isprintable as unicode_isprintable
12626
12627
Return True if all characters in the string are printable, False otherwise.
12628
12629
A character is printable if repr() may use it in its output.
12630
[clinic start generated code]*/
12631
12632
static PyObject *
12633
unicode_isprintable_impl(PyObject *self)
12634
/*[clinic end generated code: output=3ab9626cd32dd1a0 input=18345ba847084ec5]*/
12635
0
{
12636
0
    Py_ssize_t i, length;
12637
0
    int kind;
12638
0
    const void *data;
12639
12640
0
    length = PyUnicode_GET_LENGTH(self);
12641
0
    kind = PyUnicode_KIND(self);
12642
0
    data = PyUnicode_DATA(self);
12643
12644
    /* Shortcut for single character strings */
12645
0
    if (length == 1)
12646
0
        return PyBool_FromLong(
12647
0
            Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
12648
12649
0
    for (i = 0; i < length; i++) {
12650
0
        if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
12651
0
            Py_RETURN_FALSE;
12652
0
        }
12653
0
    }
12654
0
    Py_RETURN_TRUE;
12655
0
}
12656
12657
/*[clinic input]
12658
str.join as unicode_join
12659
12660
    iterable: object
12661
    /
12662
12663
Concatenate any number of strings.
12664
12665
The string whose method is called is inserted in between each given
12666
string.  The result is returned as a new string.
12667
12668
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12669
[clinic start generated code]*/
12670
12671
static PyObject *
12672
unicode_join(PyObject *self, PyObject *iterable)
12673
/*[clinic end generated code: output=6857e7cecfe7bf98 input=fd330a11ee845fb2]*/
12674
220k
{
12675
220k
    return PyUnicode_Join(self, iterable);
12676
220k
}
12677
12678
static Py_ssize_t
12679
unicode_length(PyObject *self)
12680
6.05M
{
12681
6.05M
    return PyUnicode_GET_LENGTH(self);
12682
6.05M
}
12683
12684
/*[clinic input]
12685
str.ljust as unicode_ljust
12686
12687
    width: Py_ssize_t
12688
    fillchar: Py_UCS4 = ' '
12689
    /
12690
12691
Return a left-justified string of length width.
12692
12693
Padding is done using the specified fill character (default is
12694
a space).
12695
[clinic start generated code]*/
12696
12697
static PyObject *
12698
unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12699
/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=8a55f06694c20ed6]*/
12700
0
{
12701
0
    if (PyUnicode_GET_LENGTH(self) >= width)
12702
0
        return unicode_result_unchanged(self);
12703
12704
0
    return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
12705
0
}
12706
12707
/*[clinic input]
12708
str.lower as unicode_lower
12709
12710
Return a copy of the string converted to lowercase.
12711
[clinic start generated code]*/
12712
12713
static PyObject *
12714
unicode_lower_impl(PyObject *self)
12715
/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
12716
423k
{
12717
423k
    if (PyUnicode_IS_ASCII(self))
12718
70.5k
        return ascii_upper_or_lower(self, 1);
12719
352k
    return case_operation(self, do_lower);
12720
423k
}
12721
12722
38.4k
#define LEFTSTRIP 0
12723
76.7k
#define RIGHTSTRIP 1
12724
12
#define BOTHSTRIP 2
12725
12726
/* Arrays indexed by above */
12727
static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
12728
12729
0
#define STRIPNAME(i) (stripfuncnames[i])
12730
12731
/* externally visible for str.strip(unicode) */
12732
PyObject *
12733
_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
12734
18.0k
{
12735
18.0k
    const void *data;
12736
18.0k
    int kind;
12737
18.0k
    Py_ssize_t i, j, len;
12738
18.0k
    BLOOM_MASK sepmask;
12739
18.0k
    Py_ssize_t seplen;
12740
12741
18.0k
    kind = PyUnicode_KIND(self);
12742
18.0k
    data = PyUnicode_DATA(self);
12743
18.0k
    len = PyUnicode_GET_LENGTH(self);
12744
18.0k
    seplen = PyUnicode_GET_LENGTH(sepobj);
12745
18.0k
    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12746
18.0k
                              PyUnicode_DATA(sepobj),
12747
18.0k
                              seplen);
12748
12749
0
    i = 0;
12750
18.0k
    if (striptype != RIGHTSTRIP) {
12751
41
        while (i < len) {
12752
37
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12753
37
            if (!BLOOM(sepmask, ch))
12754
33
                break;
12755
4
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12756
0
                break;
12757
4
            i++;
12758
4
        }
12759
37
    }
12760
12761
18.0k
    j = len;
12762
18.0k
    if (striptype != LEFTSTRIP) {
12763
18.0k
        j--;
12764
18.0k
        while (j >= i) {
12765
18.0k
            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12766
18.0k
            if (!BLOOM(sepmask, ch))
12767
11.4k
                break;
12768
6.62k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12769
6.58k
                break;
12770
44
            j--;
12771
44
        }
12772
12773
18.0k
        j++;
12774
18.0k
    }
12775
12776
18.0k
    return PyUnicode_Substring(self, i, j);
12777
18.0k
}
12778
12779
PyObject*
12780
_PyUnicode_BinarySlice(PyObject *container, PyObject *start_o, PyObject *stop_o)
12781
452k
{
12782
452k
    assert(PyUnicode_CheckExact(container));
12783
452k
    Py_ssize_t len = PyUnicode_GET_LENGTH(container);
12784
452k
    Py_ssize_t istart, istop;
12785
452k
    if (!_PyEval_UnpackIndices(start_o, stop_o, len, &istart, &istop)) {
12786
0
        return NULL;
12787
0
    }
12788
452k
    return PyUnicode_Substring(container, istart, istop);
12789
452k
}
12790
12791
PyObject*
12792
PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12793
1.21M
{
12794
1.21M
    const unsigned char *data;
12795
1.21M
    int kind;
12796
1.21M
    Py_ssize_t length;
12797
12798
1.21M
    length = PyUnicode_GET_LENGTH(self);
12799
1.21M
    end = Py_MIN(end, length);
12800
12801
1.21M
    if (start == 0 && end == length)
12802
119k
        return unicode_result_unchanged(self);
12803
12804
1.09M
    if (start < 0 || end < 0) {
12805
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12806
0
        return NULL;
12807
0
    }
12808
1.09M
    if (start >= length || end < start)
12809
31.4k
        _Py_RETURN_UNICODE_EMPTY();
12810
12811
1.06M
    length = end - start;
12812
1.06M
    if (PyUnicode_IS_ASCII(self)) {
12813
450k
        data = PyUnicode_1BYTE_DATA(self);
12814
450k
        return _PyUnicode_FromASCII((const char*)(data + start), length);
12815
450k
    }
12816
614k
    else {
12817
614k
        kind = PyUnicode_KIND(self);
12818
614k
        data = PyUnicode_1BYTE_DATA(self);
12819
614k
        return PyUnicode_FromKindAndData(kind,
12820
614k
                                         data + kind * start,
12821
614k
                                         length);
12822
614k
    }
12823
1.06M
}
12824
12825
static PyObject *
12826
do_strip(PyObject *self, int striptype)
12827
20.3k
{
12828
20.3k
    Py_ssize_t len, i, j;
12829
12830
20.3k
    len = PyUnicode_GET_LENGTH(self);
12831
12832
20.3k
    if (PyUnicode_IS_ASCII(self)) {
12833
20.3k
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12834
12835
20.3k
        i = 0;
12836
20.3k
        if (striptype != RIGHTSTRIP) {
12837
12
            while (i < len) {
12838
12
                Py_UCS1 ch = data[i];
12839
12
                if (!_Py_ascii_whitespace[ch])
12840
12
                    break;
12841
0
                i++;
12842
0
            }
12843
12
        }
12844
12845
20.3k
        j = len;
12846
20.3k
        if (striptype != LEFTSTRIP) {
12847
20.3k
            j--;
12848
20.3k
            while (j >= i) {
12849
20.3k
                Py_UCS1 ch = data[j];
12850
20.3k
                if (!_Py_ascii_whitespace[ch])
12851
20.3k
                    break;
12852
0
                j--;
12853
0
            }
12854
20.3k
            j++;
12855
20.3k
        }
12856
20.3k
    }
12857
0
    else {
12858
0
        int kind = PyUnicode_KIND(self);
12859
0
        const void *data = PyUnicode_DATA(self);
12860
12861
0
        i = 0;
12862
0
        if (striptype != RIGHTSTRIP) {
12863
0
            while (i < len) {
12864
0
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12865
0
                if (!Py_UNICODE_ISSPACE(ch))
12866
0
                    break;
12867
0
                i++;
12868
0
            }
12869
0
        }
12870
12871
0
        j = len;
12872
0
        if (striptype != LEFTSTRIP) {
12873
0
            j--;
12874
0
            while (j >= i) {
12875
0
                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12876
0
                if (!Py_UNICODE_ISSPACE(ch))
12877
0
                    break;
12878
0
                j--;
12879
0
            }
12880
0
            j++;
12881
0
        }
12882
0
    }
12883
12884
20.3k
    return PyUnicode_Substring(self, i, j);
12885
20.3k
}
12886
12887
12888
static PyObject *
12889
do_argstrip(PyObject *self, int striptype, PyObject *sep)
12890
38.4k
{
12891
38.4k
    if (sep != Py_None) {
12892
18.0k
        if (PyUnicode_Check(sep))
12893
18.0k
            return _PyUnicode_XStrip(self, striptype, sep);
12894
0
        else {
12895
0
            PyErr_Format(PyExc_TypeError,
12896
0
                         "%s arg must be None or str",
12897
0
                         STRIPNAME(striptype));
12898
0
            return NULL;
12899
0
        }
12900
18.0k
    }
12901
12902
20.3k
    return do_strip(self, striptype);
12903
38.4k
}
12904
12905
12906
/*[clinic input]
12907
@permit_long_summary
12908
str.strip as unicode_strip
12909
12910
    chars: object = None
12911
    /
12912
12913
Return a copy of the string with leading and trailing whitespace removed.
12914
12915
If chars is given and not None, remove characters in chars instead.
12916
[clinic start generated code]*/
12917
12918
static PyObject *
12919
unicode_strip_impl(PyObject *self, PyObject *chars)
12920
/*[clinic end generated code: output=ca19018454345d57 input=8bc6353450345fbd]*/
12921
12
{
12922
12
    return do_argstrip(self, BOTHSTRIP, chars);
12923
12
}
12924
12925
12926
/*[clinic input]
12927
str.lstrip as unicode_lstrip
12928
12929
    chars: object = None
12930
    /
12931
12932
Return a copy of the string with leading whitespace removed.
12933
12934
If chars is given and not None, remove characters in chars instead.
12935
[clinic start generated code]*/
12936
12937
static PyObject *
12938
unicode_lstrip_impl(PyObject *self, PyObject *chars)
12939
/*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
12940
37
{
12941
37
    return do_argstrip(self, LEFTSTRIP, chars);
12942
37
}
12943
12944
12945
/*[clinic input]
12946
str.rstrip as unicode_rstrip
12947
12948
    chars: object = None
12949
    /
12950
12951
Return a copy of the string with trailing whitespace removed.
12952
12953
If chars is given and not None, remove characters in chars instead.
12954
[clinic start generated code]*/
12955
12956
static PyObject *
12957
unicode_rstrip_impl(PyObject *self, PyObject *chars)
12958
/*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
12959
38.3k
{
12960
38.3k
    return do_argstrip(self, RIGHTSTRIP, chars);
12961
38.3k
}
12962
12963
12964
PyObject *
12965
_PyUnicode_Repeat(PyObject *str, Py_ssize_t len)
12966
8.54k
{
12967
8.54k
    PyObject *u;
12968
8.54k
    Py_ssize_t nchars, n;
12969
12970
8.54k
    if (len < 1)
12971
929
        _Py_RETURN_UNICODE_EMPTY();
12972
12973
    /* no repeat, return original string */
12974
7.61k
    if (len == 1)
12975
1.49k
        return unicode_result_unchanged(str);
12976
12977
6.11k
    if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
12978
0
        PyErr_SetString(PyExc_OverflowError,
12979
0
                        "repeated string is too long");
12980
0
        return NULL;
12981
0
    }
12982
6.11k
    nchars = len * PyUnicode_GET_LENGTH(str);
12983
12984
6.11k
    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
12985
6.11k
    if (!u)
12986
0
        return NULL;
12987
6.11k
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
12988
12989
6.11k
    if (PyUnicode_GET_LENGTH(str) == 1) {
12990
2.21k
        int kind = PyUnicode_KIND(str);
12991
2.21k
        Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12992
2.21k
        if (kind == PyUnicode_1BYTE_KIND) {
12993
2.15k
            void *to = PyUnicode_DATA(u);
12994
2.15k
            memset(to, (unsigned char)fill_char, len);
12995
2.15k
        }
12996
65
        else if (kind == PyUnicode_2BYTE_KIND) {
12997
17
            Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
12998
326
            for (n = 0; n < len; ++n)
12999
309
                ucs2[n] = fill_char;
13000
48
        } else {
13001
48
            Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
13002
48
            assert(kind == PyUnicode_4BYTE_KIND);
13003
11.6k
            for (n = 0; n < len; ++n)
13004
11.6k
                ucs4[n] = fill_char;
13005
48
        }
13006
2.21k
    }
13007
3.89k
    else {
13008
3.89k
        Py_ssize_t char_size = PyUnicode_KIND(str);
13009
3.89k
        char *to = (char *) PyUnicode_DATA(u);
13010
3.89k
        _PyBytes_RepeatBuffer(to, nchars * char_size, PyUnicode_DATA(str),
13011
3.89k
            PyUnicode_GET_LENGTH(str) * char_size);
13012
3.89k
    }
13013
13014
6.11k
    assert(_PyUnicode_CheckConsistency(u, 1));
13015
6.11k
    return u;
13016
6.11k
}
13017
13018
PyObject *
13019
PyUnicode_Replace(PyObject *str,
13020
                  PyObject *substr,
13021
                  PyObject *replstr,
13022
                  Py_ssize_t maxcount)
13023
39.6k
{
13024
39.6k
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
13025
39.6k
            ensure_unicode(replstr) < 0)
13026
0
        return NULL;
13027
39.6k
    return replace(str, substr, replstr, maxcount);
13028
39.6k
}
13029
13030
/*[clinic input]
13031
str.replace as unicode_replace
13032
13033
    old: unicode
13034
    new: unicode
13035
    /
13036
    count: Py_ssize_t = -1
13037
        Maximum number of occurrences to replace.
13038
        -1 (the default value) means replace all occurrences.
13039
13040
Return a copy with all occurrences of substring old replaced by new.
13041
13042
If count is given, only the first count occurrences are replaced.
13043
If count is not specified or -1, then all occurrences are replaced.
13044
[clinic start generated code]*/
13045
13046
static PyObject *
13047
unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
13048
                     Py_ssize_t count)
13049
/*[clinic end generated code: output=b63f1a8b5eebf448 input=d15a6886b05e2edc]*/
13050
21.5k
{
13051
21.5k
    return replace(self, old, new, count);
13052
21.5k
}
13053
13054
/*[clinic input]
13055
str.removeprefix as unicode_removeprefix
13056
13057
    prefix: unicode
13058
    /
13059
13060
Return a str with the given prefix string removed if present.
13061
13062
If the string starts with the prefix string, return
13063
string[len(prefix):].  Otherwise, return a copy of the original
13064
string.
13065
[clinic start generated code]*/
13066
13067
static PyObject *
13068
unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
13069
/*[clinic end generated code: output=f1e5945e9763bcb9 input=90d162724944bfa7]*/
13070
0
{
13071
0
    int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
13072
0
    if (match == -1) {
13073
0
        return NULL;
13074
0
    }
13075
0
    if (match) {
13076
0
        return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
13077
0
                                   PyUnicode_GET_LENGTH(self));
13078
0
    }
13079
0
    return unicode_result_unchanged(self);
13080
0
}
13081
13082
/*[clinic input]
13083
str.removesuffix as unicode_removesuffix
13084
13085
    suffix: unicode
13086
    /
13087
13088
Return a str with the given suffix string removed if present.
13089
13090
If the string ends with the suffix string and that suffix is not
13091
empty, return string[:-len(suffix)].  Otherwise, return a copy of
13092
the original string.
13093
[clinic start generated code]*/
13094
13095
static PyObject *
13096
unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
13097
/*[clinic end generated code: output=d36629e227636822 input=6efc96152d4bfcd5]*/
13098
0
{
13099
0
    int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
13100
0
    if (match == -1) {
13101
0
        return NULL;
13102
0
    }
13103
0
    if (match) {
13104
0
        return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
13105
0
                                            - PyUnicode_GET_LENGTH(suffix));
13106
0
    }
13107
0
    return unicode_result_unchanged(self);
13108
0
}
13109
13110
static PyObject *
13111
unicode_repr(PyObject *unicode)
13112
14.0k
{
13113
14.0k
    Py_ssize_t isize = PyUnicode_GET_LENGTH(unicode);
13114
14.0k
    const void *idata = PyUnicode_DATA(unicode);
13115
13116
    /* Compute length of output, quote characters, and
13117
       maximum character */
13118
14.0k
    Py_ssize_t osize = 0;
13119
14.0k
    Py_UCS4 maxch = 127;
13120
14.0k
    Py_ssize_t squote = 0;
13121
14.0k
    Py_ssize_t dquote = 0;
13122
14.0k
    int ikind = PyUnicode_KIND(unicode);
13123
33.5M
    for (Py_ssize_t i = 0; i < isize; i++) {
13124
33.5M
        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
13125
33.5M
        Py_ssize_t incr = 1;
13126
33.5M
        switch (ch) {
13127
22.7k
        case '\'': squote++; break;
13128
155k
        case '"':  dquote++; break;
13129
65.0k
        case '\\': case '\t': case '\r': case '\n':
13130
65.0k
            incr = 2;
13131
65.0k
            break;
13132
33.2M
        default:
13133
            /* Fast-path ASCII */
13134
33.2M
            if (ch < ' ' || ch == 0x7f)
13135
11.4M
                incr = 4; /* \xHH */
13136
21.8M
            else if (ch < 0x7f)
13137
21.1M
                ;
13138
750k
            else if (Py_UNICODE_ISPRINTABLE(ch))
13139
195k
                maxch = (ch > maxch) ? ch : maxch;
13140
554k
            else if (ch < 0x100)
13141
542k
                incr = 4; /* \xHH */
13142
12.3k
            else if (ch < 0x10000)
13143
10.0k
                incr = 6; /* \uHHHH */
13144
2.30k
            else
13145
2.30k
                incr = 10; /* \uHHHHHHHH */
13146
33.5M
        }
13147
33.5M
        if (osize > PY_SSIZE_T_MAX - incr) {
13148
0
            PyErr_SetString(PyExc_OverflowError,
13149
0
                            "string is too long to generate repr");
13150
0
            return NULL;
13151
0
        }
13152
33.5M
        osize += incr;
13153
33.5M
    }
13154
13155
14.0k
    Py_UCS4 quote = '\'';
13156
14.0k
    int changed = (osize != isize);
13157
14.0k
    if (squote) {
13158
1.21k
        changed = 1;
13159
1.21k
        if (dquote)
13160
            /* Both squote and dquote present. Use squote,
13161
               and escape them */
13162
782
            osize += squote;
13163
437
        else
13164
437
            quote = '"';
13165
1.21k
    }
13166
14.0k
    osize += 2;   /* quotes */
13167
13168
14.0k
    PyObject *repr = PyUnicode_New(osize, maxch);
13169
14.0k
    if (repr == NULL)
13170
0
        return NULL;
13171
14.0k
    int okind = PyUnicode_KIND(repr);
13172
14.0k
    void *odata = PyUnicode_DATA(repr);
13173
13174
14.0k
    if (!changed) {
13175
7.81k
        PyUnicode_WRITE(okind, odata, 0, quote);
13176
13177
7.81k
        _PyUnicode_FastCopyCharacters(repr, 1,
13178
7.81k
                                      unicode, 0,
13179
7.81k
                                      isize);
13180
13181
7.81k
        PyUnicode_WRITE(okind, odata, osize-1, quote);
13182
7.81k
    }
13183
6.28k
    else {
13184
6.28k
        switch (okind) {
13185
4.05k
        case PyUnicode_1BYTE_KIND:
13186
4.05k
            ucs1lib_repr(unicode, quote, odata);
13187
4.05k
            break;
13188
1.53k
        case PyUnicode_2BYTE_KIND:
13189
1.53k
            ucs2lib_repr(unicode, quote, odata);
13190
1.53k
            break;
13191
694
        default:
13192
694
            assert(okind == PyUnicode_4BYTE_KIND);
13193
694
            ucs4lib_repr(unicode, quote, odata);
13194
6.28k
        }
13195
6.28k
    }
13196
13197
14.0k
    assert(_PyUnicode_CheckConsistency(repr, 1));
13198
14.0k
    return repr;
13199
14.0k
}
13200
13201
/*[clinic input]
13202
@permit_long_summary
13203
str.rfind as unicode_rfind = str.count
13204
13205
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13206
13207
Optional arguments start and end are interpreted as in slice
13208
notation.  Return -1 on failure.
13209
[clinic start generated code]*/
13210
13211
static Py_ssize_t
13212
unicode_rfind_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13213
                   Py_ssize_t end)
13214
/*[clinic end generated code: output=880b29f01dd014c8 input=2e67789533baf2f5]*/
13215
6.69k
{
13216
6.69k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13217
6.69k
    if (result < 0) {
13218
5.50k
        return -1;
13219
5.50k
    }
13220
1.18k
    return result;
13221
6.69k
}
13222
13223
/*[clinic input]
13224
@permit_long_summary
13225
str.rindex as unicode_rindex = str.count
13226
13227
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13228
13229
Optional arguments start and end are interpreted as in slice
13230
notation.  Raises ValueError when the substring is not found.
13231
[clinic start generated code]*/
13232
13233
static Py_ssize_t
13234
unicode_rindex_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13235
                    Py_ssize_t end)
13236
/*[clinic end generated code: output=5f3aef124c867fe1 input=e29d446c8234c9d9]*/
13237
0
{
13238
0
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13239
0
    if (result == -1) {
13240
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
13241
0
    }
13242
0
    else if (result < 0) {
13243
0
        return -1;
13244
0
    }
13245
0
    return result;
13246
0
}
13247
13248
/*[clinic input]
13249
str.rjust as unicode_rjust
13250
13251
    width: Py_ssize_t
13252
    fillchar: Py_UCS4 = ' '
13253
    /
13254
13255
Return a right-justified string of length width.
13256
13257
Padding is done using the specified fill character (default is
13258
a space).
13259
[clinic start generated code]*/
13260
13261
static PyObject *
13262
unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
13263
/*[clinic end generated code: output=804a1a57fbe8d5cf input=1256a8d659589907]*/
13264
0
{
13265
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13266
0
        return unicode_result_unchanged(self);
13267
13268
0
    return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
13269
0
}
13270
13271
PyObject *
13272
PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13273
0
{
13274
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13275
0
        return NULL;
13276
13277
0
    return split(s, sep, maxsplit);
13278
0
}
13279
13280
/*[clinic input]
13281
@permit_long_summary
13282
str.split as unicode_split
13283
13284
    sep: object = None
13285
        The separator used to split the string.
13286
13287
        When set to None (the default value), will split on any
13288
        whitespace character (including \n \r \t \f and spaces) and
13289
        will discard empty strings from the result.
13290
    maxsplit: Py_ssize_t = -1
13291
        Maximum number of splits.
13292
        -1 (the default value) means no limit.
13293
13294
Return a list of the substrings in the string, using sep as the separator string.
13295
13296
Splitting starts at the front of the string and works to the end.
13297
13298
Note, str.split() is mainly useful for data that has been
13299
intentionally delimited.  With natural text that includes
13300
punctuation, consider using the regular expression module.
13301
13302
[clinic start generated code]*/
13303
13304
static PyObject *
13305
unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13306
/*[clinic end generated code: output=3a65b1db356948dc input=288cfd6bc8828f5a]*/
13307
3.34k
{
13308
3.34k
    if (sep == Py_None)
13309
7
        return split(self, NULL, maxsplit);
13310
3.34k
    if (PyUnicode_Check(sep))
13311
3.34k
        return split(self, sep, maxsplit);
13312
13313
0
    PyErr_Format(PyExc_TypeError,
13314
0
                 "must be str or None, not %.100s",
13315
0
                 Py_TYPE(sep)->tp_name);
13316
0
    return NULL;
13317
3.34k
}
13318
13319
PyObject *
13320
PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
13321
0
{
13322
0
    PyObject* out;
13323
0
    int kind1, kind2;
13324
0
    const void *buf1, *buf2;
13325
0
    Py_ssize_t len1, len2;
13326
13327
0
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13328
0
        return NULL;
13329
13330
0
    kind1 = PyUnicode_KIND(str_obj);
13331
0
    kind2 = PyUnicode_KIND(sep_obj);
13332
0
    len1 = PyUnicode_GET_LENGTH(str_obj);
13333
0
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13334
0
    if (kind1 < kind2 || len1 < len2) {
13335
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13336
0
        return PyTuple_Pack(3, str_obj, empty, empty);
13337
0
    }
13338
0
    buf1 = PyUnicode_DATA(str_obj);
13339
0
    buf2 = PyUnicode_DATA(sep_obj);
13340
0
    if (kind2 != kind1) {
13341
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13342
0
        if (!buf2)
13343
0
            return NULL;
13344
0
    }
13345
13346
0
    switch (kind1) {
13347
0
    case PyUnicode_1BYTE_KIND:
13348
0
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13349
0
            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13350
0
        else
13351
0
            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13352
0
        break;
13353
0
    case PyUnicode_2BYTE_KIND:
13354
0
        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13355
0
        break;
13356
0
    case PyUnicode_4BYTE_KIND:
13357
0
        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13358
0
        break;
13359
0
    default:
13360
0
        Py_UNREACHABLE();
13361
0
    }
13362
13363
0
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13364
0
    if (kind2 != kind1)
13365
0
        PyMem_Free((void *)buf2);
13366
13367
0
    return out;
13368
0
}
13369
13370
13371
PyObject *
13372
PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
13373
6.28k
{
13374
6.28k
    PyObject* out;
13375
6.28k
    int kind1, kind2;
13376
6.28k
    const void *buf1, *buf2;
13377
6.28k
    Py_ssize_t len1, len2;
13378
13379
6.28k
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13380
0
        return NULL;
13381
13382
6.28k
    kind1 = PyUnicode_KIND(str_obj);
13383
6.28k
    kind2 = PyUnicode_KIND(sep_obj);
13384
6.28k
    len1 = PyUnicode_GET_LENGTH(str_obj);
13385
6.28k
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13386
6.28k
    if (kind1 < kind2 || len1 < len2) {
13387
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13388
0
        return PyTuple_Pack(3, empty, empty, str_obj);
13389
0
    }
13390
6.28k
    buf1 = PyUnicode_DATA(str_obj);
13391
6.28k
    buf2 = PyUnicode_DATA(sep_obj);
13392
6.28k
    if (kind2 != kind1) {
13393
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13394
0
        if (!buf2)
13395
0
            return NULL;
13396
0
    }
13397
13398
6.28k
    switch (kind1) {
13399
6.28k
    case PyUnicode_1BYTE_KIND:
13400
6.28k
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13401
6.28k
            out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13402
0
        else
13403
0
            out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13404
6.28k
        break;
13405
0
    case PyUnicode_2BYTE_KIND:
13406
0
        out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13407
0
        break;
13408
0
    case PyUnicode_4BYTE_KIND:
13409
0
        out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13410
0
        break;
13411
0
    default:
13412
0
        Py_UNREACHABLE();
13413
6.28k
    }
13414
13415
6.28k
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13416
6.28k
    if (kind2 != kind1)
13417
0
        PyMem_Free((void *)buf2);
13418
13419
6.28k
    return out;
13420
6.28k
}
13421
13422
/*[clinic input]
13423
str.partition as unicode_partition
13424
13425
    sep: object
13426
    /
13427
13428
Partition the string into three parts using the given separator.
13429
13430
This will search for the separator in the string.  If the separator
13431
is found, returns a 3-tuple containing the part before the
13432
separator, the separator itself, and the part after it.
13433
13434
If the separator is not found, returns a 3-tuple containing
13435
the original string and two empty strings.
13436
[clinic start generated code]*/
13437
13438
static PyObject *
13439
unicode_partition(PyObject *self, PyObject *sep)
13440
/*[clinic end generated code: output=e4ced7bd253ca3c4 input=e45faa8c26270cb1]*/
13441
0
{
13442
0
    return PyUnicode_Partition(self, sep);
13443
0
}
13444
13445
/*[clinic input]
13446
str.rpartition as unicode_rpartition = str.partition
13447
13448
Partition the string into three parts using the given separator.
13449
13450
This will search for the separator in the string, starting at the
13451
end.  If the separator is found, returns a 3-tuple containing the
13452
part before the separator, the separator itself, and the part after
13453
it.
13454
13455
If the separator is not found, returns a 3-tuple containing two
13456
empty strings and the original string.
13457
[clinic start generated code]*/
13458
13459
static PyObject *
13460
unicode_rpartition(PyObject *self, PyObject *sep)
13461
/*[clinic end generated code: output=1aa13cf1156572aa input=53a7f8cb19975b7c]*/
13462
6.28k
{
13463
6.28k
    return PyUnicode_RPartition(self, sep);
13464
6.28k
}
13465
13466
PyObject *
13467
PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13468
0
{
13469
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13470
0
        return NULL;
13471
13472
0
    return rsplit(s, sep, maxsplit);
13473
0
}
13474
13475
/*[clinic input]
13476
@permit_long_summary
13477
str.rsplit as unicode_rsplit = str.split
13478
13479
Return a list of the substrings in the string, using sep as the separator string.
13480
13481
Splitting starts at the end of the string and works to the front.
13482
[clinic start generated code]*/
13483
13484
static PyObject *
13485
unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13486
/*[clinic end generated code: output=c2b815c63bcabffc input=0f762e30d267fa83]*/
13487
0
{
13488
0
    if (sep == Py_None)
13489
0
        return rsplit(self, NULL, maxsplit);
13490
0
    if (PyUnicode_Check(sep))
13491
0
        return rsplit(self, sep, maxsplit);
13492
13493
0
    PyErr_Format(PyExc_TypeError,
13494
0
                 "must be str or None, not %.100s",
13495
0
                 Py_TYPE(sep)->tp_name);
13496
0
    return NULL;
13497
0
}
13498
13499
/*[clinic input]
13500
@permit_long_summary
13501
str.splitlines as unicode_splitlines
13502
13503
    keepends: bool = False
13504
13505
Return a list of the lines in the string, breaking at line boundaries.
13506
13507
Line breaks are not included in the resulting list unless keepends
13508
is given and true.
13509
[clinic start generated code]*/
13510
13511
static PyObject *
13512
unicode_splitlines_impl(PyObject *self, int keepends)
13513
/*[clinic end generated code: output=f664dcdad153ec40 input=b45ea0f87645a06d]*/
13514
0
{
13515
0
    return PyUnicode_Splitlines(self, keepends);
13516
0
}
13517
13518
static
13519
PyObject *unicode_str(PyObject *self)
13520
0
{
13521
0
    return unicode_result_unchanged(self);
13522
0
}
13523
13524
/*[clinic input]
13525
@permit_long_summary
13526
str.swapcase as unicode_swapcase
13527
13528
Convert uppercase characters to lowercase and lowercase characters to uppercase.
13529
[clinic start generated code]*/
13530
13531
static PyObject *
13532
unicode_swapcase_impl(PyObject *self)
13533
/*[clinic end generated code: output=5d28966bf6d7b2af input=85bc39a9b4e8ee91]*/
13534
0
{
13535
0
    return case_operation(self, do_swapcase);
13536
0
}
13537
13538
static int
13539
unicode_maketrans_from_dict(PyObject *x, PyObject *newdict)
13540
0
{
13541
0
    PyObject *key, *value;
13542
0
    Py_ssize_t i = 0;
13543
0
    int res;
13544
0
    while (PyDict_Next(x, &i, &key, &value)) {
13545
0
        if (PyUnicode_Check(key)) {
13546
0
            PyObject *newkey;
13547
0
            int kind;
13548
0
            const void *data;
13549
0
            if (PyUnicode_GET_LENGTH(key) != 1) {
13550
0
                PyErr_SetString(PyExc_ValueError, "string keys in translate"
13551
0
                                "table must be of length 1");
13552
0
                return -1;
13553
0
            }
13554
0
            kind = PyUnicode_KIND(key);
13555
0
            data = PyUnicode_DATA(key);
13556
0
            newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
13557
0
            if (!newkey)
13558
0
                return -1;
13559
0
            res = PyDict_SetItem(newdict, newkey, value);
13560
0
            Py_DECREF(newkey);
13561
0
            if (res < 0)
13562
0
                return -1;
13563
0
        }
13564
0
        else if (PyLong_Check(key)) {
13565
0
            if (PyDict_SetItem(newdict, key, value) < 0)
13566
0
                return -1;
13567
0
        }
13568
0
        else {
13569
0
            PyErr_SetString(PyExc_TypeError, "keys in translate table must"
13570
0
                            "be strings or integers");
13571
0
            return -1;
13572
0
        }
13573
0
    }
13574
0
    return 0;
13575
0
}
13576
13577
/*[clinic input]
13578
13579
@staticmethod
13580
str.maketrans as unicode_maketrans
13581
13582
  x: object
13583
13584
  y: unicode=NULL
13585
13586
  z: unicode=NULL
13587
13588
  /
13589
13590
Return a translation table usable for str.translate().
13591
13592
If there is only one argument, it must be a dictionary mapping
13593
Unicode ordinals (integers) or characters to Unicode ordinals,
13594
strings or None.  Character keys will be then converted to ordinals.
13595
If there are two arguments, they must be strings of equal length,
13596
and in the resulting dictionary, each character in x will be mapped
13597
to the character at the same position in y.  If there is a third
13598
argument, it must be a string, whose characters will be mapped to
13599
None in the result.
13600
[clinic start generated code]*/
13601
13602
static PyObject *
13603
unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
13604
/*[clinic end generated code: output=a925c89452bd5881 input=66bc00a1b4258a6e]*/
13605
0
{
13606
0
    PyObject *new = NULL, *key, *value;
13607
0
    Py_ssize_t i = 0;
13608
0
    int res;
13609
13610
0
    new = PyDict_New();
13611
0
    if (!new)
13612
0
        return NULL;
13613
0
    if (y != NULL) {
13614
0
        int x_kind, y_kind, z_kind;
13615
0
        const void *x_data, *y_data, *z_data;
13616
13617
        /* x must be a string too, of equal length */
13618
0
        if (!PyUnicode_Check(x)) {
13619
0
            PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13620
0
                            "be a string if there is a second argument");
13621
0
            goto err;
13622
0
        }
13623
0
        if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
13624
0
            PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13625
0
                            "arguments must have equal length");
13626
0
            goto err;
13627
0
        }
13628
        /* create entries for translating chars in x to those in y */
13629
0
        x_kind = PyUnicode_KIND(x);
13630
0
        y_kind = PyUnicode_KIND(y);
13631
0
        x_data = PyUnicode_DATA(x);
13632
0
        y_data = PyUnicode_DATA(y);
13633
0
        for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13634
0
            key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
13635
0
            if (!key)
13636
0
                goto err;
13637
0
            value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
13638
0
            if (!value) {
13639
0
                Py_DECREF(key);
13640
0
                goto err;
13641
0
            }
13642
0
            res = PyDict_SetItem(new, key, value);
13643
0
            Py_DECREF(key);
13644
0
            Py_DECREF(value);
13645
0
            if (res < 0)
13646
0
                goto err;
13647
0
        }
13648
        /* create entries for deleting chars in z */
13649
0
        if (z != NULL) {
13650
0
            z_kind = PyUnicode_KIND(z);
13651
0
            z_data = PyUnicode_DATA(z);
13652
0
            for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
13653
0
                key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
13654
0
                if (!key)
13655
0
                    goto err;
13656
0
                res = PyDict_SetItem(new, key, Py_None);
13657
0
                Py_DECREF(key);
13658
0
                if (res < 0)
13659
0
                    goto err;
13660
0
            }
13661
0
        }
13662
0
    } else {
13663
        /* x must be a dict */
13664
0
        if (!PyAnyDict_CheckExact(x)) {
13665
0
            PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13666
0
                            "to maketrans it must be a dict");
13667
0
            goto err;
13668
0
        }
13669
        /* copy entries into the new dict, converting string keys to int keys */
13670
0
        int errcode;
13671
0
        Py_BEGIN_CRITICAL_SECTION(x);
13672
0
        errcode = unicode_maketrans_from_dict(x, new);
13673
0
        Py_END_CRITICAL_SECTION();
13674
0
        if (errcode < 0)
13675
0
            goto err;
13676
0
    }
13677
0
    return new;
13678
0
  err:
13679
0
    Py_DECREF(new);
13680
0
    return NULL;
13681
0
}
13682
13683
/*[clinic input]
13684
@permit_long_summary
13685
str.translate as unicode_translate
13686
13687
    table: object
13688
        Translation table, which must be a mapping of Unicode ordinals
13689
        to Unicode ordinals, strings, or None.
13690
    /
13691
13692
Replace each character in the string using the given translation table.
13693
13694
The table must implement lookup/indexing via __getitem__, for
13695
instance a dictionary or list.  If this operation raises
13696
LookupError, the character is left untouched.  Characters mapped to
13697
None are deleted.
13698
[clinic start generated code]*/
13699
13700
static PyObject *
13701
unicode_translate(PyObject *self, PyObject *table)
13702
/*[clinic end generated code: output=3cb448ff2fd96bf3 input=48cf0efe06bc1b75]*/
13703
144
{
13704
144
    return _PyUnicode_TranslateCharmap(self, table, "ignore");
13705
144
}
13706
13707
/*[clinic input]
13708
str.upper as unicode_upper
13709
13710
Return a copy of the string converted to uppercase.
13711
[clinic start generated code]*/
13712
13713
static PyObject *
13714
unicode_upper_impl(PyObject *self)
13715
/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
13716
153
{
13717
153
    if (PyUnicode_IS_ASCII(self))
13718
153
        return ascii_upper_or_lower(self, 0);
13719
0
    return case_operation(self, do_upper);
13720
153
}
13721
13722
/*[clinic input]
13723
@permit_long_summary
13724
str.zfill as unicode_zfill
13725
13726
    width: Py_ssize_t
13727
    /
13728
13729
Pad a numeric string with zeros on the left, to fill a field of the given width.
13730
13731
The string is never truncated.
13732
[clinic start generated code]*/
13733
13734
static PyObject *
13735
unicode_zfill_impl(PyObject *self, Py_ssize_t width)
13736
/*[clinic end generated code: output=e13fb6bdf8e3b9df input=25a4ee0ea3e58ce0]*/
13737
0
{
13738
0
    Py_ssize_t fill;
13739
0
    PyObject *u;
13740
0
    int kind;
13741
0
    const void *data;
13742
0
    Py_UCS4 chr;
13743
13744
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13745
0
        return unicode_result_unchanged(self);
13746
13747
0
    fill = width - PyUnicode_GET_LENGTH(self);
13748
13749
0
    u = pad(self, fill, 0, '0');
13750
13751
0
    if (u == NULL)
13752
0
        return NULL;
13753
13754
0
    kind = PyUnicode_KIND(u);
13755
0
    data = PyUnicode_DATA(u);
13756
0
    chr = PyUnicode_READ(kind, data, fill);
13757
13758
0
    if (chr == '+' || chr == '-') {
13759
        /* move sign to beginning of string */
13760
0
        PyUnicode_WRITE(kind, data, 0, chr);
13761
0
        PyUnicode_WRITE(kind, data, fill, '0');
13762
0
    }
13763
13764
0
    assert(_PyUnicode_CheckConsistency(u, 1));
13765
0
    return u;
13766
0
}
13767
13768
/*[clinic input]
13769
@permit_long_summary
13770
@text_signature "($self, prefix[, start[, end]], /)"
13771
str.startswith as unicode_startswith
13772
13773
    prefix as subobj: object
13774
        A string or a tuple of strings to try.
13775
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13776
        Optional start position. Default: start of the string.
13777
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13778
        Optional stop position. Default: end of the string.
13779
    /
13780
13781
Return True if the string starts with the specified prefix, False otherwise.
13782
[clinic start generated code]*/
13783
13784
static PyObject *
13785
unicode_startswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13786
                        Py_ssize_t end)
13787
/*[clinic end generated code: output=4bd7cfd0803051d4 input=766bdbd33df251dc]*/
13788
279k
{
13789
279k
    if (PyTuple_Check(subobj)) {
13790
120
        Py_ssize_t i;
13791
960
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13792
840
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13793
840
            if (!PyUnicode_Check(substring)) {
13794
0
                PyErr_Format(PyExc_TypeError,
13795
0
                             "tuple for startswith must only contain str, "
13796
0
                             "not %.100s",
13797
0
                             Py_TYPE(substring)->tp_name);
13798
0
                return NULL;
13799
0
            }
13800
840
            int result = tailmatch(self, substring, start, end, -1);
13801
840
            if (result < 0) {
13802
0
                return NULL;
13803
0
            }
13804
840
            if (result) {
13805
0
                Py_RETURN_TRUE;
13806
0
            }
13807
840
        }
13808
        /* nothing matched */
13809
120
        Py_RETURN_FALSE;
13810
120
    }
13811
279k
    if (!PyUnicode_Check(subobj)) {
13812
0
        PyErr_Format(PyExc_TypeError,
13813
0
                     "startswith first arg must be str or "
13814
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13815
0
        return NULL;
13816
0
    }
13817
279k
    int result = tailmatch(self, subobj, start, end, -1);
13818
279k
    if (result < 0) {
13819
0
        return NULL;
13820
0
    }
13821
279k
    return PyBool_FromLong(result);
13822
279k
}
13823
13824
13825
/*[clinic input]
13826
@permit_long_summary
13827
@text_signature "($self, suffix[, start[, end]], /)"
13828
str.endswith as unicode_endswith
13829
13830
    suffix as subobj: object
13831
        A string or a tuple of strings to try.
13832
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13833
        Optional start position. Default: start of the string.
13834
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13835
        Optional stop position. Default: end of the string.
13836
    /
13837
13838
Return True if the string ends with the specified suffix, False otherwise.
13839
[clinic start generated code]*/
13840
13841
static PyObject *
13842
unicode_endswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13843
                      Py_ssize_t end)
13844
/*[clinic end generated code: output=cce6f8ceb0102ca9 input=b66bf6d5547ba1aa]*/
13845
131k
{
13846
131k
    if (PyTuple_Check(subobj)) {
13847
0
        Py_ssize_t i;
13848
0
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13849
0
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13850
0
            if (!PyUnicode_Check(substring)) {
13851
0
                PyErr_Format(PyExc_TypeError,
13852
0
                             "tuple for endswith must only contain str, "
13853
0
                             "not %.100s",
13854
0
                             Py_TYPE(substring)->tp_name);
13855
0
                return NULL;
13856
0
            }
13857
0
            int result = tailmatch(self, substring, start, end, +1);
13858
0
            if (result < 0) {
13859
0
                return NULL;
13860
0
            }
13861
0
            if (result) {
13862
0
                Py_RETURN_TRUE;
13863
0
            }
13864
0
        }
13865
0
        Py_RETURN_FALSE;
13866
0
    }
13867
131k
    if (!PyUnicode_Check(subobj)) {
13868
0
        PyErr_Format(PyExc_TypeError,
13869
0
                     "endswith first arg must be str or "
13870
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13871
0
        return NULL;
13872
0
    }
13873
131k
    int result = tailmatch(self, subobj, start, end, +1);
13874
131k
    if (result < 0) {
13875
0
        return NULL;
13876
0
    }
13877
131k
    return PyBool_FromLong(result);
13878
131k
}
13879
13880
13881
#include "stringlib/unicode_format.h"
13882
13883
PyDoc_STRVAR(format__doc__,
13884
             "format($self, /, *args, **kwargs)\n\
13885
--\n\
13886
\n\
13887
Return a formatted version of the string, using substitutions from args and kwargs.\n\
13888
The substitutions are identified by braces ('{' and '}').");
13889
13890
PyDoc_STRVAR(format_map__doc__,
13891
             "format_map($self, mapping, /)\n\
13892
--\n\
13893
\n\
13894
Return a formatted version of the string, using substitutions from mapping.\n\
13895
The substitutions are identified by braces ('{' and '}').");
13896
13897
/*[clinic input]
13898
@permit_long_summary
13899
str.__format__ as unicode___format__
13900
13901
    format_spec: unicode
13902
    /
13903
13904
Return a formatted version of the string as described by format_spec.
13905
[clinic start generated code]*/
13906
13907
static PyObject *
13908
unicode___format___impl(PyObject *self, PyObject *format_spec)
13909
/*[clinic end generated code: output=45fceaca6d2ba4c8 input=77a2a19f3f7969f2]*/
13910
0
{
13911
0
    _PyUnicodeWriter writer;
13912
0
    int ret;
13913
13914
0
    _PyUnicodeWriter_Init(&writer);
13915
0
    ret = _PyUnicode_FormatAdvancedWriter(&writer,
13916
0
                                          self, format_spec, 0,
13917
0
                                          PyUnicode_GET_LENGTH(format_spec));
13918
0
    if (ret == -1) {
13919
0
        _PyUnicodeWriter_Dealloc(&writer);
13920
0
        return NULL;
13921
0
    }
13922
0
    return _PyUnicodeWriter_Finish(&writer);
13923
0
}
13924
13925
/*[clinic input]
13926
str.__sizeof__ as unicode_sizeof
13927
13928
Return the size of the string in memory, in bytes.
13929
[clinic start generated code]*/
13930
13931
static PyObject *
13932
unicode_sizeof_impl(PyObject *self)
13933
/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
13934
0
{
13935
0
    Py_ssize_t size;
13936
13937
    /* If it's a compact object, account for base structure +
13938
       character data. */
13939
0
    if (PyUnicode_IS_COMPACT_ASCII(self)) {
13940
0
        size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13941
0
    }
13942
0
    else if (PyUnicode_IS_COMPACT(self)) {
13943
0
        size = sizeof(PyCompactUnicodeObject) +
13944
0
            (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
13945
0
    }
13946
0
    else {
13947
        /* If it is a two-block object, account for base object, and
13948
           for character block if present. */
13949
0
        size = sizeof(PyUnicodeObject);
13950
0
        if (_PyUnicode_DATA_ANY(self))
13951
0
            size += (PyUnicode_GET_LENGTH(self) + 1) *
13952
0
                PyUnicode_KIND(self);
13953
0
    }
13954
0
    if (_PyUnicode_HAS_UTF8_MEMORY(self))
13955
0
        size += PyUnicode_UTF8_LENGTH(self) + 1;
13956
13957
0
    return PyLong_FromSsize_t(size);
13958
0
}
13959
13960
static PyObject *
13961
unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
13962
0
{
13963
0
    PyObject *copy = _PyUnicode_Copy(v);
13964
0
    if (!copy)
13965
0
        return NULL;
13966
0
    return Py_BuildValue("(N)", copy);
13967
0
}
13968
13969
/*
13970
This function searchs the longest common leading whitespace
13971
of all lines in the [src, end).
13972
It returns the length of the common leading whitespace and sets `output` to
13973
point to the beginning of the common leading whitespace if length > 0.
13974
*/
13975
static Py_ssize_t
13976
search_longest_common_leading_whitespace(
13977
    const char *const src,
13978
    const char *const end,
13979
    const char **output)
13980
0
{
13981
    // [_start, _start + _len)
13982
    // describes the current longest common leading whitespace
13983
0
    const char *_start = NULL;
13984
0
    Py_ssize_t _len = 0;
13985
13986
0
    for (const char *iter = src; iter < end; ++iter) {
13987
0
        const char *line_start = iter;
13988
0
        const char *leading_whitespace_end = NULL;
13989
13990
        // scan the whole line
13991
0
        while (iter < end && *iter != '\n') {
13992
0
            if (!leading_whitespace_end && *iter != ' ' && *iter != '\t') {
13993
                /* `iter` points to the first non-whitespace character
13994
                   in this line */
13995
0
                if (iter == line_start) {
13996
                    // some line has no indent, fast exit!
13997
0
                    return 0;
13998
0
                }
13999
0
                leading_whitespace_end = iter;
14000
0
            }
14001
0
            ++iter;
14002
0
        }
14003
14004
        // if this line has all white space, skip it
14005
0
        if (!leading_whitespace_end) {
14006
0
            continue;
14007
0
        }
14008
14009
0
        if (!_start) {
14010
            // update the first leading whitespace
14011
0
            _start = line_start;
14012
0
            _len = leading_whitespace_end - line_start;
14013
0
            assert(_len > 0);
14014
0
        }
14015
0
        else {
14016
            /* We then compare with the current longest leading whitespace.
14017
14018
               [line_start, leading_whitespace_end) is the leading
14019
               whitespace of this line,
14020
14021
               [_start, _start + _len) is the leading whitespace of the
14022
               current longest leading whitespace. */
14023
0
            Py_ssize_t new_len = 0;
14024
0
            const char *_iter = _start, *line_iter = line_start;
14025
14026
0
            while (_iter < _start + _len && line_iter < leading_whitespace_end
14027
0
                   && *_iter == *line_iter)
14028
0
            {
14029
0
                ++_iter;
14030
0
                ++line_iter;
14031
0
                ++new_len;
14032
0
            }
14033
14034
0
            _len = new_len;
14035
0
            if (_len == 0) {
14036
                // No common things now, fast exit!
14037
0
                return 0;
14038
0
            }
14039
0
        }
14040
0
    }
14041
14042
0
    assert(_len >= 0);
14043
0
    if (_len > 0) {
14044
0
        *output = _start;
14045
0
    }
14046
0
    return _len;
14047
0
}
14048
14049
/* Dedent a string.
14050
   Intended to dedent Python source. Unlike `textwrap.dedent`, this
14051
   only supports spaces and tabs and doesn't normalize empty lines.
14052
   Return a new reference on success, NULL with exception set on error.
14053
   */
14054
PyObject *
14055
_PyUnicode_Dedent(PyObject *unicode)
14056
0
{
14057
0
    Py_ssize_t src_len = 0;
14058
0
    const char *src = PyUnicode_AsUTF8AndSize(unicode, &src_len);
14059
0
    if (!src) {
14060
0
        return NULL;
14061
0
    }
14062
0
    assert(src_len >= 0);
14063
0
    if (src_len == 0) {
14064
0
        return Py_NewRef(unicode);
14065
0
    }
14066
14067
0
    const char *const end = src + src_len;
14068
14069
    // [whitespace_start, whitespace_start + whitespace_len)
14070
    // describes the current longest common leading whitespace
14071
0
    const char *whitespace_start = NULL;
14072
0
    Py_ssize_t whitespace_len = search_longest_common_leading_whitespace(
14073
0
        src, end, &whitespace_start);
14074
14075
0
    if (whitespace_len == 0) {
14076
0
        return Py_NewRef(unicode);
14077
0
    }
14078
14079
    // now we should trigger a dedent
14080
0
    char *dest = PyMem_Malloc(src_len);
14081
0
    if (!dest) {
14082
0
        PyErr_NoMemory();
14083
0
        return NULL;
14084
0
    }
14085
0
    char *dest_iter = dest;
14086
14087
0
    for (const char *iter = src; iter < end; ++iter) {
14088
0
        const char *line_start = iter;
14089
0
        bool in_leading_space = true;
14090
14091
        // iterate over a line to find the end of a line
14092
0
        while (iter < end && *iter != '\n') {
14093
0
            if (in_leading_space && *iter != ' ' && *iter != '\t') {
14094
0
                in_leading_space = false;
14095
0
            }
14096
0
            ++iter;
14097
0
        }
14098
14099
        // invariant: *iter == '\n' or iter == end
14100
0
        bool append_newline = iter < end;
14101
14102
        // if this line has all white space, write '\n' and continue
14103
0
        if (in_leading_space && append_newline) {
14104
0
            *dest_iter++ = '\n';
14105
0
            continue;
14106
0
        }
14107
14108
        /* copy [new_line_start + whitespace_len, iter) to buffer, then
14109
            conditionally append '\n' */
14110
14111
0
        Py_ssize_t new_line_len = iter - line_start - whitespace_len;
14112
0
        assert(new_line_len >= 0);
14113
0
        memcpy(dest_iter, line_start + whitespace_len, new_line_len);
14114
14115
0
        dest_iter += new_line_len;
14116
14117
0
        if (append_newline) {
14118
0
            *dest_iter++ = '\n';
14119
0
        }
14120
0
    }
14121
14122
0
    PyObject *res = PyUnicode_FromStringAndSize(dest, dest_iter - dest);
14123
0
    PyMem_Free(dest);
14124
0
    return res;
14125
0
}
14126
14127
static PyMethodDef unicode_methods[] = {
14128
    UNICODE_ENCODE_METHODDEF
14129
    UNICODE_REPLACE_METHODDEF
14130
    UNICODE_SPLIT_METHODDEF
14131
    UNICODE_RSPLIT_METHODDEF
14132
    UNICODE_JOIN_METHODDEF
14133
    UNICODE_CAPITALIZE_METHODDEF
14134
    UNICODE_CASEFOLD_METHODDEF
14135
    UNICODE_TITLE_METHODDEF
14136
    UNICODE_CENTER_METHODDEF
14137
    UNICODE_COUNT_METHODDEF
14138
    UNICODE_EXPANDTABS_METHODDEF
14139
    UNICODE_FIND_METHODDEF
14140
    UNICODE_PARTITION_METHODDEF
14141
    UNICODE_INDEX_METHODDEF
14142
    UNICODE_LJUST_METHODDEF
14143
    UNICODE_LOWER_METHODDEF
14144
    UNICODE_LSTRIP_METHODDEF
14145
    UNICODE_RFIND_METHODDEF
14146
    UNICODE_RINDEX_METHODDEF
14147
    UNICODE_RJUST_METHODDEF
14148
    UNICODE_RSTRIP_METHODDEF
14149
    UNICODE_RPARTITION_METHODDEF
14150
    UNICODE_SPLITLINES_METHODDEF
14151
    UNICODE_STRIP_METHODDEF
14152
    UNICODE_SWAPCASE_METHODDEF
14153
    UNICODE_TRANSLATE_METHODDEF
14154
    UNICODE_UPPER_METHODDEF
14155
    UNICODE_STARTSWITH_METHODDEF
14156
    UNICODE_ENDSWITH_METHODDEF
14157
    UNICODE_REMOVEPREFIX_METHODDEF
14158
    UNICODE_REMOVESUFFIX_METHODDEF
14159
    UNICODE_ISASCII_METHODDEF
14160
    UNICODE_ISLOWER_METHODDEF
14161
    UNICODE_ISUPPER_METHODDEF
14162
    UNICODE_ISTITLE_METHODDEF
14163
    UNICODE_ISSPACE_METHODDEF
14164
    UNICODE_ISDECIMAL_METHODDEF
14165
    UNICODE_ISDIGIT_METHODDEF
14166
    UNICODE_ISNUMERIC_METHODDEF
14167
    UNICODE_ISALPHA_METHODDEF
14168
    UNICODE_ISALNUM_METHODDEF
14169
    UNICODE_ISIDENTIFIER_METHODDEF
14170
    UNICODE_ISPRINTABLE_METHODDEF
14171
    UNICODE_ZFILL_METHODDEF
14172
    {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
14173
    {"format_map", do_string_format_map, METH_O, format_map__doc__},
14174
    UNICODE___FORMAT___METHODDEF
14175
    UNICODE_MAKETRANS_METHODDEF
14176
    UNICODE_SIZEOF_METHODDEF
14177
    {"__getnewargs__",  unicode_getnewargs, METH_NOARGS},
14178
    {NULL, NULL}
14179
};
14180
14181
static PyObject *
14182
unicode_mod(PyObject *v, PyObject *w)
14183
1.61M
{
14184
1.61M
    if (!PyUnicode_Check(v))
14185
159
        Py_RETURN_NOTIMPLEMENTED;
14186
1.61M
    return PyUnicode_Format(v, w);
14187
1.61M
}
14188
14189
static PyNumberMethods unicode_as_number = {
14190
    0,              /*nb_add*/
14191
    0,              /*nb_subtract*/
14192
    0,              /*nb_multiply*/
14193
    unicode_mod,            /*nb_remainder*/
14194
};
14195
14196
static PySequenceMethods unicode_as_sequence = {
14197
    unicode_length,     /* sq_length */
14198
    PyUnicode_Concat,   /* sq_concat */
14199
    _PyUnicode_Repeat,  /* sq_repeat */
14200
    unicode_getitem,    /* sq_item */
14201
    0,                  /* sq_slice */
14202
    0,                  /* sq_ass_item */
14203
    0,                  /* sq_ass_slice */
14204
    PyUnicode_Contains, /* sq_contains */
14205
};
14206
14207
static PyObject*
14208
unicode_subscript(PyObject* self, PyObject* item)
14209
6.46M
{
14210
6.46M
    if (_PyIndex_Check(item)) {
14211
6.32M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
14212
6.32M
        if (i == -1 && PyErr_Occurred())
14213
739
            return NULL;
14214
6.32M
        if (i < 0)
14215
2.07k
            i += PyUnicode_GET_LENGTH(self);
14216
6.32M
        return unicode_getitem(self, i);
14217
6.32M
    } else if (PySlice_Check(item)) {
14218
138k
        Py_ssize_t start, stop, step, slicelength, i;
14219
138k
        size_t cur;
14220
138k
        PyObject *result;
14221
138k
        const void *src_data;
14222
138k
        void *dest_data;
14223
138k
        int src_kind, dest_kind;
14224
138k
        Py_UCS4 ch, max_char, kind_limit;
14225
14226
138k
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
14227
996
            return NULL;
14228
996
        }
14229
137k
        slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14230
137k
                                            &start, &stop, step);
14231
14232
137k
        if (slicelength <= 0) {
14233
1.61k
            _Py_RETURN_UNICODE_EMPTY();
14234
136k
        } else if (start == 0 && step == 1 &&
14235
821
                   slicelength == PyUnicode_GET_LENGTH(self)) {
14236
193
            return unicode_result_unchanged(self);
14237
135k
        } else if (step == 1) {
14238
134k
            return PyUnicode_Substring(self,
14239
134k
                                       start, start + slicelength);
14240
134k
        }
14241
        /* General case */
14242
1.38k
        src_kind = PyUnicode_KIND(self);
14243
1.38k
        src_data = PyUnicode_DATA(self);
14244
1.38k
        if (!PyUnicode_IS_ASCII(self)) {
14245
751
            kind_limit = kind_maxchar_limit(src_kind);
14246
751
            max_char = 0;
14247
15.2k
            for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14248
14.6k
                ch = PyUnicode_READ(src_kind, src_data, cur);
14249
14.6k
                if (ch > max_char) {
14250
3.04k
                    max_char = ch;
14251
3.04k
                    if (max_char >= kind_limit)
14252
143
                        break;
14253
3.04k
                }
14254
14.6k
            }
14255
751
        }
14256
633
        else
14257
633
            max_char = 127;
14258
1.38k
        result = PyUnicode_New(slicelength, max_char);
14259
1.38k
        if (result == NULL)
14260
0
            return NULL;
14261
1.38k
        dest_kind = PyUnicode_KIND(result);
14262
1.38k
        dest_data = PyUnicode_DATA(result);
14263
14264
23.4k
        for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14265
22.0k
            Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14266
22.0k
            PyUnicode_WRITE(dest_kind, dest_data, i, ch);
14267
22.0k
        }
14268
1.38k
        assert(_PyUnicode_CheckConsistency(result, 1));
14269
1.38k
        return result;
14270
1.38k
    } else {
14271
290
        PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
14272
290
                     Py_TYPE(item)->tp_name);
14273
290
        return NULL;
14274
290
    }
14275
6.46M
}
14276
14277
static PyMappingMethods unicode_as_mapping = {
14278
    unicode_length,     /* mp_length */
14279
    unicode_subscript,  /* mp_subscript */
14280
    0,                  /* mp_ass_subscript */
14281
};
14282
14283
14284
static PyObject *
14285
unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
14286
14287
/*[clinic input]
14288
@classmethod
14289
str.__new__ as unicode_new
14290
14291
    object as x: object = NULL
14292
    encoding: str = NULL
14293
    errors: str = NULL
14294
14295
[clinic start generated code]*/
14296
14297
static PyObject *
14298
unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
14299
                 const char *errors)
14300
/*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
14301
49
{
14302
49
    PyObject *unicode;
14303
49
    if (x == NULL) {
14304
0
        unicode = _PyUnicode_GetEmpty();
14305
0
    }
14306
49
    else if (encoding == NULL && errors == NULL) {
14307
49
        unicode = PyObject_Str(x);
14308
49
    }
14309
0
    else {
14310
0
        unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
14311
0
    }
14312
14313
49
    if (unicode != NULL && type != &PyUnicode_Type) {
14314
49
        Py_SETREF(unicode, unicode_subtype_new(type, unicode));
14315
49
    }
14316
49
    return unicode;
14317
49
}
14318
14319
static const char *
14320
arg_as_utf8(PyObject *obj, const char *name)
14321
176k
{
14322
176k
    if (!PyUnicode_Check(obj)) {
14323
0
        PyErr_Format(PyExc_TypeError,
14324
0
                     "str() argument '%s' must be str, not %T",
14325
0
                     name, obj);
14326
0
        return NULL;
14327
0
    }
14328
176k
    return _PyUnicode_AsUTF8NoNUL(obj);
14329
176k
}
14330
14331
static PyObject *
14332
unicode_vectorcall(PyObject *type, PyObject *const *args,
14333
                   size_t nargsf, PyObject *kwnames)
14334
174k
{
14335
174k
    assert(Py_Is(_PyType_CAST(type), &PyUnicode_Type));
14336
14337
174k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
14338
174k
    if (kwnames != NULL && PyTuple_GET_SIZE(kwnames) != 0) {
14339
        // Fallback to unicode_new()
14340
0
        PyObject *tuple = PyTuple_FromArray(args, nargs);
14341
0
        if (tuple == NULL) {
14342
0
            return NULL;
14343
0
        }
14344
0
        PyObject *dict = _PyStack_AsDict(args + nargs, kwnames);
14345
0
        if (dict == NULL) {
14346
0
            Py_DECREF(tuple);
14347
0
            return NULL;
14348
0
        }
14349
0
        PyObject *ret = unicode_new(_PyType_CAST(type), tuple, dict);
14350
0
        Py_DECREF(tuple);
14351
0
        Py_DECREF(dict);
14352
0
        return ret;
14353
0
    }
14354
174k
    if (!_PyArg_CheckPositional("str", nargs, 0, 3)) {
14355
0
        return NULL;
14356
0
    }
14357
174k
    if (nargs == 0) {
14358
0
        return _PyUnicode_GetEmpty();
14359
0
    }
14360
174k
    PyObject *object = args[0];
14361
174k
    if (nargs == 1) {
14362
142
        return PyObject_Str(object);
14363
142
    }
14364
174k
    const char *encoding = arg_as_utf8(args[1], "encoding");
14365
174k
    if (encoding == NULL) {
14366
0
        return NULL;
14367
0
    }
14368
174k
    const char *errors = NULL;
14369
174k
    if (nargs == 3) {
14370
2.64k
        errors = arg_as_utf8(args[2], "errors");
14371
2.64k
        if (errors == NULL) {
14372
0
            return NULL;
14373
0
        }
14374
2.64k
    }
14375
174k
    return PyUnicode_FromEncodedObject(object, encoding, errors);
14376
174k
}
14377
14378
static PyObject *
14379
unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
14380
49
{
14381
49
    PyObject *self;
14382
49
    Py_ssize_t length, char_size;
14383
49
    int share_utf8;
14384
49
    int kind;
14385
49
    void *data;
14386
14387
49
    assert(PyType_IsSubtype(type, &PyUnicode_Type));
14388
49
    assert(_PyUnicode_CHECK(unicode));
14389
14390
49
    self = type->tp_alloc(type, 0);
14391
49
    if (self == NULL) {
14392
0
        return NULL;
14393
0
    }
14394
49
    kind = PyUnicode_KIND(unicode);
14395
49
    length = PyUnicode_GET_LENGTH(unicode);
14396
14397
49
    _PyUnicode_LENGTH(self) = length;
14398
#ifdef Py_DEBUG
14399
    _PyUnicode_HASH(self) = -1;
14400
#else
14401
49
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14402
0
#endif
14403
49
    _PyUnicode_STATE(self).interned = 0;
14404
49
    _PyUnicode_STATE(self).kind = kind;
14405
49
    _PyUnicode_STATE(self).compact = 0;
14406
49
    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
14407
49
    _PyUnicode_STATE(self).statically_allocated = 0;
14408
0
    PyUnicode_SET_UTF8_LENGTH(self, 0);
14409
49
    PyUnicode_SET_UTF8(self, NULL);
14410
49
    _PyUnicode_DATA_ANY(self) = NULL;
14411
14412
0
    share_utf8 = 0;
14413
49
    if (kind == PyUnicode_1BYTE_KIND) {
14414
49
        char_size = 1;
14415
49
        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14416
49
            share_utf8 = 1;
14417
49
    }
14418
0
    else if (kind == PyUnicode_2BYTE_KIND) {
14419
0
        char_size = 2;
14420
0
    }
14421
0
    else {
14422
0
        assert(kind == PyUnicode_4BYTE_KIND);
14423
0
        char_size = 4;
14424
0
    }
14425
14426
    /* Ensure we won't overflow the length. */
14427
49
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14428
0
        PyErr_NoMemory();
14429
0
        goto onError;
14430
0
    }
14431
49
    data = PyMem_Malloc((length + 1) * char_size);
14432
49
    if (data == NULL) {
14433
0
        PyErr_NoMemory();
14434
0
        goto onError;
14435
0
    }
14436
14437
98
    _PyUnicode_DATA_ANY(self) = data;
14438
49
    if (share_utf8) {
14439
49
        PyUnicode_SET_UTF8_LENGTH(self, length);
14440
49
        PyUnicode_SET_UTF8(self, data);
14441
49
    }
14442
14443
98
    memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
14444
98
    assert(_PyUnicode_CheckConsistency(self, 1));
14445
#ifdef Py_DEBUG
14446
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14447
#endif
14448
49
    return self;
14449
14450
0
onError:
14451
0
    Py_DECREF(self);
14452
0
    return NULL;
14453
98
}
14454
14455
static _PyObjectIndexPair
14456
unicode_iteritem(PyObject *obj, Py_ssize_t index)
14457
3.87M
{
14458
3.87M
    if (index >= PyUnicode_GET_LENGTH(obj)) {
14459
368k
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
14460
368k
    }
14461
3.50M
    const void *data = PyUnicode_DATA(obj);
14462
3.50M
    int kind = PyUnicode_KIND(obj);
14463
3.50M
    Py_UCS4 ch = PyUnicode_READ(kind, data, index);
14464
3.50M
    PyObject *result = unicode_char(ch);
14465
3.50M
    index = (result == NULL) ? -1 : index + 1;
14466
3.50M
    return (_PyObjectIndexPair) { .object = result, .index = index };
14467
3.50M
}
14468
14469
void
14470
_PyUnicode_ExactDealloc(PyObject *op)
14471
1.30M
{
14472
1.30M
    assert(PyUnicode_CheckExact(op));
14473
1.30M
    unicode_dealloc(op);
14474
1.30M
}
14475
14476
PyDoc_STRVAR(unicode_doc,
14477
"str(object='') -> str\n\
14478
str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
14479
\n\
14480
Create a new string object from the given object. If encoding or\n\
14481
errors is specified, then the object must expose a data buffer\n\
14482
that will be decoded using the given encoding and error handler.\n\
14483
Otherwise, returns the result of object.__str__() (if defined)\n\
14484
or repr(object).\n\
14485
encoding defaults to 'utf-8'.\n\
14486
errors defaults to 'strict'.");
14487
14488
static PyObject *unicode_iter(PyObject *seq);
14489
14490
PyTypeObject PyUnicode_Type = {
14491
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
14492
    "str",                        /* tp_name */
14493
    sizeof(PyUnicodeObject),      /* tp_basicsize */
14494
    0,                            /* tp_itemsize */
14495
    /* Slots */
14496
    unicode_dealloc,              /* tp_dealloc */
14497
    0,                            /* tp_vectorcall_offset */
14498
    0,                            /* tp_getattr */
14499
    0,                            /* tp_setattr */
14500
    0,                            /* tp_as_async */
14501
    unicode_repr,                 /* tp_repr */
14502
    &unicode_as_number,           /* tp_as_number */
14503
    &unicode_as_sequence,         /* tp_as_sequence */
14504
    &unicode_as_mapping,          /* tp_as_mapping */
14505
    unicode_hash,                 /* tp_hash*/
14506
    0,                            /* tp_call*/
14507
    unicode_str,                  /* tp_str */
14508
    PyObject_GenericGetAttr,      /* tp_getattro */
14509
    0,                            /* tp_setattro */
14510
    0,                            /* tp_as_buffer */
14511
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
14512
        Py_TPFLAGS_UNICODE_SUBCLASS |
14513
        _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
14514
    unicode_doc,                  /* tp_doc */
14515
    0,                            /* tp_traverse */
14516
    0,                            /* tp_clear */
14517
    PyUnicode_RichCompare,        /* tp_richcompare */
14518
    0,                            /* tp_weaklistoffset */
14519
    unicode_iter,                 /* tp_iter */
14520
    0,                            /* tp_iternext */
14521
    unicode_methods,              /* tp_methods */
14522
    0,                            /* tp_members */
14523
    0,                            /* tp_getset */
14524
    0,                            /* tp_base */
14525
    0,                            /* tp_dict */
14526
    0,                            /* tp_descr_get */
14527
    0,                            /* tp_descr_set */
14528
    0,                            /* tp_dictoffset */
14529
    0,                            /* tp_init */
14530
    0,                            /* tp_alloc */
14531
    unicode_new,                  /* tp_new */
14532
    PyObject_Free,                /* tp_free */
14533
    .tp_version_tag = _Py_TYPE_VERSION_STR,
14534
    .tp_vectorcall = unicode_vectorcall,
14535
    ._tp_iteritem = unicode_iteritem,
14536
};
14537
14538
/* Initialize the Unicode implementation */
14539
14540
static void
14541
_init_global_state(void)
14542
22
{
14543
22
    static int initialized = 0;
14544
22
    if (initialized) {
14545
0
        return;
14546
0
    }
14547
22
    initialized = 1;
14548
14549
    /* initialize the linebreak bloom filter */
14550
22
    const Py_UCS2 linebreak[] = {
14551
22
        0x000A, /* LINE FEED */
14552
22
        0x000D, /* CARRIAGE RETURN */
14553
22
        0x001C, /* FILE SEPARATOR */
14554
22
        0x001D, /* GROUP SEPARATOR */
14555
22
        0x001E, /* RECORD SEPARATOR */
14556
22
        0x0085, /* NEXT LINE */
14557
22
        0x2028, /* LINE SEPARATOR */
14558
22
        0x2029, /* PARAGRAPH SEPARATOR */
14559
22
    };
14560
22
    bloom_linebreak = make_bloom_mask(
14561
22
        PyUnicode_2BYTE_KIND, linebreak,
14562
22
        Py_ARRAY_LENGTH(linebreak));
14563
22
}
14564
14565
void
14566
_PyUnicode_InitState(PyInterpreterState *interp)
14567
22
{
14568
22
    if (!_Py_IsMainInterpreter(interp)) {
14569
0
        return;
14570
0
    }
14571
22
    _init_global_state();
14572
22
}
14573
14574
14575
PyStatus
14576
_PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
14577
22
{
14578
22
    if (_Py_IsMainInterpreter(interp)) {
14579
22
        PyStatus status = init_global_interned_strings(interp);
14580
22
        if (_PyStatus_EXCEPTION(status)) {
14581
0
            return status;
14582
0
        }
14583
22
    }
14584
22
    assert(INTERNED_STRINGS);
14585
14586
22
    if (init_interned_dict(interp)) {
14587
0
        PyErr_Clear();
14588
0
        return _PyStatus_ERR("failed to create interned dict");
14589
0
    }
14590
14591
22
    return _PyStatus_OK();
14592
22
}
14593
14594
14595
PyStatus
14596
_PyUnicode_InitTypes(PyInterpreterState *interp)
14597
22
{
14598
22
    if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
14599
0
        goto error;
14600
0
    }
14601
22
    if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
14602
0
        goto error;
14603
0
    }
14604
22
    if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
14605
0
        goto error;
14606
0
    }
14607
22
    return _PyStatus_OK();
14608
14609
0
error:
14610
0
    return _PyStatus_ERR("Can't initialize unicode types");
14611
22
}
14612
14613
static /* non-null */ PyObject*
14614
intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
14615
25.3k
{
14616
    // Note that this steals a reference to `s`, but in many cases that
14617
    // stolen ref is returned, requiring no decref/incref.
14618
14619
25.3k
    assert(s != NULL);
14620
25.3k
    assert(_PyUnicode_CHECK(s));
14621
25.3k
    assert(_PyUnicode_STATE(s).statically_allocated);
14622
25.3k
    assert(!PyUnicode_CHECK_INTERNED(s));
14623
14624
#ifdef Py_DEBUG
14625
    /* We must not add process-global interned string if there's already a
14626
     * per-interpreter interned_dict, which might contain duplicates.
14627
     */
14628
    PyObject *interned = get_interned_dict(interp);
14629
    assert(interned == NULL);
14630
#endif
14631
14632
    /* Look in the global cache first. */
14633
25.3k
    PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14634
    /* We should only init each string once */
14635
25.3k
    assert(r == NULL);
14636
    /* but just in case (for the non-debug build), handle this */
14637
25.3k
    if (r != NULL && r != s) {
14638
0
        assert(_PyUnicode_STATE(r).interned == SSTATE_INTERNED_IMMORTAL_STATIC);
14639
0
        assert(_PyUnicode_CHECK(r));
14640
0
        Py_DECREF(s);
14641
0
        return Py_NewRef(r);
14642
0
    }
14643
14644
25.3k
    if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < 0) {
14645
0
        Py_FatalError("failed to intern static string");
14646
0
    }
14647
14648
25.3k
    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
14649
0
    return s;
14650
25.3k
}
14651
14652
void
14653
_PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
14654
25.3k
{
14655
    // This should only be called as part of runtime initialization
14656
25.3k
    assert(!Py_IsInitialized());
14657
14658
25.3k
    *p = intern_static(interp, *p);
14659
25.3k
    assert(*p);
14660
25.3k
}
14661
14662
static void
14663
immortalize_interned(PyObject *s)
14664
113k
{
14665
113k
    assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
14666
113k
    assert(!_Py_IsImmortal(s));
14667
#ifdef Py_REF_DEBUG
14668
    /* The reference count value should be excluded from the RefTotal.
14669
       The decrements to these objects will not be registered so they
14670
       need to be accounted for in here. */
14671
    for (Py_ssize_t i = 0; i < Py_REFCNT(s); i++) {
14672
        _Py_DecRefTotal(_PyThreadState_GET());
14673
    }
14674
#endif
14675
113k
    _Py_SetImmortal(s);
14676
    // The switch to SSTATE_INTERNED_IMMORTAL must be the last thing done here
14677
    // to synchronize with the check in intern_common() that avoids locking if
14678
    // the string is already immortal.
14679
113k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_IMMORTAL);
14680
113k
}
14681
14682
#ifdef Py_GIL_DISABLED
14683
static bool
14684
can_immortalize_safely(PyObject *s)
14685
{
14686
    if (_Py_IsOwnedByCurrentThread(s) || _Py_IsImmortal(s)) {
14687
        return true;
14688
    }
14689
    Py_ssize_t shared = _Py_atomic_load_ssize(&s->ob_ref_shared);
14690
    return _Py_REF_IS_MERGED(shared);
14691
}
14692
#endif
14693
14694
static /* non-null */ PyObject*
14695
intern_common(PyInterpreterState *interp, PyObject *s /* stolen */,
14696
              bool immortalize)
14697
5.04M
{
14698
    // Note that this steals a reference to `s`, but in many cases that
14699
    // stolen ref is returned, requiring no decref/incref.
14700
14701
#ifdef Py_DEBUG
14702
    assert(s != NULL);
14703
    assert(_PyUnicode_CHECK(s));
14704
#else
14705
5.04M
    if (s == NULL || !PyUnicode_Check(s)) {
14706
0
        return s;
14707
0
    }
14708
5.04M
#endif
14709
14710
    /* If it's a subclass, we don't really know what putting
14711
       it in the interned dict might do. */
14712
5.04M
    if (!PyUnicode_CheckExact(s)) {
14713
0
        return s;
14714
0
    }
14715
14716
    /* Is it already interned? */
14717
5.04M
    switch (PyUnicode_CHECK_INTERNED(s)) {
14718
1.27M
        case SSTATE_NOT_INTERNED:
14719
            // no, go on
14720
1.27M
            break;
14721
166k
        case SSTATE_INTERNED_MORTAL:
14722
166k
#ifndef Py_GIL_DISABLED
14723
            // yes but we might need to make it immortal
14724
166k
            if (immortalize) {
14725
222
                immortalize_interned(s);
14726
222
            }
14727
166k
            return s;
14728
#else
14729
            // not fully interned yet; fall through to the locking path
14730
            break;
14731
#endif
14732
3.60M
        default:
14733
            // all done
14734
3.60M
            return s;
14735
5.04M
    }
14736
14737
    /* Statically allocated strings must be already interned. */
14738
5.04M
    assert(!_PyUnicode_STATE(s).statically_allocated);
14739
14740
#ifdef Py_GIL_DISABLED
14741
    /* In the free-threaded build, all interned strings are immortal */
14742
    immortalize = 1;
14743
#endif
14744
14745
    /* If it's already immortal, intern it as such */
14746
1.27M
    if (_Py_IsImmortal(s)) {
14747
0
        immortalize = 1;
14748
0
    }
14749
14750
    /* if it's a short string, get the singleton */
14751
1.27M
    if (PyUnicode_GET_LENGTH(s) == 1 &&
14752
1.32k
                PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) {
14753
19
        PyObject *r = LATIN1(*(unsigned char*)PyUnicode_DATA(s));
14754
19
        assert(PyUnicode_CHECK_INTERNED(r));
14755
19
        Py_DECREF(s);
14756
19
        return r;
14757
19
    }
14758
#ifdef Py_DEBUG
14759
    assert(!unicode_is_singleton(s));
14760
#endif
14761
14762
    /* Look in the global cache now. */
14763
1.27M
    {
14764
1.27M
        PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14765
1.27M
        if (r != NULL) {
14766
92.3k
            assert(_PyUnicode_STATE(r).statically_allocated);
14767
92.3k
            assert(r != s);  // r must be statically_allocated; s is not
14768
92.3k
            Py_DECREF(s);
14769
92.3k
            return Py_NewRef(r);
14770
92.3k
        }
14771
1.27M
    }
14772
14773
    /* Do a setdefault on the per-interpreter cache. */
14774
1.17M
    PyObject *interned = get_interned_dict(interp);
14775
1.17M
    assert(interned != NULL);
14776
#ifdef Py_GIL_DISABLED
14777
#  define INTERN_MUTEX &_Py_INTERP_CACHED_OBJECT(interp, interned_mutex)
14778
    // Lock-free fast path: check if there's already an interned copy that
14779
    // is in its final immortal state.
14780
    PyObject *r;
14781
    int res = PyDict_GetItemRef(interned, s, &r);
14782
    if (res < 0) {
14783
        PyErr_Clear();
14784
        return s;
14785
    }
14786
    if (res > 0) {
14787
        unsigned int state = _Py_atomic_load_uint8(&_PyUnicode_STATE(r).interned);
14788
        if (state == SSTATE_INTERNED_IMMORTAL) {
14789
            Py_DECREF(s);
14790
            return r;
14791
        }
14792
        // Not yet fully interned; fall through to the locking path.
14793
        Py_DECREF(r);
14794
    }
14795
#endif
14796
14797
#ifdef Py_GIL_DISABLED
14798
    // Immortalization writes to the refcount fields non-atomically. That
14799
    // races with Py_INCREF / Py_DECREF on the thread that owns `s`. If we
14800
    // don't own it (and its refcount hasn't been merged), intern a copy
14801
    // we own instead.
14802
    if (!can_immortalize_safely(s)) {
14803
        PyObject *copy = _PyUnicode_Copy(s);
14804
        if (copy == NULL) {
14805
            PyErr_Clear();
14806
            return s;
14807
        }
14808
        Py_DECREF(s);
14809
        s = copy;
14810
    }
14811
#endif
14812
14813
    // Why _Py_LOCK_DONT_DETACH is used here: waiting for the interned mutex
14814
    // must not detach the thread state. Extension code is expected to
14815
    // detach before blocking on opaque external synchronization. However,
14816
    // the lock used for C++ static initialization is hidden, making
14817
    // that difficult, and it is common for C++ extensions to call
14818
    // PyUnicode_InternFromString() from static initializers. Detaching here
14819
    // can therefore deadlock: a stop-the-world pause may prevent the lock
14820
    // owner from reattaching while the pause waits for another attached
14821
    // thread blocked on the hidden lock.
14822
1.17M
    FT_MUTEX_LOCK_FLAGS(INTERN_MUTEX, _Py_LOCK_DONT_DETACH);
14823
1.17M
    PyObject *t;
14824
1.17M
    {
14825
1.17M
        int res = PyDict_SetDefaultRef(interned, s, s, &t);
14826
1.17M
        if (res < 0) {
14827
0
            PyErr_Clear();
14828
0
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14829
0
            return s;
14830
0
        }
14831
1.17M
        else if (res == 1) {
14832
            // value was already present (not inserted)
14833
880k
            Py_DECREF(s);
14834
880k
            if (immortalize &&
14835
112k
                    PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
14836
3.81k
                immortalize_interned(t);
14837
3.81k
            }
14838
880k
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14839
880k
            return t;
14840
880k
        }
14841
299k
        else {
14842
            // value was newly inserted
14843
299k
            assert (s == t);
14844
299k
            Py_DECREF(t);
14845
299k
        }
14846
1.17M
    }
14847
14848
    /* NOT_INTERNED -> INTERNED_MORTAL */
14849
14850
1.17M
    assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
14851
14852
299k
    if (!_Py_IsImmortal(s)) {
14853
        /* The two references in interned dict (key and value) are not counted.
14854
        unicode_dealloc() and _PyUnicode_ClearInterned() take care of this. */
14855
299k
        Py_DECREF(s);
14856
299k
        Py_DECREF(s);
14857
299k
    }
14858
299k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_MORTAL);
14859
14860
    /* INTERNED_MORTAL -> INTERNED_IMMORTAL (if needed) */
14861
14862
#ifdef Py_DEBUG
14863
    if (_Py_IsImmortal(s)) {
14864
        assert(immortalize);
14865
    }
14866
#endif
14867
299k
    if (immortalize) {
14868
109k
        immortalize_interned(s);
14869
109k
    }
14870
14871
299k
    FT_MUTEX_UNLOCK(INTERN_MUTEX);
14872
299k
    return s;
14873
299k
}
14874
14875
void
14876
_PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
14877
1.31M
{
14878
1.31M
    *p = intern_common(interp, *p, 1);
14879
1.31M
    assert(*p);
14880
1.31M
}
14881
14882
void
14883
_PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
14884
3.73M
{
14885
3.73M
    *p = intern_common(interp, *p, 0);
14886
3.73M
    assert(*p);
14887
3.73M
}
14888
14889
14890
void
14891
_PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
14892
0
{
14893
0
    _PyUnicode_InternImmortal(interp, p);
14894
0
    return;
14895
0
}
14896
14897
void
14898
PyUnicode_InternInPlace(PyObject **p)
14899
0
{
14900
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14901
0
    _PyUnicode_InternMortal(interp, p);
14902
0
}
14903
14904
// Public-looking name kept for the stable ABI; user should not call this:
14905
PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
14906
void
14907
PyUnicode_InternImmortal(PyObject **p)
14908
0
{
14909
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14910
0
    _PyUnicode_InternImmortal(interp, p);
14911
0
}
14912
14913
PyObject *
14914
PyUnicode_InternFromString(const char *cp)
14915
332k
{
14916
332k
    PyObject *s = PyUnicode_FromString(cp);
14917
332k
    if (s == NULL) {
14918
0
        return NULL;
14919
0
    }
14920
332k
    PyInterpreterState *interp = _PyInterpreterState_GET();
14921
332k
    _PyUnicode_InternMortal(interp, &s);
14922
332k
    return s;
14923
332k
}
14924
14925
14926
void
14927
_PyUnicode_ClearInterned(PyInterpreterState *interp)
14928
0
{
14929
0
    PyObject *interned = get_interned_dict(interp);
14930
0
    if (interned == NULL) {
14931
0
        return;
14932
0
    }
14933
0
    assert(PyDict_CheckExact(interned));
14934
14935
0
    if (has_shared_intern_dict(interp)) {
14936
        // the dict doesn't belong to this interpreter, skip the debug
14937
        // checks on it and just clear the pointer to it
14938
0
        clear_interned_dict(interp);
14939
0
        return;
14940
0
    }
14941
14942
#ifdef INTERNED_STATS
14943
    fprintf(stderr, "releasing %zd interned strings\n",
14944
            PyDict_GET_SIZE(interned));
14945
14946
    Py_ssize_t total_length = 0;
14947
#endif
14948
0
    Py_ssize_t pos = 0;
14949
0
    PyObject *s, *ignored_value;
14950
0
    while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
14951
0
        int shared = 0;
14952
0
        switch (PyUnicode_CHECK_INTERNED(s)) {
14953
0
        case SSTATE_INTERNED_IMMORTAL:
14954
            /* Make immortal interned strings mortal again. */
14955
            // Skip the Immortal Instance check and restore
14956
            // the two references (key and value) ignored
14957
            // by PyUnicode_InternInPlace().
14958
0
            _Py_SetMortal(s, 2);
14959
#ifdef Py_REF_DEBUG
14960
            /* let's be pedantic with the ref total */
14961
            _Py_IncRefTotal(_PyThreadState_GET());
14962
            _Py_IncRefTotal(_PyThreadState_GET());
14963
#endif
14964
#ifdef INTERNED_STATS
14965
            total_length += PyUnicode_GET_LENGTH(s);
14966
#endif
14967
0
            break;
14968
0
        case SSTATE_INTERNED_IMMORTAL_STATIC:
14969
            /* It is shared between interpreters, so we should unmark it
14970
               only when this is the last interpreter in which it's
14971
               interned.  We immortalize all the statically initialized
14972
               strings during startup, so we can rely on the
14973
               main interpreter to be the last one. */
14974
0
            if (!_Py_IsMainInterpreter(interp)) {
14975
0
                shared = 1;
14976
0
            }
14977
0
            break;
14978
0
        case SSTATE_INTERNED_MORTAL:
14979
            // Restore 2 references held by the interned dict; these will
14980
            // be decref'd by clear_interned_dict's PyDict_Clear.
14981
0
            _Py_RefcntAdd(s, 2);
14982
#ifdef Py_REF_DEBUG
14983
            /* let's be pedantic with the ref total */
14984
            _Py_IncRefTotal(_PyThreadState_GET());
14985
            _Py_IncRefTotal(_PyThreadState_GET());
14986
#endif
14987
0
            break;
14988
0
        case SSTATE_NOT_INTERNED:
14989
0
            _Py_FALLTHROUGH;
14990
0
        default:
14991
0
            Py_UNREACHABLE();
14992
0
        }
14993
0
        if (!shared) {
14994
0
            FT_ATOMIC_STORE_UINT8_RELAXED(_PyUnicode_STATE(s).interned, SSTATE_NOT_INTERNED);
14995
0
        }
14996
0
    }
14997
#ifdef INTERNED_STATS
14998
    fprintf(stderr,
14999
            "total length of all interned strings: %zd characters\n",
15000
            total_length);
15001
#endif
15002
15003
0
    struct _Py_unicode_state *state = &interp->unicode;
15004
0
    struct _Py_unicode_ids *ids = &state->ids;
15005
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
15006
0
        Py_XINCREF(ids->array[i]);
15007
0
    }
15008
0
    clear_interned_dict(interp);
15009
0
    if (_Py_IsMainInterpreter(interp)) {
15010
0
        clear_global_interned_strings();
15011
0
    }
15012
0
}
15013
15014
15015
/********************* Unicode Iterator **************************/
15016
15017
typedef struct {
15018
    PyObject_HEAD
15019
    Py_ssize_t it_index;
15020
    PyObject *it_seq;    /* Set to NULL when iterator is exhausted */
15021
} unicodeiterobject;
15022
15023
static void
15024
unicodeiter_dealloc(PyObject *op)
15025
419k
{
15026
419k
    unicodeiterobject *it = (unicodeiterobject *)op;
15027
419k
    _PyObject_GC_UNTRACK(it);
15028
419k
    Py_XDECREF(it->it_seq);
15029
419k
    PyObject_GC_Del(it);
15030
419k
}
15031
15032
static int
15033
unicodeiter_traverse(PyObject *op, visitproc visit, void *arg)
15034
0
{
15035
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15036
0
    Py_VISIT(it->it_seq);
15037
0
    return 0;
15038
0
}
15039
15040
static PyObject *
15041
unicodeiter_next(PyObject *op)
15042
106M
{
15043
106M
    unicodeiterobject *it = (unicodeiterobject *)op;
15044
106M
    PyObject *seq;
15045
15046
106M
    assert(it != NULL);
15047
106M
    seq = it->it_seq;
15048
106M
    if (seq == NULL)
15049
0
        return NULL;
15050
106M
    assert(_PyUnicode_CHECK(seq));
15051
15052
106M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15053
105M
        int kind = PyUnicode_KIND(seq);
15054
105M
        const void *data = PyUnicode_DATA(seq);
15055
105M
        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15056
105M
        it->it_index++;
15057
105M
        return unicode_char(chr);
15058
105M
    }
15059
15060
399k
    it->it_seq = NULL;
15061
399k
    Py_DECREF(seq);
15062
399k
    return NULL;
15063
106M
}
15064
15065
static PyObject *
15066
unicode_ascii_iter_next(PyObject *op)
15067
954k
{
15068
954k
    unicodeiterobject *it = (unicodeiterobject *)op;
15069
954k
    assert(it != NULL);
15070
954k
    PyObject *seq = it->it_seq;
15071
954k
    if (seq == NULL) {
15072
0
        return NULL;
15073
0
    }
15074
954k
    assert(_PyUnicode_CHECK(seq));
15075
954k
    assert(PyUnicode_IS_COMPACT_ASCII(seq));
15076
954k
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15077
934k
        const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
15078
934k
        Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
15079
934k
                                              data, it->it_index);
15080
934k
        it->it_index++;
15081
934k
        return (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
15082
934k
    }
15083
19.8k
    it->it_seq = NULL;
15084
19.8k
    Py_DECREF(seq);
15085
19.8k
    return NULL;
15086
954k
}
15087
15088
static PyObject *
15089
unicodeiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
15090
403k
{
15091
403k
    unicodeiterobject *it = (unicodeiterobject *)op;
15092
403k
    Py_ssize_t len = 0;
15093
403k
    if (it->it_seq)
15094
403k
        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
15095
403k
    return PyLong_FromSsize_t(len);
15096
403k
}
15097
15098
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15099
15100
static PyObject *
15101
unicodeiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
15102
0
{
15103
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15104
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
15105
15106
    /* _PyEval_GetBuiltin can invoke arbitrary code,
15107
     * call must be before access of iterator pointers.
15108
     * see issue #101765 */
15109
15110
0
    if (it->it_seq != NULL) {
15111
0
        return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
15112
0
    } else {
15113
0
        PyObject *u = _PyUnicode_GetEmpty();
15114
0
        if (u == NULL) {
15115
0
            Py_XDECREF(iter);
15116
0
            return NULL;
15117
0
        }
15118
0
        return Py_BuildValue("N(N)", iter, u);
15119
0
    }
15120
0
}
15121
15122
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15123
15124
static PyObject *
15125
unicodeiter_setstate(PyObject *op, PyObject *state)
15126
0
{
15127
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15128
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
15129
0
    if (index == -1 && PyErr_Occurred())
15130
0
        return NULL;
15131
0
    if (it->it_seq != NULL) {
15132
0
        if (index < 0)
15133
0
            index = 0;
15134
0
        else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15135
0
            index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15136
0
        it->it_index = index;
15137
0
    }
15138
0
    Py_RETURN_NONE;
15139
0
}
15140
15141
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15142
15143
static PyMethodDef unicodeiter_methods[] = {
15144
    {"__length_hint__", unicodeiter_len, METH_NOARGS, length_hint_doc},
15145
    {"__reduce__",      unicodeiter_reduce, METH_NOARGS, reduce_doc},
15146
    {"__setstate__",    unicodeiter_setstate, METH_O, setstate_doc},
15147
    {NULL,      NULL}       /* sentinel */
15148
};
15149
15150
PyTypeObject PyUnicodeIter_Type = {
15151
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15152
    "str_iterator",         /* tp_name */
15153
    sizeof(unicodeiterobject),      /* tp_basicsize */
15154
    0,                  /* tp_itemsize */
15155
    /* methods */
15156
    unicodeiter_dealloc,/* tp_dealloc */
15157
    0,                  /* tp_vectorcall_offset */
15158
    0,                  /* tp_getattr */
15159
    0,                  /* tp_setattr */
15160
    0,                  /* tp_as_async */
15161
    0,                  /* tp_repr */
15162
    0,                  /* tp_as_number */
15163
    0,                  /* tp_as_sequence */
15164
    0,                  /* tp_as_mapping */
15165
    0,                  /* tp_hash */
15166
    0,                  /* tp_call */
15167
    0,                  /* tp_str */
15168
    PyObject_GenericGetAttr,        /* tp_getattro */
15169
    0,                  /* tp_setattro */
15170
    0,                  /* tp_as_buffer */
15171
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15172
    0,                  /* tp_doc */
15173
    unicodeiter_traverse, /* tp_traverse */
15174
    0,                  /* tp_clear */
15175
    0,                  /* tp_richcompare */
15176
    0,                  /* tp_weaklistoffset */
15177
    PyObject_SelfIter,          /* tp_iter */
15178
    unicodeiter_next,   /* tp_iternext */
15179
    unicodeiter_methods,            /* tp_methods */
15180
    0,
15181
};
15182
15183
PyTypeObject _PyUnicodeASCIIIter_Type = {
15184
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15185
    .tp_name = "str_ascii_iterator",
15186
    .tp_basicsize = sizeof(unicodeiterobject),
15187
    .tp_dealloc = unicodeiter_dealloc,
15188
    .tp_getattro = PyObject_GenericGetAttr,
15189
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
15190
    .tp_traverse = unicodeiter_traverse,
15191
    .tp_iter = PyObject_SelfIter,
15192
    .tp_iternext = unicode_ascii_iter_next,
15193
    .tp_methods = unicodeiter_methods,
15194
};
15195
15196
static PyObject *
15197
unicode_iter(PyObject *seq)
15198
419k
{
15199
419k
    unicodeiterobject *it;
15200
15201
419k
    if (!PyUnicode_Check(seq)) {
15202
0
        PyErr_BadInternalCall();
15203
0
        return NULL;
15204
0
    }
15205
419k
    if (PyUnicode_IS_COMPACT_ASCII(seq)) {
15206
19.8k
        it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
15207
19.8k
    }
15208
399k
    else {
15209
399k
        it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15210
399k
    }
15211
419k
    if (it == NULL)
15212
0
        return NULL;
15213
419k
    it->it_index = 0;
15214
419k
    it->it_seq = Py_NewRef(seq);
15215
419k
    _PyObject_GC_TRACK(it);
15216
419k
    return (PyObject *)it;
15217
419k
}
15218
15219
static int
15220
encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
15221
88
{
15222
88
    assert(str != NULL);
15223
15224
88
    size_t unused_output_length;
15225
88
    int res = _Py_EncodeUTF8(wstr, str, &unused_output_length,
15226
88
                             NULL, 1, _Py_ERROR_STRICT);
15227
88
    if (res == -2) {
15228
0
        PyErr_Format(PyExc_RuntimeError, "cannot encode %s", name);
15229
0
        return -1;
15230
0
    }
15231
88
    if (res < 0) {
15232
0
        PyErr_NoMemory();
15233
0
        return -1;
15234
0
    }
15235
88
    return 0;
15236
88
}
15237
15238
15239
static int
15240
config_get_codec_name(wchar_t **config_encoding)
15241
44
{
15242
44
    char *encoding;
15243
44
    if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15244
0
        return -1;
15245
0
    }
15246
15247
44
    PyObject *name_obj = NULL;
15248
44
    PyObject *codec = _PyCodec_Lookup(encoding);
15249
44
    PyMem_RawFree(encoding);
15250
15251
44
    if (!codec)
15252
0
        goto error;
15253
15254
44
    name_obj = PyObject_GetAttrString(codec, "name");
15255
44
    Py_CLEAR(codec);
15256
44
    if (!name_obj) {
15257
0
        goto error;
15258
0
    }
15259
15260
44
    wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
15261
44
    Py_DECREF(name_obj);
15262
44
    if (wname == NULL) {
15263
0
        goto error;
15264
0
    }
15265
15266
44
    wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
15267
44
    if (raw_wname == NULL) {
15268
0
        PyMem_Free(wname);
15269
0
        PyErr_NoMemory();
15270
0
        goto error;
15271
0
    }
15272
15273
44
    PyMem_RawFree(*config_encoding);
15274
44
    *config_encoding = raw_wname;
15275
15276
44
    PyMem_Free(wname);
15277
44
    return 0;
15278
15279
0
error:
15280
0
    Py_XDECREF(codec);
15281
0
    Py_XDECREF(name_obj);
15282
0
    return -1;
15283
44
}
15284
15285
15286
static PyStatus
15287
init_stdio_encoding(PyInterpreterState *interp)
15288
22
{
15289
    /* Update the stdio encoding to the normalized Python codec name. */
15290
22
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15291
22
    if (config->stdio_encoding == NULL) {
15292
        /* gh-86427: The encoding is determined for every stream. */
15293
0
        return _PyStatus_OK();
15294
0
    }
15295
22
    if (config_get_codec_name(&config->stdio_encoding) < 0) {
15296
0
        return _PyStatus_ERR("failed to get the Python codec name "
15297
0
                             "of the stdio encoding");
15298
0
    }
15299
22
    return _PyStatus_OK();
15300
22
}
15301
15302
15303
static int
15304
init_fs_codec(PyInterpreterState *interp)
15305
22
{
15306
22
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
15307
15308
22
    _Py_error_handler error_handler;
15309
22
    error_handler = get_error_handler_wide(config->filesystem_errors);
15310
22
    if (error_handler == _Py_ERROR_UNKNOWN) {
15311
0
        PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
15312
0
        return -1;
15313
0
    }
15314
15315
22
    char *encoding, *errors;
15316
22
    if (encode_wstr_utf8(config->filesystem_encoding,
15317
22
                         &encoding,
15318
22
                         "filesystem_encoding") < 0) {
15319
0
        return -1;
15320
0
    }
15321
15322
22
    if (encode_wstr_utf8(config->filesystem_errors,
15323
22
                         &errors,
15324
22
                         "filesystem_errors") < 0) {
15325
0
        PyMem_RawFree(encoding);
15326
0
        return -1;
15327
0
    }
15328
15329
22
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
15330
22
    PyMem_RawFree(fs_codec->encoding);
15331
22
    fs_codec->encoding = encoding;
15332
    /* encoding has been normalized by init_fs_encoding() */
15333
22
    fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
15334
22
    PyMem_RawFree(fs_codec->errors);
15335
22
    fs_codec->errors = errors;
15336
22
    fs_codec->error_handler = error_handler;
15337
15338
#ifdef _Py_FORCE_UTF8_FS_ENCODING
15339
    assert(fs_codec->utf8 == 1);
15340
#endif
15341
15342
    /* At this point, PyUnicode_EncodeFSDefault() and
15343
       PyUnicode_DecodeFSDefault() can now use the Python codec rather than
15344
       the C implementation of the filesystem encoding. */
15345
15346
    /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
15347
       global configuration variables. */
15348
22
    if (_Py_IsMainInterpreter(interp)) {
15349
15350
22
        if (_Py_SetFileSystemEncoding(fs_codec->encoding,
15351
22
                                      fs_codec->errors) < 0) {
15352
0
            PyErr_NoMemory();
15353
0
            return -1;
15354
0
        }
15355
22
    }
15356
22
    return 0;
15357
22
}
15358
15359
15360
static PyStatus
15361
init_fs_encoding(PyThreadState *tstate)
15362
22
{
15363
22
    PyInterpreterState *interp = tstate->interp;
15364
15365
    /* Update the filesystem encoding to the normalized Python codec name.
15366
       For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
15367
       (Python codec name). */
15368
22
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15369
22
    if (config_get_codec_name(&config->filesystem_encoding) < 0) {
15370
0
        _Py_DumpPathConfig(tstate);
15371
0
        return _PyStatus_ERR("failed to get the Python codec "
15372
0
                             "of the filesystem encoding");
15373
0
    }
15374
15375
22
    if (init_fs_codec(interp) < 0) {
15376
0
        return _PyStatus_ERR("cannot initialize filesystem codec");
15377
0
    }
15378
22
    return _PyStatus_OK();
15379
22
}
15380
15381
15382
PyStatus
15383
_PyUnicode_InitEncodings(PyThreadState *tstate)
15384
22
{
15385
22
    PyStatus status = _PyCodec_InitRegistry(tstate->interp);
15386
22
    if (_PyStatus_EXCEPTION(status)) {
15387
0
        return status;
15388
0
    }
15389
22
    status = init_fs_encoding(tstate);
15390
22
    if (_PyStatus_EXCEPTION(status)) {
15391
0
        return status;
15392
0
    }
15393
15394
22
    return init_stdio_encoding(tstate->interp);
15395
22
}
15396
15397
15398
static void
15399
_PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
15400
0
{
15401
0
    PyMem_RawFree(fs_codec->encoding);
15402
0
    fs_codec->encoding = NULL;
15403
0
    fs_codec->utf8 = 0;
15404
0
    PyMem_RawFree(fs_codec->errors);
15405
0
    fs_codec->errors = NULL;
15406
0
    fs_codec->error_handler = _Py_ERROR_UNKNOWN;
15407
0
}
15408
15409
15410
#ifdef Py_DEBUG
15411
static inline int
15412
unicode_is_finalizing(void)
15413
{
15414
    return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
15415
}
15416
#endif
15417
15418
15419
void
15420
_PyUnicode_FiniTypes(PyInterpreterState *interp)
15421
0
{
15422
0
    _PyStaticType_FiniBuiltin(interp, &EncodingMapType);
15423
0
    _PyStaticType_FiniBuiltin(interp, &PyFieldNameIter_Type);
15424
0
    _PyStaticType_FiniBuiltin(interp, &PyFormatterIter_Type);
15425
0
}
15426
15427
15428
void
15429
_PyUnicode_Fini(PyInterpreterState *interp)
15430
0
{
15431
0
    struct _Py_unicode_state *state = &interp->unicode;
15432
15433
0
    if (!has_shared_intern_dict(interp)) {
15434
        // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
15435
0
        assert(get_interned_dict(interp) == NULL);
15436
0
    }
15437
15438
0
    _PyUnicode_FiniEncodings(&state->fs_codec);
15439
15440
    // bpo-47182: force a unicodedata CAPI capsule re-import on
15441
    // subsequent initialization of interpreter.
15442
0
    interp->unicode.ucnhash_capi = NULL;
15443
15444
0
    unicode_clear_identifiers(state);
15445
0
}
15446
15447
/* A _string module, to export formatter_parser and formatter_field_name_split
15448
   to the string.Formatter class implemented in Python. */
15449
15450
static PyMethodDef _string_methods[] = {
15451
    {"formatter_field_name_split", formatter_field_name_split,
15452
     METH_O, PyDoc_STR("split the argument as a field name")},
15453
    {"formatter_parser", formatter_parser,
15454
     METH_O, PyDoc_STR("parse the argument as a format string")},
15455
    {NULL, NULL}
15456
};
15457
15458
static PyModuleDef_Slot module_slots[] = {
15459
    _Py_ABI_SLOT,
15460
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
15461
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
15462
    {0, NULL}
15463
};
15464
15465
static struct PyModuleDef _string_module = {
15466
    PyModuleDef_HEAD_INIT,
15467
    .m_name = "_string",
15468
    .m_doc = PyDoc_STR("string helper module"),
15469
    .m_size = 0,
15470
    .m_methods = _string_methods,
15471
    .m_slots = module_slots,
15472
};
15473
15474
PyMODINIT_FUNC
15475
PyInit__string(void)
15476
0
{
15477
0
    return PyModuleDef_Init(&_string_module);
15478
0
}
15479
15480
15481
#undef PyUnicode_KIND
15482
int PyUnicode_KIND(PyObject *op)
15483
0
{
15484
0
    if (!PyUnicode_Check(op)) {
15485
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15486
0
        return -1;
15487
0
    }
15488
0
    return _PyASCIIObject_CAST(op)->state.kind;
15489
0
}
15490
15491
#undef PyUnicode_DATA
15492
void* PyUnicode_DATA(PyObject *op)
15493
0
{
15494
0
    if (!PyUnicode_Check(op)) {
15495
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15496
0
        return NULL;
15497
0
    }
15498
0
    return _PyUnicode_DATA(op);
15499
0
}