Coverage Report

Created: 2026-07-14 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/unicodeobject.c
Line
Count
Source
1
/*
2
3
Unicode implementation based on original code by Fredrik Lundh,
4
modified by Marc-Andre Lemburg <mal@lemburg.com>.
5
6
Major speed upgrades to the method implementations at the Reykjavik
7
NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
9
Copyright (c) Corporation for National Research Initiatives.
10
11
--------------------------------------------------------------------
12
The original string type implementation is:
13
14
  Copyright (c) 1999 by Secret Labs AB
15
  Copyright (c) 1999 by Fredrik Lundh
16
17
By obtaining, using, and/or copying this software and/or its
18
associated documentation, you agree that you have read, understood,
19
and will comply with the following terms and conditions:
20
21
Permission to use, copy, modify, and distribute this software and its
22
associated documentation for any purpose and without fee is hereby
23
granted, provided that the above copyright notice appears in all
24
copies, and that both that copyright notice and this permission notice
25
appear in supporting documentation, and that the name of Secret Labs
26
AB or the author not be used in advertising or publicity pertaining to
27
distribution of the software without specific, written prior
28
permission.
29
30
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32
FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37
--------------------------------------------------------------------
38
39
*/
40
41
#include "Python.h"
42
#include "pycore_abstract.h"      // _PyIndex_Check()
43
#include "pycore_bytes_methods.h" // _Py_bytes_lower()
44
#include "pycore_bytesobject.h"   // _PyBytes_RepeatBuffer()
45
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
46
#include "pycore_codecs.h"        // _PyCodec_Lookup()
47
#include "pycore_critical_section.h" // Py_*_CRITICAL_SECTION_SEQUENCE_FAST
48
#include "pycore_format.h"        // F_LJUST
49
#include "pycore_initconfig.h"    // _PyStatus_OK()
50
#include "pycore_interp.h"        // PyInterpreterState.fs_codec
51
#include "pycore_long.h"          // _PyLong_FormatWriter()
52
#include "pycore_object.h"        // _PyObject_GC_TRACK(), _Py_FatalRefcountError()
53
#include "pycore_pathconfig.h"    // _Py_DumpPathConfig()
54
#include "pycore_pyerrors.h"      // _PyUnicodeTranslateError_Create()
55
#include "pycore_pyhash.h"        // _Py_HashSecret_t
56
#include "pycore_pylifecycle.h"   // _Py_SetFileSystemEncoding()
57
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
58
#include "pycore_ucnhash.h"       // _PyUnicode_Name_CAPI
59
#include "pycore_unicodectype.h"  // _PyUnicode_IsXidStart
60
#include "pycore_unicodeobject.h" // struct _Py_unicode_state
61
#include "pycore_unicodeobject_generated.h"  // _PyUnicode_InitStaticStrings()
62
63
#include "stringlib/eq.h"         // unicode_eq()
64
#include <stddef.h>               // ptrdiff_t
65
66
#ifdef MS_WINDOWS
67
#include <windows.h>
68
#endif
69
70
#ifdef 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
20.2M
#define MAX_UNICODE _Py_MAX_UNICODE
109
272M
#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
249M
{
119
249M
    return FT_ATOMIC_LOAD_PTR_ACQUIRE(_PyCompactUnicodeObject_CAST(op)->utf8);
120
249M
}
121
122
static inline char* PyUnicode_UTF8(PyObject *op)
123
141M
{
124
141M
    assert(_PyUnicode_CHECK(op));
125
141M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
126
126M
        return ((char*)(_PyASCIIObject_CAST(op) + 1));
127
126M
    }
128
15.2M
    else {
129
15.2M
         return _PyUnicode_UTF8(op);
130
15.2M
    }
131
141M
}
132
133
static inline void PyUnicode_SET_UTF8(PyObject *op, char *utf8)
134
21.0M
{
135
21.0M
    FT_ATOMIC_STORE_PTR_RELEASE(_PyCompactUnicodeObject_CAST(op)->utf8, utf8);
136
21.0M
}
137
138
static inline Py_ssize_t PyUnicode_UTF8_LENGTH(PyObject *op)
139
66.1M
{
140
66.1M
    assert(_PyUnicode_CHECK(op));
141
66.1M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
142
63.0M
         return _PyASCIIObject_CAST(op)->length;
143
63.0M
    }
144
3.06M
    else {
145
3.06M
         return _PyCompactUnicodeObject_CAST(op)->utf8_length;
146
3.06M
    }
147
66.1M
}
148
149
static inline void PyUnicode_SET_UTF8_LENGTH(PyObject *op, Py_ssize_t length)
150
21.0M
{
151
21.0M
    _PyCompactUnicodeObject_CAST(op)->utf8_length = length;
152
21.0M
}
153
154
#define _PyUnicode_LENGTH(op)                           \
155
585M
    (_PyASCIIObject_CAST(op)->length)
156
#define _PyUnicode_STATE(op)                            \
157
3.72G
    (_PyASCIIObject_CAST(op)->state)
158
#define _PyUnicode_HASH(op)                             \
159
542M
    (_PyASCIIObject_CAST(op)->hash)
160
161
180M
#define PyUnicode_HASH PyUnstable_Unicode_GET_CACHED_HASH
162
163
static inline void PyUnicode_SET_HASH(PyObject *op, Py_hash_t hash)
164
46.5M
{
165
46.5M
    FT_ATOMIC_STORE_SSIZE_RELAXED(_PyASCIIObject_CAST(op)->hash, hash);
166
46.5M
}
167
168
#define _PyUnicode_DATA_ANY(op)                         \
169
44.4M
    (_PyUnicodeObject_CAST(op)->data.any)
170
171
static inline int _PyUnicode_SHARE_UTF8(PyObject *op)
172
0
{
173
0
    assert(_PyUnicode_CHECK(op));
174
0
    assert(!PyUnicode_IS_COMPACT_ASCII(op));
175
0
    return (_PyUnicode_UTF8(op) == PyUnicode_DATA(op));
176
0
}
177
178
/* true if the Unicode object has an allocated UTF-8 memory block
179
   (not shared with other data) */
180
static inline int _PyUnicode_HAS_UTF8_MEMORY(PyObject *op)
181
584M
{
182
584M
    return (!PyUnicode_IS_COMPACT_ASCII(op)
183
224M
            && _PyUnicode_UTF8(op) != NULL
184
9.99M
            && _PyUnicode_UTF8(op) != PyUnicode_DATA(op));
185
584M
}
186
187
188
236M
#define LATIN1 _Py_LATIN1_CHR
189
190
/* Forward declaration */
191
static PyObject *
192
unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
193
                    const char *errors);
194
static PyObject *
195
unicode_decode_utf8(const char *s, Py_ssize_t size,
196
                    _Py_error_handler error_handler, const char *errors,
197
                    Py_ssize_t *consumed);
198
#ifdef Py_DEBUG
199
static inline int unicode_is_finalizing(void);
200
static int unicode_is_singleton(PyObject *unicode);
201
#endif
202
203
204
// Return a reference to the immortal empty string singleton.
205
PyObject*
206
_PyUnicode_GetEmpty(void)
207
103M
{
208
103M
    _Py_DECLARE_STR(empty, "");
209
103M
    return &_Py_STR(empty);
210
103M
}
211
212
/* This dictionary holds per-interpreter interned strings.
213
 * See InternalDocs/string_interning.md for details.
214
 */
215
static inline PyObject *get_interned_dict(PyInterpreterState *interp)
216
6.11M
{
217
6.11M
    return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
218
6.11M
}
219
220
/* This hashtable holds statically allocated interned strings.
221
 * See InternalDocs/string_interning.md for details.
222
 */
223
6.34M
#define INTERNED_STRINGS _PyRuntime.cached_objects.interned_strings
224
225
/* Get number of all interned strings for the current interpreter. */
226
Py_ssize_t
227
_PyUnicode_InternedSize(void)
228
0
{
229
0
    PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
230
0
    return _Py_hashtable_len(INTERNED_STRINGS) + PyDict_GET_SIZE(dict);
231
0
}
232
233
/* Get number of immortal interned strings for the current interpreter. */
234
Py_ssize_t
235
_PyUnicode_InternedSize_Immortal(void)
236
0
{
237
0
    PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
238
0
    PyObject *key, *value;
239
0
    Py_ssize_t pos = 0;
240
0
    Py_ssize_t count = 0;
241
242
    // It's tempting to keep a count and avoid a loop here. But, this function
243
    // is intended for refleak tests. It spends extra work to report the true
244
    // value, to help detect bugs in optimizations.
245
246
0
    while (PyDict_Next(dict, &pos, &key, &value)) {
247
0
        assert(PyUnicode_CHECK_INTERNED(key) != SSTATE_INTERNED_IMMORTAL_STATIC);
248
0
        if (PyUnicode_CHECK_INTERNED(key) == SSTATE_INTERNED_IMMORTAL) {
249
0
           count++;
250
0
       }
251
0
    }
252
0
    return _Py_hashtable_len(INTERNED_STRINGS) + count;
253
0
}
254
255
static Py_hash_t unicode_hash(PyObject *);
256
257
static Py_uhash_t
258
hashtable_unicode_hash(const void *key)
259
6.34M
{
260
6.34M
    return unicode_hash((PyObject *)key);
261
6.34M
}
262
263
static int
264
hashtable_unicode_compare(const void *key1, const void *key2)
265
492k
{
266
492k
    PyObject *obj1 = (PyObject *)key1;
267
492k
    PyObject *obj2 = (PyObject *)key2;
268
492k
    if (obj1 != NULL && obj2 != NULL) {
269
492k
        return unicode_eq(obj1, obj2);
270
492k
    }
271
0
    else {
272
0
        return obj1 == obj2;
273
0
    }
274
492k
}
275
276
/* Return true if this interpreter should share the main interpreter's
277
   intern_dict.  That's important for interpreters which load basic
278
   single-phase init extension modules (m_size == -1).  There could be interned
279
   immortal strings that are shared between interpreters, due to the
280
   PyDict_Update(mdict, m_copy) call in import_find_extension().
281
282
   It's not safe to deallocate those strings until all interpreters that
283
   potentially use them are freed.  By storing them in the main interpreter, we
284
   ensure they get freed after all other interpreters are freed.
285
*/
286
static bool
287
has_shared_intern_dict(PyInterpreterState *interp)
288
36
{
289
36
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
290
36
    return interp != main_interp  && interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC;
291
36
}
292
293
static int
294
init_interned_dict(PyInterpreterState *interp)
295
36
{
296
36
    assert(get_interned_dict(interp) == NULL);
297
36
    PyObject *interned;
298
36
    if (has_shared_intern_dict(interp)) {
299
0
        interned = get_interned_dict(_PyInterpreterState_Main());
300
0
        Py_INCREF(interned);
301
0
    }
302
36
    else {
303
36
        interned = PyDict_New();
304
36
        if (interned == NULL) {
305
0
            return -1;
306
0
        }
307
36
    }
308
36
    _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
309
36
    return 0;
310
36
}
311
312
static void
313
clear_interned_dict(PyInterpreterState *interp)
314
0
{
315
0
    PyObject *interned = get_interned_dict(interp);
316
0
    if (interned != NULL) {
317
0
        if (!has_shared_intern_dict(interp)) {
318
            // only clear if the dict belongs to this interpreter
319
0
            PyDict_Clear(interned);
320
0
        }
321
0
        Py_DECREF(interned);
322
0
        _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = NULL;
323
0
    }
324
0
}
325
326
static PyStatus
327
init_global_interned_strings(PyInterpreterState *interp)
328
36
{
329
36
    assert(INTERNED_STRINGS == NULL);
330
36
    _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
331
332
36
    INTERNED_STRINGS = _Py_hashtable_new_full(
333
36
        hashtable_unicode_hash,
334
36
        hashtable_unicode_compare,
335
        // Objects stored here are immortal and statically allocated,
336
        // so we don't need key_destroy_func & value_destroy_func:
337
36
        NULL,
338
36
        NULL,
339
36
        &hashtable_alloc
340
36
    );
341
36
    if (INTERNED_STRINGS == NULL) {
342
0
        PyErr_Clear();
343
0
        return _PyStatus_ERR("failed to create global interned dict");
344
0
    }
345
346
    /* Intern statically allocated string identifiers, deepfreeze strings,
347
        * and one-byte latin-1 strings.
348
        * This must be done before any module initialization so that statically
349
        * allocated string identifiers are used instead of heap allocated strings.
350
        * Deepfreeze uses the interned identifiers if present to save space
351
        * else generates them and they are interned to speed up dict lookups.
352
    */
353
36
    _PyUnicode_InitStaticStrings(interp);
354
355
9.25k
    for (int i = 0; i < 256; i++) {
356
9.21k
        PyObject *s = LATIN1(i);
357
9.21k
        _PyUnicode_InternStatic(interp, &s);
358
9.21k
        assert(s == LATIN1(i));
359
9.21k
    }
360
#ifdef Py_DEBUG
361
    assert(_PyUnicode_CheckConsistency(&_Py_STR(empty), 1));
362
363
    for (int i = 0; i < 256; i++) {
364
        assert(_PyUnicode_CheckConsistency(LATIN1(i), 1));
365
    }
366
#endif
367
36
    return _PyStatus_OK();
368
36
}
369
370
static void clear_global_interned_strings(void)
371
0
{
372
0
    if (INTERNED_STRINGS != NULL) {
373
0
        _Py_hashtable_destroy(INTERNED_STRINGS);
374
0
        INTERNED_STRINGS = NULL;
375
0
    }
376
0
}
377
378
#define _Py_RETURN_UNICODE_EMPTY()   \
379
53.6M
    do {                             \
380
53.6M
        return _PyUnicode_GetEmpty();\
381
53.6M
    } while (0)
382
383
384
/* Fast detection of the most frequent whitespace characters */
385
const unsigned char _Py_ascii_whitespace[] = {
386
    0, 0, 0, 0, 0, 0, 0, 0,
387
/*     case 0x0009: * CHARACTER TABULATION */
388
/*     case 0x000A: * LINE FEED */
389
/*     case 0x000B: * LINE TABULATION */
390
/*     case 0x000C: * FORM FEED */
391
/*     case 0x000D: * CARRIAGE RETURN */
392
    0, 1, 1, 1, 1, 1, 0, 0,
393
    0, 0, 0, 0, 0, 0, 0, 0,
394
/*     case 0x001C: * FILE SEPARATOR */
395
/*     case 0x001D: * GROUP SEPARATOR */
396
/*     case 0x001E: * RECORD SEPARATOR */
397
/*     case 0x001F: * UNIT SEPARATOR */
398
    0, 0, 0, 0, 1, 1, 1, 1,
399
/*     case 0x0020: * SPACE */
400
    1, 0, 0, 0, 0, 0, 0, 0,
401
    0, 0, 0, 0, 0, 0, 0, 0,
402
    0, 0, 0, 0, 0, 0, 0, 0,
403
    0, 0, 0, 0, 0, 0, 0, 0,
404
405
    0, 0, 0, 0, 0, 0, 0, 0,
406
    0, 0, 0, 0, 0, 0, 0, 0,
407
    0, 0, 0, 0, 0, 0, 0, 0,
408
    0, 0, 0, 0, 0, 0, 0, 0,
409
    0, 0, 0, 0, 0, 0, 0, 0,
410
    0, 0, 0, 0, 0, 0, 0, 0,
411
    0, 0, 0, 0, 0, 0, 0, 0,
412
    0, 0, 0, 0, 0, 0, 0, 0
413
};
414
415
/* forward */
416
static PyObject* get_latin1_char(unsigned char ch);
417
418
419
static PyObject *
420
_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
421
static PyObject *
422
_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
423
static PyObject *
424
_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
425
426
static PyObject *
427
unicode_encode_call_errorhandler(const char *errors,
428
       PyObject **errorHandler,const char *encoding, const char *reason,
429
       PyObject *unicode, PyObject **exceptionObject,
430
       Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
431
432
static void
433
raise_encode_exception(PyObject **exceptionObject,
434
                       const char *encoding,
435
                       PyObject *unicode,
436
                       Py_ssize_t startpos, Py_ssize_t endpos,
437
                       const char *reason);
438
439
/* Same for linebreaks */
440
static const unsigned char ascii_linebreak[] = {
441
    0, 0, 0, 0, 0, 0, 0, 0,
442
/*         0x000A, * LINE FEED */
443
/*         0x000B, * LINE TABULATION */
444
/*         0x000C, * FORM FEED */
445
/*         0x000D, * CARRIAGE RETURN */
446
    0, 0, 1, 1, 1, 1, 0, 0,
447
    0, 0, 0, 0, 0, 0, 0, 0,
448
/*         0x001C, * FILE SEPARATOR */
449
/*         0x001D, * GROUP SEPARATOR */
450
/*         0x001E, * RECORD SEPARATOR */
451
    0, 0, 0, 0, 1, 1, 1, 0,
452
    0, 0, 0, 0, 0, 0, 0, 0,
453
    0, 0, 0, 0, 0, 0, 0, 0,
454
    0, 0, 0, 0, 0, 0, 0, 0,
455
    0, 0, 0, 0, 0, 0, 0, 0,
456
457
    0, 0, 0, 0, 0, 0, 0, 0,
458
    0, 0, 0, 0, 0, 0, 0, 0,
459
    0, 0, 0, 0, 0, 0, 0, 0,
460
    0, 0, 0, 0, 0, 0, 0, 0,
461
    0, 0, 0, 0, 0, 0, 0, 0,
462
    0, 0, 0, 0, 0, 0, 0, 0,
463
    0, 0, 0, 0, 0, 0, 0, 0,
464
    0, 0, 0, 0, 0, 0, 0, 0
465
};
466
467
static int convert_uc(PyObject *obj, void *addr);
468
469
struct encoding_map;
470
#include "clinic/unicodeobject.c.h"
471
472
_Py_error_handler
473
_Py_GetErrorHandler(const char *errors)
474
3.97M
{
475
3.97M
    if (errors == NULL || strcmp(errors, "strict") == 0) {
476
3.27M
        return _Py_ERROR_STRICT;
477
3.27M
    }
478
706k
    if (strcmp(errors, "surrogateescape") == 0) {
479
489k
        return _Py_ERROR_SURROGATEESCAPE;
480
489k
    }
481
217k
    if (strcmp(errors, "replace") == 0) {
482
217k
        return _Py_ERROR_REPLACE;
483
217k
    }
484
4
    if (strcmp(errors, "ignore") == 0) {
485
0
        return _Py_ERROR_IGNORE;
486
0
    }
487
4
    if (strcmp(errors, "backslashreplace") == 0) {
488
0
        return _Py_ERROR_BACKSLASHREPLACE;
489
0
    }
490
4
    if (strcmp(errors, "surrogatepass") == 0) {
491
4
        return _Py_ERROR_SURROGATEPASS;
492
4
    }
493
0
    if (strcmp(errors, "xmlcharrefreplace") == 0) {
494
0
        return _Py_ERROR_XMLCHARREFREPLACE;
495
0
    }
496
0
    return _Py_ERROR_OTHER;
497
0
}
498
499
500
static _Py_error_handler
501
get_error_handler_wide(const wchar_t *errors)
502
360
{
503
360
    if (errors == NULL || wcscmp(errors, L"strict") == 0) {
504
0
        return _Py_ERROR_STRICT;
505
0
    }
506
360
    if (wcscmp(errors, L"surrogateescape") == 0) {
507
360
        return _Py_ERROR_SURROGATEESCAPE;
508
360
    }
509
0
    if (wcscmp(errors, L"replace") == 0) {
510
0
        return _Py_ERROR_REPLACE;
511
0
    }
512
0
    if (wcscmp(errors, L"ignore") == 0) {
513
0
        return _Py_ERROR_IGNORE;
514
0
    }
515
0
    if (wcscmp(errors, L"backslashreplace") == 0) {
516
0
        return _Py_ERROR_BACKSLASHREPLACE;
517
0
    }
518
0
    if (wcscmp(errors, L"surrogatepass") == 0) {
519
0
        return _Py_ERROR_SURROGATEPASS;
520
0
    }
521
0
    if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
522
0
        return _Py_ERROR_XMLCHARREFREPLACE;
523
0
    }
524
0
    return _Py_ERROR_OTHER;
525
0
}
526
527
528
static inline int
529
unicode_check_encoding_errors(const char *encoding, const char *errors)
530
40.0M
{
531
40.0M
    if (encoding == NULL && errors == NULL) {
532
12.9M
        return 0;
533
12.9M
    }
534
535
27.1M
    PyInterpreterState *interp = _PyInterpreterState_GET();
536
27.1M
#ifndef Py_DEBUG
537
    /* In release mode, only check in development mode (-X dev) */
538
27.1M
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
539
27.1M
        return 0;
540
27.1M
    }
541
#else
542
    /* Always check in debug mode */
543
#endif
544
545
    /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
546
       codec registry is ready: before_PyUnicode_InitEncodings() is called. */
547
0
    if (!interp->unicode.fs_codec.encoding) {
548
0
        return 0;
549
0
    }
550
551
    /* Disable checks during Python finalization. For example, it allows to
552
     * call PyObject_Dump() during finalization for debugging purpose.
553
     */
554
0
    if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
555
0
        return 0;
556
0
    }
557
558
0
    if (encoding != NULL
559
        // Fast path for the most common built-in encodings. Even if the codec
560
        // is cached, _PyCodec_Lookup() decodes the bytes string from UTF-8 to
561
        // create a temporary Unicode string (the key in the cache).
562
0
        && strcmp(encoding, "utf-8") != 0
563
0
        && strcmp(encoding, "utf8") != 0
564
0
        && strcmp(encoding, "ascii") != 0)
565
0
    {
566
0
        PyObject *handler = _PyCodec_Lookup(encoding);
567
0
        if (handler == NULL) {
568
0
            return -1;
569
0
        }
570
0
        Py_DECREF(handler);
571
0
    }
572
573
0
    if (errors != NULL
574
        // Fast path for the most common built-in error handlers.
575
0
        && strcmp(errors, "strict") != 0
576
0
        && strcmp(errors, "ignore") != 0
577
0
        && strcmp(errors, "replace") != 0
578
0
        && strcmp(errors, "surrogateescape") != 0
579
0
        && strcmp(errors, "surrogatepass") != 0)
580
0
    {
581
0
        PyObject *handler = PyCodec_LookupError(errors);
582
0
        if (handler == NULL) {
583
0
            return -1;
584
0
        }
585
0
        Py_DECREF(handler);
586
0
    }
587
0
    return 0;
588
0
}
589
590
591
int
592
_PyUnicode_CheckConsistency(PyObject *op, int check_content)
593
0
{
594
0
#define CHECK(expr) \
595
0
    do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
596
#ifdef Py_GIL_DISABLED
597
# define CHECK_IF_GIL(expr) (void)(expr)
598
# define CHECK_IF_FT(expr) CHECK(expr)
599
#else
600
0
# define CHECK_IF_GIL(expr) CHECK(expr)
601
0
# define CHECK_IF_FT(expr) (void)(expr)
602
0
#endif
603
604
605
0
    assert(op != NULL);
606
0
    CHECK(PyUnicode_Check(op));
607
608
0
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
609
0
    int kind = ascii->state.kind;
610
611
0
    if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
612
0
        CHECK(kind == PyUnicode_1BYTE_KIND);
613
0
    }
614
0
    else {
615
0
        PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
616
0
        void *data;
617
618
0
        if (ascii->state.compact == 1) {
619
0
            data = compact + 1;
620
0
            CHECK(kind == PyUnicode_1BYTE_KIND
621
0
                                 || kind == PyUnicode_2BYTE_KIND
622
0
                                 || kind == PyUnicode_4BYTE_KIND);
623
0
            CHECK(ascii->state.ascii == 0);
624
0
            CHECK(_PyUnicode_UTF8(op) != data);
625
0
        }
626
0
        else {
627
0
            PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
628
629
0
            data = unicode->data.any;
630
0
            CHECK(kind == PyUnicode_1BYTE_KIND
631
0
                     || kind == PyUnicode_2BYTE_KIND
632
0
                     || kind == PyUnicode_4BYTE_KIND);
633
0
            CHECK(ascii->state.compact == 0);
634
0
            CHECK(data != NULL);
635
0
            if (ascii->state.ascii) {
636
0
                CHECK(_PyUnicode_UTF8(op) == data);
637
0
                CHECK(compact->utf8_length == ascii->length);
638
0
            }
639
0
            else {
640
0
                CHECK(_PyUnicode_UTF8(op) != data);
641
0
            }
642
0
        }
643
0
#ifndef Py_GIL_DISABLED
644
0
        if (_PyUnicode_UTF8(op) == NULL)
645
0
            CHECK(compact->utf8_length == 0);
646
0
#endif
647
0
    }
648
649
    /* check that the best kind is used: O(n) operation */
650
0
    if (check_content) {
651
0
        Py_ssize_t i;
652
0
        Py_UCS4 maxchar = 0;
653
0
        const void *data;
654
0
        Py_UCS4 ch;
655
656
0
        data = PyUnicode_DATA(ascii);
657
0
        for (i=0; i < ascii->length; i++)
658
0
        {
659
0
            ch = PyUnicode_READ(kind, data, i);
660
0
            if (ch > maxchar)
661
0
                maxchar = ch;
662
0
        }
663
0
        if (kind == PyUnicode_1BYTE_KIND) {
664
0
            if (ascii->state.ascii == 0) {
665
0
                CHECK(maxchar >= 128);
666
0
                CHECK(maxchar <= 255);
667
0
            }
668
0
            else
669
0
                CHECK(maxchar < 128);
670
0
        }
671
0
        else if (kind == PyUnicode_2BYTE_KIND) {
672
0
            CHECK(maxchar >= 0x100);
673
0
            CHECK(maxchar <= 0xFFFF);
674
0
        }
675
0
        else {
676
0
            CHECK(maxchar >= 0x10000);
677
0
            CHECK(maxchar <= MAX_UNICODE);
678
0
        }
679
0
        CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
680
0
    }
681
682
    /* Check interning state */
683
#ifdef Py_DEBUG
684
    // Note that we do not check `_Py_IsImmortal(op)` in the GIL-enabled build
685
    // since stable ABI extensions can make immortal strings mortal (but with a
686
    // high enough refcount).
687
    switch (PyUnicode_CHECK_INTERNED(op)) {
688
        case SSTATE_NOT_INTERNED:
689
            if (ascii->state.statically_allocated) {
690
                // This state is for two exceptions:
691
                // - strings are currently checked before they're interned
692
                // - the 256 one-latin1-character strings
693
                //   are static but use SSTATE_NOT_INTERNED
694
            }
695
            else {
696
                CHECK_IF_GIL(!_Py_IsImmortal(op));
697
            }
698
            break;
699
        case SSTATE_INTERNED_MORTAL:
700
            CHECK(!ascii->state.statically_allocated);
701
            CHECK_IF_GIL(!_Py_IsImmortal(op));
702
            break;
703
        case SSTATE_INTERNED_IMMORTAL:
704
            CHECK(!ascii->state.statically_allocated);
705
            CHECK_IF_FT(_Py_IsImmortal(op));
706
            break;
707
        case SSTATE_INTERNED_IMMORTAL_STATIC:
708
            CHECK(ascii->state.statically_allocated);
709
            CHECK_IF_FT(_Py_IsImmortal(op));
710
            break;
711
        default:
712
            Py_UNREACHABLE();
713
    }
714
#endif
715
716
0
    return 1;
717
718
0
#undef CHECK
719
0
}
720
721
PyObject*
722
_PyUnicode_Result(PyObject *unicode)
723
48.1M
{
724
48.1M
    assert(_PyUnicode_CHECK(unicode));
725
726
48.1M
    Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
727
48.1M
    if (length == 0) {
728
228
        PyObject *empty = _PyUnicode_GetEmpty();
729
228
        if (unicode != empty) {
730
0
            Py_DECREF(unicode);
731
0
        }
732
228
        return empty;
733
228
    }
734
735
48.1M
    if (length == 1) {
736
1.66M
        int kind = PyUnicode_KIND(unicode);
737
1.66M
        if (kind == PyUnicode_1BYTE_KIND) {
738
134k
            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
739
134k
            Py_UCS1 ch = data[0];
740
134k
            PyObject *latin1_char = LATIN1(ch);
741
134k
            if (unicode != latin1_char) {
742
130k
                Py_DECREF(unicode);
743
130k
            }
744
134k
            return latin1_char;
745
134k
        }
746
1.66M
    }
747
748
48.1M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
749
47.9M
    return unicode;
750
48.1M
}
751
1.47M
#define unicode_result _PyUnicode_Result
752
753
static PyObject*
754
unicode_result_unchanged(PyObject *unicode)
755
74.7M
{
756
74.7M
    if (PyUnicode_CheckExact(unicode)) {
757
71.4M
        return Py_NewRef(unicode);
758
71.4M
    }
759
3.26M
    else
760
        /* Subtype -- return genuine unicode string with the same value. */
761
3.26M
        return _PyUnicode_Copy(unicode);
762
74.7M
}
763
764
/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
765
   ASCII, Latin1, UTF-8, etc. */
766
static char*
767
backslashreplace(PyBytesWriter *writer, char *str,
768
                 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
769
0
{
770
0
    Py_ssize_t size, i;
771
0
    Py_UCS4 ch;
772
0
    int kind;
773
0
    const void *data;
774
775
0
    kind = PyUnicode_KIND(unicode);
776
0
    data = PyUnicode_DATA(unicode);
777
778
0
    size = 0;
779
    /* determine replacement size */
780
0
    for (i = collstart; i < collend; ++i) {
781
0
        Py_ssize_t incr;
782
783
0
        ch = PyUnicode_READ(kind, data, i);
784
0
        if (ch < 0x100)
785
0
            incr = 2+2;
786
0
        else if (ch < 0x10000)
787
0
            incr = 2+4;
788
0
        else {
789
0
            assert(ch <= MAX_UNICODE);
790
0
            incr = 2+8;
791
0
        }
792
0
        if (size > PY_SSIZE_T_MAX - incr) {
793
0
            PyErr_SetString(PyExc_OverflowError,
794
0
                            "encoded result is too long for a Python string");
795
0
            return NULL;
796
0
        }
797
0
        size += incr;
798
0
    }
799
800
0
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
801
0
    if (str == NULL) {
802
0
        return NULL;
803
0
    }
804
805
    /* generate replacement */
806
0
    for (i = collstart; i < collend; ++i) {
807
0
        ch = PyUnicode_READ(kind, data, i);
808
0
        *str++ = '\\';
809
0
        if (ch >= 0x00010000) {
810
0
            *str++ = 'U';
811
0
            *str++ = Py_hexdigits[(ch>>28)&0xf];
812
0
            *str++ = Py_hexdigits[(ch>>24)&0xf];
813
0
            *str++ = Py_hexdigits[(ch>>20)&0xf];
814
0
            *str++ = Py_hexdigits[(ch>>16)&0xf];
815
0
            *str++ = Py_hexdigits[(ch>>12)&0xf];
816
0
            *str++ = Py_hexdigits[(ch>>8)&0xf];
817
0
        }
818
0
        else if (ch >= 0x100) {
819
0
            *str++ = 'u';
820
0
            *str++ = Py_hexdigits[(ch>>12)&0xf];
821
0
            *str++ = Py_hexdigits[(ch>>8)&0xf];
822
0
        }
823
0
        else
824
0
            *str++ = 'x';
825
0
        *str++ = Py_hexdigits[(ch>>4)&0xf];
826
0
        *str++ = Py_hexdigits[ch&0xf];
827
0
    }
828
0
    return str;
829
0
}
830
831
/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
832
   ASCII, Latin1, UTF-8, etc. */
833
static char*
834
xmlcharrefreplace(PyBytesWriter *writer, char *str,
835
                  PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
836
0
{
837
0
    Py_ssize_t size, i;
838
0
    Py_UCS4 ch;
839
0
    int kind;
840
0
    const void *data;
841
842
0
    kind = PyUnicode_KIND(unicode);
843
0
    data = PyUnicode_DATA(unicode);
844
845
0
    size = 0;
846
    /* determine replacement size */
847
0
    for (i = collstart; i < collend; ++i) {
848
0
        Py_ssize_t incr;
849
850
0
        ch = PyUnicode_READ(kind, data, i);
851
0
        if (ch < 10)
852
0
            incr = 2+1+1;
853
0
        else if (ch < 100)
854
0
            incr = 2+2+1;
855
0
        else if (ch < 1000)
856
0
            incr = 2+3+1;
857
0
        else if (ch < 10000)
858
0
            incr = 2+4+1;
859
0
        else if (ch < 100000)
860
0
            incr = 2+5+1;
861
0
        else if (ch < 1000000)
862
0
            incr = 2+6+1;
863
0
        else {
864
0
            assert(ch <= MAX_UNICODE);
865
0
            incr = 2+7+1;
866
0
        }
867
0
        if (size > PY_SSIZE_T_MAX - incr) {
868
0
            PyErr_SetString(PyExc_OverflowError,
869
0
                            "encoded result is too long for a Python string");
870
0
            return NULL;
871
0
        }
872
0
        size += incr;
873
0
    }
874
875
0
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
876
0
    if (str == NULL) {
877
0
        return NULL;
878
0
    }
879
880
    /* generate replacement */
881
0
    for (i = collstart; i < collend; ++i) {
882
0
        size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
883
0
        if (size < 0) {
884
0
            return NULL;
885
0
        }
886
0
        str += size;
887
0
    }
888
0
    return str;
889
0
}
890
891
/* --- Bloom Filters ----------------------------------------------------- */
892
893
/* stuff to implement simple "bloom filters" for Unicode characters.
894
   to keep things simple, we use a single bitmask, using the least 5
895
   bits from each unicode characters as the bit index. */
896
897
/* the linebreak mask is set up by _PyUnicode_Init() below */
898
899
#if LONG_BIT >= 128
900
#define BLOOM_WIDTH 128
901
#elif LONG_BIT >= 64
902
26.7M
#define BLOOM_WIDTH 64
903
#elif LONG_BIT >= 32
904
#define BLOOM_WIDTH 32
905
#else
906
#error "LONG_BIT is smaller than 32"
907
#endif
908
909
8.55M
#define BLOOM_MASK unsigned long
910
911
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
912
913
37.5M
#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
914
915
#define BLOOM_LINEBREAK(ch)                                             \
916
134M
    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
917
134M
     (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
918
919
static inline BLOOM_MASK
920
make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
921
4.27M
{
922
4.27M
#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
923
4.27M
    do {                                               \
924
4.27M
        TYPE *data = (TYPE *)PTR;                      \
925
4.27M
        TYPE *end = data + LEN;                        \
926
4.27M
        Py_UCS4 ch;                                    \
927
10.2M
        for (; data != end; data++) {                  \
928
6.01M
            ch = *data;                                \
929
6.01M
            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
930
6.01M
        }                                              \
931
4.27M
        break;                                         \
932
4.27M
    } while (0)
933
934
    /* calculate simple bloom-style bitmask for a given unicode string */
935
936
4.27M
    BLOOM_MASK mask;
937
938
4.27M
    mask = 0;
939
4.27M
    switch (kind) {
940
4.27M
    case PyUnicode_1BYTE_KIND:
941
4.27M
        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
942
4.27M
        break;
943
36
    case PyUnicode_2BYTE_KIND:
944
36
        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
945
36
        break;
946
0
    case PyUnicode_4BYTE_KIND:
947
0
        BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
948
0
        break;
949
0
    default:
950
0
        Py_UNREACHABLE();
951
4.27M
    }
952
4.27M
    return mask;
953
954
4.27M
#undef BLOOM_UPDATE
955
4.27M
}
956
957
/* Compilation of templated routines */
958
959
778k
#define STRINGLIB_GET_EMPTY() _PyUnicode_GetEmpty()
960
961
#include "stringlib/asciilib.h"
962
#include "stringlib/fastsearch.h"
963
#include "stringlib/partition.h"
964
#include "stringlib/split.h"
965
#include "stringlib/count.h"
966
#include "stringlib/find.h"
967
#include "stringlib/find_max_char.h"
968
#include "stringlib/undef.h"
969
970
#include "stringlib/ucs1lib.h"
971
#include "stringlib/fastsearch.h"
972
#include "stringlib/partition.h"
973
#include "stringlib/split.h"
974
#include "stringlib/count.h"
975
#include "stringlib/find.h"
976
#include "stringlib/replace.h"
977
#include "stringlib/repr.h"
978
#include "stringlib/find_max_char.h"
979
#include "stringlib/undef.h"
980
981
#include "stringlib/ucs2lib.h"
982
#include "stringlib/fastsearch.h"
983
#include "stringlib/partition.h"
984
#include "stringlib/split.h"
985
#include "stringlib/count.h"
986
#include "stringlib/find.h"
987
#include "stringlib/replace.h"
988
#include "stringlib/repr.h"
989
#include "stringlib/find_max_char.h"
990
#include "stringlib/undef.h"
991
992
#include "stringlib/ucs4lib.h"
993
#include "stringlib/fastsearch.h"
994
#include "stringlib/partition.h"
995
#include "stringlib/split.h"
996
#include "stringlib/count.h"
997
#include "stringlib/find.h"
998
#include "stringlib/replace.h"
999
#include "stringlib/repr.h"
1000
#include "stringlib/find_max_char.h"
1001
#include "stringlib/undef.h"
1002
1003
#undef STRINGLIB_GET_EMPTY
1004
1005
/* --- Unicode Object ----------------------------------------------------- */
1006
1007
static inline Py_ssize_t
1008
findchar(const void *s, int kind,
1009
         Py_ssize_t size, Py_UCS4 ch,
1010
         int direction)
1011
227M
{
1012
227M
    switch (kind) {
1013
219M
    case PyUnicode_1BYTE_KIND:
1014
219M
        if ((Py_UCS1) ch != ch)
1015
4.80k
            return -1;
1016
219M
        if (direction > 0)
1017
218M
            return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1018
59.3k
        else
1019
59.3k
            return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1020
5.22M
    case PyUnicode_2BYTE_KIND:
1021
5.22M
        if ((Py_UCS2) ch != ch)
1022
0
            return -1;
1023
5.22M
        if (direction > 0)
1024
5.04M
            return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1025
177k
        else
1026
177k
            return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1027
2.83M
    case PyUnicode_4BYTE_KIND:
1028
2.83M
        if (direction > 0)
1029
2.70M
            return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
1030
128k
        else
1031
128k
            return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
1032
0
    default:
1033
0
        Py_UNREACHABLE();
1034
227M
    }
1035
227M
}
1036
1037
#ifdef Py_DEBUG
1038
/* Fill the data of a Unicode string with invalid characters to detect bugs
1039
   earlier.
1040
1041
   _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
1042
   ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
1043
   invalid character in Unicode 6.0. */
1044
static void
1045
unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
1046
{
1047
    int kind = PyUnicode_KIND(unicode);
1048
    Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
1049
    Py_ssize_t length = _PyUnicode_LENGTH(unicode);
1050
    if (length <= old_length)
1051
        return;
1052
    memset(data + old_length * kind, 0xff, (length - old_length) * kind);
1053
}
1054
#endif
1055
1056
static PyObject*
1057
resize_copy(PyObject *unicode, Py_ssize_t length)
1058
0
{
1059
0
    Py_ssize_t copy_length;
1060
0
    PyObject *copy;
1061
1062
0
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1063
0
    if (copy == NULL)
1064
0
        return NULL;
1065
1066
0
    copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
1067
0
    _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
1068
0
    return copy;
1069
0
}
1070
1071
PyObject*
1072
_PyUnicode_ResizeCompact(PyObject *unicode, Py_ssize_t length)
1073
53.7M
{
1074
53.7M
    Py_ssize_t char_size;
1075
53.7M
    Py_ssize_t struct_size;
1076
53.7M
    Py_ssize_t new_size;
1077
53.7M
    PyObject *new_unicode;
1078
#ifdef Py_DEBUG
1079
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1080
#endif
1081
1082
53.7M
    if (!_PyUnicode_IsModifiable(unicode)) {
1083
0
        PyObject *copy = resize_copy(unicode, length);
1084
0
        if (copy == NULL) {
1085
0
            return NULL;
1086
0
        }
1087
0
        Py_DECREF(unicode);
1088
0
        return copy;
1089
0
    }
1090
53.7M
    assert(PyUnicode_IS_COMPACT(unicode));
1091
1092
53.7M
    char_size = PyUnicode_KIND(unicode);
1093
53.7M
    if (PyUnicode_IS_ASCII(unicode))
1094
37.9M
        struct_size = sizeof(PyASCIIObject);
1095
15.8M
    else
1096
15.8M
        struct_size = sizeof(PyCompactUnicodeObject);
1097
1098
53.7M
    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1099
0
        PyErr_NoMemory();
1100
0
        return NULL;
1101
0
    }
1102
53.7M
    new_size = (struct_size + (length + 1) * char_size);
1103
1104
53.7M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1105
0
        PyMem_Free(_PyUnicode_UTF8(unicode));
1106
0
        PyUnicode_SET_UTF8_LENGTH(unicode, 0);
1107
0
        PyUnicode_SET_UTF8(unicode, NULL);
1108
0
    }
1109
#ifdef Py_TRACE_REFS
1110
    _Py_ForgetReference(unicode);
1111
#endif
1112
53.7M
    _PyReftracerTrack(unicode, PyRefTracer_DESTROY);
1113
1114
53.7M
    new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
1115
53.7M
    if (new_unicode == NULL) {
1116
0
        _Py_NewReferenceNoTotal(unicode);
1117
0
        PyErr_NoMemory();
1118
0
        return NULL;
1119
0
    }
1120
53.7M
    unicode = new_unicode;
1121
53.7M
    _Py_NewReferenceNoTotal(unicode);
1122
1123
53.7M
    _PyUnicode_LENGTH(unicode) = length;
1124
#ifdef Py_DEBUG
1125
    unicode_fill_invalid(unicode, old_length);
1126
#endif
1127
53.7M
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1128
53.7M
                    length, 0);
1129
53.7M
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1130
53.7M
    return unicode;
1131
53.7M
}
1132
1133
static int
1134
resize_inplace(PyObject *unicode, Py_ssize_t length)
1135
0
{
1136
0
    assert(!PyUnicode_IS_COMPACT(unicode));
1137
0
    assert(Py_REFCNT(unicode) == 1);
1138
1139
0
    Py_ssize_t new_size;
1140
0
    Py_ssize_t char_size;
1141
0
    int share_utf8;
1142
0
    void *data;
1143
#ifdef Py_DEBUG
1144
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1145
#endif
1146
1147
0
    data = _PyUnicode_DATA_ANY(unicode);
1148
0
    char_size = PyUnicode_KIND(unicode);
1149
0
    share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
1150
1151
0
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1152
0
        PyErr_NoMemory();
1153
0
        return -1;
1154
0
    }
1155
0
    new_size = (length + 1) * char_size;
1156
1157
0
    if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1158
0
    {
1159
0
        PyMem_Free(_PyUnicode_UTF8(unicode));
1160
0
        PyUnicode_SET_UTF8_LENGTH(unicode, 0);
1161
0
        PyUnicode_SET_UTF8(unicode, NULL);
1162
0
    }
1163
1164
0
    data = (PyObject *)PyObject_Realloc(data, new_size);
1165
0
    if (data == NULL) {
1166
0
        PyErr_NoMemory();
1167
0
        return -1;
1168
0
    }
1169
0
    _PyUnicode_DATA_ANY(unicode) = data;
1170
0
    if (share_utf8) {
1171
0
        PyUnicode_SET_UTF8_LENGTH(unicode, length);
1172
0
        PyUnicode_SET_UTF8(unicode, data);
1173
0
    }
1174
0
    _PyUnicode_LENGTH(unicode) = length;
1175
0
    PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
1176
#ifdef Py_DEBUG
1177
    unicode_fill_invalid(unicode, old_length);
1178
#endif
1179
1180
    /* check for integer overflow */
1181
0
    if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
1182
0
        PyErr_NoMemory();
1183
0
        return -1;
1184
0
    }
1185
0
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1186
0
    return 0;
1187
0
}
1188
1189
static const char*
1190
unicode_kind_name(PyObject *unicode)
1191
0
{
1192
    /* don't check consistency: unicode_kind_name() is called from
1193
       _PyUnicode_Dump() */
1194
0
    if (!PyUnicode_IS_COMPACT(unicode))
1195
0
    {
1196
0
        switch (PyUnicode_KIND(unicode))
1197
0
        {
1198
0
        case PyUnicode_1BYTE_KIND:
1199
0
            if (PyUnicode_IS_ASCII(unicode))
1200
0
                return "legacy ascii";
1201
0
            else
1202
0
                return "legacy latin1";
1203
0
        case PyUnicode_2BYTE_KIND:
1204
0
            return "legacy UCS2";
1205
0
        case PyUnicode_4BYTE_KIND:
1206
0
            return "legacy UCS4";
1207
0
        default:
1208
0
            return "<legacy invalid kind>";
1209
0
        }
1210
0
    }
1211
0
    switch (PyUnicode_KIND(unicode)) {
1212
0
    case PyUnicode_1BYTE_KIND:
1213
0
        if (PyUnicode_IS_ASCII(unicode))
1214
0
            return "ascii";
1215
0
        else
1216
0
            return "latin1";
1217
0
    case PyUnicode_2BYTE_KIND:
1218
0
        return "UCS2";
1219
0
    case PyUnicode_4BYTE_KIND:
1220
0
        return "UCS4";
1221
0
    default:
1222
0
        return "<invalid compact kind>";
1223
0
    }
1224
0
}
1225
1226
#ifdef Py_DEBUG
1227
/* Functions wrapping macros for use in debugger */
1228
const char *_PyUnicode_utf8(void *unicode_raw){
1229
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1230
    return PyUnicode_UTF8(unicode);
1231
}
1232
1233
const void *_PyUnicode_compact_data(void *unicode_raw) {
1234
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1235
    return _PyUnicode_COMPACT_DATA(unicode);
1236
}
1237
const void *_PyUnicode_data(void *unicode_raw) {
1238
    PyObject *unicode = _PyObject_CAST(unicode_raw);
1239
    printf("obj %p\n", (void*)unicode);
1240
    printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1241
    printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1242
    printf("ascii op %p\n", (void*)(_PyASCIIObject_CAST(unicode) + 1));
1243
    printf("compact op %p\n", (void*)(_PyCompactUnicodeObject_CAST(unicode) + 1));
1244
    printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1245
    return PyUnicode_DATA(unicode);
1246
}
1247
1248
void
1249
_PyUnicode_Dump(PyObject *op)
1250
{
1251
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
1252
    PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
1253
    PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
1254
    const void *data;
1255
1256
    if (ascii->state.compact)
1257
    {
1258
        if (ascii->state.ascii)
1259
            data = (ascii + 1);
1260
        else
1261
            data = (compact + 1);
1262
    }
1263
    else
1264
        data = unicode->data.any;
1265
    printf("%s: len=%zu, ", unicode_kind_name(op), ascii->length);
1266
1267
    if (!ascii->state.ascii) {
1268
        printf("utf8=%p (%zu)", (void *)compact->utf8, compact->utf8_length);
1269
    }
1270
    printf(", data=%p\n", data);
1271
}
1272
#endif
1273
1274
1275
PyObject *
1276
PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1277
536M
{
1278
    /* Optimization for empty strings */
1279
536M
    if (size == 0) {
1280
16.3M
        return _PyUnicode_GetEmpty();
1281
16.3M
    }
1282
1283
520M
    PyObject *obj;
1284
520M
    PyCompactUnicodeObject *unicode;
1285
520M
    void *data;
1286
520M
    int kind;
1287
520M
    int is_ascii;
1288
520M
    Py_ssize_t char_size;
1289
520M
    Py_ssize_t struct_size;
1290
1291
520M
    is_ascii = 0;
1292
520M
    struct_size = sizeof(PyCompactUnicodeObject);
1293
520M
    if (maxchar < 128) {
1294
322M
        kind = PyUnicode_1BYTE_KIND;
1295
322M
        char_size = 1;
1296
322M
        is_ascii = 1;
1297
322M
        struct_size = sizeof(PyASCIIObject);
1298
322M
    }
1299
197M
    else if (maxchar < 256) {
1300
14.0M
        kind = PyUnicode_1BYTE_KIND;
1301
14.0M
        char_size = 1;
1302
14.0M
    }
1303
183M
    else if (maxchar < 65536) {
1304
172M
        kind = PyUnicode_2BYTE_KIND;
1305
172M
        char_size = 2;
1306
172M
    }
1307
11.4M
    else {
1308
11.4M
        if (maxchar > MAX_UNICODE) {
1309
0
            PyErr_SetString(PyExc_SystemError,
1310
0
                            "invalid maximum character passed to PyUnicode_New");
1311
0
            return NULL;
1312
0
        }
1313
11.4M
        kind = PyUnicode_4BYTE_KIND;
1314
11.4M
        char_size = 4;
1315
11.4M
    }
1316
1317
    /* Ensure we won't overflow the size. */
1318
520M
    if (size < 0) {
1319
0
        PyErr_SetString(PyExc_SystemError,
1320
0
                        "Negative size passed to PyUnicode_New");
1321
0
        return NULL;
1322
0
    }
1323
520M
    if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1324
0
        return PyErr_NoMemory();
1325
1326
    /* Duplicated allocation code from _PyObject_New() instead of a call to
1327
     * PyObject_New() so we are able to allocate space for the object and
1328
     * it's data buffer.
1329
     */
1330
520M
    obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
1331
520M
    if (obj == NULL) {
1332
0
        return PyErr_NoMemory();
1333
0
    }
1334
520M
    _PyObject_Init(obj, &PyUnicode_Type);
1335
1336
520M
    unicode = (PyCompactUnicodeObject *)obj;
1337
520M
    if (is_ascii)
1338
322M
        data = ((PyASCIIObject*)obj) + 1;
1339
197M
    else
1340
197M
        data = unicode + 1;
1341
520M
    _PyUnicode_LENGTH(unicode) = size;
1342
520M
    _PyUnicode_HASH(unicode) = -1;
1343
520M
    _PyUnicode_STATE(unicode).interned = 0;
1344
520M
    _PyUnicode_STATE(unicode).kind = kind;
1345
520M
    _PyUnicode_STATE(unicode).compact = 1;
1346
520M
    _PyUnicode_STATE(unicode).ascii = is_ascii;
1347
520M
    _PyUnicode_STATE(unicode).statically_allocated = 0;
1348
520M
    if (is_ascii) {
1349
322M
        ((char*)data)[size] = 0;
1350
322M
    }
1351
197M
    else if (kind == PyUnicode_1BYTE_KIND) {
1352
14.0M
        ((char*)data)[size] = 0;
1353
14.0M
        unicode->utf8 = NULL;
1354
14.0M
        unicode->utf8_length = 0;
1355
14.0M
    }
1356
183M
    else {
1357
183M
        unicode->utf8 = NULL;
1358
183M
        unicode->utf8_length = 0;
1359
183M
        if (kind == PyUnicode_2BYTE_KIND)
1360
172M
            ((Py_UCS2*)data)[size] = 0;
1361
11.4M
        else /* kind == PyUnicode_4BYTE_KIND */
1362
11.4M
            ((Py_UCS4*)data)[size] = 0;
1363
183M
    }
1364
#ifdef Py_DEBUG
1365
    unicode_fill_invalid((PyObject*)unicode, 0);
1366
#endif
1367
520M
    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
1368
520M
    return obj;
1369
520M
}
1370
1371
static int
1372
unicode_check_modifiable(PyObject *unicode)
1373
673
{
1374
673
    if (!_PyUnicode_IsModifiable(unicode)) {
1375
0
        PyErr_SetString(PyExc_SystemError,
1376
0
                        "Cannot modify a string currently used");
1377
0
        return -1;
1378
0
    }
1379
673
    return 0;
1380
673
}
1381
1382
static int
1383
_copy_characters(PyObject *to, Py_ssize_t to_start,
1384
                 PyObject *from, Py_ssize_t from_start,
1385
                 Py_ssize_t how_many, int check_maxchar)
1386
280M
{
1387
280M
    int from_kind, to_kind;
1388
280M
    const void *from_data;
1389
280M
    void *to_data;
1390
1391
280M
    assert(0 <= how_many);
1392
280M
    assert(0 <= from_start);
1393
280M
    assert(0 <= to_start);
1394
280M
    assert(PyUnicode_Check(from));
1395
280M
    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
1396
1397
280M
    assert(to == NULL || PyUnicode_Check(to));
1398
1399
280M
    if (how_many == 0) {
1400
2.85M
        return 0;
1401
2.85M
    }
1402
1403
280M
    assert(to != NULL);
1404
277M
    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1405
1406
277M
    from_kind = PyUnicode_KIND(from);
1407
277M
    from_data = PyUnicode_DATA(from);
1408
277M
    to_kind = PyUnicode_KIND(to);
1409
277M
    to_data = PyUnicode_DATA(to);
1410
1411
#ifdef Py_DEBUG
1412
    if (!check_maxchar
1413
        && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1414
    {
1415
        Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1416
        Py_UCS4 ch;
1417
        Py_ssize_t i;
1418
        for (i=0; i < how_many; i++) {
1419
            ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1420
            assert(ch <= to_maxchar);
1421
        }
1422
    }
1423
#endif
1424
1425
277M
    if (from_kind == to_kind) {
1426
163M
        if (check_maxchar
1427
0
            && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1428
0
        {
1429
            /* Writing Latin-1 characters into an ASCII string requires to
1430
               check that all written characters are pure ASCII */
1431
0
            Py_UCS4 max_char;
1432
0
            max_char = ucs1lib_find_max_char(from_data,
1433
0
                                             (const Py_UCS1*)from_data + how_many);
1434
0
            if (max_char >= 128)
1435
0
                return -1;
1436
0
        }
1437
163M
        memcpy((char*)to_data + to_kind * to_start,
1438
163M
                  (const char*)from_data + from_kind * from_start,
1439
163M
                  to_kind * how_many);
1440
163M
    }
1441
113M
    else if (from_kind == PyUnicode_1BYTE_KIND
1442
111M
             && to_kind == PyUnicode_2BYTE_KIND)
1443
97.0M
    {
1444
97.0M
        _PyUnicode_CONVERT_BYTES(
1445
97.0M
            Py_UCS1, Py_UCS2,
1446
97.0M
            PyUnicode_1BYTE_DATA(from) + from_start,
1447
97.0M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448
97.0M
            PyUnicode_2BYTE_DATA(to) + to_start
1449
97.0M
            );
1450
97.0M
    }
1451
16.8M
    else if (from_kind == PyUnicode_1BYTE_KIND
1452
14.4M
             && to_kind == PyUnicode_4BYTE_KIND)
1453
14.4M
    {
1454
14.4M
        _PyUnicode_CONVERT_BYTES(
1455
14.4M
            Py_UCS1, Py_UCS4,
1456
14.4M
            PyUnicode_1BYTE_DATA(from) + from_start,
1457
14.4M
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458
14.4M
            PyUnicode_4BYTE_DATA(to) + to_start
1459
14.4M
            );
1460
14.4M
    }
1461
2.39M
    else if (from_kind == PyUnicode_2BYTE_KIND
1462
2.38M
             && to_kind == PyUnicode_4BYTE_KIND)
1463
2.37M
    {
1464
2.37M
        _PyUnicode_CONVERT_BYTES(
1465
2.37M
            Py_UCS2, Py_UCS4,
1466
2.37M
            PyUnicode_2BYTE_DATA(from) + from_start,
1467
2.37M
            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468
2.37M
            PyUnicode_4BYTE_DATA(to) + to_start
1469
2.37M
            );
1470
2.37M
    }
1471
15.1k
    else {
1472
15.1k
        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
1474
15.1k
        if (!check_maxchar) {
1475
15.1k
            if (from_kind == PyUnicode_2BYTE_KIND
1476
2.46k
                && to_kind == PyUnicode_1BYTE_KIND)
1477
2.46k
            {
1478
2.46k
                _PyUnicode_CONVERT_BYTES(
1479
2.46k
                    Py_UCS2, Py_UCS1,
1480
2.46k
                    PyUnicode_2BYTE_DATA(from) + from_start,
1481
2.46k
                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482
2.46k
                    PyUnicode_1BYTE_DATA(to) + to_start
1483
2.46k
                    );
1484
2.46k
            }
1485
12.6k
            else if (from_kind == PyUnicode_4BYTE_KIND
1486
12.6k
                     && to_kind == PyUnicode_1BYTE_KIND)
1487
6.40k
            {
1488
6.40k
                _PyUnicode_CONVERT_BYTES(
1489
6.40k
                    Py_UCS4, Py_UCS1,
1490
6.40k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1491
6.40k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492
6.40k
                    PyUnicode_1BYTE_DATA(to) + to_start
1493
6.40k
                    );
1494
6.40k
            }
1495
6.29k
            else if (from_kind == PyUnicode_4BYTE_KIND
1496
6.29k
                     && to_kind == PyUnicode_2BYTE_KIND)
1497
6.29k
            {
1498
6.29k
                _PyUnicode_CONVERT_BYTES(
1499
6.29k
                    Py_UCS4, Py_UCS2,
1500
6.29k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1501
6.29k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502
6.29k
                    PyUnicode_2BYTE_DATA(to) + to_start
1503
6.29k
                    );
1504
6.29k
            }
1505
0
            else {
1506
0
                Py_UNREACHABLE();
1507
0
            }
1508
15.1k
        }
1509
0
        else {
1510
0
            const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1511
0
            Py_UCS4 ch;
1512
0
            Py_ssize_t i;
1513
1514
0
            for (i=0; i < how_many; i++) {
1515
0
                ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1516
0
                if (ch > to_maxchar)
1517
0
                    return -1;
1518
0
                PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1519
0
            }
1520
0
        }
1521
15.1k
    }
1522
277M
    return 0;
1523
277M
}
1524
1525
void
1526
_PyUnicode_FastCopyCharacters(
1527
    PyObject *to, Py_ssize_t to_start,
1528
    PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
1529
280M
{
1530
280M
    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1531
280M
}
1532
1533
Py_ssize_t
1534
PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1535
                         PyObject *from, Py_ssize_t from_start,
1536
                         Py_ssize_t how_many)
1537
0
{
1538
0
    int err;
1539
1540
0
    if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1541
0
        PyErr_BadInternalCall();
1542
0
        return -1;
1543
0
    }
1544
1545
0
    if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
1546
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
1547
0
        return -1;
1548
0
    }
1549
0
    if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
1550
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
1551
0
        return -1;
1552
0
    }
1553
0
    if (how_many < 0) {
1554
0
        PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1555
0
        return -1;
1556
0
    }
1557
0
    how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
1558
0
    if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1559
0
        PyErr_Format(PyExc_SystemError,
1560
0
                     "Cannot write %zi characters at %zi "
1561
0
                     "in a string of %zi characters",
1562
0
                     how_many, to_start, PyUnicode_GET_LENGTH(to));
1563
0
        return -1;
1564
0
    }
1565
1566
0
    if (how_many == 0)
1567
0
        return 0;
1568
1569
0
    if (unicode_check_modifiable(to))
1570
0
        return -1;
1571
1572
0
    err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1573
0
    if (err) {
1574
0
        PyErr_Format(PyExc_SystemError,
1575
0
                     "Cannot copy %s characters "
1576
0
                     "into a string of %s characters",
1577
0
                     unicode_kind_name(from),
1578
0
                     unicode_kind_name(to));
1579
0
        return -1;
1580
0
    }
1581
0
    return how_many;
1582
0
}
1583
1584
/* Find the maximum code point and count the number of surrogate pairs so a
1585
   correct string length can be computed before converting a string to UCS4.
1586
   This function counts single surrogates as a character and not as a pair.
1587
1588
   Return 0 on success, or -1 on error. */
1589
static int
1590
find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1591
                        Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
1592
399k
{
1593
399k
    const wchar_t *iter;
1594
399k
    Py_UCS4 ch;
1595
1596
399k
    assert(num_surrogates != NULL && maxchar != NULL);
1597
399k
    *num_surrogates = 0;
1598
399k
    *maxchar = 0;
1599
1600
12.0M
    for (iter = begin; iter < end; ) {
1601
#if SIZEOF_WCHAR_T == 2
1602
        if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1603
            && (iter+1) < end
1604
            && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1605
        {
1606
            ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1607
            ++(*num_surrogates);
1608
            iter += 2;
1609
        }
1610
        else
1611
#endif
1612
11.6M
        {
1613
11.6M
            ch = *iter;
1614
11.6M
            iter++;
1615
11.6M
        }
1616
11.6M
        if (ch > *maxchar) {
1617
1.67M
            *maxchar = ch;
1618
1.67M
            if (*maxchar > MAX_UNICODE) {
1619
0
                PyErr_Format(PyExc_ValueError,
1620
0
                             "character U+%x is not in range [U+0000; U+%x]",
1621
0
                             ch, MAX_UNICODE);
1622
0
                return -1;
1623
0
            }
1624
1.67M
        }
1625
11.6M
    }
1626
399k
    return 0;
1627
399k
}
1628
1629
static void
1630
unicode_dealloc(PyObject *unicode)
1631
530M
{
1632
#ifdef Py_DEBUG
1633
    if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
1634
        _Py_FatalRefcountError("deallocating an Unicode singleton");
1635
    }
1636
#endif
1637
530M
    if (_PyUnicode_STATE(unicode).statically_allocated) {
1638
        /* This should never get called, but we also don't want to SEGV if
1639
        * we accidentally decref an immortal string out of existence. Since
1640
        * the string is an immortal object, just re-set the reference count.
1641
        */
1642
#ifdef Py_DEBUG
1643
        Py_UNREACHABLE();
1644
#endif
1645
0
        _Py_SetImmortal(unicode);
1646
0
        return;
1647
0
    }
1648
530M
    switch (_PyUnicode_STATE(unicode).interned) {
1649
530M
        case SSTATE_NOT_INTERNED:
1650
530M
            break;
1651
347k
        case SSTATE_INTERNED_MORTAL:
1652
            /* Remove the object from the intern dict.
1653
             * Before doing so, we set the refcount to 2: the key and value
1654
             * in the interned_dict.
1655
             */
1656
347k
            assert(Py_REFCNT(unicode) == 0);
1657
347k
            Py_SET_REFCNT(unicode, 2);
1658
#ifdef Py_REF_DEBUG
1659
            /* let's be pedantic with the ref total */
1660
            _Py_IncRefTotal(_PyThreadState_GET());
1661
            _Py_IncRefTotal(_PyThreadState_GET());
1662
#endif
1663
347k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1664
347k
            PyObject *interned = get_interned_dict(interp);
1665
347k
            assert(interned != NULL);
1666
347k
            PyObject *popped;
1667
347k
            int r = PyDict_Pop(interned, unicode, &popped);
1668
347k
            if (r == -1) {
1669
0
                PyErr_FormatUnraisable("Exception ignored while "
1670
0
                                       "removing an interned string %R",
1671
0
                                       unicode);
1672
                // We don't know what happened to the string. It's probably
1673
                // best to leak it:
1674
                // - if it was popped, there are no more references to it
1675
                //   so it can't cause trouble (except wasted memory)
1676
                // - if it wasn't popped, it'll remain interned
1677
0
                _Py_SetImmortal(unicode);
1678
0
                _PyUnicode_STATE(unicode).interned = SSTATE_INTERNED_IMMORTAL;
1679
0
                return;
1680
0
            }
1681
347k
            if (r == 0) {
1682
                // The interned string was not found in the interned_dict.
1683
#ifdef Py_DEBUG
1684
                Py_UNREACHABLE();
1685
#endif
1686
0
                _Py_SetImmortal(unicode);
1687
0
                return;
1688
0
            }
1689
            // Successfully popped.
1690
347k
            assert(popped == unicode);
1691
            // Only our `popped` reference should be left; remove it too.
1692
347k
            assert(Py_REFCNT(unicode) == 1);
1693
347k
            Py_SET_REFCNT(unicode, 0);
1694
#ifdef Py_REF_DEBUG
1695
            /* let's be pedantic with the ref total */
1696
            _Py_DecRefTotal(_PyThreadState_GET());
1697
#endif
1698
347k
            break;
1699
0
        default:
1700
            // As with `statically_allocated` above.
1701
#ifdef Py_REF_DEBUG
1702
            Py_UNREACHABLE();
1703
#endif
1704
0
            _Py_SetImmortal(unicode);
1705
0
            return;
1706
530M
    }
1707
530M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1708
159k
        PyMem_Free(_PyUnicode_UTF8(unicode));
1709
159k
    }
1710
530M
    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
1711
11.1M
        PyMem_Free(_PyUnicode_DATA_ANY(unicode));
1712
11.1M
    }
1713
1714
530M
    Py_TYPE(unicode)->tp_free(unicode);
1715
530M
}
1716
1717
#ifdef Py_DEBUG
1718
static int
1719
unicode_is_singleton(PyObject *unicode)
1720
{
1721
    if (unicode == &_Py_STR(empty)) {
1722
        return 1;
1723
    }
1724
1725
    PyASCIIObject *ascii = _PyASCIIObject_CAST(unicode);
1726
    if (ascii->length == 1) {
1727
        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1728
        if (ch < 256 && LATIN1(ch) == unicode) {
1729
            return 1;
1730
        }
1731
    }
1732
    return 0;
1733
}
1734
#endif
1735
1736
int
1737
_PyUnicode_IsModifiable(PyObject *unicode)
1738
61.7M
{
1739
61.7M
    assert(_PyUnicode_CHECK(unicode));
1740
61.7M
    if (!_PyObject_IsUniquelyReferenced(unicode))
1741
3.44M
        return 0;
1742
58.3M
    if (PyUnicode_HASH(unicode) != -1)
1743
0
        return 0;
1744
58.3M
    if (PyUnicode_CHECK_INTERNED(unicode))
1745
0
        return 0;
1746
58.3M
    if (!PyUnicode_CheckExact(unicode))
1747
0
        return 0;
1748
#ifdef Py_DEBUG
1749
    /* singleton refcount is greater than 1 */
1750
    assert(!unicode_is_singleton(unicode));
1751
#endif
1752
58.3M
    return 1;
1753
58.3M
}
1754
1755
static int
1756
unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1757
2.27M
{
1758
2.27M
    PyObject *unicode;
1759
2.27M
    Py_ssize_t old_length;
1760
1761
2.27M
    assert(p_unicode != NULL);
1762
2.27M
    unicode = *p_unicode;
1763
1764
2.27M
    assert(unicode != NULL);
1765
2.27M
    assert(PyUnicode_Check(unicode));
1766
2.27M
    assert(0 <= length);
1767
1768
2.27M
    old_length = PyUnicode_GET_LENGTH(unicode);
1769
2.27M
    if (old_length == length)
1770
0
        return 0;
1771
1772
2.27M
    if (length == 0) {
1773
0
        PyObject *empty = _PyUnicode_GetEmpty();
1774
0
        Py_SETREF(*p_unicode, empty);
1775
0
        return 0;
1776
0
    }
1777
1778
2.27M
    if (!_PyUnicode_IsModifiable(unicode)) {
1779
0
        PyObject *copy = resize_copy(unicode, length);
1780
0
        if (copy == NULL)
1781
0
            return -1;
1782
0
        Py_SETREF(*p_unicode, copy);
1783
0
        return 0;
1784
0
    }
1785
1786
2.27M
    if (PyUnicode_IS_COMPACT(unicode)) {
1787
2.27M
        PyObject *new_unicode = _PyUnicode_ResizeCompact(unicode, length);
1788
2.27M
        if (new_unicode == NULL)
1789
0
            return -1;
1790
2.27M
        *p_unicode = new_unicode;
1791
2.27M
        return 0;
1792
2.27M
    }
1793
0
    return resize_inplace(unicode, length);
1794
2.27M
}
1795
1796
int
1797
PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
1798
0
{
1799
0
    PyObject *unicode;
1800
0
    if (p_unicode == NULL) {
1801
0
        PyErr_BadInternalCall();
1802
0
        return -1;
1803
0
    }
1804
0
    unicode = *p_unicode;
1805
0
    if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
1806
0
    {
1807
0
        PyErr_BadInternalCall();
1808
0
        return -1;
1809
0
    }
1810
0
    return unicode_resize(p_unicode, length);
1811
0
}
1812
1813
static PyObject*
1814
get_latin1_char(Py_UCS1 ch)
1815
235M
{
1816
235M
    PyObject *o = LATIN1(ch);
1817
235M
    return o;
1818
235M
}
1819
1820
static PyObject*
1821
unicode_char(Py_UCS4 ch)
1822
280M
{
1823
280M
    PyObject *unicode;
1824
1825
280M
    assert(ch <= MAX_UNICODE);
1826
1827
280M
    if (ch < 256) {
1828
147M
        return get_latin1_char(ch);
1829
147M
    }
1830
1831
133M
    unicode = PyUnicode_New(1, ch);
1832
133M
    if (unicode == NULL)
1833
0
        return NULL;
1834
1835
133M
    assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1836
133M
    if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
1837
124M
        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1838
124M
    } else {
1839
8.75M
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1840
8.75M
        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1841
8.75M
    }
1842
133M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
1843
133M
    return unicode;
1844
133M
}
1845
1846
1847
static inline void
1848
unicode_write_widechar(int kind, void *data,
1849
                       const wchar_t *u, Py_ssize_t size,
1850
                       Py_ssize_t num_surrogates)
1851
399k
{
1852
399k
    switch (kind) {
1853
374k
    case PyUnicode_1BYTE_KIND:
1854
374k
        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, u, u + size, data);
1855
374k
        break;
1856
1857
23.7k
    case PyUnicode_2BYTE_KIND:
1858
#if SIZEOF_WCHAR_T == 2
1859
        memcpy(data, u, size * 2);
1860
#else
1861
23.7k
        _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2, u, u + size, data);
1862
23.7k
#endif
1863
23.7k
        break;
1864
1865
1.12k
    case PyUnicode_4BYTE_KIND:
1866
1.12k
    {
1867
#if SIZEOF_WCHAR_T == 2
1868
        // Convert a 16-bits wchar_t representation to UCS4, this will decode
1869
        // surrogate pairs.
1870
        const wchar_t *end = u + size;
1871
        Py_UCS4 *ucs4_out = (Py_UCS4*)data;
1872
#  ifndef NDEBUG
1873
        Py_UCS4 *ucs4_end = (Py_UCS4*)data + (size - num_surrogates);
1874
#  endif
1875
        for (const wchar_t *iter = u; iter < end; ) {
1876
            assert(ucs4_out < ucs4_end);
1877
            if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1878
                && (iter+1) < end
1879
                && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1880
            {
1881
                *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1882
                iter += 2;
1883
            }
1884
            else {
1885
                *ucs4_out++ = *iter;
1886
                iter++;
1887
            }
1888
        }
1889
        assert(ucs4_out == ucs4_end);
1890
#else
1891
1.12k
        assert(num_surrogates == 0);
1892
1.12k
        memcpy(data, u, size * 4);
1893
1.12k
#endif
1894
1.12k
        break;
1895
0
    }
1896
0
    default:
1897
0
        Py_UNREACHABLE();
1898
399k
    }
1899
399k
}
1900
1901
1902
PyObject *
1903
PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
1904
701k
{
1905
701k
    PyObject *unicode;
1906
701k
    Py_UCS4 maxchar = 0;
1907
701k
    Py_ssize_t num_surrogates;
1908
1909
701k
    if (u == NULL && size != 0) {
1910
0
        PyErr_BadInternalCall();
1911
0
        return NULL;
1912
0
    }
1913
1914
701k
    if (size == -1) {
1915
1.26k
        size = wcslen(u);
1916
1.26k
    }
1917
1918
    /* If the Unicode data is known at construction time, we can apply
1919
       some optimizations which share commonly used objects. */
1920
1921
    /* Optimization for empty strings */
1922
701k
    if (size == 0)
1923
241k
        _Py_RETURN_UNICODE_EMPTY();
1924
1925
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
1926
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
1927
       non-Unicode locales and hence needs conversion to UCS-4 first. */
1928
    if (_Py_LocaleUsesNonUnicodeWchar()) {
1929
        wchar_t* converted = _Py_DecodeNonUnicodeWchar(u, size);
1930
        if (!converted) {
1931
            return NULL;
1932
        }
1933
        PyObject *unicode = _PyUnicode_FromUCS4(converted, size);
1934
        PyMem_Free(converted);
1935
        return unicode;
1936
    }
1937
#endif
1938
1939
    /* Single character Unicode objects in the Latin-1 range are
1940
       shared when using this constructor */
1941
460k
    if (size == 1 && (Py_UCS4)*u < 256)
1942
60.4k
        return get_latin1_char((unsigned char)*u);
1943
1944
    /* If not empty and not single character, copy the Unicode data
1945
       into the new object */
1946
399k
    if (find_maxchar_surrogates(u, u + size,
1947
399k
                                &maxchar, &num_surrogates) == -1)
1948
0
        return NULL;
1949
1950
399k
    unicode = PyUnicode_New(size - num_surrogates, maxchar);
1951
399k
    if (!unicode)
1952
0
        return NULL;
1953
1954
399k
    unicode_write_widechar(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1955
399k
                           u, size, num_surrogates);
1956
1957
399k
    return unicode_result(unicode);
1958
399k
}
1959
1960
1961
int
1962
PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *pub_writer,
1963
                              const wchar_t *str,
1964
                              Py_ssize_t size)
1965
0
{
1966
0
    _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer;
1967
1968
0
    if (size < 0) {
1969
0
        size = wcslen(str);
1970
0
    }
1971
1972
0
    if (size == 0) {
1973
0
        return 0;
1974
0
    }
1975
1976
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
1977
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
1978
       non-Unicode locales and hence needs conversion to UCS-4 first. */
1979
    if (_Py_LocaleUsesNonUnicodeWchar()) {
1980
        wchar_t* converted = _Py_DecodeNonUnicodeWchar(str, size);
1981
        if (!converted) {
1982
            return -1;
1983
        }
1984
1985
        int res = PyUnicodeWriter_WriteUCS4(pub_writer, converted, size);
1986
        PyMem_Free(converted);
1987
        return res;
1988
    }
1989
#endif
1990
1991
0
    Py_UCS4 maxchar = 0;
1992
0
    Py_ssize_t num_surrogates;
1993
0
    if (find_maxchar_surrogates(str, str + size,
1994
0
                                &maxchar, &num_surrogates) == -1) {
1995
0
        return -1;
1996
0
    }
1997
1998
0
    if (_PyUnicodeWriter_Prepare(writer, size - num_surrogates, maxchar) < 0) {
1999
0
        return -1;
2000
0
    }
2001
2002
0
    int kind = writer->kind;
2003
0
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2004
0
    unicode_write_widechar(kind, data, str, size, num_surrogates);
2005
2006
0
    writer->pos += size - num_surrogates;
2007
0
    return 0;
2008
0
}
2009
2010
2011
PyObject *
2012
PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
2013
8.18M
{
2014
8.18M
    if (size < 0) {
2015
0
        PyErr_SetString(PyExc_SystemError,
2016
0
                        "Negative size passed to PyUnicode_FromStringAndSize");
2017
0
        return NULL;
2018
0
    }
2019
8.18M
    if (u != NULL) {
2020
8.18M
        return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2021
8.18M
    }
2022
0
    if (size > 0) {
2023
0
        PyErr_SetString(PyExc_SystemError,
2024
0
            "NULL string with positive size with NULL passed to PyUnicode_FromStringAndSize");
2025
0
        return NULL;
2026
0
    }
2027
0
    return _PyUnicode_GetEmpty();
2028
0
}
2029
2030
PyObject *
2031
PyUnicode_FromString(const char *u)
2032
21.9M
{
2033
21.9M
    size_t size = strlen(u);
2034
21.9M
    if (size > PY_SSIZE_T_MAX) {
2035
0
        PyErr_SetString(PyExc_OverflowError, "input too long");
2036
0
        return NULL;
2037
0
    }
2038
21.9M
    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
2039
21.9M
}
2040
2041
2042
PyObject *
2043
_PyUnicode_FromId(_Py_Identifier *id)
2044
0
{
2045
0
    PyMutex_Lock((PyMutex *)&id->mutex);
2046
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2047
0
    struct _Py_unicode_ids *ids = &interp->unicode.ids;
2048
2049
0
    Py_ssize_t index = _Py_atomic_load_ssize(&id->index);
2050
0
    if (index < 0) {
2051
0
        struct _Py_unicode_runtime_ids *rt_ids = &interp->runtime->unicode_state.ids;
2052
2053
0
        PyMutex_Lock(&rt_ids->mutex);
2054
        // Check again to detect concurrent access. Another thread can have
2055
        // initialized the index while this thread waited for the lock.
2056
0
        index = _Py_atomic_load_ssize(&id->index);
2057
0
        if (index < 0) {
2058
0
            assert(rt_ids->next_index < PY_SSIZE_T_MAX);
2059
0
            index = rt_ids->next_index;
2060
0
            rt_ids->next_index++;
2061
0
            _Py_atomic_store_ssize(&id->index, index);
2062
0
        }
2063
0
        PyMutex_Unlock(&rt_ids->mutex);
2064
0
    }
2065
0
    assert(index >= 0);
2066
2067
0
    PyObject *obj;
2068
0
    if (index < ids->size) {
2069
0
        obj = ids->array[index];
2070
0
        if (obj) {
2071
            // Return a borrowed reference
2072
0
            goto end;
2073
0
        }
2074
0
    }
2075
2076
0
    obj = PyUnicode_DecodeUTF8Stateful(id->string, strlen(id->string),
2077
0
                                       NULL, NULL);
2078
0
    if (!obj) {
2079
0
        goto end;
2080
0
    }
2081
0
    _PyUnicode_InternImmortal(interp, &obj);
2082
2083
0
    if (index >= ids->size) {
2084
        // Overallocate to reduce the number of realloc
2085
0
        Py_ssize_t new_size = Py_MAX(index * 2, 16);
2086
0
        Py_ssize_t item_size = sizeof(ids->array[0]);
2087
0
        PyObject **new_array = PyMem_Realloc(ids->array, new_size * item_size);
2088
0
        if (new_array == NULL) {
2089
0
            PyErr_NoMemory();
2090
0
            obj = NULL;
2091
0
            goto end;
2092
0
        }
2093
0
        memset(&new_array[ids->size], 0, (new_size - ids->size) * item_size);
2094
0
        ids->array = new_array;
2095
0
        ids->size = new_size;
2096
0
    }
2097
2098
    // The array stores a strong reference
2099
0
    ids->array[index] = obj;
2100
2101
0
end:
2102
0
    PyMutex_Unlock((PyMutex *)&id->mutex);
2103
    // Return a borrowed reference
2104
0
    return obj;
2105
0
}
2106
2107
2108
static void
2109
unicode_clear_identifiers(struct _Py_unicode_state *state)
2110
0
{
2111
0
    struct _Py_unicode_ids *ids = &state->ids;
2112
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
2113
0
        Py_XDECREF(ids->array[i]);
2114
0
    }
2115
0
    ids->size = 0;
2116
0
    PyMem_Free(ids->array);
2117
0
    ids->array = NULL;
2118
    // Don't reset _PyRuntime next_index: _Py_Identifier.id remains valid
2119
    // after Py_Finalize().
2120
0
}
2121
2122
2123
/* Internal function, doesn't check maximum character */
2124
2125
PyObject*
2126
_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
2127
109M
{
2128
109M
    const unsigned char *s = (const unsigned char *)buffer;
2129
109M
    PyObject *unicode;
2130
109M
    if (size == 1) {
2131
#ifdef Py_DEBUG
2132
        assert((unsigned char)s[0] < 128);
2133
#endif
2134
42.1M
        return get_latin1_char(s[0]);
2135
42.1M
    }
2136
67.4M
    unicode = PyUnicode_New(size, 127);
2137
67.4M
    if (!unicode)
2138
0
        return NULL;
2139
67.4M
    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2140
67.4M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
2141
67.4M
    return unicode;
2142
67.4M
}
2143
2144
static Py_UCS4
2145
kind_maxchar_limit(int kind)
2146
0
{
2147
0
    switch (kind) {
2148
0
    case PyUnicode_1BYTE_KIND:
2149
0
        return 0x80;
2150
0
    case PyUnicode_2BYTE_KIND:
2151
0
        return 0x100;
2152
0
    case PyUnicode_4BYTE_KIND:
2153
0
        return 0x10000;
2154
0
    default:
2155
0
        Py_UNREACHABLE();
2156
0
    }
2157
0
}
2158
2159
static PyObject*
2160
_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
2161
52.7M
{
2162
52.7M
    PyObject *res;
2163
52.7M
    unsigned char max_char;
2164
2165
52.7M
    if (size == 0) {
2166
10.7M
        _Py_RETURN_UNICODE_EMPTY();
2167
10.7M
    }
2168
52.7M
    assert(size > 0);
2169
42.0M
    if (size == 1) {
2170
11.2M
        return get_latin1_char(u[0]);
2171
11.2M
    }
2172
2173
30.7M
    max_char = ucs1lib_find_max_char(u, u + size);
2174
30.7M
    res = PyUnicode_New(size, max_char);
2175
30.7M
    if (!res)
2176
0
        return NULL;
2177
30.7M
    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
2178
30.7M
    assert(_PyUnicode_CheckConsistency(res, 1));
2179
30.7M
    return res;
2180
30.7M
}
2181
2182
static PyObject*
2183
_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
2184
108M
{
2185
108M
    PyObject *res;
2186
108M
    Py_UCS2 max_char;
2187
2188
108M
    if (size == 0)
2189
14.2M
        _Py_RETURN_UNICODE_EMPTY();
2190
108M
    assert(size > 0);
2191
94.4M
    if (size == 1)
2192
66.8M
        return unicode_char(u[0]);
2193
2194
27.6M
    max_char = ucs2lib_find_max_char(u, u + size);
2195
27.6M
    res = PyUnicode_New(size, max_char);
2196
27.6M
    if (!res)
2197
0
        return NULL;
2198
27.6M
    if (max_char >= 256)
2199
17.1M
        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
2200
10.5M
    else {
2201
10.5M
        _PyUnicode_CONVERT_BYTES(
2202
10.5M
            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2203
10.5M
    }
2204
27.6M
    assert(_PyUnicode_CheckConsistency(res, 1));
2205
27.6M
    return res;
2206
27.6M
}
2207
2208
static PyObject*
2209
_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
2210
71.3M
{
2211
71.3M
    PyObject *res;
2212
71.3M
    Py_UCS4 max_char;
2213
2214
71.3M
    if (size == 0)
2215
11.2M
        _Py_RETURN_UNICODE_EMPTY();
2216
71.3M
    assert(size > 0);
2217
60.0M
    if (size == 1)
2218
43.4M
        return unicode_char(u[0]);
2219
2220
16.6M
    max_char = ucs4lib_find_max_char(u, u + size);
2221
16.6M
    res = PyUnicode_New(size, max_char);
2222
16.6M
    if (!res)
2223
0
        return NULL;
2224
16.6M
    if (max_char < 256)
2225
11.7M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2226
16.6M
                                 PyUnicode_1BYTE_DATA(res));
2227
4.87M
    else if (max_char < 0x10000)
2228
3.34M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2229
4.87M
                                 PyUnicode_2BYTE_DATA(res));
2230
1.53M
    else
2231
1.53M
        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
2232
16.6M
    assert(_PyUnicode_CheckConsistency(res, 1));
2233
16.6M
    return res;
2234
16.6M
}
2235
2236
2237
int
2238
PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *pub_writer,
2239
                          const Py_UCS4 *str,
2240
                          Py_ssize_t size)
2241
10.6k
{
2242
10.6k
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
2243
2244
10.6k
    if (size < 0) {
2245
0
        PyErr_SetString(PyExc_ValueError,
2246
0
                        "size must be positive");
2247
0
        return -1;
2248
0
    }
2249
2250
10.6k
    if (size == 0) {
2251
0
        return 0;
2252
0
    }
2253
2254
10.6k
    Py_UCS4 max_char = ucs4lib_find_max_char(str, str + size);
2255
2256
10.6k
    if (_PyUnicodeWriter_Prepare(writer, size, max_char) < 0) {
2257
0
        return -1;
2258
0
    }
2259
2260
10.6k
    int kind = writer->kind;
2261
10.6k
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2262
10.6k
    if (kind == PyUnicode_1BYTE_KIND) {
2263
1.34k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1,
2264
1.34k
                                 str, str + size,
2265
1.34k
                                 data);
2266
1.34k
    }
2267
9.26k
    else if (kind == PyUnicode_2BYTE_KIND) {
2268
9.25k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2,
2269
9.25k
                                 str, str + size,
2270
9.25k
                                 data);
2271
9.25k
    }
2272
1
    else {
2273
1
        memcpy(data, str, size * sizeof(Py_UCS4));
2274
1
    }
2275
10.6k
    writer->pos += size;
2276
2277
10.6k
    return 0;
2278
10.6k
}
2279
2280
2281
PyObject*
2282
PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2283
170M
{
2284
170M
    if (size < 0) {
2285
0
        PyErr_SetString(PyExc_ValueError, "size must be positive");
2286
0
        return NULL;
2287
0
    }
2288
170M
    switch (kind) {
2289
22.8M
    case PyUnicode_1BYTE_KIND:
2290
22.8M
        return _PyUnicode_FromUCS1(buffer, size);
2291
91.7M
    case PyUnicode_2BYTE_KIND:
2292
91.7M
        return _PyUnicode_FromUCS2(buffer, size);
2293
55.4M
    case PyUnicode_4BYTE_KIND:
2294
55.4M
        return _PyUnicode_FromUCS4(buffer, size);
2295
0
    default:
2296
0
        PyErr_SetString(PyExc_SystemError, "invalid kind");
2297
0
        return NULL;
2298
170M
    }
2299
170M
}
2300
2301
Py_UCS4
2302
_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2303
11.3M
{
2304
11.3M
    int kind;
2305
11.3M
    const void *startptr, *endptr;
2306
2307
11.3M
    assert(0 <= start);
2308
11.3M
    assert(end <= PyUnicode_GET_LENGTH(unicode));
2309
11.3M
    assert(start <= end);
2310
2311
11.3M
    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2312
77.5k
        return PyUnicode_MAX_CHAR_VALUE(unicode);
2313
2314
11.3M
    if (start == end)
2315
0
        return 127;
2316
2317
11.3M
    if (PyUnicode_IS_ASCII(unicode))
2318
11.2M
        return 127;
2319
2320
24.2k
    kind = PyUnicode_KIND(unicode);
2321
24.2k
    startptr = PyUnicode_DATA(unicode);
2322
24.2k
    endptr = (char *)startptr + end * kind;
2323
24.2k
    startptr = (char *)startptr + start * kind;
2324
24.2k
    switch(kind) {
2325
1.97k
    case PyUnicode_1BYTE_KIND:
2326
1.97k
        return ucs1lib_find_max_char(startptr, endptr);
2327
5.85k
    case PyUnicode_2BYTE_KIND:
2328
5.85k
        return ucs2lib_find_max_char(startptr, endptr);
2329
16.4k
    case PyUnicode_4BYTE_KIND:
2330
16.4k
        return ucs4lib_find_max_char(startptr, endptr);
2331
0
    default:
2332
0
        Py_UNREACHABLE();
2333
24.2k
    }
2334
24.2k
}
2335
2336
/* Ensure that a string uses the most efficient storage, if it is not the
2337
   case: create a new string with of the right kind. Write NULL into *p_unicode
2338
   on error. */
2339
static void
2340
unicode_adjust_maxchar(PyObject **p_unicode)
2341
0
{
2342
0
    PyObject *unicode, *copy;
2343
0
    Py_UCS4 max_char;
2344
0
    Py_ssize_t len;
2345
0
    int kind;
2346
2347
0
    assert(p_unicode != NULL);
2348
0
    unicode = *p_unicode;
2349
0
    if (PyUnicode_IS_ASCII(unicode))
2350
0
        return;
2351
2352
0
    len = PyUnicode_GET_LENGTH(unicode);
2353
0
    kind = PyUnicode_KIND(unicode);
2354
0
    if (kind == PyUnicode_1BYTE_KIND) {
2355
0
        const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
2356
0
        max_char = ucs1lib_find_max_char(u, u + len);
2357
0
        if (max_char >= 128)
2358
0
            return;
2359
0
    }
2360
0
    else if (kind == PyUnicode_2BYTE_KIND) {
2361
0
        const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
2362
0
        max_char = ucs2lib_find_max_char(u, u + len);
2363
0
        if (max_char >= 256)
2364
0
            return;
2365
0
    }
2366
0
    else if (kind == PyUnicode_4BYTE_KIND) {
2367
0
        const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
2368
0
        max_char = ucs4lib_find_max_char(u, u + len);
2369
0
        if (max_char >= 0x10000)
2370
0
            return;
2371
0
    }
2372
0
    else
2373
0
        Py_UNREACHABLE();
2374
2375
0
    copy = PyUnicode_New(len, max_char);
2376
0
    if (copy != NULL)
2377
0
        _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
2378
0
    Py_DECREF(unicode);
2379
0
    *p_unicode = copy;
2380
0
}
2381
2382
PyObject*
2383
_PyUnicode_Copy(PyObject *unicode)
2384
3.26M
{
2385
3.26M
    Py_ssize_t length;
2386
3.26M
    PyObject *copy;
2387
2388
3.26M
    if (!PyUnicode_Check(unicode)) {
2389
0
        PyErr_BadInternalCall();
2390
0
        return NULL;
2391
0
    }
2392
2393
3.26M
    length = PyUnicode_GET_LENGTH(unicode);
2394
3.26M
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
2395
3.26M
    if (!copy)
2396
0
        return NULL;
2397
3.26M
    assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2398
2399
3.26M
    memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2400
3.26M
              length * PyUnicode_KIND(unicode));
2401
3.26M
    assert(_PyUnicode_CheckConsistency(copy, 1));
2402
3.26M
    return copy;
2403
3.26M
}
2404
2405
2406
/* Widen Unicode objects to larger buffers. Don't write terminating null
2407
   character. Return NULL on error. */
2408
2409
static void*
2410
unicode_askind(int skind, void const *data, Py_ssize_t len, int kind)
2411
7.46M
{
2412
7.46M
    void *result;
2413
2414
7.46M
    assert(skind < kind);
2415
7.46M
    switch (kind) {
2416
4.83M
    case PyUnicode_2BYTE_KIND:
2417
4.83M
        result = PyMem_New(Py_UCS2, len);
2418
4.83M
        if (!result)
2419
0
            return PyErr_NoMemory();
2420
4.83M
        assert(skind == PyUnicode_1BYTE_KIND);
2421
4.83M
        _PyUnicode_CONVERT_BYTES(
2422
4.83M
            Py_UCS1, Py_UCS2,
2423
4.83M
            (const Py_UCS1 *)data,
2424
4.83M
            ((const Py_UCS1 *)data) + len,
2425
4.83M
            result);
2426
4.83M
        return result;
2427
2.62M
    case PyUnicode_4BYTE_KIND:
2428
2.62M
        result = PyMem_New(Py_UCS4, len);
2429
2.62M
        if (!result)
2430
0
            return PyErr_NoMemory();
2431
2.62M
        if (skind == PyUnicode_2BYTE_KIND) {
2432
0
            _PyUnicode_CONVERT_BYTES(
2433
0
                Py_UCS2, Py_UCS4,
2434
0
                (const Py_UCS2 *)data,
2435
0
                ((const Py_UCS2 *)data) + len,
2436
0
                result);
2437
0
        }
2438
2.62M
        else {
2439
2.62M
            assert(skind == PyUnicode_1BYTE_KIND);
2440
2.62M
            _PyUnicode_CONVERT_BYTES(
2441
2.62M
                Py_UCS1, Py_UCS4,
2442
2.62M
                (const Py_UCS1 *)data,
2443
2.62M
                ((const Py_UCS1 *)data) + len,
2444
2.62M
                result);
2445
2.62M
        }
2446
2.62M
        return result;
2447
0
    default:
2448
0
        Py_UNREACHABLE();
2449
0
        return NULL;
2450
7.46M
    }
2451
7.46M
}
2452
2453
static Py_UCS4*
2454
as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2455
        int copy_null)
2456
71.4k
{
2457
71.4k
    int kind;
2458
71.4k
    const void *data;
2459
71.4k
    Py_ssize_t len, targetlen;
2460
71.4k
    kind = PyUnicode_KIND(string);
2461
71.4k
    data = PyUnicode_DATA(string);
2462
71.4k
    len = PyUnicode_GET_LENGTH(string);
2463
71.4k
    targetlen = len;
2464
71.4k
    if (copy_null)
2465
0
        targetlen++;
2466
71.4k
    if (!target) {
2467
0
        target = PyMem_New(Py_UCS4, targetlen);
2468
0
        if (!target) {
2469
0
            PyErr_NoMemory();
2470
0
            return NULL;
2471
0
        }
2472
0
    }
2473
71.4k
    else {
2474
71.4k
        if (targetsize < targetlen) {
2475
0
            PyErr_Format(PyExc_SystemError,
2476
0
                         "string is longer than the buffer");
2477
0
            if (copy_null && 0 < targetsize)
2478
0
                target[0] = 0;
2479
0
            return NULL;
2480
0
        }
2481
71.4k
    }
2482
71.4k
    if (kind == PyUnicode_1BYTE_KIND) {
2483
53.3k
        const Py_UCS1 *start = (const Py_UCS1 *) data;
2484
53.3k
        _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
2485
53.3k
    }
2486
18.0k
    else if (kind == PyUnicode_2BYTE_KIND) {
2487
13.5k
        const Py_UCS2 *start = (const Py_UCS2 *) data;
2488
13.5k
        _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2489
13.5k
    }
2490
4.50k
    else if (kind == PyUnicode_4BYTE_KIND) {
2491
4.50k
        memcpy(target, data, len * sizeof(Py_UCS4));
2492
4.50k
    }
2493
0
    else {
2494
0
        Py_UNREACHABLE();
2495
0
    }
2496
71.4k
    if (copy_null)
2497
0
        target[len] = 0;
2498
71.4k
    return target;
2499
71.4k
}
2500
2501
Py_UCS4*
2502
PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2503
                 int copy_null)
2504
71.4k
{
2505
71.4k
    if (target == NULL || targetsize < 0) {
2506
0
        PyErr_BadInternalCall();
2507
0
        return NULL;
2508
0
    }
2509
71.4k
    return as_ucs4(string, target, targetsize, copy_null);
2510
71.4k
}
2511
2512
Py_UCS4*
2513
PyUnicode_AsUCS4Copy(PyObject *string)
2514
0
{
2515
0
    return as_ucs4(string, NULL, 0, 1);
2516
0
}
2517
2518
/* maximum number of characters required for output of %jo or %jd or %p.
2519
   We need at most ceil(log8(256)*sizeof(intmax_t)) digits,
2520
   plus 1 for the sign, plus 2 for the 0x prefix (for %p),
2521
   plus 1 for the terminal NUL. */
2522
#define MAX_INTMAX_CHARS (5 + (sizeof(intmax_t)*8-1) / 3)
2523
2524
static int
2525
unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2526
                             Py_ssize_t width, Py_ssize_t precision, int flags)
2527
7.69M
{
2528
7.69M
    Py_ssize_t length, fill, arglen;
2529
7.69M
    Py_UCS4 maxchar;
2530
2531
7.69M
    length = PyUnicode_GET_LENGTH(str);
2532
7.69M
    if ((precision == -1 || precision >= length)
2533
7.69M
        && width <= length)
2534
7.69M
        return _PyUnicodeWriter_WriteStr(writer, str);
2535
2536
47
    if (precision != -1)
2537
47
        length = Py_MIN(precision, length);
2538
2539
47
    arglen = Py_MAX(length, width);
2540
47
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2541
19
        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2542
28
    else
2543
28
        maxchar = writer->maxchar;
2544
2545
47
    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2546
0
        return -1;
2547
2548
47
    fill = Py_MAX(width - length, 0);
2549
47
    if (fill && !(flags & F_LJUST)) {
2550
0
        if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2551
0
            return -1;
2552
0
        writer->pos += fill;
2553
0
    }
2554
2555
47
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2556
47
                                  str, 0, length);
2557
47
    writer->pos += length;
2558
2559
47
    if (fill && (flags & F_LJUST)) {
2560
0
        if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2561
0
            return -1;
2562
0
        writer->pos += fill;
2563
0
    }
2564
2565
47
    return 0;
2566
47
}
2567
2568
static int
2569
unicode_fromformat_write_utf8(_PyUnicodeWriter *writer, const char *str,
2570
                              Py_ssize_t width, Py_ssize_t precision, int flags)
2571
3.57M
{
2572
    /* UTF-8 */
2573
3.57M
    Py_ssize_t *pconsumed = NULL;
2574
3.57M
    Py_ssize_t length;
2575
3.57M
    if (precision == -1) {
2576
810k
        length = strlen(str);
2577
810k
    }
2578
2.76M
    else {
2579
2.76M
        length = 0;
2580
43.9M
        while (length < precision && str[length]) {
2581
41.1M
            length++;
2582
41.1M
        }
2583
2.76M
        if (length == precision) {
2584
            /* The input string is not NUL-terminated.  If it ends with an
2585
             * incomplete UTF-8 sequence, truncate the string just before it.
2586
             * Incomplete sequences in the middle and sequences which cannot
2587
             * be valid prefixes are still treated as errors and replaced
2588
             * with \xfffd. */
2589
2.92k
            pconsumed = &length;
2590
2.92k
        }
2591
2.76M
    }
2592
2593
3.57M
    if (width < 0) {
2594
3.57M
        return _PyUnicode_DecodeUTF8Writer(writer, str, length,
2595
3.57M
                                           _Py_ERROR_REPLACE, "replace", pconsumed);
2596
3.57M
    }
2597
2598
0
    PyObject *unicode = PyUnicode_DecodeUTF8Stateful(str, length,
2599
0
                                                     "replace", pconsumed);
2600
0
    if (unicode == NULL)
2601
0
        return -1;
2602
2603
0
    int res = unicode_fromformat_write_str(writer, unicode,
2604
0
                                           width, -1, flags);
2605
0
    Py_DECREF(unicode);
2606
0
    return res;
2607
0
}
2608
2609
static int
2610
unicode_fromformat_write_wcstr(_PyUnicodeWriter *writer, const wchar_t *str,
2611
                              Py_ssize_t width, Py_ssize_t precision, int flags)
2612
0
{
2613
0
    Py_ssize_t length;
2614
0
    if (precision == -1) {
2615
0
        length = wcslen(str);
2616
0
    }
2617
0
    else {
2618
0
        length = 0;
2619
0
        while (length < precision && str[length]) {
2620
0
            length++;
2621
0
        }
2622
0
    }
2623
2624
0
    if (width < 0) {
2625
0
        return PyUnicodeWriter_WriteWideChar((PyUnicodeWriter*)writer,
2626
0
                                             str, length);
2627
0
    }
2628
2629
0
    PyObject *unicode = PyUnicode_FromWideChar(str, length);
2630
0
    if (unicode == NULL)
2631
0
        return -1;
2632
2633
0
    int res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
2634
0
    Py_DECREF(unicode);
2635
0
    return res;
2636
0
}
2637
2638
0
#define F_LONG 1
2639
0
#define F_LONGLONG 2
2640
250k
#define F_SIZE 3
2641
0
#define F_PTRDIFF 4
2642
0
#define F_INTMAX 5
2643
2644
static const char*
2645
unicode_fromformat_arg(_PyUnicodeWriter *writer,
2646
                       const char *f, va_list *vargs)
2647
26.1M
{
2648
26.1M
    const char *p;
2649
26.1M
    Py_ssize_t len;
2650
26.1M
    int flags = 0;
2651
26.1M
    Py_ssize_t width;
2652
26.1M
    Py_ssize_t precision;
2653
2654
26.1M
    p = f;
2655
26.1M
    f++;
2656
26.1M
    if (*f == '%') {
2657
950k
        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
2658
0
            return NULL;
2659
950k
        f++;
2660
950k
        return f;
2661
950k
    }
2662
2663
    /* Parse flags. Example: "%-i" => flags=F_LJUST. */
2664
    /* Flags '+', ' ' and '#' are not particularly useful.
2665
     * They are not worth the implementation and maintenance costs.
2666
     * In addition, '#' should add "0" for "o" conversions for compatibility
2667
     * with printf, but it would confuse Python users. */
2668
25.1M
    while (1) {
2669
25.1M
        switch (*f++) {
2670
0
        case '-': flags |= F_LJUST; continue;
2671
1.72k
        case '0': flags |= F_ZERO; continue;
2672
0
        case '#': flags |= F_ALT; continue;
2673
25.1M
        }
2674
25.1M
        f--;
2675
25.1M
        break;
2676
25.1M
    }
2677
2678
    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2679
25.1M
    width = -1;
2680
25.1M
    if (*f == '*') {
2681
0
        width = va_arg(*vargs, int);
2682
0
        if (width < 0) {
2683
0
            flags |= F_LJUST;
2684
0
            width = -width;
2685
0
        }
2686
0
        f++;
2687
0
    }
2688
25.1M
    else if (Py_ISDIGIT((unsigned)*f)) {
2689
1.72k
        width = *f - '0';
2690
1.72k
        f++;
2691
1.72k
        while (Py_ISDIGIT((unsigned)*f)) {
2692
0
            if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2693
0
                PyErr_SetString(PyExc_ValueError,
2694
0
                                "width too big");
2695
0
                return NULL;
2696
0
            }
2697
0
            width = (width * 10) + (*f - '0');
2698
0
            f++;
2699
0
        }
2700
1.72k
    }
2701
25.1M
    precision = -1;
2702
25.1M
    if (*f == '.') {
2703
5.36M
        f++;
2704
5.36M
        if (*f == '*') {
2705
0
            precision = va_arg(*vargs, int);
2706
0
            if (precision < 0) {
2707
0
                precision = -2;
2708
0
            }
2709
0
            f++;
2710
0
        }
2711
5.36M
        else if (Py_ISDIGIT((unsigned)*f)) {
2712
5.36M
            precision = (*f - '0');
2713
5.36M
            f++;
2714
16.0M
            while (Py_ISDIGIT((unsigned)*f)) {
2715
10.7M
                if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2716
0
                    PyErr_SetString(PyExc_ValueError,
2717
0
                                    "precision too big");
2718
0
                    return NULL;
2719
0
                }
2720
10.7M
                precision = (precision * 10) + (*f - '0');
2721
10.7M
                f++;
2722
10.7M
            }
2723
5.36M
        }
2724
5.36M
    }
2725
2726
25.1M
    int sizemod = 0;
2727
25.1M
    if (*f == 'l') {
2728
0
        if (f[1] == 'l') {
2729
0
            sizemod = F_LONGLONG;
2730
0
            f += 2;
2731
0
        }
2732
0
        else {
2733
0
            sizemod = F_LONG;
2734
0
            ++f;
2735
0
        }
2736
0
    }
2737
25.1M
    else if (*f == 'z') {
2738
125k
        sizemod = F_SIZE;
2739
125k
        ++f;
2740
125k
    }
2741
25.0M
    else if (*f == 't') {
2742
0
        sizemod = F_PTRDIFF;
2743
0
        ++f;
2744
0
    }
2745
25.0M
    else if (*f == 'j') {
2746
0
        sizemod = F_INTMAX;
2747
0
        ++f;
2748
0
    }
2749
25.1M
    if (f[0] != '\0' && f[1] == '\0')
2750
4.18M
        writer->overallocate = 0;
2751
2752
25.1M
    switch (*f) {
2753
12.4M
    case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
2754
12.4M
        break;
2755
1.42M
    case 'c': case 'p':
2756
1.42M
        if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
2757
1.42M
        break;
2758
3.57M
    case 's':
2759
3.57M
    case 'V':
2760
3.57M
        if (sizemod && sizemod != F_LONG) goto invalid_format;
2761
3.57M
        break;
2762
7.69M
    default:
2763
7.69M
        if (sizemod) goto invalid_format;
2764
7.69M
        break;
2765
25.1M
    }
2766
2767
25.1M
    switch (*f) {
2768
1.41M
    case 'c':
2769
1.41M
    {
2770
1.41M
        int ordinal = va_arg(*vargs, int);
2771
1.41M
        if (ordinal < 0 || ordinal > MAX_UNICODE) {
2772
0
            PyErr_SetString(PyExc_OverflowError,
2773
0
                            "character argument not in range(0x110000)");
2774
0
            return NULL;
2775
0
        }
2776
1.41M
        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
2777
0
            return NULL;
2778
1.41M
        break;
2779
1.41M
    }
2780
2781
12.4M
    case 'd': case 'i':
2782
12.4M
    case 'o': case 'u': case 'x': case 'X':
2783
12.4M
    {
2784
12.4M
        char buffer[MAX_INTMAX_CHARS];
2785
2786
        // Fill buffer using sprinf, with one of many possible format
2787
        // strings, like "%llX" for `long long` in hexadecimal.
2788
        // The type/size is in `sizemod`; the format is in `*f`.
2789
2790
        // Use macros with nested switches to keep the sprintf format strings
2791
        // as compile-time literals, avoiding warnings and maybe allowing
2792
        // optimizations.
2793
2794
        // `SPRINT` macro does one sprintf
2795
        // Example usage: SPRINT("l", "X", unsigned long) expands to
2796
        // sprintf(buffer, "%" "l" "X", va_arg(*vargs, unsigned long))
2797
12.4M
        #define SPRINT(SIZE_SPEC, FMT_CHAR, TYPE) \
2798
12.4M
            sprintf(buffer, "%" SIZE_SPEC FMT_CHAR, va_arg(*vargs, TYPE))
2799
2800
        // One inner switch to handle all format variants
2801
12.4M
        #define DO_SPRINTS(SIZE_SPEC, SIGNED_TYPE, UNSIGNED_TYPE)             \
2802
12.4M
            switch (*f) {                                                     \
2803
91
                case 'o': len = SPRINT(SIZE_SPEC, "o", UNSIGNED_TYPE); break; \
2804
21.2k
                case 'u': len = SPRINT(SIZE_SPEC, "u", UNSIGNED_TYPE); break; \
2805
1.35k
                case 'x': len = SPRINT(SIZE_SPEC, "x", UNSIGNED_TYPE); break; \
2806
971
                case 'X': len = SPRINT(SIZE_SPEC, "X", UNSIGNED_TYPE); break; \
2807
12.4M
                default:  len = SPRINT(SIZE_SPEC, "d", SIGNED_TYPE); break;   \
2808
12.4M
            }
2809
2810
        // Outer switch to handle all the sizes/types
2811
12.4M
        switch (sizemod) {
2812
0
            case F_LONG:     DO_SPRINTS("l", long, unsigned long); break;
2813
0
            case F_LONGLONG: DO_SPRINTS("ll", long long, unsigned long long); break;
2814
125k
            case F_SIZE:     DO_SPRINTS("z", Py_ssize_t, size_t); break;
2815
0
            case F_PTRDIFF:  DO_SPRINTS("t", ptrdiff_t, ptrdiff_t); break;
2816
0
            case F_INTMAX:   DO_SPRINTS("j", intmax_t, uintmax_t); break;
2817
12.3M
            default:         DO_SPRINTS("", int, unsigned int); break;
2818
12.4M
        }
2819
12.4M
        #undef SPRINT
2820
12.4M
        #undef DO_SPRINTS
2821
2822
12.4M
        assert(len >= 0);
2823
2824
12.4M
        int sign = (buffer[0] == '-');
2825
12.4M
        len -= sign;
2826
2827
12.4M
        precision = Py_MAX(precision, len);
2828
12.4M
        width = Py_MAX(width, precision + sign);
2829
12.4M
        if ((flags & F_ZERO) && !(flags & F_LJUST)) {
2830
1.72k
            precision = width - sign;
2831
1.72k
        }
2832
2833
12.4M
        Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
2834
12.4M
        Py_ssize_t zeropad = Py_MAX(precision - len, 0);
2835
2836
12.4M
        if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1)
2837
0
            return NULL;
2838
2839
12.4M
        if (spacepad && !(flags & F_LJUST)) {
2840
0
            if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
2841
0
                return NULL;
2842
0
            writer->pos += spacepad;
2843
0
        }
2844
2845
12.4M
        if (sign) {
2846
760
            if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
2847
0
                return NULL;
2848
760
        }
2849
2850
12.4M
        if (zeropad) {
2851
673
            if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
2852
0
                return NULL;
2853
673
            writer->pos += zeropad;
2854
673
        }
2855
2856
12.4M
        if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
2857
0
            return NULL;
2858
2859
12.4M
        if (spacepad && (flags & F_LJUST)) {
2860
0
            if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
2861
0
                return NULL;
2862
0
            writer->pos += spacepad;
2863
0
        }
2864
12.4M
        break;
2865
12.4M
    }
2866
2867
12.4M
    case 'p':
2868
2.92k
    {
2869
2.92k
        char number[MAX_INTMAX_CHARS];
2870
2871
2.92k
        len = sprintf(number, "%p", va_arg(*vargs, void*));
2872
2.92k
        assert(len >= 0);
2873
2874
        /* %p is ill-defined:  ensure leading 0x. */
2875
2.92k
        if (number[1] == 'X')
2876
0
            number[1] = 'x';
2877
2.92k
        else if (number[1] != 'x') {
2878
0
            memmove(number + 2, number,
2879
0
                    strlen(number) + 1);
2880
0
            number[0] = '0';
2881
0
            number[1] = 'x';
2882
0
            len += 2;
2883
0
        }
2884
2885
2.92k
        if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
2886
0
            return NULL;
2887
2.92k
        break;
2888
2.92k
    }
2889
2890
3.57M
    case 's':
2891
3.57M
    {
2892
3.57M
        if (sizemod) {
2893
0
            const wchar_t *s = va_arg(*vargs, const wchar_t*);
2894
0
            if (unicode_fromformat_write_wcstr(writer, s, width, precision, flags) < 0)
2895
0
                return NULL;
2896
0
        }
2897
3.57M
        else {
2898
            /* UTF-8 */
2899
3.57M
            const char *s = va_arg(*vargs, const char*);
2900
3.57M
            if (unicode_fromformat_write_utf8(writer, s, width, precision, flags) < 0)
2901
0
                return NULL;
2902
3.57M
        }
2903
3.57M
        break;
2904
3.57M
    }
2905
2906
3.67M
    case 'U':
2907
3.67M
    {
2908
3.67M
        PyObject *obj = va_arg(*vargs, PyObject *);
2909
3.67M
        assert(obj && _PyUnicode_CHECK(obj));
2910
2911
3.67M
        if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2912
0
            return NULL;
2913
3.67M
        break;
2914
3.67M
    }
2915
2916
3.67M
    case 'V':
2917
603
    {
2918
603
        PyObject *obj = va_arg(*vargs, PyObject *);
2919
603
        const char *str;
2920
603
        const wchar_t *wstr;
2921
603
        if (sizemod) {
2922
0
            wstr = va_arg(*vargs, const wchar_t*);
2923
0
        }
2924
603
        else {
2925
603
            str = va_arg(*vargs, const char *);
2926
603
        }
2927
603
        if (obj) {
2928
0
            assert(_PyUnicode_CHECK(obj));
2929
0
            if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2930
0
                return NULL;
2931
0
        }
2932
603
        else if (sizemod) {
2933
0
            assert(wstr != NULL);
2934
0
            if (unicode_fromformat_write_wcstr(writer, wstr, width, precision, flags) < 0)
2935
0
                return NULL;
2936
0
        }
2937
603
        else {
2938
603
            assert(str != NULL);
2939
603
            if (unicode_fromformat_write_utf8(writer, str, width, precision, flags) < 0)
2940
0
                return NULL;
2941
603
        }
2942
603
        break;
2943
603
    }
2944
2945
1.44k
    case 'S':
2946
1.44k
    {
2947
1.44k
        PyObject *obj = va_arg(*vargs, PyObject *);
2948
1.44k
        PyObject *str;
2949
1.44k
        assert(obj);
2950
1.44k
        str = PyObject_Str(obj);
2951
1.44k
        if (!str)
2952
0
            return NULL;
2953
1.44k
        if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
2954
0
            Py_DECREF(str);
2955
0
            return NULL;
2956
0
        }
2957
1.44k
        Py_DECREF(str);
2958
1.44k
        break;
2959
1.44k
    }
2960
2961
2.60M
    case 'R':
2962
2.60M
    {
2963
2.60M
        PyObject *obj = va_arg(*vargs, PyObject *);
2964
2.60M
        PyObject *repr;
2965
2.60M
        assert(obj);
2966
2.60M
        repr = PyObject_Repr(obj);
2967
2.60M
        if (!repr)
2968
0
            return NULL;
2969
2.60M
        if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
2970
0
            Py_DECREF(repr);
2971
0
            return NULL;
2972
0
        }
2973
2.60M
        Py_DECREF(repr);
2974
2.60M
        break;
2975
2.60M
    }
2976
2977
0
    case 'A':
2978
0
    {
2979
0
        PyObject *obj = va_arg(*vargs, PyObject *);
2980
0
        PyObject *ascii;
2981
0
        assert(obj);
2982
0
        ascii = PyObject_ASCII(obj);
2983
0
        if (!ascii)
2984
0
            return NULL;
2985
0
        if (unicode_fromformat_write_str(writer, ascii, width, precision, flags) == -1) {
2986
0
            Py_DECREF(ascii);
2987
0
            return NULL;
2988
0
        }
2989
0
        Py_DECREF(ascii);
2990
0
        break;
2991
0
    }
2992
2993
1.40M
    case 'T':
2994
1.40M
    {
2995
1.40M
        PyObject *obj = va_arg(*vargs, PyObject *);
2996
1.40M
        PyTypeObject *type = (PyTypeObject *)Py_NewRef(Py_TYPE(obj));
2997
2998
1.40M
        PyObject *type_name;
2999
1.40M
        if (flags & F_ALT) {
3000
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3001
0
        }
3002
1.40M
        else {
3003
1.40M
            type_name = PyType_GetFullyQualifiedName(type);
3004
1.40M
        }
3005
1.40M
        Py_DECREF(type);
3006
1.40M
        if (!type_name) {
3007
0
            return NULL;
3008
0
        }
3009
3010
1.40M
        if (unicode_fromformat_write_str(writer, type_name,
3011
1.40M
                                         width, precision, flags) == -1) {
3012
0
            Py_DECREF(type_name);
3013
0
            return NULL;
3014
0
        }
3015
1.40M
        Py_DECREF(type_name);
3016
1.40M
        break;
3017
1.40M
    }
3018
3019
0
    case 'N':
3020
0
    {
3021
0
        PyObject *type_raw = va_arg(*vargs, PyObject *);
3022
0
        assert(type_raw != NULL);
3023
3024
0
        if (!PyType_Check(type_raw)) {
3025
0
            PyErr_SetString(PyExc_TypeError, "%N argument must be a type");
3026
0
            return NULL;
3027
0
        }
3028
0
        PyTypeObject *type = (PyTypeObject*)type_raw;
3029
3030
0
        PyObject *type_name;
3031
0
        if (flags & F_ALT) {
3032
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3033
0
        }
3034
0
        else {
3035
0
            type_name = PyType_GetFullyQualifiedName(type);
3036
0
        }
3037
0
        if (!type_name) {
3038
0
            return NULL;
3039
0
        }
3040
0
        if (unicode_fromformat_write_str(writer, type_name,
3041
0
                                         width, precision, flags) == -1) {
3042
0
            Py_DECREF(type_name);
3043
0
            return NULL;
3044
0
        }
3045
0
        Py_DECREF(type_name);
3046
0
        break;
3047
0
    }
3048
3049
0
    default:
3050
0
    invalid_format:
3051
0
        PyErr_Format(PyExc_SystemError, "invalid format string: %s", p);
3052
0
        return NULL;
3053
25.1M
    }
3054
3055
25.1M
    f++;
3056
25.1M
    return f;
3057
25.1M
}
3058
3059
static int
3060
unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
3061
12.5M
{
3062
12.5M
    Py_ssize_t len = strlen(format);
3063
12.5M
    writer->min_length += len + 100;
3064
12.5M
    writer->overallocate = 1;
3065
3066
    // Copy varags to be able to pass a reference to a subfunction.
3067
12.5M
    va_list vargs2;
3068
12.5M
    va_copy(vargs2, vargs);
3069
3070
    // _PyUnicodeWriter_WriteASCIIString() below requires the format string
3071
    // to be encoded to ASCII.
3072
12.5M
    int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)format, (Py_UCS1*)format + len) < 128);
3073
12.5M
    if (!is_ascii) {
3074
0
        Py_ssize_t i;
3075
0
        for (i=0; i < len && (unsigned char)format[i] <= 127; i++);
3076
0
        PyErr_Format(PyExc_ValueError,
3077
0
            "PyUnicode_FromFormatV() expects an ASCII-encoded format "
3078
0
            "string, got a non-ASCII byte: 0x%02x",
3079
0
            (unsigned char)format[i]);
3080
0
        goto fail;
3081
0
    }
3082
3083
70.6M
    for (const char *f = format; *f; ) {
3084
58.1M
        if (*f == '%') {
3085
26.1M
            f = unicode_fromformat_arg(writer, f, &vargs2);
3086
26.1M
            if (f == NULL)
3087
0
                goto fail;
3088
26.1M
        }
3089
31.9M
        else {
3090
31.9M
            const char *p = strchr(f, '%');
3091
31.9M
            if (p != NULL) {
3092
23.6M
                len = p - f;
3093
23.6M
            }
3094
8.32M
            else {
3095
8.32M
                len = strlen(f);
3096
8.32M
                writer->overallocate = 0;
3097
8.32M
            }
3098
3099
31.9M
            if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
3100
0
                goto fail;
3101
0
            }
3102
31.9M
            f += len;
3103
31.9M
        }
3104
58.1M
    }
3105
12.5M
    va_end(vargs2);
3106
12.5M
    return 0;
3107
3108
0
  fail:
3109
0
    va_end(vargs2);
3110
0
    return -1;
3111
12.5M
}
3112
3113
PyObject *
3114
PyUnicode_FromFormatV(const char *format, va_list vargs)
3115
12.5M
{
3116
12.5M
    _PyUnicodeWriter writer;
3117
12.5M
    _PyUnicodeWriter_Init(&writer);
3118
3119
12.5M
    if (unicode_from_format(&writer, format, vargs) < 0) {
3120
0
        _PyUnicodeWriter_Dealloc(&writer);
3121
0
        return NULL;
3122
0
    }
3123
12.5M
    return _PyUnicodeWriter_Finish(&writer);
3124
12.5M
}
3125
3126
PyObject *
3127
PyUnicode_FromFormat(const char *format, ...)
3128
510k
{
3129
510k
    PyObject* ret;
3130
510k
    va_list vargs;
3131
3132
510k
    va_start(vargs, format);
3133
510k
    ret = PyUnicode_FromFormatV(format, vargs);
3134
510k
    va_end(vargs);
3135
510k
    return ret;
3136
510k
}
3137
3138
int
3139
PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...)
3140
0
{
3141
0
    va_list vargs;
3142
0
    va_start(vargs, format);
3143
0
    int res = _PyUnicodeWriter_FormatV(writer, format, vargs);
3144
0
    va_end(vargs);
3145
0
    return res;
3146
0
}
3147
3148
int
3149
_PyUnicodeWriter_FormatV(PyUnicodeWriter *writer, const char *format,
3150
                         va_list vargs)
3151
0
{
3152
0
    _PyUnicodeWriter *_writer = (_PyUnicodeWriter*)writer;
3153
0
    Py_ssize_t old_pos = _writer->pos;
3154
3155
0
    int res = unicode_from_format(_writer, format, vargs);
3156
3157
0
    if (res < 0) {
3158
0
        _writer->pos = old_pos;
3159
0
    }
3160
0
    return res;
3161
0
}
3162
3163
static Py_ssize_t
3164
unicode_get_widechar_size(PyObject *unicode)
3165
162k
{
3166
162k
    Py_ssize_t res;
3167
3168
162k
    assert(unicode != NULL);
3169
162k
    assert(_PyUnicode_CHECK(unicode));
3170
3171
162k
    res = _PyUnicode_LENGTH(unicode);
3172
#if SIZEOF_WCHAR_T == 2
3173
    if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
3174
        const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3175
        const Py_UCS4 *end = s + res;
3176
        for (; s < end; ++s) {
3177
            if (*s > 0xFFFF) {
3178
                ++res;
3179
            }
3180
        }
3181
    }
3182
#endif
3183
162k
    return res;
3184
162k
}
3185
3186
static void
3187
unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3188
162k
{
3189
162k
    assert(unicode != NULL);
3190
162k
    assert(_PyUnicode_CHECK(unicode));
3191
3192
162k
    if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
3193
1.12k
        memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
3194
1.12k
        return;
3195
1.12k
    }
3196
3197
161k
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3198
137k
        const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3199
3.87M
        for (; size--; ++s, ++w) {
3200
3.73M
            *w = *s;
3201
3.73M
        }
3202
137k
    }
3203
23.7k
    else {
3204
23.7k
#if SIZEOF_WCHAR_T == 4
3205
23.7k
        assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3206
23.7k
        const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3207
1.60M
        for (; size--; ++s, ++w) {
3208
1.58M
            *w = *s;
3209
1.58M
        }
3210
#else
3211
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3212
        const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3213
        for (; size--; ++s, ++w) {
3214
            Py_UCS4 ch = *s;
3215
            if (ch > 0xFFFF) {
3216
                assert(ch <= MAX_UNICODE);
3217
                /* encode surrogate pair in this case */
3218
                *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3219
                if (!size--)
3220
                    break;
3221
                *w = Py_UNICODE_LOW_SURROGATE(ch);
3222
            }
3223
            else {
3224
                *w = ch;
3225
            }
3226
        }
3227
#endif
3228
23.7k
    }
3229
161k
}
3230
3231
#ifdef HAVE_WCHAR_H
3232
3233
/* Convert a Unicode object to a wide character string.
3234
3235
   - If w is NULL: return the number of wide characters (including the null
3236
     character) required to convert the unicode object. Ignore size argument.
3237
3238
   - Otherwise: return the number of wide characters (excluding the null
3239
     character) written into w. Write at most size wide characters (including
3240
     the null character). */
3241
Py_ssize_t
3242
PyUnicode_AsWideChar(PyObject *unicode,
3243
                     wchar_t *w,
3244
                     Py_ssize_t size)
3245
1.43k
{
3246
1.43k
    Py_ssize_t res;
3247
3248
1.43k
    if (unicode == NULL) {
3249
0
        PyErr_BadInternalCall();
3250
0
        return -1;
3251
0
    }
3252
1.43k
    if (!PyUnicode_Check(unicode)) {
3253
0
        PyErr_BadArgument();
3254
0
        return -1;
3255
0
    }
3256
3257
1.43k
    res = unicode_get_widechar_size(unicode);
3258
1.43k
    if (w == NULL) {
3259
0
        return res + 1;
3260
0
    }
3261
3262
1.43k
    if (size > res) {
3263
1.43k
        size = res + 1;
3264
1.43k
    }
3265
0
    else {
3266
0
        res = size;
3267
0
    }
3268
1.43k
    unicode_copy_as_widechar(unicode, w, size);
3269
3270
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
3271
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
3272
       non-Unicode locales and hence needs conversion first. */
3273
    if (_Py_LocaleUsesNonUnicodeWchar()) {
3274
        if (_Py_EncodeNonUnicodeWchar_InPlace(w, size) < 0) {
3275
            return -1;
3276
        }
3277
    }
3278
#endif
3279
3280
1.43k
    return res;
3281
1.43k
}
3282
3283
wchar_t*
3284
PyUnicode_AsWideCharString(PyObject *unicode,
3285
                           Py_ssize_t *size)
3286
160k
{
3287
160k
    wchar_t *buffer;
3288
160k
    Py_ssize_t buflen;
3289
3290
160k
    if (unicode == NULL) {
3291
0
        PyErr_BadInternalCall();
3292
0
        return NULL;
3293
0
    }
3294
160k
    if (!PyUnicode_Check(unicode)) {
3295
0
        PyErr_BadArgument();
3296
0
        return NULL;
3297
0
    }
3298
3299
160k
    buflen = unicode_get_widechar_size(unicode);
3300
160k
    buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
3301
160k
    if (buffer == NULL) {
3302
0
        PyErr_NoMemory();
3303
0
        return NULL;
3304
0
    }
3305
160k
    unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3306
3307
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
3308
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
3309
       non-Unicode locales and hence needs conversion first. */
3310
    if (_Py_LocaleUsesNonUnicodeWchar()) {
3311
        if (_Py_EncodeNonUnicodeWchar_InPlace(buffer, (buflen + 1)) < 0) {
3312
            return NULL;
3313
        }
3314
    }
3315
#endif
3316
3317
160k
    if (size != NULL) {
3318
159k
        *size = buflen;
3319
159k
    }
3320
864
    else if (wcslen(buffer) != (size_t)buflen) {
3321
0
        PyMem_Free(buffer);
3322
0
        PyErr_SetString(PyExc_ValueError,
3323
0
                        "embedded null character");
3324
0
        return NULL;
3325
0
    }
3326
160k
    return buffer;
3327
160k
}
3328
3329
#endif /* HAVE_WCHAR_H */
3330
3331
int
3332
_PyUnicode_WideCharString_Converter(PyObject *obj, void *ptr)
3333
0
{
3334
0
    wchar_t **p = (wchar_t **)ptr;
3335
0
    if (obj == NULL) {
3336
0
        PyMem_Free(*p);
3337
0
        *p = NULL;
3338
0
        return 1;
3339
0
    }
3340
0
    if (PyUnicode_Check(obj)) {
3341
0
        *p = PyUnicode_AsWideCharString(obj, NULL);
3342
0
        if (*p == NULL) {
3343
0
            return 0;
3344
0
        }
3345
0
        return Py_CLEANUP_SUPPORTED;
3346
0
    }
3347
0
    PyErr_Format(PyExc_TypeError,
3348
0
                 "argument must be str, not %.50s",
3349
0
                 Py_TYPE(obj)->tp_name);
3350
0
    return 0;
3351
0
}
3352
3353
int
3354
_PyUnicode_WideCharString_Opt_Converter(PyObject *obj, void *ptr)
3355
0
{
3356
0
    wchar_t **p = (wchar_t **)ptr;
3357
0
    if (obj == NULL) {
3358
0
        PyMem_Free(*p);
3359
0
        *p = NULL;
3360
0
        return 1;
3361
0
    }
3362
0
    if (obj == Py_None) {
3363
0
        *p = NULL;
3364
0
        return 1;
3365
0
    }
3366
0
    if (PyUnicode_Check(obj)) {
3367
0
        *p = PyUnicode_AsWideCharString(obj, NULL);
3368
0
        if (*p == NULL) {
3369
0
            return 0;
3370
0
        }
3371
0
        return Py_CLEANUP_SUPPORTED;
3372
0
    }
3373
0
    PyErr_Format(PyExc_TypeError,
3374
0
                 "argument must be str or None, not %.50s",
3375
0
                 Py_TYPE(obj)->tp_name);
3376
0
    return 0;
3377
0
}
3378
3379
PyObject *
3380
PyUnicode_FromOrdinal(int ordinal)
3381
5.75M
{
3382
5.75M
    if (ordinal < 0 || ordinal > MAX_UNICODE) {
3383
29
        PyErr_SetString(PyExc_ValueError,
3384
29
                        "chr() arg not in range(0x110000)");
3385
29
        return NULL;
3386
29
    }
3387
3388
5.75M
    return unicode_char((Py_UCS4)ordinal);
3389
5.75M
}
3390
3391
PyObject *
3392
PyUnicode_FromObject(PyObject *obj)
3393
2.06M
{
3394
    /* XXX Perhaps we should make this API an alias of
3395
       PyObject_Str() instead ?! */
3396
2.06M
    if (PyUnicode_CheckExact(obj)) {
3397
2.06M
        return Py_NewRef(obj);
3398
2.06M
    }
3399
0
    if (PyUnicode_Check(obj)) {
3400
        /* For a Unicode subtype that's not a Unicode object,
3401
           return a true Unicode object with the same data. */
3402
0
        return _PyUnicode_Copy(obj);
3403
0
    }
3404
0
    PyErr_Format(PyExc_TypeError,
3405
0
                 "Can't convert '%.100s' object to str implicitly",
3406
0
                 Py_TYPE(obj)->tp_name);
3407
0
    return NULL;
3408
0
}
3409
3410
PyObject *
3411
PyUnicode_FromEncodedObject(PyObject *obj,
3412
                            const char *encoding,
3413
                            const char *errors)
3414
19.8M
{
3415
19.8M
    Py_buffer buffer;
3416
19.8M
    PyObject *v;
3417
3418
19.8M
    if (obj == NULL) {
3419
0
        PyErr_BadInternalCall();
3420
0
        return NULL;
3421
0
    }
3422
3423
    /* Decoding bytes objects is the most common case and should be fast */
3424
19.8M
    if (PyBytes_Check(obj)) {
3425
19.3M
        if (PyBytes_GET_SIZE(obj) == 0) {
3426
1.84M
            if (unicode_check_encoding_errors(encoding, errors) < 0) {
3427
0
                return NULL;
3428
0
            }
3429
1.84M
            _Py_RETURN_UNICODE_EMPTY();
3430
1.84M
        }
3431
17.5M
        return PyUnicode_Decode(
3432
17.5M
                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3433
17.5M
                encoding, errors);
3434
19.3M
    }
3435
3436
488k
    if (PyUnicode_Check(obj)) {
3437
0
        PyErr_SetString(PyExc_TypeError,
3438
0
                        "decoding str is not supported");
3439
0
        return NULL;
3440
0
    }
3441
3442
    /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3443
488k
    if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3444
0
        PyErr_Format(PyExc_TypeError,
3445
0
                     "decoding to str: need a bytes-like object, %.80s found",
3446
0
                     Py_TYPE(obj)->tp_name);
3447
0
        return NULL;
3448
0
    }
3449
3450
488k
    if (buffer.len == 0) {
3451
0
        PyBuffer_Release(&buffer);
3452
0
        if (unicode_check_encoding_errors(encoding, errors) < 0) {
3453
0
            return NULL;
3454
0
        }
3455
0
        _Py_RETURN_UNICODE_EMPTY();
3456
0
    }
3457
3458
488k
    v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
3459
488k
    PyBuffer_Release(&buffer);
3460
488k
    return v;
3461
488k
}
3462
3463
/* Normalize an encoding name like encodings.normalize_encoding()
3464
   but allow to convert to lowercase if *to_lower* is true.
3465
   Return 1 on success, or 0 on error (encoding is longer than lower_len-1). */
3466
int
3467
_Py_normalize_encoding(const char *encoding,
3468
                       char *lower,
3469
                       size_t lower_len,
3470
                       int to_lower)
3471
25.2M
{
3472
25.2M
    const char *e;
3473
25.2M
    char *l;
3474
25.2M
    char *l_end;
3475
25.2M
    int punct;
3476
3477
25.2M
    assert(encoding != NULL);
3478
3479
25.2M
    e = encoding;
3480
25.2M
    l = lower;
3481
25.2M
    l_end = &lower[lower_len - 1];
3482
25.2M
    punct = 0;
3483
171M
    while (1) {
3484
171M
        char c = *e;
3485
171M
        if (c == 0) {
3486
24.2M
            break;
3487
24.2M
        }
3488
3489
146M
        if (Py_ISALNUM(c) || c == '.') {
3490
130M
            if (punct && l != lower) {
3491
12.0M
                if (l == l_end) {
3492
1.41k
                    return 0;
3493
1.41k
                }
3494
12.0M
                *l++ = '_';
3495
12.0M
            }
3496
130M
            punct = 0;
3497
3498
130M
            if (l == l_end) {
3499
1.00M
                return 0;
3500
1.00M
            }
3501
129M
            *l++ = to_lower ? Py_TOLOWER(c) : c;
3502
129M
        }
3503
16.3M
        else {
3504
16.3M
            punct = 1;
3505
16.3M
        }
3506
3507
145M
        e++;
3508
145M
    }
3509
24.2M
    *l = '\0';
3510
24.2M
    return 1;
3511
25.2M
}
3512
3513
PyObject *
3514
PyUnicode_Decode(const char *s,
3515
                 Py_ssize_t size,
3516
                 const char *encoding,
3517
                 const char *errors)
3518
18.1M
{
3519
18.1M
    PyObject *buffer = NULL, *unicode;
3520
18.1M
    Py_buffer info;
3521
18.1M
    char buflower[11];   /* strlen("iso-8859-1\0") == 11, longest shortcut */
3522
3523
18.1M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3524
0
        return NULL;
3525
0
    }
3526
3527
18.1M
    if (size == 0) {
3528
0
        _Py_RETURN_UNICODE_EMPTY();
3529
0
    }
3530
3531
18.1M
    if (encoding == NULL) {
3532
52.7k
        return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3533
52.7k
    }
3534
3535
    /* Shortcuts for common default encodings */
3536
18.0M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3537
18.0M
        char *lower = buflower;
3538
3539
        /* Fast paths */
3540
18.0M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3541
2.72M
            lower += 3;
3542
2.72M
            if (*lower == '_') {
3543
                /* Match "utf8" and "utf_8" */
3544
2.72M
                lower++;
3545
2.72M
            }
3546
3547
2.72M
            if (lower[0] == '8' && lower[1] == 0) {
3548
2.71M
                return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3549
2.71M
            }
3550
1.30k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3551
157
                return PyUnicode_DecodeUTF16(s, size, errors, 0);
3552
157
            }
3553
1.14k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3554
183
                return PyUnicode_DecodeUTF32(s, size, errors, 0);
3555
183
            }
3556
2.72M
        }
3557
15.3M
        else {
3558
15.3M
            if (strcmp(lower, "ascii") == 0
3559
11.2M
                || strcmp(lower, "us_ascii") == 0) {
3560
11.2M
                return PyUnicode_DecodeASCII(s, size, errors);
3561
11.2M
            }
3562
    #ifdef MS_WINDOWS
3563
            else if (strcmp(lower, "mbcs") == 0) {
3564
                return PyUnicode_DecodeMBCS(s, size, errors);
3565
            }
3566
    #endif
3567
4.10M
            else if (strcmp(lower, "latin1") == 0
3568
4.10M
                     || strcmp(lower, "latin_1") == 0
3569
1.14M
                     || strcmp(lower, "iso_8859_1") == 0
3570
2.98M
                     || strcmp(lower, "iso8859_1") == 0) {
3571
2.98M
                return PyUnicode_DecodeLatin1(s, size, errors);
3572
2.98M
            }
3573
15.3M
        }
3574
18.0M
    }
3575
3576
    /* Decode via the codec registry */
3577
1.13M
    buffer = NULL;
3578
1.13M
    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
3579
0
        goto onError;
3580
1.13M
    buffer = PyMemoryView_FromBuffer(&info);
3581
1.13M
    if (buffer == NULL)
3582
0
        goto onError;
3583
1.13M
    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
3584
1.13M
    if (unicode == NULL)
3585
93.0k
        goto onError;
3586
1.03M
    if (!PyUnicode_Check(unicode)) {
3587
0
        PyErr_Format(PyExc_TypeError,
3588
0
                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
3589
0
                     "use codecs.decode() to decode to arbitrary types",
3590
0
                     encoding,
3591
0
                     Py_TYPE(unicode)->tp_name);
3592
0
        Py_DECREF(unicode);
3593
0
        goto onError;
3594
0
    }
3595
1.03M
    Py_DECREF(buffer);
3596
1.03M
    return unicode_result(unicode);
3597
3598
93.0k
  onError:
3599
93.0k
    Py_XDECREF(buffer);
3600
93.0k
    return NULL;
3601
1.03M
}
3602
3603
PyAPI_FUNC(PyObject *)
3604
PyUnicode_AsDecodedObject(PyObject *unicode,
3605
                          const char *encoding,
3606
                          const char *errors)
3607
0
{
3608
0
    if (!PyUnicode_Check(unicode)) {
3609
0
        PyErr_BadArgument();
3610
0
        return NULL;
3611
0
    }
3612
3613
0
    if (encoding == NULL)
3614
0
        encoding = PyUnicode_GetDefaultEncoding();
3615
3616
    /* Decode via the codec registry */
3617
0
    return PyCodec_Decode(unicode, encoding, errors);
3618
0
}
3619
3620
PyAPI_FUNC(PyObject *)
3621
PyUnicode_AsDecodedUnicode(PyObject *unicode,
3622
                           const char *encoding,
3623
                           const char *errors)
3624
0
{
3625
0
    PyObject *v;
3626
3627
0
    if (!PyUnicode_Check(unicode)) {
3628
0
        PyErr_BadArgument();
3629
0
        goto onError;
3630
0
    }
3631
3632
0
    if (encoding == NULL)
3633
0
        encoding = PyUnicode_GetDefaultEncoding();
3634
3635
    /* Decode via the codec registry */
3636
0
    v = PyCodec_Decode(unicode, encoding, errors);
3637
0
    if (v == NULL)
3638
0
        goto onError;
3639
0
    if (!PyUnicode_Check(v)) {
3640
0
        PyErr_Format(PyExc_TypeError,
3641
0
                     "'%.400s' decoder returned '%.400s' instead of 'str'; "
3642
0
                     "use codecs.decode() to decode to arbitrary types",
3643
0
                     encoding,
3644
0
                     Py_TYPE(unicode)->tp_name);
3645
0
        Py_DECREF(v);
3646
0
        goto onError;
3647
0
    }
3648
0
    return unicode_result(v);
3649
3650
0
  onError:
3651
0
    return NULL;
3652
0
}
3653
3654
PyAPI_FUNC(PyObject *)
3655
PyUnicode_AsEncodedObject(PyObject *unicode,
3656
                          const char *encoding,
3657
                          const char *errors)
3658
0
{
3659
0
    PyObject *v;
3660
3661
0
    if (!PyUnicode_Check(unicode)) {
3662
0
        PyErr_BadArgument();
3663
0
        goto onError;
3664
0
    }
3665
3666
0
    if (encoding == NULL)
3667
0
        encoding = PyUnicode_GetDefaultEncoding();
3668
3669
    /* Encode via the codec registry */
3670
0
    v = PyCodec_Encode(unicode, encoding, errors);
3671
0
    if (v == NULL)
3672
0
        goto onError;
3673
0
    return v;
3674
3675
0
  onError:
3676
0
    return NULL;
3677
0
}
3678
3679
3680
static PyObject *
3681
unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
3682
                      int current_locale)
3683
288
{
3684
288
    Py_ssize_t wlen;
3685
288
    wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3686
288
    if (wstr == NULL) {
3687
0
        return NULL;
3688
0
    }
3689
3690
288
    if ((size_t)wlen != wcslen(wstr)) {
3691
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
3692
0
        PyMem_Free(wstr);
3693
0
        return NULL;
3694
0
    }
3695
3696
288
    char *str;
3697
288
    size_t error_pos;
3698
288
    const char *reason;
3699
288
    int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
3700
288
                                 current_locale, error_handler);
3701
288
    PyMem_Free(wstr);
3702
3703
288
    if (res != 0) {
3704
0
        if (res == -2) {
3705
0
            PyObject *exc;
3706
0
            exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3707
0
                    "locale", unicode,
3708
0
                    (Py_ssize_t)error_pos,
3709
0
                    (Py_ssize_t)(error_pos+1),
3710
0
                    reason);
3711
0
            if (exc != NULL) {
3712
0
                PyCodec_StrictErrors(exc);
3713
0
                Py_DECREF(exc);
3714
0
            }
3715
0
        }
3716
0
        else if (res == -3) {
3717
0
            PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3718
0
        }
3719
0
        else {
3720
0
            PyErr_NoMemory();
3721
0
        }
3722
0
        return NULL;
3723
0
    }
3724
3725
288
    PyObject *bytes = PyBytes_FromString(str);
3726
288
    PyMem_RawFree(str);
3727
288
    return bytes;
3728
288
}
3729
3730
PyObject *
3731
PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3732
0
{
3733
0
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3734
0
    return unicode_encode_locale(unicode, error_handler, 1);
3735
0
}
3736
3737
PyObject *
3738
PyUnicode_EncodeFSDefault(PyObject *unicode)
3739
747k
{
3740
747k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3741
747k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3742
747k
    if (fs_codec->utf8) {
3743
747k
        return unicode_encode_utf8(unicode,
3744
747k
                                   fs_codec->error_handler,
3745
747k
                                   fs_codec->errors);
3746
747k
    }
3747
288
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3748
288
    else if (fs_codec->encoding) {
3749
0
        return PyUnicode_AsEncodedString(unicode,
3750
0
                                         fs_codec->encoding,
3751
0
                                         fs_codec->errors);
3752
0
    }
3753
288
#endif
3754
288
    else {
3755
        /* Before _PyUnicode_InitEncodings() is called, the Python codec
3756
           machinery is not ready and so cannot be used:
3757
           use wcstombs() in this case. */
3758
288
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3759
288
        const wchar_t *filesystem_errors = config->filesystem_errors;
3760
288
        assert(filesystem_errors != NULL);
3761
288
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3762
288
        assert(errors != _Py_ERROR_UNKNOWN);
3763
#ifdef _Py_FORCE_UTF8_FS_ENCODING
3764
        return unicode_encode_utf8(unicode, errors, NULL);
3765
#else
3766
288
        return unicode_encode_locale(unicode, errors, 0);
3767
288
#endif
3768
288
    }
3769
747k
}
3770
3771
PyObject *
3772
PyUnicode_AsEncodedString(PyObject *unicode,
3773
                          const char *encoding,
3774
                          const char *errors)
3775
20.1M
{
3776
20.1M
    PyObject *v;
3777
20.1M
    char buflower[11];   /* strlen("iso_8859_1\0") == 11, longest shortcut */
3778
3779
20.1M
    if (!PyUnicode_Check(unicode)) {
3780
0
        PyErr_BadArgument();
3781
0
        return NULL;
3782
0
    }
3783
3784
20.1M
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3785
0
        return NULL;
3786
0
    }
3787
3788
20.1M
    if (encoding == NULL) {
3789
12.8M
        return _PyUnicode_AsUTF8String(unicode, errors);
3790
12.8M
    }
3791
3792
    /* Shortcuts for common default encodings */
3793
7.22M
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3794
6.22M
        char *lower = buflower;
3795
3796
        /* Fast paths */
3797
6.22M
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3798
5.12M
            lower += 3;
3799
5.12M
            if (*lower == '_') {
3800
                /* Match "utf8" and "utf_8" */
3801
5.12M
                lower++;
3802
5.12M
            }
3803
3804
5.12M
            if (lower[0] == '8' && lower[1] == 0) {
3805
5.11M
                return _PyUnicode_AsUTF8String(unicode, errors);
3806
5.11M
            }
3807
9.70k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3808
0
                return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3809
0
            }
3810
9.70k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3811
0
                return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3812
0
            }
3813
5.12M
        }
3814
1.10M
        else {
3815
1.10M
            if (strcmp(lower, "ascii") == 0
3816
837k
                || strcmp(lower, "us_ascii") == 0) {
3817
837k
                return _PyUnicode_AsASCIIString(unicode, errors);
3818
837k
            }
3819
#ifdef MS_WINDOWS
3820
            else if (strcmp(lower, "mbcs") == 0) {
3821
                return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3822
            }
3823
#endif
3824
265k
            else if (strcmp(lower, "latin1") == 0 ||
3825
265k
                     strcmp(lower, "latin_1") == 0 ||
3826
265k
                     strcmp(lower, "iso_8859_1") == 0 ||
3827
265k
                     strcmp(lower, "iso8859_1") == 0) {
3828
10
                return _PyUnicode_AsLatin1String(unicode, errors);
3829
10
            }
3830
1.10M
        }
3831
6.22M
    }
3832
3833
    /* Encode via the codec registry */
3834
1.27M
    v = _PyCodec_EncodeText(unicode, encoding, errors);
3835
1.27M
    if (v == NULL)
3836
0
        return NULL;
3837
3838
    /* The normal path */
3839
1.27M
    if (PyBytes_Check(v))
3840
1.27M
        return v;
3841
3842
    /* If the codec returns a buffer, raise a warning and convert to bytes */
3843
0
    if (PyByteArray_Check(v)) {
3844
0
        int error;
3845
0
        PyObject *b;
3846
3847
0
        error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3848
0
            "encoder %s returned bytearray instead of bytes; "
3849
0
            "use codecs.encode() to encode to arbitrary types",
3850
0
            encoding);
3851
0
        if (error) {
3852
0
            Py_DECREF(v);
3853
0
            return NULL;
3854
0
        }
3855
3856
0
        b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3857
0
                                      PyByteArray_GET_SIZE(v));
3858
0
        Py_DECREF(v);
3859
0
        return b;
3860
0
    }
3861
3862
0
    PyErr_Format(PyExc_TypeError,
3863
0
                 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3864
0
                 "use codecs.encode() to encode to arbitrary types",
3865
0
                 encoding,
3866
0
                 Py_TYPE(v)->tp_name);
3867
0
    Py_DECREF(v);
3868
0
    return NULL;
3869
0
}
3870
3871
PyAPI_FUNC(PyObject *)
3872
PyUnicode_AsEncodedUnicode(PyObject *unicode,
3873
                           const char *encoding,
3874
                           const char *errors)
3875
0
{
3876
0
    PyObject *v;
3877
3878
0
    if (!PyUnicode_Check(unicode)) {
3879
0
        PyErr_BadArgument();
3880
0
        goto onError;
3881
0
    }
3882
3883
0
    if (encoding == NULL)
3884
0
        encoding = PyUnicode_GetDefaultEncoding();
3885
3886
    /* Encode via the codec registry */
3887
0
    v = PyCodec_Encode(unicode, encoding, errors);
3888
0
    if (v == NULL)
3889
0
        goto onError;
3890
0
    if (!PyUnicode_Check(v)) {
3891
0
        PyErr_Format(PyExc_TypeError,
3892
0
                     "'%.400s' encoder returned '%.400s' instead of 'str'; "
3893
0
                     "use codecs.encode() to encode to arbitrary types",
3894
0
                     encoding,
3895
0
                     Py_TYPE(v)->tp_name);
3896
0
        Py_DECREF(v);
3897
0
        goto onError;
3898
0
    }
3899
0
    return v;
3900
3901
0
  onError:
3902
0
    return NULL;
3903
0
}
3904
3905
static PyObject*
3906
unicode_decode_locale(const char *str, Py_ssize_t len,
3907
                      _Py_error_handler errors, int current_locale)
3908
275k
{
3909
275k
    if (str[len] != '\0' || (size_t)len != strlen(str))  {
3910
0
        PyErr_SetString(PyExc_ValueError, "embedded null byte");
3911
0
        return NULL;
3912
0
    }
3913
3914
275k
    wchar_t *wstr;
3915
275k
    size_t wlen;
3916
275k
    const char *reason;
3917
275k
    int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
3918
275k
                                 current_locale, errors);
3919
275k
    if (res != 0) {
3920
0
        if (res == -2) {
3921
0
            PyObject *exc;
3922
0
            exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3923
0
                                        "locale", str, len,
3924
0
                                        (Py_ssize_t)wlen,
3925
0
                                        (Py_ssize_t)(wlen + 1),
3926
0
                                        reason);
3927
0
            if (exc != NULL) {
3928
0
                PyCodec_StrictErrors(exc);
3929
0
                Py_DECREF(exc);
3930
0
            }
3931
0
        }
3932
0
        else if (res == -3) {
3933
0
            PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3934
0
        }
3935
0
        else {
3936
0
            PyErr_NoMemory();
3937
0
        }
3938
0
        return NULL;
3939
0
    }
3940
3941
275k
    PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3942
275k
    PyMem_RawFree(wstr);
3943
275k
    return unicode;
3944
275k
}
3945
3946
PyObject*
3947
PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3948
                              const char *errors)
3949
0
{
3950
0
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3951
0
    return unicode_decode_locale(str, len, error_handler, 1);
3952
0
}
3953
3954
PyObject*
3955
PyUnicode_DecodeLocale(const char *str, const char *errors)
3956
275k
{
3957
275k
    Py_ssize_t size = (Py_ssize_t)strlen(str);
3958
275k
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3959
275k
    return unicode_decode_locale(str, size, error_handler, 1);
3960
275k
}
3961
3962
3963
PyObject*
3964
376
PyUnicode_DecodeFSDefault(const char *s) {
3965
376
    Py_ssize_t size = (Py_ssize_t)strlen(s);
3966
376
    return PyUnicode_DecodeFSDefaultAndSize(s, size);
3967
376
}
3968
3969
PyObject*
3970
PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3971
124k
{
3972
124k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3973
124k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3974
124k
    if (fs_codec->utf8) {
3975
124k
        return unicode_decode_utf8(s, size,
3976
124k
                                   fs_codec->error_handler,
3977
124k
                                   fs_codec->errors,
3978
124k
                                   NULL);
3979
124k
    }
3980
36
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3981
36
    else if (fs_codec->encoding) {
3982
0
        return PyUnicode_Decode(s, size,
3983
0
                                fs_codec->encoding,
3984
0
                                fs_codec->errors);
3985
0
    }
3986
36
#endif
3987
36
    else {
3988
        /* Before _PyUnicode_InitEncodings() is called, the Python codec
3989
           machinery is not ready and so cannot be used:
3990
           use mbstowcs() in this case. */
3991
36
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3992
36
        const wchar_t *filesystem_errors = config->filesystem_errors;
3993
36
        assert(filesystem_errors != NULL);
3994
36
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3995
36
        assert(errors != _Py_ERROR_UNKNOWN);
3996
#ifdef _Py_FORCE_UTF8_FS_ENCODING
3997
        return unicode_decode_utf8(s, size, errors, NULL, NULL);
3998
#else
3999
36
        return unicode_decode_locale(s, size, errors, 0);
4000
36
#endif
4001
36
    }
4002
124k
}
4003
4004
4005
int
4006
PyUnicode_FSConverter(PyObject* arg, void* addr)
4007
202k
{
4008
202k
    PyObject *path = NULL;
4009
202k
    PyObject *output = NULL;
4010
202k
    Py_ssize_t size;
4011
202k
    const char *data;
4012
202k
    if (arg == NULL) {
4013
0
        Py_DECREF(*(PyObject**)addr);
4014
0
        *(PyObject**)addr = NULL;
4015
0
        return 1;
4016
0
    }
4017
202k
    path = PyOS_FSPath(arg);
4018
202k
    if (path == NULL) {
4019
0
        return 0;
4020
0
    }
4021
202k
    if (PyBytes_Check(path)) {
4022
0
        output = path;
4023
0
    }
4024
202k
    else {  // PyOS_FSPath() guarantees its returned value is bytes or str.
4025
202k
        output = PyUnicode_EncodeFSDefault(path);
4026
202k
        Py_DECREF(path);
4027
202k
        if (!output) {
4028
0
            return 0;
4029
0
        }
4030
202k
        assert(PyBytes_Check(output));
4031
202k
    }
4032
4033
202k
    size = PyBytes_GET_SIZE(output);
4034
202k
    data = PyBytes_AS_STRING(output);
4035
202k
    if ((size_t)size != strlen(data)) {
4036
0
        PyErr_SetString(PyExc_ValueError, "embedded null byte");
4037
0
        Py_DECREF(output);
4038
0
        return 0;
4039
0
    }
4040
202k
    *(PyObject**)addr = output;
4041
202k
    return Py_CLEANUP_SUPPORTED;
4042
202k
}
4043
4044
4045
int
4046
PyUnicode_FSDecoder(PyObject* arg, void* addr)
4047
102k
{
4048
102k
    if (arg == NULL) {
4049
0
        Py_DECREF(*(PyObject**)addr);
4050
0
        *(PyObject**)addr = NULL;
4051
0
        return 1;
4052
0
    }
4053
4054
102k
    PyObject *path = PyOS_FSPath(arg);
4055
102k
    if (path == NULL) {
4056
0
        return 0;
4057
0
    }
4058
4059
102k
    PyObject *output = NULL;
4060
102k
    if (PyUnicode_Check(path)) {
4061
102k
        output = path;
4062
102k
    }
4063
0
    else if (PyBytes_Check(path)) {
4064
0
        output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path),
4065
0
                                                  PyBytes_GET_SIZE(path));
4066
0
        Py_DECREF(path);
4067
0
        if (!output) {
4068
0
            return 0;
4069
0
        }
4070
0
    }
4071
0
    else {
4072
0
        PyErr_Format(PyExc_TypeError,
4073
0
                     "path should be string, bytes, or os.PathLike, not %.200s",
4074
0
                     Py_TYPE(arg)->tp_name);
4075
0
        Py_DECREF(path);
4076
0
        return 0;
4077
0
    }
4078
4079
102k
    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
4080
102k
                 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
4081
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4082
0
        Py_DECREF(output);
4083
0
        return 0;
4084
0
    }
4085
102k
    *(PyObject**)addr = output;
4086
102k
    return Py_CLEANUP_SUPPORTED;
4087
102k
}
4088
4089
4090
static int unicode_fill_utf8(PyObject *unicode);
4091
4092
4093
static int
4094
unicode_ensure_utf8(PyObject *unicode)
4095
56.5M
{
4096
56.5M
    int err = 0;
4097
56.5M
    if (PyUnicode_UTF8(unicode) == NULL) {
4098
160k
        Py_BEGIN_CRITICAL_SECTION(unicode);
4099
160k
        if (PyUnicode_UTF8(unicode) == NULL) {
4100
160k
            err = unicode_fill_utf8(unicode);
4101
160k
        }
4102
160k
        Py_END_CRITICAL_SECTION();
4103
160k
    }
4104
56.5M
    return err;
4105
56.5M
}
4106
4107
const char *
4108
PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
4109
56.5M
{
4110
56.5M
    if (!PyUnicode_Check(unicode)) {
4111
0
        PyErr_BadArgument();
4112
0
        if (psize) {
4113
0
            *psize = -1;
4114
0
        }
4115
0
        return NULL;
4116
0
    }
4117
4118
56.5M
    if (unicode_ensure_utf8(unicode) == -1) {
4119
206
        if (psize) {
4120
206
            *psize = -1;
4121
206
        }
4122
206
        return NULL;
4123
206
    }
4124
4125
56.5M
    if (psize) {
4126
56.2M
        *psize = PyUnicode_UTF8_LENGTH(unicode);
4127
56.2M
    }
4128
56.5M
    return PyUnicode_UTF8(unicode);
4129
56.5M
}
4130
4131
const char *
4132
PyUnicode_AsUTF8(PyObject *unicode)
4133
238k
{
4134
238k
    return PyUnicode_AsUTF8AndSize(unicode, NULL);
4135
238k
}
4136
4137
const char *
4138
_PyUnicode_AsUTF8NoNUL(PyObject *unicode)
4139
2.85M
{
4140
2.85M
    Py_ssize_t size;
4141
2.85M
    const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
4142
2.85M
    if (s && strlen(s) != (size_t)size) {
4143
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4144
0
        return NULL;
4145
0
    }
4146
2.85M
    return s;
4147
2.85M
}
4148
4149
/*
4150
PyUnicode_GetSize() has been deprecated since Python 3.3
4151
because it returned length of Py_UNICODE.
4152
4153
But this function is part of stable abi, because it doesn't
4154
include Py_UNICODE in signature and it was not excluded from
4155
stable ABI in PEP 384.
4156
*/
4157
PyAPI_FUNC(Py_ssize_t)
4158
PyUnicode_GetSize(PyObject *unicode)
4159
0
{
4160
0
    PyErr_SetString(PyExc_RuntimeError,
4161
0
                    "PyUnicode_GetSize has been removed.");
4162
0
    return -1;
4163
0
}
4164
4165
Py_ssize_t
4166
PyUnicode_GetLength(PyObject *unicode)
4167
19.7k
{
4168
19.7k
    if (!PyUnicode_Check(unicode)) {
4169
0
        PyErr_BadArgument();
4170
0
        return -1;
4171
0
    }
4172
19.7k
    return PyUnicode_GET_LENGTH(unicode);
4173
19.7k
}
4174
4175
Py_UCS4
4176
PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4177
58
{
4178
58
    const void *data;
4179
58
    int kind;
4180
4181
58
    if (!PyUnicode_Check(unicode)) {
4182
0
        PyErr_BadArgument();
4183
0
        return (Py_UCS4)-1;
4184
0
    }
4185
58
    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
4186
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
4187
0
        return (Py_UCS4)-1;
4188
0
    }
4189
58
    data = PyUnicode_DATA(unicode);
4190
58
    kind = PyUnicode_KIND(unicode);
4191
58
    return PyUnicode_READ(kind, data, index);
4192
58
}
4193
4194
int
4195
PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4196
0
{
4197
0
    if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
4198
0
        PyErr_BadArgument();
4199
0
        return -1;
4200
0
    }
4201
0
    if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
4202
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
4203
0
        return -1;
4204
0
    }
4205
0
    if (unicode_check_modifiable(unicode))
4206
0
        return -1;
4207
0
    if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4208
0
        PyErr_SetString(PyExc_ValueError, "character out of range");
4209
0
        return -1;
4210
0
    }
4211
0
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4212
0
                    index, ch);
4213
0
    return 0;
4214
0
}
4215
4216
const char *
4217
PyUnicode_GetDefaultEncoding(void)
4218
0
{
4219
0
    return "utf-8";
4220
0
}
4221
4222
/* create or adjust a UnicodeDecodeError */
4223
static void
4224
make_decode_exception(PyObject **exceptionObject,
4225
                      const char *encoding,
4226
                      const char *input, Py_ssize_t length,
4227
                      Py_ssize_t startpos, Py_ssize_t endpos,
4228
                      const char *reason)
4229
3.07M
{
4230
3.07M
    if (*exceptionObject == NULL) {
4231
2.63M
        *exceptionObject = PyUnicodeDecodeError_Create(
4232
2.63M
            encoding, input, length, startpos, endpos, reason);
4233
2.63M
    }
4234
435k
    else {
4235
435k
        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4236
0
            goto onError;
4237
435k
        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4238
0
            goto onError;
4239
435k
        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4240
0
            goto onError;
4241
435k
    }
4242
3.07M
    return;
4243
4244
3.07M
onError:
4245
0
    Py_CLEAR(*exceptionObject);
4246
0
}
4247
4248
#ifdef MS_WINDOWS
4249
static int
4250
widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
4251
{
4252
    if (newsize > *size) {
4253
        wchar_t *newbuf = *buf;
4254
        if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
4255
            PyErr_NoMemory();
4256
            return -1;
4257
        }
4258
        *buf = newbuf;
4259
    }
4260
    *size = newsize;
4261
    return 0;
4262
}
4263
4264
/* error handling callback helper:
4265
   build arguments, call the callback and check the arguments,
4266
   if no exception occurred, copy the replacement to the output
4267
   and adjust various state variables.
4268
   return 0 on success, -1 on error
4269
*/
4270
4271
static int
4272
unicode_decode_call_errorhandler_wchar(
4273
    const char *errors, PyObject **errorHandler,
4274
    const char *encoding, const char *reason,
4275
    const char **input, const char **inend, Py_ssize_t *startinpos,
4276
    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4277
    wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
4278
{
4279
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4280
4281
    PyObject *restuple = NULL;
4282
    PyObject *repunicode = NULL;
4283
    Py_ssize_t outsize;
4284
    Py_ssize_t insize;
4285
    Py_ssize_t requiredsize;
4286
    Py_ssize_t newpos;
4287
    PyObject *inputobj = NULL;
4288
    Py_ssize_t repwlen;
4289
4290
    if (*errorHandler == NULL) {
4291
        *errorHandler = PyCodec_LookupError(errors);
4292
        if (*errorHandler == NULL)
4293
            goto onError;
4294
    }
4295
4296
    make_decode_exception(exceptionObject,
4297
        encoding,
4298
        *input, *inend - *input,
4299
        *startinpos, *endinpos,
4300
        reason);
4301
    if (*exceptionObject == NULL)
4302
        goto onError;
4303
4304
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4305
    if (restuple == NULL)
4306
        goto onError;
4307
    if (!PyTuple_Check(restuple)) {
4308
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4309
        goto onError;
4310
    }
4311
    if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
4312
        goto onError;
4313
4314
    /* Copy back the bytes variables, which might have been modified by the
4315
       callback */
4316
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4317
    if (!inputobj)
4318
        goto onError;
4319
    *input = PyBytes_AS_STRING(inputobj);
4320
    insize = PyBytes_GET_SIZE(inputobj);
4321
    *inend = *input + insize;
4322
    /* we can DECREF safely, as the exception has another reference,
4323
       so the object won't go away. */
4324
    Py_DECREF(inputobj);
4325
4326
    if (newpos<0)
4327
        newpos = insize+newpos;
4328
    if (newpos<0 || newpos>insize) {
4329
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4330
        goto onError;
4331
    }
4332
4333
    repwlen = PyUnicode_AsWideChar(repunicode, NULL, 0);
4334
    if (repwlen < 0)
4335
        goto onError;
4336
    repwlen--;
4337
    /* need more space? (at least enough for what we
4338
       have+the replacement+the rest of the string (starting
4339
       at the new input position), so we won't have to check space
4340
       when there are no errors in the rest of the string) */
4341
    requiredsize = *outpos;
4342
    if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4343
        goto overflow;
4344
    requiredsize += repwlen;
4345
    if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4346
        goto overflow;
4347
    requiredsize += insize - newpos;
4348
    outsize = *bufsize;
4349
    if (requiredsize > outsize) {
4350
        if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
4351
            requiredsize = 2*outsize;
4352
        if (widechar_resize(buf, bufsize, requiredsize) < 0) {
4353
            goto onError;
4354
        }
4355
    }
4356
    PyUnicode_AsWideChar(repunicode, *buf + *outpos, repwlen);
4357
    *outpos += repwlen;
4358
    *endinpos = newpos;
4359
    *inptr = *input + newpos;
4360
4361
    /* we made it! */
4362
    Py_DECREF(restuple);
4363
    return 0;
4364
4365
  overflow:
4366
    PyErr_SetString(PyExc_OverflowError,
4367
                    "decoded result is too long for a Python string");
4368
4369
  onError:
4370
    Py_XDECREF(restuple);
4371
    return -1;
4372
}
4373
#endif   /* MS_WINDOWS */
4374
4375
static int
4376
unicode_decode_call_errorhandler_writer(
4377
    const char *errors, PyObject **errorHandler,
4378
    const char *encoding, const char *reason,
4379
    const char **input, const char **inend, Py_ssize_t *startinpos,
4380
    Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4381
    _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4382
3.07M
{
4383
3.07M
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4384
4385
3.07M
    PyObject *restuple = NULL;
4386
3.07M
    PyObject *repunicode = NULL;
4387
3.07M
    Py_ssize_t insize;
4388
3.07M
    Py_ssize_t newpos;
4389
3.07M
    Py_ssize_t replen;
4390
3.07M
    Py_ssize_t remain;
4391
3.07M
    PyObject *inputobj = NULL;
4392
3.07M
    int need_to_grow = 0;
4393
3.07M
    const char *new_inptr;
4394
4395
3.07M
    if (*errorHandler == NULL) {
4396
2.63M
        *errorHandler = PyCodec_LookupError(errors);
4397
2.63M
        if (*errorHandler == NULL)
4398
0
            goto onError;
4399
2.63M
    }
4400
4401
3.07M
    make_decode_exception(exceptionObject,
4402
3.07M
        encoding,
4403
3.07M
        *input, *inend - *input,
4404
3.07M
        *startinpos, *endinpos,
4405
3.07M
        reason);
4406
3.07M
    if (*exceptionObject == NULL)
4407
0
        goto onError;
4408
4409
3.07M
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4410
3.07M
    if (restuple == NULL)
4411
2.59M
        goto onError;
4412
478k
    if (!PyTuple_Check(restuple)) {
4413
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4414
0
        goto onError;
4415
0
    }
4416
478k
    if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
4417
0
        goto onError;
4418
4419
    /* Copy back the bytes variables, which might have been modified by the
4420
       callback */
4421
478k
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4422
478k
    if (!inputobj)
4423
0
        goto onError;
4424
478k
    remain = *inend - *input - *endinpos;
4425
478k
    *input = PyBytes_AS_STRING(inputobj);
4426
478k
    insize = PyBytes_GET_SIZE(inputobj);
4427
478k
    *inend = *input + insize;
4428
    /* we can DECREF safely, as the exception has another reference,
4429
       so the object won't go away. */
4430
478k
    Py_DECREF(inputobj);
4431
4432
478k
    if (newpos<0)
4433
0
        newpos = insize+newpos;
4434
478k
    if (newpos<0 || newpos>insize) {
4435
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4436
0
        goto onError;
4437
0
    }
4438
4439
478k
    replen = PyUnicode_GET_LENGTH(repunicode);
4440
478k
    if (replen > 1) {
4441
32.6k
        writer->min_length += replen - 1;
4442
32.6k
        need_to_grow = 1;
4443
32.6k
    }
4444
478k
    new_inptr = *input + newpos;
4445
478k
    if (*inend - new_inptr > remain) {
4446
        /* We don't know the decoding algorithm here so we make the worst
4447
           assumption that one byte decodes to one unicode character.
4448
           If unfortunately one byte could decode to more unicode characters,
4449
           the decoder may write out-of-bound then.  Is it possible for the
4450
           algorithms using this function? */
4451
15.4k
        writer->min_length += *inend - new_inptr - remain;
4452
15.4k
        need_to_grow = 1;
4453
15.4k
    }
4454
478k
    if (need_to_grow) {
4455
32.8k
        writer->overallocate = 1;
4456
32.8k
        if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
4457
32.8k
                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4458
0
            goto onError;
4459
32.8k
    }
4460
478k
    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4461
0
        goto onError;
4462
4463
478k
    *endinpos = newpos;
4464
478k
    *inptr = new_inptr;
4465
4466
    /* we made it! */
4467
478k
    Py_DECREF(restuple);
4468
478k
    return 0;
4469
4470
2.59M
  onError:
4471
2.59M
    Py_XDECREF(restuple);
4472
2.59M
    return -1;
4473
478k
}
4474
4475
/* --- UTF-7 Codec -------------------------------------------------------- */
4476
4477
/* See RFC2152 for details.  We encode conservatively and decode liberally. */
4478
4479
/* Three simple macros defining base-64. */
4480
4481
/* Is c a base-64 character? */
4482
4483
#define IS_BASE64(c) \
4484
345k
    (((c) >= 'A' && (c) <= 'Z') ||     \
4485
345k
     ((c) >= 'a' && (c) <= 'z') ||     \
4486
345k
     ((c) >= '0' && (c) <= '9') ||     \
4487
345k
     (c) == '+' || (c) == '/')
4488
4489
/* given that c is a base-64 character, what is its base-64 value? */
4490
4491
#define FROM_BASE64(c)                                                  \
4492
302k
    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
4493
302k
     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
4494
237k
     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
4495
136k
     (c) == '+' ? 62 : 63)
4496
4497
/* What is the base-64 character of the bottom 6 bits of n? */
4498
4499
#define TO_BASE64(n)  \
4500
0
    ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4501
4502
/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4503
 * decoded as itself.  We are permissive on decoding; the only ASCII
4504
 * byte not decoding to itself is the + which begins a base64
4505
 * string. */
4506
4507
#define DECODE_DIRECT(c)                                \
4508
11.6M
    ((c) <= 127 && (c) != '+')
4509
4510
/* The UTF-7 encoder treats ASCII characters differently according to
4511
 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4512
 * the above).  See RFC2152.  This array identifies these different
4513
 * sets:
4514
 * 0 : "Set D"
4515
 *     alphanumeric and '(),-./:?
4516
 * 1 : "Set O"
4517
 *     !"#$%&*;<=>@[]^_`{|}
4518
 * 2 : "whitespace"
4519
 *     ht nl cr sp
4520
 * 3 : special (must be base64 encoded)
4521
 *     everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4522
 */
4523
4524
static
4525
char utf7_category[128] = {
4526
/* nul soh stx etx eot enq ack bel bs  ht  nl  vt  np  cr  so  si  */
4527
    3,  3,  3,  3,  3,  3,  3,  3,  3,  2,  2,  3,  3,  2,  3,  3,
4528
/* dle dc1 dc2 dc3 dc4 nak syn etb can em  sub esc fs  gs  rs  us  */
4529
    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
4530
/* sp   !   "   #   $   %   &   '   (   )   *   +   ,   -   .   /  */
4531
    2,  1,  1,  1,  1,  1,  1,  0,  0,  0,  1,  3,  0,  0,  0,  0,
4532
/*  0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?  */
4533
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0,
4534
/*  @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O  */
4535
    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
4536
/*  P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _  */
4537
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  3,  1,  1,  1,
4538
/*  `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o  */
4539
    1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
4540
/*  p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~  del */
4541
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  3,  3,
4542
};
4543
4544
/* ENCODE_DIRECT: this character should be encoded as itself.  The
4545
 * answer depends on whether we are encoding set O as itself, and also
4546
 * on whether we are encoding whitespace as itself.  RFC 2152 makes it
4547
 * clear that the answers to these questions vary between
4548
 * applications, so this code needs to be flexible.  */
4549
4550
#define ENCODE_DIRECT(c) \
4551
0
    ((c) < 128 && (c) > 0 && ((utf7_category[(c)] != 3)))
4552
4553
PyObject *
4554
PyUnicode_DecodeUTF7(const char *s,
4555
                     Py_ssize_t size,
4556
                     const char *errors)
4557
0
{
4558
0
    return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4559
0
}
4560
4561
/* The decoder.  The only state we preserve is our read position,
4562
 * i.e. how many characters we have consumed.  So if we end in the
4563
 * middle of a shift sequence we have to back off the read position
4564
 * and the output to the beginning of the sequence, otherwise we lose
4565
 * all the shift state (seen bits, number of bits seen, high
4566
 * surrogate). */
4567
4568
PyObject *
4569
PyUnicode_DecodeUTF7Stateful(const char *s,
4570
                             Py_ssize_t size,
4571
                             const char *errors,
4572
                             Py_ssize_t *consumed)
4573
31.5k
{
4574
31.5k
    const char *starts = s;
4575
31.5k
    Py_ssize_t startinpos;
4576
31.5k
    Py_ssize_t endinpos;
4577
31.5k
    const char *e;
4578
31.5k
    _PyUnicodeWriter writer;
4579
31.5k
    const char *errmsg = "";
4580
31.5k
    int inShift = 0;
4581
31.5k
    Py_ssize_t shiftOutStart;
4582
31.5k
    unsigned int base64bits = 0;
4583
31.5k
    unsigned long base64buffer = 0;
4584
31.5k
    Py_UCS4 surrogate = 0;
4585
31.5k
    PyObject *errorHandler = NULL;
4586
31.5k
    PyObject *exc = NULL;
4587
4588
31.5k
    if (size == 0) {
4589
0
        if (consumed)
4590
0
            *consumed = 0;
4591
0
        _Py_RETURN_UNICODE_EMPTY();
4592
0
    }
4593
4594
    /* Start off assuming it's all ASCII. Widen later as necessary. */
4595
31.5k
    _PyUnicodeWriter_Init(&writer);
4596
31.5k
    writer.min_length = size;
4597
4598
31.5k
    shiftOutStart = 0;
4599
31.5k
    e = s + size;
4600
4601
11.9M
    while (s < e) {
4602
11.9M
        Py_UCS4 ch;
4603
11.9M
      restart:
4604
11.9M
        ch = (unsigned char) *s;
4605
4606
11.9M
        if (inShift) { /* in a base-64 section */
4607
319k
            if (IS_BASE64(ch)) { /* consume a base-64 character */
4608
302k
                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4609
302k
                base64bits += 6;
4610
302k
                s++;
4611
302k
                if (base64bits >= 16) {
4612
                    /* we have enough bits for a UTF-16 value */
4613
107k
                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
4614
107k
                    base64bits -= 16;
4615
107k
                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4616
107k
                    assert(outCh <= 0xffff);
4617
107k
                    if (surrogate) {
4618
                        /* expecting a second surrogate */
4619
8.39k
                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4620
3.08k
                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
4621
3.08k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
4622
0
                                goto onError;
4623
3.08k
                            surrogate = 0;
4624
3.08k
                            continue;
4625
3.08k
                        }
4626
5.31k
                        else {
4627
5.31k
                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4628
0
                                goto onError;
4629
5.31k
                            surrogate = 0;
4630
5.31k
                        }
4631
8.39k
                    }
4632
104k
                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
4633
                        /* first surrogate */
4634
11.9k
                        surrogate = outCh;
4635
11.9k
                    }
4636
92.6k
                    else {
4637
92.6k
                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
4638
0
                            goto onError;
4639
92.6k
                    }
4640
104k
                }
4641
302k
            }
4642
16.7k
            else { /* now leaving a base-64 section */
4643
16.7k
                inShift = 0;
4644
16.7k
                if (base64bits > 0) { /* left-over bits */
4645
13.0k
                    if (base64bits >= 6) {
4646
                        /* We've seen at least one base-64 character */
4647
6.57k
                        s++;
4648
6.57k
                        errmsg = "partial character in shift sequence";
4649
6.57k
                        goto utf7Error;
4650
6.57k
                    }
4651
6.42k
                    else {
4652
                        /* Some bits remain; they should be zero */
4653
6.42k
                        if (base64buffer != 0) {
4654
1.24k
                            s++;
4655
1.24k
                            errmsg = "non-zero padding bits in shift sequence";
4656
1.24k
                            goto utf7Error;
4657
1.24k
                        }
4658
6.42k
                    }
4659
13.0k
                }
4660
8.89k
                if (surrogate && DECODE_DIRECT(ch)) {
4661
2.69k
                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4662
0
                        goto onError;
4663
2.69k
                }
4664
8.89k
                surrogate = 0;
4665
8.89k
                if (ch == '-') {
4666
                    /* '-' is absorbed; other terminating
4667
                       characters are preserved */
4668
1.99k
                    s++;
4669
1.99k
                }
4670
8.89k
            }
4671
319k
        }
4672
11.6M
        else if ( ch == '+' ) {
4673
29.4k
            startinpos = s-starts;
4674
29.4k
            s++; /* consume '+' */
4675
29.4k
            if (s < e && *s == '-') { /* '+-' encodes '+' */
4676
2.63k
                s++;
4677
2.63k
                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
4678
0
                    goto onError;
4679
2.63k
            }
4680
26.7k
            else if (s < e && !IS_BASE64(*s)) {
4681
6.64k
                s++;
4682
6.64k
                errmsg = "ill-formed sequence";
4683
6.64k
                goto utf7Error;
4684
6.64k
            }
4685
20.1k
            else { /* begin base64-encoded section */
4686
20.1k
                inShift = 1;
4687
20.1k
                surrogate = 0;
4688
20.1k
                shiftOutStart = writer.pos;
4689
20.1k
                base64bits = 0;
4690
20.1k
                base64buffer = 0;
4691
20.1k
            }
4692
29.4k
        }
4693
11.6M
        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
4694
11.5M
            s++;
4695
11.5M
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
4696
0
                goto onError;
4697
11.5M
        }
4698
115k
        else {
4699
115k
            startinpos = s-starts;
4700
115k
            s++;
4701
115k
            errmsg = "unexpected special character";
4702
115k
            goto utf7Error;
4703
115k
        }
4704
11.8M
        continue;
4705
11.8M
utf7Error:
4706
129k
        endinpos = s-starts;
4707
129k
        if (unicode_decode_call_errorhandler_writer(
4708
129k
                errors, &errorHandler,
4709
129k
                "utf7", errmsg,
4710
129k
                &starts, &e, &startinpos, &endinpos, &exc, &s,
4711
129k
                &writer))
4712
16.5k
            goto onError;
4713
129k
    }
4714
4715
    /* end of string */
4716
4717
14.9k
    if (inShift && !consumed) { /* in shift sequence, no more to follow */
4718
        /* if we're in an inconsistent state, that's an error */
4719
3.42k
        inShift = 0;
4720
3.42k
        if (surrogate ||
4721
3.05k
                (base64bits >= 6) ||
4722
2.06k
                (base64bits > 0 && base64buffer != 0)) {
4723
1.81k
            endinpos = size;
4724
1.81k
            if (unicode_decode_call_errorhandler_writer(
4725
1.81k
                    errors, &errorHandler,
4726
1.81k
                    "utf7", "unterminated shift sequence",
4727
1.81k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
4728
1.81k
                    &writer))
4729
1.46k
                goto onError;
4730
346
            if (s < e)
4731
0
                goto restart;
4732
346
        }
4733
3.42k
    }
4734
4735
    /* return state */
4736
13.5k
    if (consumed) {
4737
0
        if (inShift) {
4738
0
            *consumed = startinpos;
4739
0
            if (writer.pos != shiftOutStart && writer.maxchar > 127) {
4740
0
                PyObject *result = PyUnicode_FromKindAndData(
4741
0
                        writer.kind, writer.data, shiftOutStart);
4742
0
                Py_XDECREF(errorHandler);
4743
0
                Py_XDECREF(exc);
4744
0
                _PyUnicodeWriter_Dealloc(&writer);
4745
0
                return result;
4746
0
            }
4747
0
            writer.pos = shiftOutStart; /* back off output */
4748
0
        }
4749
0
        else {
4750
0
            *consumed = s-starts;
4751
0
        }
4752
0
    }
4753
4754
13.5k
    Py_XDECREF(errorHandler);
4755
13.5k
    Py_XDECREF(exc);
4756
13.5k
    return _PyUnicodeWriter_Finish(&writer);
4757
4758
18.0k
  onError:
4759
18.0k
    Py_XDECREF(errorHandler);
4760
18.0k
    Py_XDECREF(exc);
4761
18.0k
    _PyUnicodeWriter_Dealloc(&writer);
4762
18.0k
    return NULL;
4763
13.5k
}
4764
4765
4766
PyObject *
4767
_PyUnicode_EncodeUTF7(PyObject *str,
4768
                      const char *errors)
4769
0
{
4770
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
4771
0
    if (len == 0) {
4772
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
4773
0
    }
4774
0
    int kind = PyUnicode_KIND(str);
4775
0
    const void *data = PyUnicode_DATA(str);
4776
4777
    /* It might be possible to tighten this worst case */
4778
0
    if (len > PY_SSIZE_T_MAX / 8) {
4779
0
        return PyErr_NoMemory();
4780
0
    }
4781
0
    PyBytesWriter *writer = PyBytesWriter_Create(len * 8);
4782
0
    if (writer == NULL) {
4783
0
        return NULL;
4784
0
    }
4785
4786
0
    int inShift = 0;
4787
0
    unsigned int base64bits = 0;
4788
0
    unsigned long base64buffer = 0;
4789
0
    char *out = PyBytesWriter_GetData(writer);
4790
0
    for (Py_ssize_t i = 0; i < len; ++i) {
4791
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
4792
4793
0
        if (inShift) {
4794
0
            if (ENCODE_DIRECT(ch)) {
4795
                /* shifting out */
4796
0
                if (base64bits) { /* output remaining bits */
4797
0
                    *out++ = TO_BASE64(base64buffer << (6-base64bits));
4798
0
                    base64buffer = 0;
4799
0
                    base64bits = 0;
4800
0
                }
4801
0
                inShift = 0;
4802
                /* Characters not in the BASE64 set implicitly unshift the sequence
4803
                   so no '-' is required, except if the character is itself a '-' */
4804
0
                if (IS_BASE64(ch) || ch == '-') {
4805
0
                    *out++ = '-';
4806
0
                }
4807
0
                *out++ = (char) ch;
4808
0
            }
4809
0
            else {
4810
0
                goto encode_char;
4811
0
            }
4812
0
        }
4813
0
        else { /* not in a shift sequence */
4814
0
            if (ch == '+') {
4815
0
                *out++ = '+';
4816
0
                        *out++ = '-';
4817
0
            }
4818
0
            else if (ENCODE_DIRECT(ch)) {
4819
0
                *out++ = (char) ch;
4820
0
            }
4821
0
            else {
4822
0
                *out++ = '+';
4823
0
                inShift = 1;
4824
0
                goto encode_char;
4825
0
            }
4826
0
        }
4827
0
        continue;
4828
0
encode_char:
4829
0
        if (ch >= 0x10000) {
4830
0
            assert(ch <= MAX_UNICODE);
4831
4832
            /* code first surrogate */
4833
0
            base64bits += 16;
4834
0
            base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
4835
0
            while (base64bits >= 6) {
4836
0
                *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4837
0
                base64bits -= 6;
4838
0
            }
4839
            /* prepare second surrogate */
4840
0
            ch = Py_UNICODE_LOW_SURROGATE(ch);
4841
0
        }
4842
0
        base64bits += 16;
4843
0
        base64buffer = (base64buffer << 16) | ch;
4844
0
        while (base64bits >= 6) {
4845
0
            *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4846
0
            base64bits -= 6;
4847
0
        }
4848
0
    }
4849
0
    if (base64bits)
4850
0
        *out++= TO_BASE64(base64buffer << (6-base64bits) );
4851
0
    if (inShift)
4852
0
        *out++ = '-';
4853
0
    return PyBytesWriter_FinishWithPointer(writer, out);
4854
0
}
4855
4856
#undef IS_BASE64
4857
#undef FROM_BASE64
4858
#undef TO_BASE64
4859
#undef DECODE_DIRECT
4860
#undef ENCODE_DIRECT
4861
4862
/* --- UTF-8 Codec -------------------------------------------------------- */
4863
4864
PyObject *
4865
PyUnicode_DecodeUTF8(const char *s,
4866
                     Py_ssize_t size,
4867
                     const char *errors)
4868
62.9M
{
4869
62.9M
    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4870
62.9M
}
4871
4872
#include "stringlib/asciilib.h"
4873
#include "stringlib/codecs.h"
4874
#include "stringlib/undef.h"
4875
4876
#include "stringlib/ucs1lib.h"
4877
#include "stringlib/codecs.h"
4878
#include "stringlib/undef.h"
4879
4880
#include "stringlib/ucs2lib.h"
4881
#include "stringlib/codecs.h"
4882
#include "stringlib/undef.h"
4883
4884
#include "stringlib/ucs4lib.h"
4885
#include "stringlib/codecs.h"
4886
#include "stringlib/undef.h"
4887
4888
#if (SIZEOF_SIZE_T == 8)
4889
/* Mask to quickly check whether a C 'size_t' contains a
4890
   non-ASCII, UTF8-encoded char. */
4891
169M
# define ASCII_CHAR_MASK 0x8080808080808080ULL
4892
// used to count codepoints in UTF-8 string.
4893
50.3M
# define VECTOR_0101     0x0101010101010101ULL
4894
935k
# define VECTOR_00FF     0x00ff00ff00ff00ffULL
4895
#elif (SIZEOF_SIZE_T == 4)
4896
# define ASCII_CHAR_MASK 0x80808080U
4897
# define VECTOR_0101     0x01010101U
4898
# define VECTOR_00FF     0x00ff00ffU
4899
#else
4900
# error C 'size_t' size should be either 4 or 8!
4901
#endif
4902
4903
#if (defined(__clang__) || defined(__GNUC__))
4904
#define HAVE_CTZ 1
4905
static inline unsigned int
4906
ctz(size_t v)
4907
8.20M
{
4908
8.20M
    return __builtin_ctzll((unsigned long long)v);
4909
8.20M
}
4910
#elif defined(_MSC_VER)
4911
#define HAVE_CTZ 1
4912
static inline unsigned int
4913
ctz(size_t v)
4914
{
4915
    unsigned long pos;
4916
#if SIZEOF_SIZE_T == 4
4917
    _BitScanForward(&pos, v);
4918
#else
4919
    _BitScanForward64(&pos, v);
4920
#endif /* SIZEOF_SIZE_T */
4921
    return pos;
4922
}
4923
#else
4924
#define HAVE_CTZ 0
4925
#endif
4926
4927
#if HAVE_CTZ && PY_LITTLE_ENDIAN
4928
// load p[0]..p[size-1] as a size_t without unaligned access nor read ahead.
4929
static size_t
4930
load_unaligned(const unsigned char *p, size_t size)
4931
55.1M
{
4932
55.1M
    union {
4933
55.1M
        size_t s;
4934
55.1M
        unsigned char b[SIZEOF_SIZE_T];
4935
55.1M
    } u;
4936
55.1M
    u.s = 0;
4937
    // This switch statement assumes little endian because:
4938
    // * union is faster than bitwise or and shift.
4939
    // * big endian machine is rare and hard to maintain.
4940
55.1M
    switch (size) {
4941
0
    default:
4942
0
#if SIZEOF_SIZE_T == 8
4943
0
    case 8:
4944
0
        u.b[7] = p[7];
4945
0
        _Py_FALLTHROUGH;
4946
3.70M
    case 7:
4947
3.70M
        u.b[6] = p[6];
4948
3.70M
        _Py_FALLTHROUGH;
4949
10.0M
    case 6:
4950
10.0M
        u.b[5] = p[5];
4951
10.0M
        _Py_FALLTHROUGH;
4952
17.9M
    case 5:
4953
17.9M
        u.b[4] = p[4];
4954
17.9M
        _Py_FALLTHROUGH;
4955
17.9M
#endif
4956
22.7M
    case 4:
4957
22.7M
        u.b[3] = p[3];
4958
22.7M
        _Py_FALLTHROUGH;
4959
33.0M
    case 3:
4960
33.0M
        u.b[2] = p[2];
4961
33.0M
        _Py_FALLTHROUGH;
4962
47.4M
    case 2:
4963
47.4M
        u.b[1] = p[1];
4964
47.4M
        _Py_FALLTHROUGH;
4965
48.8M
    case 1:
4966
48.8M
        u.b[0] = p[0];
4967
48.8M
        break;
4968
6.27M
    case 0:
4969
6.27M
        break;
4970
55.1M
    }
4971
55.1M
    return u.s;
4972
55.1M
}
4973
#endif
4974
4975
/*
4976
 * Find the first non-ASCII character in a byte sequence.
4977
 *
4978
 * This function scans a range of bytes from `start` to `end` and returns the
4979
 * index of the first byte that is not an ASCII character (i.e., has the most
4980
 * significant bit set). If all characters in the range are ASCII, it returns
4981
 * `end - start`.
4982
 */
4983
static Py_ssize_t
4984
find_first_nonascii(const unsigned char *start, const unsigned char *end)
4985
59.8M
{
4986
    // The search is done in `size_t` chunks.
4987
    // The start and end might not be aligned at `size_t` boundaries,
4988
    // so they're handled specially.
4989
4990
59.8M
    const unsigned char *p = start;
4991
4992
59.8M
    if (end - start >= SIZEOF_SIZE_T) {
4993
        // Avoid unaligned read.
4994
22.2M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
4995
22.2M
        size_t u;
4996
22.2M
        memcpy(&u, p, sizeof(size_t));
4997
22.2M
        u &= ASCII_CHAR_MASK;
4998
22.2M
        if (u) {
4999
3.69M
            return (ctz(u) - 7) / 8;
5000
3.69M
        }
5001
18.5M
        p = _Py_ALIGN_DOWN(p + SIZEOF_SIZE_T, SIZEOF_SIZE_T);
5002
#else /* PY_LITTLE_ENDIAN && HAVE_CTZ */
5003
        const unsigned char *p2 = _Py_ALIGN_UP(p, SIZEOF_SIZE_T);
5004
        while (p < p2) {
5005
            if (*p & 0x80) {
5006
                return p - start;
5007
            }
5008
            p++;
5009
        }
5010
#endif
5011
5012
18.5M
        const unsigned char *e = end - SIZEOF_SIZE_T;
5013
101M
        while (p <= e) {
5014
84.4M
            size_t u = (*(const size_t *)p) & ASCII_CHAR_MASK;
5015
84.4M
            if (u) {
5016
1.05M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5017
1.05M
                return p - start + (ctz(u) - 7) / 8;
5018
#else
5019
                // big endian and minor compilers are difficult to test.
5020
                // fallback to per byte check.
5021
                break;
5022
#endif
5023
1.05M
            }
5024
83.3M
            p += SIZEOF_SIZE_T;
5025
83.3M
        }
5026
18.5M
    }
5027
55.1M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5028
59.8M
    assert((end - p) < SIZEOF_SIZE_T);
5029
    // we can not use *(const size_t*)p to avoid buffer overrun.
5030
55.1M
    size_t u = load_unaligned(p, end - p) & ASCII_CHAR_MASK;
5031
55.1M
    if (u) {
5032
3.45M
        return p - start + (ctz(u) - 7) / 8;
5033
3.45M
    }
5034
51.6M
    return end - start;
5035
#else
5036
    while (p < end) {
5037
        if (*p & 0x80) {
5038
            break;
5039
        }
5040
        p++;
5041
    }
5042
    return p - start;
5043
#endif
5044
55.1M
}
5045
5046
static inline int
5047
scalar_utf8_start_char(unsigned int ch)
5048
991k
{
5049
    // 0xxxxxxx or 11xxxxxx are first byte.
5050
991k
    return (~ch >> 7 | ch >> 6) & 1;
5051
991k
}
5052
5053
static inline size_t
5054
vector_utf8_start_chars(size_t v)
5055
50.3M
{
5056
50.3M
    return ((~v >> 7) | (v >> 6)) & VECTOR_0101;
5057
50.3M
}
5058
5059
5060
// Count the number of UTF-8 code points in a given byte sequence.
5061
static Py_ssize_t
5062
utf8_count_codepoints(const unsigned char *s, const unsigned char *end)
5063
375k
{
5064
375k
    Py_ssize_t len = 0;
5065
5066
375k
    if (end - s >= SIZEOF_SIZE_T) {
5067
301k
        while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
5068
21.4k
            len += scalar_utf8_start_char(*s++);
5069
21.4k
        }
5070
5071
747k
        while (s + SIZEOF_SIZE_T <= end) {
5072
467k
            const unsigned char *e = end;
5073
467k
            if (e - s > SIZEOF_SIZE_T * 255) {
5074
189k
                e = s + SIZEOF_SIZE_T * 255;
5075
189k
            }
5076
467k
            Py_ssize_t vstart = 0;
5077
50.7M
            while (s + SIZEOF_SIZE_T <= e) {
5078
50.3M
                size_t v = *(size_t*)s;
5079
50.3M
                size_t vs = vector_utf8_start_chars(v);
5080
50.3M
                vstart += vs;
5081
50.3M
                s += SIZEOF_SIZE_T;
5082
50.3M
            }
5083
467k
            vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF);
5084
467k
            vstart += vstart >> 16;
5085
467k
#if SIZEOF_SIZE_T == 8
5086
467k
            vstart += vstart >> 32;
5087
467k
#endif
5088
467k
            len += vstart & 0x7ff;
5089
467k
        }
5090
280k
    }
5091
1.34M
    while (s < end) {
5092
969k
        len += scalar_utf8_start_char(*s++);
5093
969k
    }
5094
375k
    return len;
5095
375k
}
5096
5097
static Py_ssize_t
5098
ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
5099
14.2M
{
5100
14.2M
#if SIZEOF_SIZE_T <= SIZEOF_VOID_P
5101
14.2M
    if (_Py_IS_ALIGNED(start, ALIGNOF_SIZE_T)
5102
14.1M
        && _Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T))
5103
10.7M
    {
5104
        /* Fast path, see in STRINGLIB(utf8_decode) for
5105
           an explanation. */
5106
10.7M
        const char *p = start;
5107
10.7M
        Py_UCS1 *q = dest;
5108
15.7M
        while (p + SIZEOF_SIZE_T <= end) {
5109
7.66M
            size_t value = *(const size_t *) p;
5110
7.66M
            if (value & ASCII_CHAR_MASK)
5111
2.66M
                break;
5112
4.99M
            *((size_t *)q) = value;
5113
4.99M
            p += SIZEOF_SIZE_T;
5114
4.99M
            q += SIZEOF_SIZE_T;
5115
4.99M
        }
5116
45.9M
        while (p < end) {
5117
37.9M
            if ((unsigned char)*p & 0x80)
5118
2.69M
                break;
5119
35.2M
            *q++ = *p++;
5120
35.2M
        }
5121
10.7M
        return p - start;
5122
10.7M
    }
5123
3.56M
#endif
5124
3.56M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)start,
5125
3.56M
                                         (const unsigned char*)end);
5126
3.56M
    memcpy(dest, start, pos);
5127
3.56M
    return pos;
5128
14.2M
}
5129
5130
static int
5131
unicode_decode_utf8_impl(_PyUnicodeWriter *writer,
5132
                         const char *starts, const char *s, const char *end,
5133
                         _Py_error_handler error_handler,
5134
                         const char *errors,
5135
                         Py_ssize_t *consumed)
5136
8.21M
{
5137
8.21M
    Py_ssize_t startinpos, endinpos;
5138
8.21M
    const char *errmsg = "";
5139
8.21M
    PyObject *error_handler_obj = NULL;
5140
8.21M
    PyObject *exc = NULL;
5141
5142
314M
    while (s < end) {
5143
311M
        Py_UCS4 ch;
5144
311M
        int kind = writer->kind;
5145
5146
311M
        if (kind == PyUnicode_1BYTE_KIND) {
5147
8.27M
            if (PyUnicode_IS_ASCII(writer->buffer))
5148
7.83M
                ch = asciilib_utf8_decode(&s, end, writer->data, &writer->pos);
5149
443k
            else
5150
443k
                ch = ucs1lib_utf8_decode(&s, end, writer->data, &writer->pos);
5151
303M
        } else if (kind == PyUnicode_2BYTE_KIND) {
5152
120M
            ch = ucs2lib_utf8_decode(&s, end, writer->data, &writer->pos);
5153
182M
        } else {
5154
182M
            assert(kind == PyUnicode_4BYTE_KIND);
5155
182M
            ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos);
5156
182M
        }
5157
5158
311M
        switch (ch) {
5159
5.83M
        case 0:
5160
5.83M
            if (s == end || consumed)
5161
5.80M
                goto End;
5162
25.5k
            errmsg = "unexpected end of data";
5163
25.5k
            startinpos = s - starts;
5164
25.5k
            endinpos = end - starts;
5165
25.5k
            break;
5166
221M
        case 1:
5167
221M
            errmsg = "invalid start byte";
5168
221M
            startinpos = s - starts;
5169
221M
            endinpos = startinpos + 1;
5170
221M
            break;
5171
75.6M
        case 2:
5172
75.6M
            if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5173
0
                && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
5174
0
            {
5175
                /* Truncated surrogate code in range D800-DFFF */
5176
0
                goto End;
5177
0
            }
5178
75.6M
            _Py_FALLTHROUGH;
5179
76.9M
        case 3:
5180
77.1M
        case 4:
5181
77.1M
            errmsg = "invalid continuation byte";
5182
77.1M
            startinpos = s - starts;
5183
77.1M
            endinpos = startinpos + ch - 1;
5184
77.1M
            break;
5185
7.93M
        default:
5186
            // ch doesn't fit into kind, so change the buffer kind to write
5187
            // the character
5188
7.93M
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
5189
0
                goto onError;
5190
7.93M
            continue;
5191
311M
        }
5192
5193
298M
        if (error_handler == _Py_ERROR_UNKNOWN)
5194
180k
            error_handler = _Py_GetErrorHandler(errors);
5195
5196
298M
        switch (error_handler) {
5197
0
        case _Py_ERROR_IGNORE:
5198
0
            s += (endinpos - startinpos);
5199
0
            break;
5200
5201
294M
        case _Py_ERROR_REPLACE:
5202
294M
            if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0)
5203
0
                goto onError;
5204
294M
            s += (endinpos - startinpos);
5205
294M
            break;
5206
5207
3.80M
        case _Py_ERROR_SURROGATEESCAPE:
5208
3.80M
        {
5209
3.80M
            Py_ssize_t i;
5210
5211
3.80M
            if (_PyUnicodeWriter_PrepareKind(writer, PyUnicode_2BYTE_KIND) < 0)
5212
0
                goto onError;
5213
7.61M
            for (i=startinpos; i<endinpos; i++) {
5214
3.80M
                ch = (Py_UCS4)(unsigned char)(starts[i]);
5215
3.80M
                PyUnicode_WRITE(writer->kind, writer->data, writer->pos,
5216
3.80M
                                ch + 0xdc00);
5217
3.80M
                writer->pos++;
5218
3.80M
            }
5219
3.80M
            s += (endinpos - startinpos);
5220
3.80M
            break;
5221
3.80M
        }
5222
5223
1.49k
        default:
5224
1.49k
            if (unicode_decode_call_errorhandler_writer(
5225
1.49k
                    errors, &error_handler_obj,
5226
1.49k
                    "utf-8", errmsg,
5227
1.49k
                    &starts, &end, &startinpos, &endinpos, &exc, &s,
5228
1.49k
                    writer)) {
5229
1.48k
                goto onError;
5230
1.48k
            }
5231
5232
8
            if (_PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) {
5233
0
                goto onError;
5234
0
            }
5235
298M
        }
5236
298M
    }
5237
5238
8.21M
End:
5239
8.21M
    if (consumed)
5240
1.44k
        *consumed = s - starts;
5241
5242
8.21M
    Py_XDECREF(error_handler_obj);
5243
8.21M
    Py_XDECREF(exc);
5244
8.21M
    return 0;
5245
5246
1.48k
onError:
5247
1.48k
    Py_XDECREF(error_handler_obj);
5248
1.48k
    Py_XDECREF(exc);
5249
1.48k
    return -1;
5250
8.21M
}
5251
5252
5253
static PyObject *
5254
unicode_decode_utf8(const char *s, Py_ssize_t size,
5255
                    _Py_error_handler error_handler, const char *errors,
5256
                    Py_ssize_t *consumed)
5257
96.1M
{
5258
96.1M
    if (size == 0) {
5259
5.36M
        if (consumed) {
5260
0
            *consumed = 0;
5261
0
        }
5262
5.36M
        _Py_RETURN_UNICODE_EMPTY();
5263
5.36M
    }
5264
5265
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5266
90.8M
    if (size == 1 && (unsigned char)s[0] < 128) {
5267
34.4M
        if (consumed) {
5268
0
            *consumed = 1;
5269
0
        }
5270
34.4M
        return get_latin1_char((unsigned char)s[0]);
5271
34.4M
    }
5272
5273
    // I don't know this check is necessary or not. But there is a test
5274
    // case that requires size=PY_SSIZE_T_MAX cause MemoryError.
5275
56.3M
    if (PY_SSIZE_T_MAX - sizeof(PyCompactUnicodeObject) < (size_t)size) {
5276
0
        PyErr_NoMemory();
5277
0
        return NULL;
5278
0
    }
5279
5280
56.3M
    const char *starts = s;
5281
56.3M
    const char *end = s + size;
5282
5283
56.3M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end);
5284
56.3M
    if (pos == size) {  // fast path: ASCII string.
5285
48.2M
        PyObject *u = PyUnicode_New(size, 127);
5286
48.2M
        if (u == NULL) {
5287
0
            return NULL;
5288
0
        }
5289
48.2M
        memcpy(PyUnicode_1BYTE_DATA(u), s, size);
5290
48.2M
        if (consumed) {
5291
111
            *consumed = size;
5292
111
        }
5293
48.2M
        return u;
5294
48.2M
    }
5295
5296
8.13M
    int maxchr = 127;
5297
8.13M
    Py_ssize_t maxsize = size;
5298
5299
8.13M
    unsigned char ch = (unsigned char)(s[pos]);
5300
    // error handler other than strict may remove/replace the invalid byte.
5301
    // consumed != NULL allows 1~3 bytes remainings.
5302
    // 0x80 <= ch < 0xc2 is invalid start byte that cause UnicodeDecodeError.
5303
    // otherwise: check the input and decide the maxchr and maxsize to reduce
5304
    // reallocation and copy.
5305
8.13M
    if (error_handler == _Py_ERROR_STRICT && !consumed && ch >= 0xc2) {
5306
        // we only calculate the number of codepoints and don't determine the exact maxchr.
5307
        // This is because writing fast and portable SIMD code to find maxchr is difficult.
5308
        // If reallocation occurs for a larger maxchar, knowing the exact number of codepoints
5309
        // means that it is no longer necessary to allocate several times the required amount
5310
        // of memory.
5311
375k
        maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end);
5312
375k
        if (ch < 0xc4) { // latin1
5313
237k
            maxchr = 0xff;
5314
237k
        }
5315
138k
        else if (ch < 0xf0) { // ucs2
5316
123k
            maxchr = 0xffff;
5317
123k
        }
5318
15.2k
        else { // ucs4
5319
15.2k
            maxchr = 0x10ffff;
5320
15.2k
        }
5321
375k
    }
5322
8.13M
    PyObject *u = PyUnicode_New(maxsize, maxchr);
5323
8.13M
    if (!u) {
5324
0
        return NULL;
5325
0
    }
5326
5327
    // Use _PyUnicodeWriter after fast path is failed.
5328
8.13M
    _PyUnicodeWriter writer;
5329
8.13M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
5330
8.13M
    if (maxchr <= 255) {
5331
7.99M
        memcpy(PyUnicode_1BYTE_DATA(u), s, pos);
5332
7.99M
        s += pos;
5333
7.99M
        writer.pos = pos;
5334
7.99M
    }
5335
5336
8.13M
    if (unicode_decode_utf8_impl(&writer, starts, s, end,
5337
8.13M
                                 error_handler, errors,
5338
8.13M
                                 consumed) < 0) {
5339
1.48k
        _PyUnicodeWriter_Dealloc(&writer);
5340
1.48k
        return NULL;
5341
1.48k
    }
5342
8.13M
    return _PyUnicodeWriter_Finish(&writer);
5343
8.13M
}
5344
5345
5346
// Used by PyUnicodeWriter_WriteUTF8() implementation
5347
int
5348
_PyUnicode_DecodeUTF8Writer(_PyUnicodeWriter *writer,
5349
                            const char *s, Py_ssize_t size,
5350
                            _Py_error_handler error_handler, const char *errors,
5351
                            Py_ssize_t *consumed)
5352
3.57M
{
5353
3.57M
    if (size == 0) {
5354
7.10k
        if (consumed) {
5355
0
            *consumed = 0;
5356
0
        }
5357
7.10k
        return 0;
5358
7.10k
    }
5359
5360
    // fast path: try ASCII string.
5361
3.56M
    if (_PyUnicodeWriter_Prepare(writer, size, 127) < 0) {
5362
0
        return -1;
5363
0
    }
5364
5365
3.56M
    const char *starts = s;
5366
3.56M
    const char *end = s + size;
5367
3.56M
    Py_ssize_t decoded = 0;
5368
3.56M
    Py_UCS1 *dest = (Py_UCS1*)writer->data + writer->pos * writer->kind;
5369
3.56M
    if (writer->kind == PyUnicode_1BYTE_KIND) {
5370
3.56M
        decoded = ascii_decode(s, end, dest);
5371
3.56M
        writer->pos += decoded;
5372
5373
3.56M
        if (decoded == size) {
5374
3.48M
            if (consumed) {
5375
1.48k
                *consumed = size;
5376
1.48k
            }
5377
3.48M
            return 0;
5378
3.48M
        }
5379
78.1k
        s += decoded;
5380
78.1k
    }
5381
5382
80.8k
    return unicode_decode_utf8_impl(writer, starts, s, end,
5383
80.8k
                                    error_handler, errors, consumed);
5384
3.56M
}
5385
5386
5387
PyObject *
5388
PyUnicode_DecodeUTF8Stateful(const char *s,
5389
                             Py_ssize_t size,
5390
                             const char *errors,
5391
                             Py_ssize_t *consumed)
5392
96.0M
{
5393
96.0M
    return unicode_decode_utf8(s, size,
5394
96.0M
                               errors ? _Py_ERROR_UNKNOWN : _Py_ERROR_STRICT,
5395
96.0M
                               errors, consumed);
5396
96.0M
}
5397
5398
5399
/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
5400
   non-zero, use strict error handler otherwise.
5401
5402
   On success, write a pointer to a newly allocated wide character string into
5403
   *wstr (use PyMem_RawFree() to free the memory) and write the output length
5404
   (in number of wchar_t units) into *wlen (if wlen is set).
5405
5406
   On memory allocation failure, return -1.
5407
5408
   On decoding error (if surrogateescape is zero), return -2. If wlen is
5409
   non-NULL, write the start of the illegal byte sequence into *wlen. If reason
5410
   is not NULL, write the decoding error message into *reason. */
5411
int
5412
_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
5413
                 const char **reason, _Py_error_handler errors)
5414
288
{
5415
288
    const char *orig_s = s;
5416
288
    const char *e;
5417
288
    wchar_t *unicode;
5418
288
    Py_ssize_t outpos;
5419
5420
288
    int surrogateescape = 0;
5421
288
    int surrogatepass = 0;
5422
288
    switch (errors)
5423
288
    {
5424
0
    case _Py_ERROR_STRICT:
5425
0
        break;
5426
288
    case _Py_ERROR_SURROGATEESCAPE:
5427
288
        surrogateescape = 1;
5428
288
        break;
5429
0
    case _Py_ERROR_SURROGATEPASS:
5430
0
        surrogatepass = 1;
5431
0
        break;
5432
0
    default:
5433
0
        return -3;
5434
288
    }
5435
5436
    /* Note: size will always be longer than the resulting Unicode
5437
       character count */
5438
288
    if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1 < size) {
5439
0
        return -1;
5440
0
    }
5441
5442
288
    unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
5443
288
    if (!unicode) {
5444
0
        return -1;
5445
0
    }
5446
5447
    /* Unpack UTF-8 encoded data */
5448
288
    e = s + size;
5449
288
    outpos = 0;
5450
288
    while (s < e) {
5451
288
        Py_UCS4 ch;
5452
288
#if SIZEOF_WCHAR_T == 4
5453
288
        ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
5454
#else
5455
        ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
5456
#endif
5457
288
        if (ch > 0xFF) {
5458
0
#if SIZEOF_WCHAR_T == 4
5459
0
            Py_UNREACHABLE();
5460
#else
5461
            assert(ch > 0xFFFF && ch <= MAX_UNICODE);
5462
            /* write a surrogate pair */
5463
            unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5464
            unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5465
#endif
5466
0
        }
5467
288
        else {
5468
288
            if (!ch && s == e) {
5469
288
                break;
5470
288
            }
5471
5472
0
            if (surrogateescape) {
5473
0
                unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5474
0
            }
5475
0
            else {
5476
                /* Is it a valid three-byte code? */
5477
0
                if (surrogatepass
5478
0
                    && (e - s) >= 3
5479
0
                    && (s[0] & 0xf0) == 0xe0
5480
0
                    && (s[1] & 0xc0) == 0x80
5481
0
                    && (s[2] & 0xc0) == 0x80)
5482
0
                {
5483
0
                    ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5484
0
                    s += 3;
5485
0
                    unicode[outpos++] = ch;
5486
0
                }
5487
0
                else {
5488
0
                    PyMem_RawFree(unicode );
5489
0
                    if (reason != NULL) {
5490
0
                        switch (ch) {
5491
0
                        case 0:
5492
0
                            *reason = "unexpected end of data";
5493
0
                            break;
5494
0
                        case 1:
5495
0
                            *reason = "invalid start byte";
5496
0
                            break;
5497
                        /* 2, 3, 4 */
5498
0
                        default:
5499
0
                            *reason = "invalid continuation byte";
5500
0
                            break;
5501
0
                        }
5502
0
                    }
5503
0
                    if (wlen != NULL) {
5504
0
                        *wlen = s - orig_s;
5505
0
                    }
5506
0
                    return -2;
5507
0
                }
5508
0
            }
5509
0
        }
5510
288
    }
5511
288
    unicode[outpos] = L'\0';
5512
288
    if (wlen) {
5513
288
        *wlen = outpos;
5514
288
    }
5515
288
    *wstr = unicode;
5516
288
    return 0;
5517
288
}
5518
5519
5520
wchar_t*
5521
_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
5522
                               size_t *wlen)
5523
0
{
5524
0
    wchar_t *wstr;
5525
0
    int res = _Py_DecodeUTF8Ex(arg, arglen,
5526
0
                               &wstr, wlen,
5527
0
                               NULL, _Py_ERROR_SURROGATEESCAPE);
5528
0
    if (res != 0) {
5529
        /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
5530
0
        assert(res != -3);
5531
0
        if (wlen) {
5532
0
            *wlen = (size_t)res;
5533
0
        }
5534
0
        return NULL;
5535
0
    }
5536
0
    return wstr;
5537
0
}
5538
5539
5540
/* UTF-8 encoder.
5541
5542
   On success, return 0 and write the newly allocated character string (use
5543
   PyMem_Free() to free the memory) into *str.
5544
5545
   On encoding failure, return -2 and write the position of the invalid
5546
   surrogate character into *error_pos (if error_pos is set) and the decoding
5547
   error message into *reason (if reason is set).
5548
5549
   On memory allocation failure, return -1. */
5550
int
5551
_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
5552
                 const char **reason, int raw_malloc, _Py_error_handler errors)
5553
576
{
5554
576
    const Py_ssize_t max_char_size = 4;
5555
576
    Py_ssize_t len = wcslen(text);
5556
5557
576
    assert(len >= 0);
5558
5559
576
    int surrogateescape = 0;
5560
576
    int surrogatepass = 0;
5561
576
    switch (errors)
5562
576
    {
5563
144
    case _Py_ERROR_STRICT:
5564
144
        break;
5565
432
    case _Py_ERROR_SURROGATEESCAPE:
5566
432
        surrogateescape = 1;
5567
432
        break;
5568
0
    case _Py_ERROR_SURROGATEPASS:
5569
0
        surrogatepass = 1;
5570
0
        break;
5571
0
    default:
5572
0
        return -3;
5573
576
    }
5574
5575
576
    if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5576
0
        return -1;
5577
0
    }
5578
576
    char *bytes;
5579
576
    if (raw_malloc) {
5580
576
        bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5581
576
    }
5582
0
    else {
5583
0
        bytes = PyMem_Malloc((len + 1) * max_char_size);
5584
0
    }
5585
576
    if (bytes == NULL) {
5586
0
        return -1;
5587
0
    }
5588
5589
576
    char *p = bytes;
5590
576
    Py_ssize_t i;
5591
17.9k
    for (i = 0; i < len; ) {
5592
17.3k
        Py_ssize_t ch_pos = i;
5593
17.3k
        Py_UCS4 ch = text[i];
5594
17.3k
        i++;
5595
17.3k
        if (sizeof(wchar_t) == 2
5596
0
            && Py_UNICODE_IS_HIGH_SURROGATE(ch)
5597
0
            && i < len
5598
0
            && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5599
0
        {
5600
0
            ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5601
0
            i++;
5602
0
        }
5603
5604
17.3k
        if (ch < 0x80) {
5605
            /* Encode ASCII */
5606
17.3k
            *p++ = (char) ch;
5607
5608
17.3k
        }
5609
0
        else if (ch < 0x0800) {
5610
            /* Encode Latin-1 */
5611
0
            *p++ = (char)(0xc0 | (ch >> 6));
5612
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5613
0
        }
5614
0
        else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
5615
            /* surrogateescape error handler */
5616
0
            if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
5617
0
                if (error_pos != NULL) {
5618
0
                    *error_pos = (size_t)ch_pos;
5619
0
                }
5620
0
                if (reason != NULL) {
5621
0
                    *reason = "encoding error";
5622
0
                }
5623
0
                if (raw_malloc) {
5624
0
                    PyMem_RawFree(bytes);
5625
0
                }
5626
0
                else {
5627
0
                    PyMem_Free(bytes);
5628
0
                }
5629
0
                return -2;
5630
0
            }
5631
0
            *p++ = (char)(ch & 0xff);
5632
0
        }
5633
0
        else if (ch < 0x10000) {
5634
0
            *p++ = (char)(0xe0 | (ch >> 12));
5635
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5636
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5637
0
        }
5638
0
        else {  /* ch >= 0x10000 */
5639
0
            assert(ch <= MAX_UNICODE);
5640
            /* Encode UCS4 Unicode ordinals */
5641
0
            *p++ = (char)(0xf0 | (ch >> 18));
5642
0
            *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5643
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5644
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5645
0
        }
5646
17.3k
    }
5647
576
    *p++ = '\0';
5648
5649
576
    size_t final_size = (p - bytes);
5650
576
    char *bytes2;
5651
576
    if (raw_malloc) {
5652
576
        bytes2 = PyMem_RawRealloc(bytes, final_size);
5653
576
    }
5654
0
    else {
5655
0
        bytes2 = PyMem_Realloc(bytes, final_size);
5656
0
    }
5657
576
    if (bytes2 == NULL) {
5658
0
        if (error_pos != NULL) {
5659
0
            *error_pos = (size_t)-1;
5660
0
        }
5661
0
        if (raw_malloc) {
5662
0
            PyMem_RawFree(bytes);
5663
0
        }
5664
0
        else {
5665
0
            PyMem_Free(bytes);
5666
0
        }
5667
0
        return -1;
5668
0
    }
5669
576
    *str = bytes2;
5670
576
    return 0;
5671
576
}
5672
5673
5674
/* Primary internal function which creates utf8 encoded bytes objects.
5675
5676
   Allocation strategy:  if the string is short, convert into a stack buffer
5677
   and allocate exactly as much space needed at the end.  Else allocate the
5678
   maximum possible needed (4 result bytes per Unicode character), and return
5679
   the excess memory at the end.
5680
*/
5681
static PyObject *
5682
unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
5683
                    const char *errors)
5684
18.7M
{
5685
18.7M
    if (!PyUnicode_Check(unicode)) {
5686
0
        PyErr_BadArgument();
5687
0
        return NULL;
5688
0
    }
5689
5690
18.7M
    if (PyUnicode_UTF8(unicode))
5691
9.82M
        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5692
9.82M
                                         PyUnicode_UTF8_LENGTH(unicode));
5693
5694
8.93M
    int kind = PyUnicode_KIND(unicode);
5695
8.93M
    const void *data = PyUnicode_DATA(unicode);
5696
8.93M
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5697
5698
8.93M
    PyBytesWriter *writer;
5699
8.93M
    char *end;
5700
5701
8.93M
    switch (kind) {
5702
0
    default:
5703
0
        Py_UNREACHABLE();
5704
5.93M
    case PyUnicode_1BYTE_KIND:
5705
        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5706
5.93M
        assert(!PyUnicode_IS_ASCII(unicode));
5707
5.93M
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5708
5.93M
                                      error_handler, errors, &end);
5709
5.93M
        break;
5710
1.79M
    case PyUnicode_2BYTE_KIND:
5711
1.79M
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5712
1.79M
                                      error_handler, errors, &end);
5713
1.79M
        break;
5714
1.20M
    case PyUnicode_4BYTE_KIND:
5715
1.20M
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5716
1.20M
                                      error_handler, errors, &end);
5717
1.20M
        break;
5718
8.93M
    }
5719
5720
8.93M
    if (writer == NULL) {
5721
173k
        PyBytesWriter_Discard(writer);
5722
173k
        return NULL;
5723
173k
    }
5724
8.76M
    return PyBytesWriter_FinishWithPointer(writer, end);
5725
8.93M
}
5726
5727
static int
5728
unicode_fill_utf8(PyObject *unicode)
5729
160k
{
5730
160k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(unicode);
5731
    /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5732
160k
    assert(!PyUnicode_IS_ASCII(unicode));
5733
5734
160k
    int kind = PyUnicode_KIND(unicode);
5735
160k
    const void *data = PyUnicode_DATA(unicode);
5736
160k
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5737
5738
160k
    PyBytesWriter *writer;
5739
160k
    char *end;
5740
5741
160k
    switch (kind) {
5742
0
    default:
5743
0
        Py_UNREACHABLE();
5744
117k
    case PyUnicode_1BYTE_KIND:
5745
117k
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5746
117k
                                      _Py_ERROR_STRICT, NULL, &end);
5747
117k
        break;
5748
35.7k
    case PyUnicode_2BYTE_KIND:
5749
35.7k
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5750
35.7k
                                      _Py_ERROR_STRICT, NULL, &end);
5751
35.7k
        break;
5752
7.42k
    case PyUnicode_4BYTE_KIND:
5753
7.42k
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5754
7.42k
                                      _Py_ERROR_STRICT, NULL, &end);
5755
7.42k
        break;
5756
160k
    }
5757
160k
    if (writer == NULL) {
5758
206
        return -1;
5759
206
    }
5760
5761
160k
    const char *start = PyBytesWriter_GetData(writer);
5762
160k
    Py_ssize_t len = end - start;
5763
5764
160k
    char *cache = PyMem_Malloc(len + 1);
5765
160k
    if (cache == NULL) {
5766
0
        PyBytesWriter_Discard(writer);
5767
0
        PyErr_NoMemory();
5768
0
        return -1;
5769
0
    }
5770
160k
    memcpy(cache, start, len);
5771
160k
    cache[len] = '\0';
5772
160k
    PyUnicode_SET_UTF8_LENGTH(unicode, len);
5773
160k
    PyUnicode_SET_UTF8(unicode, cache);
5774
160k
    PyBytesWriter_Discard(writer);
5775
160k
    return 0;
5776
160k
}
5777
5778
PyObject *
5779
_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5780
18.0M
{
5781
18.0M
    return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5782
18.0M
}
5783
5784
5785
PyObject *
5786
PyUnicode_AsUTF8String(PyObject *unicode)
5787
2.77k
{
5788
2.77k
    return _PyUnicode_AsUTF8String(unicode, NULL);
5789
2.77k
}
5790
5791
/* --- UTF-32 Codec ------------------------------------------------------- */
5792
5793
PyObject *
5794
PyUnicode_DecodeUTF32(const char *s,
5795
                      Py_ssize_t size,
5796
                      const char *errors,
5797
                      int *byteorder)
5798
183
{
5799
183
    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5800
183
}
5801
5802
PyObject *
5803
PyUnicode_DecodeUTF32Stateful(const char *s,
5804
                              Py_ssize_t size,
5805
                              const char *errors,
5806
                              int *byteorder,
5807
                              Py_ssize_t *consumed)
5808
37.2k
{
5809
37.2k
    const char *starts = s;
5810
37.2k
    Py_ssize_t startinpos;
5811
37.2k
    Py_ssize_t endinpos;
5812
37.2k
    _PyUnicodeWriter writer;
5813
37.2k
    const unsigned char *q, *e;
5814
37.2k
    int le, bo = 0;       /* assume native ordering by default */
5815
37.2k
    const char *encoding;
5816
37.2k
    const char *errmsg = "";
5817
37.2k
    PyObject *errorHandler = NULL;
5818
37.2k
    PyObject *exc = NULL;
5819
5820
37.2k
    q = (const unsigned char *)s;
5821
37.2k
    e = q + size;
5822
5823
37.2k
    if (byteorder)
5824
37.1k
        bo = *byteorder;
5825
5826
    /* Check for BOM marks (U+FEFF) in the input and adjust current
5827
       byte order setting accordingly. In native mode, the leading BOM
5828
       mark is skipped, in all other modes, it is copied to the output
5829
       stream as-is (giving a ZWNBSP character). */
5830
37.2k
    if (bo == 0 && size >= 4) {
5831
34.7k
        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5832
34.7k
        if (bom == 0x0000FEFF) {
5833
210
            bo = -1;
5834
210
            q += 4;
5835
210
        }
5836
34.5k
        else if (bom == 0xFFFE0000) {
5837
363
            bo = 1;
5838
363
            q += 4;
5839
363
        }
5840
34.7k
        if (byteorder)
5841
34.5k
            *byteorder = bo;
5842
34.7k
    }
5843
5844
37.2k
    if (q == e) {
5845
122
        if (consumed)
5846
0
            *consumed = size;
5847
122
        _Py_RETURN_UNICODE_EMPTY();
5848
122
    }
5849
5850
#ifdef WORDS_BIGENDIAN
5851
    le = bo < 0;
5852
#else
5853
37.1k
    le = bo <= 0;
5854
37.1k
#endif
5855
37.1k
    encoding = le ? "utf-32-le" : "utf-32-be";
5856
5857
37.1k
    _PyUnicodeWriter_Init(&writer);
5858
37.1k
    writer.min_length = (e - q + 3) / 4;
5859
37.1k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
5860
0
        goto onError;
5861
5862
116k
    while (1) {
5863
116k
        Py_UCS4 ch = 0;
5864
116k
        Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
5865
5866
116k
        if (e - q >= 4) {
5867
93.4k
            int kind = writer.kind;
5868
93.4k
            void *data = writer.data;
5869
93.4k
            const unsigned char *last = e - 4;
5870
93.4k
            Py_ssize_t pos = writer.pos;
5871
93.4k
            if (le) {
5872
2.40M
                do {
5873
2.40M
                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5874
2.40M
                    if (ch > maxch)
5875
88.5k
                        break;
5876
2.31M
                    if (kind != PyUnicode_1BYTE_KIND &&
5877
2.30M
                        Py_UNICODE_IS_SURROGATE(ch))
5878
322
                        break;
5879
2.31M
                    PyUnicode_WRITE(kind, data, pos++, ch);
5880
2.31M
                    q += 4;
5881
2.31M
                } while (q <= last);
5882
89.9k
            }
5883
3.49k
            else {
5884
5.92k
                do {
5885
5.92k
                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5886
5.92k
                    if (ch > maxch)
5887
3.18k
                        break;
5888
2.74k
                    if (kind != PyUnicode_1BYTE_KIND &&
5889
2.28k
                        Py_UNICODE_IS_SURROGATE(ch))
5890
113
                        break;
5891
2.62k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5892
2.62k
                    q += 4;
5893
2.62k
                } while (q <= last);
5894
3.49k
            }
5895
93.4k
            writer.pos = pos;
5896
93.4k
        }
5897
5898
116k
        if (Py_UNICODE_IS_SURROGATE(ch)) {
5899
440
            errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
5900
440
            startinpos = ((const char *)q) - starts;
5901
440
            endinpos = startinpos + 4;
5902
440
        }
5903
115k
        else if (ch <= maxch) {
5904
24.2k
            if (q == e || consumed)
5905
3.75k
                break;
5906
            /* remaining bytes at the end? (size should be divisible by 4) */
5907
20.5k
            errmsg = "truncated data";
5908
20.5k
            startinpos = ((const char *)q) - starts;
5909
20.5k
            endinpos = ((const char *)e) - starts;
5910
20.5k
        }
5911
91.7k
        else {
5912
91.7k
            if (ch < 0x110000) {
5913
4.40k
                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
5914
0
                    goto onError;
5915
4.40k
                q += 4;
5916
4.40k
                continue;
5917
4.40k
            }
5918
87.3k
            errmsg = "code point not in range(0x110000)";
5919
87.3k
            startinpos = ((const char *)q) - starts;
5920
87.3k
            endinpos = startinpos + 4;
5921
87.3k
        }
5922
5923
        /* The remaining input chars are ignored if the callback
5924
           chooses to skip the input */
5925
108k
        if (unicode_decode_call_errorhandler_writer(
5926
108k
                errors, &errorHandler,
5927
108k
                encoding, errmsg,
5928
108k
                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5929
108k
                &writer))
5930
33.4k
            goto onError;
5931
108k
    }
5932
5933
3.75k
    if (consumed)
5934
0
        *consumed = (const char *)q-starts;
5935
5936
3.75k
    Py_XDECREF(errorHandler);
5937
3.75k
    Py_XDECREF(exc);
5938
3.75k
    return _PyUnicodeWriter_Finish(&writer);
5939
5940
33.4k
  onError:
5941
33.4k
    _PyUnicodeWriter_Dealloc(&writer);
5942
33.4k
    Py_XDECREF(errorHandler);
5943
33.4k
    Py_XDECREF(exc);
5944
33.4k
    return NULL;
5945
37.1k
}
5946
5947
PyObject *
5948
_PyUnicode_EncodeUTF32(PyObject *str,
5949
                       const char *errors,
5950
                       int byteorder)
5951
0
{
5952
0
    if (!PyUnicode_Check(str)) {
5953
0
        PyErr_BadArgument();
5954
0
        return NULL;
5955
0
    }
5956
0
    int kind = PyUnicode_KIND(str);
5957
0
    const void *data = PyUnicode_DATA(str);
5958
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
5959
5960
0
    if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
5961
0
        return PyErr_NoMemory();
5962
0
    Py_ssize_t nsize = len + (byteorder == 0);
5963
5964
0
#if PY_LITTLE_ENDIAN
5965
0
    int native_ordering = byteorder <= 0;
5966
#else
5967
    int native_ordering = byteorder >= 0;
5968
#endif
5969
5970
0
    if (kind == PyUnicode_1BYTE_KIND) {
5971
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
5972
        // on short strings
5973
0
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 4);
5974
0
        if (v == NULL) {
5975
0
            return NULL;
5976
0
        }
5977
5978
        /* output buffer is 4-bytes aligned */
5979
0
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5980
0
        uint32_t *out = (uint32_t *)PyBytes_AS_STRING(v);
5981
0
        if (byteorder == 0) {
5982
0
            *out++ = 0xFEFF;
5983
0
        }
5984
0
        if (len > 0) {
5985
0
            ucs1lib_utf32_encode((const Py_UCS1 *)data, len,
5986
0
                                 &out, native_ordering);
5987
0
        }
5988
0
        return v;
5989
0
    }
5990
5991
0
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 4);
5992
0
    if (writer == NULL) {
5993
0
        return NULL;
5994
0
    }
5995
5996
    /* output buffer is 4-bytes aligned */
5997
0
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 4));
5998
0
    uint32_t *out = (uint32_t *)PyBytesWriter_GetData(writer);
5999
0
    if (byteorder == 0) {
6000
0
        *out++ = 0xFEFF;
6001
0
    }
6002
0
    if (len == 0) {
6003
0
        return PyBytesWriter_Finish(writer);
6004
0
    }
6005
6006
0
    const char *encoding;
6007
0
    if (byteorder == -1)
6008
0
        encoding = "utf-32-le";
6009
0
    else if (byteorder == 1)
6010
0
        encoding = "utf-32-be";
6011
0
    else
6012
0
        encoding = "utf-32";
6013
6014
0
    PyObject *errorHandler = NULL;
6015
0
    PyObject *exc = NULL;
6016
0
    PyObject *rep = NULL;
6017
6018
0
    for (Py_ssize_t pos = 0; pos < len; ) {
6019
0
        if (kind == PyUnicode_2BYTE_KIND) {
6020
0
            pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
6021
0
                                        &out, native_ordering);
6022
0
        }
6023
0
        else {
6024
0
            assert(kind == PyUnicode_4BYTE_KIND);
6025
0
            pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
6026
0
                                        &out, native_ordering);
6027
0
        }
6028
0
        if (pos == len)
6029
0
            break;
6030
6031
0
        Py_ssize_t newpos;
6032
0
        rep = unicode_encode_call_errorhandler(
6033
0
                errors, &errorHandler,
6034
0
                encoding, "surrogates not allowed",
6035
0
                str, &exc, pos, pos + 1, &newpos);
6036
0
        if (!rep)
6037
0
            goto error;
6038
6039
0
        Py_ssize_t repsize, moreunits;
6040
0
        if (PyBytes_Check(rep)) {
6041
0
            repsize = PyBytes_GET_SIZE(rep);
6042
0
            if (repsize & 3) {
6043
0
                raise_encode_exception(&exc, encoding,
6044
0
                                       str, pos, pos + 1,
6045
0
                                       "surrogates not allowed");
6046
0
                goto error;
6047
0
            }
6048
0
            moreunits = repsize / 4;
6049
0
        }
6050
0
        else {
6051
0
            assert(PyUnicode_Check(rep));
6052
0
            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6053
0
            if (!PyUnicode_IS_ASCII(rep)) {
6054
0
                raise_encode_exception(&exc, encoding,
6055
0
                                       str, pos, pos + 1,
6056
0
                                       "surrogates not allowed");
6057
0
                goto error;
6058
0
            }
6059
0
        }
6060
0
        moreunits += pos - newpos;
6061
0
        pos = newpos;
6062
6063
        /* four bytes are reserved for each surrogate */
6064
0
        if (moreunits > 0) {
6065
0
            out = PyBytesWriter_GrowAndUpdatePointer(writer, 4 * moreunits, out);
6066
0
            if (out == NULL) {
6067
0
                goto error;
6068
0
            }
6069
0
        }
6070
6071
0
        if (PyBytes_Check(rep)) {
6072
0
            memcpy(out, PyBytes_AS_STRING(rep), repsize);
6073
0
            out += repsize / 4;
6074
0
        }
6075
0
        else {
6076
            /* rep is unicode */
6077
0
            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6078
0
            ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6079
0
                                 &out, native_ordering);
6080
0
        }
6081
6082
0
        Py_CLEAR(rep);
6083
0
    }
6084
6085
0
    Py_XDECREF(errorHandler);
6086
0
    Py_XDECREF(exc);
6087
6088
    /* Cut back to size actually needed. This is necessary for, for example,
6089
       encoding of a string containing isolated surrogates and the 'ignore'
6090
       handler is used. */
6091
0
    return PyBytesWriter_FinishWithPointer(writer, out);
6092
6093
0
  error:
6094
0
    Py_XDECREF(rep);
6095
0
    Py_XDECREF(errorHandler);
6096
0
    Py_XDECREF(exc);
6097
0
    PyBytesWriter_Discard(writer);
6098
0
    return NULL;
6099
0
}
6100
6101
PyObject *
6102
PyUnicode_AsUTF32String(PyObject *unicode)
6103
0
{
6104
0
    return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
6105
0
}
6106
6107
/* --- UTF-16 Codec ------------------------------------------------------- */
6108
6109
PyObject *
6110
PyUnicode_DecodeUTF16(const char *s,
6111
                      Py_ssize_t size,
6112
                      const char *errors,
6113
                      int *byteorder)
6114
157
{
6115
157
    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
6116
157
}
6117
6118
PyObject *
6119
PyUnicode_DecodeUTF16Stateful(const char *s,
6120
                              Py_ssize_t size,
6121
                              const char *errors,
6122
                              int *byteorder,
6123
                              Py_ssize_t *consumed)
6124
19.0k
{
6125
19.0k
    const char *starts = s;
6126
19.0k
    Py_ssize_t startinpos;
6127
19.0k
    Py_ssize_t endinpos;
6128
19.0k
    _PyUnicodeWriter writer;
6129
19.0k
    const unsigned char *q, *e;
6130
19.0k
    int bo = 0;       /* assume native ordering by default */
6131
19.0k
    int native_ordering;
6132
19.0k
    const char *errmsg = "";
6133
19.0k
    PyObject *errorHandler = NULL;
6134
19.0k
    PyObject *exc = NULL;
6135
19.0k
    const char *encoding;
6136
6137
19.0k
    q = (const unsigned char *)s;
6138
19.0k
    e = q + size;
6139
6140
19.0k
    if (byteorder)
6141
18.9k
        bo = *byteorder;
6142
6143
    /* Check for BOM marks (U+FEFF) in the input and adjust current
6144
       byte order setting accordingly. In native mode, the leading BOM
6145
       mark is skipped, in all other modes, it is copied to the output
6146
       stream as-is (giving a ZWNBSP character). */
6147
19.0k
    if (bo == 0 && size >= 2) {
6148
18.1k
        const Py_UCS4 bom = (q[1] << 8) | q[0];
6149
18.1k
        if (bom == 0xFEFF) {
6150
276
            q += 2;
6151
276
            bo = -1;
6152
276
        }
6153
17.9k
        else if (bom == 0xFFFE) {
6154
2.21k
            q += 2;
6155
2.21k
            bo = 1;
6156
2.21k
        }
6157
18.1k
        if (byteorder)
6158
18.0k
            *byteorder = bo;
6159
18.1k
    }
6160
6161
19.0k
    if (q == e) {
6162
56
        if (consumed)
6163
0
            *consumed = size;
6164
56
        _Py_RETURN_UNICODE_EMPTY();
6165
56
    }
6166
6167
19.0k
#if PY_LITTLE_ENDIAN
6168
19.0k
    native_ordering = bo <= 0;
6169
19.0k
    encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
6170
#else
6171
    native_ordering = bo >= 0;
6172
    encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
6173
#endif
6174
6175
    /* Note: size will always be longer than the resulting Unicode
6176
       character count normally.  Error handler will take care of
6177
       resizing when needed. */
6178
19.0k
    _PyUnicodeWriter_Init(&writer);
6179
19.0k
    writer.min_length = (e - q + 1) / 2;
6180
19.0k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
6181
0
        goto onError;
6182
6183
71.3k
    while (1) {
6184
71.3k
        Py_UCS4 ch = 0;
6185
71.3k
        if (e - q >= 2) {
6186
61.6k
            int kind = writer.kind;
6187
61.6k
            if (kind == PyUnicode_1BYTE_KIND) {
6188
22.5k
                if (PyUnicode_IS_ASCII(writer.buffer))
6189
18.4k
                    ch = asciilib_utf16_decode(&q, e,
6190
18.4k
                            (Py_UCS1*)writer.data, &writer.pos,
6191
18.4k
                            native_ordering);
6192
4.09k
                else
6193
4.09k
                    ch = ucs1lib_utf16_decode(&q, e,
6194
4.09k
                            (Py_UCS1*)writer.data, &writer.pos,
6195
4.09k
                            native_ordering);
6196
39.1k
            } else if (kind == PyUnicode_2BYTE_KIND) {
6197
21.1k
                ch = ucs2lib_utf16_decode(&q, e,
6198
21.1k
                        (Py_UCS2*)writer.data, &writer.pos,
6199
21.1k
                        native_ordering);
6200
21.1k
            } else {
6201
17.9k
                assert(kind == PyUnicode_4BYTE_KIND);
6202
17.9k
                ch = ucs4lib_utf16_decode(&q, e,
6203
17.9k
                        (Py_UCS4*)writer.data, &writer.pos,
6204
17.9k
                        native_ordering);
6205
17.9k
            }
6206
61.6k
        }
6207
6208
71.3k
        switch (ch)
6209
71.3k
        {
6210
19.3k
        case 0:
6211
            /* remaining byte at the end? (size should be even) */
6212
19.3k
            if (q == e || consumed)
6213
11.5k
                goto End;
6214
7.80k
            errmsg = "truncated data";
6215
7.80k
            startinpos = ((const char *)q) - starts;
6216
7.80k
            endinpos = ((const char *)e) - starts;
6217
7.80k
            break;
6218
            /* The remaining input chars are ignored if the callback
6219
               chooses to skip the input */
6220
1.75k
        case 1:
6221
1.75k
            q -= 2;
6222
1.75k
            if (consumed)
6223
0
                goto End;
6224
1.75k
            errmsg = "unexpected end of data";
6225
1.75k
            startinpos = ((const char *)q) - starts;
6226
1.75k
            endinpos = ((const char *)e) - starts;
6227
1.75k
            break;
6228
18.0k
        case 2:
6229
18.0k
            errmsg = "illegal encoding";
6230
18.0k
            startinpos = ((const char *)q) - 2 - starts;
6231
18.0k
            endinpos = startinpos + 2;
6232
18.0k
            break;
6233
10.7k
        case 3:
6234
10.7k
            errmsg = "illegal UTF-16 surrogate";
6235
10.7k
            startinpos = ((const char *)q) - 4 - starts;
6236
10.7k
            endinpos = startinpos + 2;
6237
10.7k
            break;
6238
21.4k
        default:
6239
21.4k
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
6240
0
                goto onError;
6241
21.4k
            continue;
6242
71.3k
        }
6243
6244
38.3k
        if (unicode_decode_call_errorhandler_writer(
6245
38.3k
                errors,
6246
38.3k
                &errorHandler,
6247
38.3k
                encoding, errmsg,
6248
38.3k
                &starts,
6249
38.3k
                (const char **)&e,
6250
38.3k
                &startinpos,
6251
38.3k
                &endinpos,
6252
38.3k
                &exc,
6253
38.3k
                (const char **)&q,
6254
38.3k
                &writer))
6255
7.47k
            goto onError;
6256
38.3k
    }
6257
6258
11.5k
End:
6259
11.5k
    if (consumed)
6260
0
        *consumed = (const char *)q-starts;
6261
6262
11.5k
    Py_XDECREF(errorHandler);
6263
11.5k
    Py_XDECREF(exc);
6264
11.5k
    return _PyUnicodeWriter_Finish(&writer);
6265
6266
7.47k
  onError:
6267
7.47k
    _PyUnicodeWriter_Dealloc(&writer);
6268
7.47k
    Py_XDECREF(errorHandler);
6269
7.47k
    Py_XDECREF(exc);
6270
7.47k
    return NULL;
6271
19.0k
}
6272
6273
PyObject *
6274
_PyUnicode_EncodeUTF16(PyObject *str,
6275
                       const char *errors,
6276
                       int byteorder)
6277
9.70k
{
6278
9.70k
    if (!PyUnicode_Check(str)) {
6279
0
        PyErr_BadArgument();
6280
0
        return NULL;
6281
0
    }
6282
9.70k
    int kind = PyUnicode_KIND(str);
6283
9.70k
    const void *data = PyUnicode_DATA(str);
6284
9.70k
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6285
6286
9.70k
    Py_ssize_t pairs = 0;
6287
9.70k
    if (kind == PyUnicode_4BYTE_KIND) {
6288
0
        const Py_UCS4 *in = (const Py_UCS4 *)data;
6289
0
        const Py_UCS4 *end = in + len;
6290
0
        while (in < end) {
6291
0
            if (*in++ >= 0x10000) {
6292
0
                pairs++;
6293
0
            }
6294
0
        }
6295
0
    }
6296
9.70k
    if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
6297
0
        return PyErr_NoMemory();
6298
0
    }
6299
9.70k
    Py_ssize_t nsize = len + pairs + (byteorder == 0);
6300
6301
#if PY_BIG_ENDIAN
6302
    int native_ordering = byteorder >= 0;
6303
#else
6304
9.70k
    int native_ordering = byteorder <= 0;
6305
9.70k
#endif
6306
6307
9.70k
    if (kind == PyUnicode_1BYTE_KIND) {
6308
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6309
        // on short strings
6310
9.63k
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 2);
6311
9.63k
        if (v == NULL) {
6312
0
            return NULL;
6313
0
        }
6314
6315
        /* output buffer is 2-bytes aligned */
6316
9.63k
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
6317
9.63k
        unsigned short *out = (unsigned short *)PyBytes_AS_STRING(v);
6318
9.63k
        if (byteorder == 0) {
6319
0
            *out++ = 0xFEFF;
6320
0
        }
6321
9.63k
        if (len > 0) {
6322
9.63k
            ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
6323
9.63k
        }
6324
9.63k
        return v;
6325
9.63k
    }
6326
6327
73
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 2);
6328
73
    if (writer == NULL) {
6329
0
        return NULL;
6330
0
    }
6331
6332
    /* output buffer is 2-bytes aligned */
6333
73
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 2));
6334
73
    unsigned short *out = PyBytesWriter_GetData(writer);
6335
73
    if (byteorder == 0) {
6336
0
        *out++ = 0xFEFF;
6337
0
    }
6338
73
    if (len == 0) {
6339
0
        return PyBytesWriter_Finish(writer);
6340
0
    }
6341
6342
73
    const char *encoding;
6343
73
    if (byteorder < 0) {
6344
0
        encoding = "utf-16-le";
6345
0
    }
6346
73
    else if (byteorder > 0) {
6347
73
        encoding = "utf-16-be";
6348
73
    }
6349
0
    else {
6350
0
        encoding = "utf-16";
6351
0
    }
6352
6353
73
    PyObject *errorHandler = NULL;
6354
73
    PyObject *exc = NULL;
6355
73
    PyObject *rep = NULL;
6356
6357
73
    for (Py_ssize_t pos = 0; pos < len; ) {
6358
73
        if (kind == PyUnicode_2BYTE_KIND) {
6359
73
            pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
6360
73
                                        &out, native_ordering);
6361
73
        }
6362
0
        else {
6363
0
            assert(kind == PyUnicode_4BYTE_KIND);
6364
0
            pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
6365
0
                                        &out, native_ordering);
6366
0
        }
6367
73
        if (pos == len)
6368
73
            break;
6369
6370
0
        Py_ssize_t newpos;
6371
0
        rep = unicode_encode_call_errorhandler(
6372
0
                errors, &errorHandler,
6373
0
                encoding, "surrogates not allowed",
6374
0
                str, &exc, pos, pos + 1, &newpos);
6375
0
        if (!rep)
6376
0
            goto error;
6377
6378
0
        Py_ssize_t repsize, moreunits;
6379
0
        if (PyBytes_Check(rep)) {
6380
0
            repsize = PyBytes_GET_SIZE(rep);
6381
0
            if (repsize & 1) {
6382
0
                raise_encode_exception(&exc, encoding,
6383
0
                                       str, pos, pos + 1,
6384
0
                                       "surrogates not allowed");
6385
0
                goto error;
6386
0
            }
6387
0
            moreunits = repsize / 2;
6388
0
        }
6389
0
        else {
6390
0
            assert(PyUnicode_Check(rep));
6391
0
            moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6392
0
            if (!PyUnicode_IS_ASCII(rep)) {
6393
0
                raise_encode_exception(&exc, encoding,
6394
0
                                       str, pos, pos + 1,
6395
0
                                       "surrogates not allowed");
6396
0
                goto error;
6397
0
            }
6398
0
        }
6399
0
        moreunits += pos - newpos;
6400
0
        pos = newpos;
6401
6402
        /* two bytes are reserved for each surrogate */
6403
0
        if (moreunits > 0) {
6404
0
            out = PyBytesWriter_GrowAndUpdatePointer(writer, 2 * moreunits, out);
6405
0
            if (out == NULL) {
6406
0
                goto error;
6407
0
            }
6408
0
        }
6409
6410
0
        if (PyBytes_Check(rep)) {
6411
0
            memcpy(out, PyBytes_AS_STRING(rep), repsize);
6412
0
            out += repsize / 2;
6413
0
        } else {
6414
            /* rep is unicode */
6415
0
            assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6416
0
            ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6417
0
                                 &out, native_ordering);
6418
0
        }
6419
6420
0
        Py_CLEAR(rep);
6421
0
    }
6422
6423
73
    Py_XDECREF(errorHandler);
6424
73
    Py_XDECREF(exc);
6425
6426
    /* Cut back to size actually needed. This is necessary for, for example,
6427
    encoding of a string containing isolated surrogates and the 'ignore' handler
6428
    is used. */
6429
73
    return PyBytesWriter_FinishWithPointer(writer, out);
6430
6431
0
  error:
6432
0
    Py_XDECREF(rep);
6433
0
    Py_XDECREF(errorHandler);
6434
0
    Py_XDECREF(exc);
6435
0
    PyBytesWriter_Discard(writer);
6436
0
    return NULL;
6437
73
}
6438
6439
PyObject *
6440
PyUnicode_AsUTF16String(PyObject *unicode)
6441
0
{
6442
0
    return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
6443
0
}
6444
6445
_PyUnicode_Name_CAPI *
6446
_PyUnicode_GetNameCAPI(void)
6447
16.4k
{
6448
16.4k
    PyInterpreterState *interp = _PyInterpreterState_GET();
6449
16.4k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6450
6451
16.4k
    ucnhash_capi = _Py_atomic_load_ptr(&interp->unicode.ucnhash_capi);
6452
16.4k
    if (ucnhash_capi == NULL) {
6453
2
        ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6454
2
                PyUnicodeData_CAPSULE_NAME, 1);
6455
6456
        // It's fine if we overwrite the value here. It's always the same value.
6457
2
        _Py_atomic_store_ptr(&interp->unicode.ucnhash_capi, ucnhash_capi);
6458
2
    }
6459
16.4k
    return ucnhash_capi;
6460
16.4k
}
6461
6462
/* --- Unicode Escape Codec ----------------------------------------------- */
6463
6464
PyObject *
6465
_PyUnicode_DecodeUnicodeEscapeInternal2(const char *s,
6466
                               Py_ssize_t size,
6467
                               const char *errors,
6468
                               Py_ssize_t *consumed,
6469
                               int *first_invalid_escape_char,
6470
                               const char **first_invalid_escape_ptr)
6471
29.7k
{
6472
29.7k
    const char *starts = s;
6473
29.7k
    const char *initial_starts = starts;
6474
29.7k
    _PyUnicodeWriter writer;
6475
29.7k
    const char *end;
6476
29.7k
    PyObject *errorHandler = NULL;
6477
29.7k
    PyObject *exc = NULL;
6478
29.7k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6479
6480
    // so we can remember if we've seen an invalid escape char or not
6481
29.7k
    *first_invalid_escape_char = -1;
6482
29.7k
    *first_invalid_escape_ptr = NULL;
6483
6484
29.7k
    if (size == 0) {
6485
2.31k
        if (consumed) {
6486
0
            *consumed = 0;
6487
0
        }
6488
2.31k
        _Py_RETURN_UNICODE_EMPTY();
6489
2.31k
    }
6490
    /* Escaped strings will always be longer than the resulting
6491
       Unicode string, so we start with size here and then reduce the
6492
       length after conversion to the true value.
6493
       (but if the error callback returns a long replacement string
6494
       we'll have to allocate more space) */
6495
27.4k
    _PyUnicodeWriter_Init(&writer);
6496
27.4k
    writer.min_length = size;
6497
27.4k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6498
0
        goto onError;
6499
0
    }
6500
6501
27.4k
    end = s + size;
6502
8.93M
    while (s < end) {
6503
8.90M
        unsigned char c = (unsigned char) *s++;
6504
8.90M
        Py_UCS4 ch;
6505
8.90M
        int count;
6506
8.90M
        const char *message;
6507
6508
8.90M
#define WRITE_ASCII_CHAR(ch)                                                  \
6509
8.90M
            do {                                                              \
6510
115k
                assert(ch <= 127);                                            \
6511
115k
                assert(writer.pos < writer.size);                             \
6512
115k
                PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch);  \
6513
115k
            } while(0)
6514
6515
8.90M
#define WRITE_CHAR(ch)                                                        \
6516
8.90M
            do {                                                              \
6517
8.82M
                if (ch <= writer.maxchar) {                                   \
6518
8.81M
                    assert(writer.pos < writer.size);                         \
6519
8.81M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6520
8.81M
                }                                                             \
6521
8.82M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6522
0
                    goto onError;                                             \
6523
0
                }                                                             \
6524
8.82M
            } while(0)
6525
6526
        /* Non-escape characters are interpreted as Unicode ordinals */
6527
8.90M
        if (c != '\\') {
6528
8.62M
            WRITE_CHAR(c);
6529
8.62M
            continue;
6530
8.62M
        }
6531
6532
280k
        Py_ssize_t startinpos = s - starts - 1;
6533
        /* \ - Escapes */
6534
280k
        if (s >= end) {
6535
15
            message = "\\ at end of string";
6536
15
            goto incomplete;
6537
15
        }
6538
280k
        c = (unsigned char) *s++;
6539
6540
280k
        assert(writer.pos < writer.size);
6541
280k
        switch (c) {
6542
6543
            /* \x escapes */
6544
1.66k
        case '\n': continue;
6545
35.9k
        case '\\': WRITE_ASCII_CHAR('\\'); continue;
6546
1.99k
        case '\'': WRITE_ASCII_CHAR('\''); continue;
6547
3.54k
        case '\"': WRITE_ASCII_CHAR('\"'); continue;
6548
3.67k
        case 'b': WRITE_ASCII_CHAR('\b'); continue;
6549
        /* FF */
6550
6.68k
        case 'f': WRITE_ASCII_CHAR('\014'); continue;
6551
1.69k
        case 't': WRITE_ASCII_CHAR('\t'); continue;
6552
2.12k
        case 'n': WRITE_ASCII_CHAR('\n'); continue;
6553
6.26k
        case 'r': WRITE_ASCII_CHAR('\r'); continue;
6554
        /* VT */
6555
14.4k
        case 'v': WRITE_ASCII_CHAR('\013'); continue;
6556
        /* BEL, not classic C */
6557
2.56k
        case 'a': WRITE_ASCII_CHAR('\007'); continue;
6558
6559
            /* \OOO (octal) escapes */
6560
42.4k
        case '0': case '1': case '2': case '3':
6561
109k
        case '4': case '5': case '6': case '7':
6562
109k
            ch = c - '0';
6563
109k
            if (s < end && '0' <= *s && *s <= '7') {
6564
64.9k
                ch = (ch<<3) + *s++ - '0';
6565
64.9k
                if (s < end && '0' <= *s && *s <= '7') {
6566
51.0k
                    ch = (ch<<3) + *s++ - '0';
6567
51.0k
                }
6568
64.9k
            }
6569
109k
            if (ch > 0377) {
6570
49.0k
                if (*first_invalid_escape_char == -1) {
6571
1.27k
                    *first_invalid_escape_char = ch;
6572
1.27k
                    if (starts == initial_starts) {
6573
                        /* Back up 3 chars, since we've already incremented s. */
6574
1.27k
                        *first_invalid_escape_ptr = s - 3;
6575
1.27k
                    }
6576
1.27k
                }
6577
49.0k
            }
6578
109k
            WRITE_CHAR(ch);
6579
109k
            continue;
6580
6581
            /* hex escapes */
6582
            /* \xXX */
6583
109k
        case 'x':
6584
14.6k
            count = 2;
6585
14.6k
            message = "truncated \\xXX escape";
6586
14.6k
            goto hexescape;
6587
6588
            /* \uXXXX */
6589
6.22k
        case 'u':
6590
6.22k
            count = 4;
6591
6.22k
            message = "truncated \\uXXXX escape";
6592
6.22k
            goto hexescape;
6593
6594
            /* \UXXXXXXXX */
6595
17.4k
        case 'U':
6596
17.4k
            count = 8;
6597
17.4k
            message = "truncated \\UXXXXXXXX escape";
6598
38.2k
        hexescape:
6599
231k
            for (ch = 0; count; ++s, --count) {
6600
193k
                if (s >= end) {
6601
19
                    goto incomplete;
6602
19
                }
6603
193k
                c = (unsigned char)*s;
6604
193k
                ch <<= 4;
6605
193k
                if (c >= '0' && c <= '9') {
6606
137k
                    ch += c - '0';
6607
137k
                }
6608
55.5k
                else if (c >= 'a' && c <= 'f') {
6609
55.2k
                    ch += c - ('a' - 10);
6610
55.2k
                }
6611
270
                else if (c >= 'A' && c <= 'F') {
6612
232
                    ch += c - ('A' - 10);
6613
232
                }
6614
38
                else {
6615
38
                    goto error;
6616
38
                }
6617
193k
            }
6618
6619
            /* when we get here, ch is a 32-bit unicode character */
6620
38.2k
            if (ch > MAX_UNICODE) {
6621
8
                message = "illegal Unicode character";
6622
8
                goto error;
6623
8
            }
6624
6625
38.2k
            WRITE_CHAR(ch);
6626
38.2k
            continue;
6627
6628
            /* \N{name} */
6629
38.2k
        case 'N':
6630
16.4k
            ucnhash_capi = _PyUnicode_GetNameCAPI();
6631
16.4k
            if (ucnhash_capi == NULL) {
6632
0
                PyErr_SetString(
6633
0
                        PyExc_UnicodeError,
6634
0
                        "\\N escapes not supported (can't load unicodedata module)"
6635
0
                );
6636
0
                goto onError;
6637
0
            }
6638
6639
16.4k
            message = "malformed \\N character escape";
6640
16.4k
            if (s >= end) {
6641
9
                goto incomplete;
6642
9
            }
6643
16.4k
            if (*s == '{') {
6644
16.3k
                const char *start = ++s;
6645
16.3k
                size_t namelen;
6646
                /* look for the closing brace */
6647
131k
                while (s < end && *s != '}')
6648
114k
                    s++;
6649
16.3k
                if (s >= end) {
6650
23
                    goto incomplete;
6651
23
                }
6652
16.3k
                namelen = s - start;
6653
16.3k
                if (namelen) {
6654
                    /* found a name.  look it up in the unicode database */
6655
16.3k
                    s++;
6656
16.3k
                    ch = 0xffffffff; /* in case 'getcode' messes up */
6657
16.3k
                    if (namelen <= INT_MAX &&
6658
16.3k
                        ucnhash_capi->getcode(start, (int)namelen,
6659
16.3k
                                              &ch, 0)) {
6660
16.2k
                        assert(ch <= MAX_UNICODE);
6661
16.2k
                        WRITE_CHAR(ch);
6662
16.2k
                        continue;
6663
16.2k
                    }
6664
116
                    message = "unknown Unicode character name";
6665
116
                }
6666
16.3k
            }
6667
135
            goto error;
6668
6669
36.1k
        default:
6670
36.1k
            if (*first_invalid_escape_char == -1) {
6671
4.35k
                *first_invalid_escape_char = c;
6672
4.35k
                if (starts == initial_starts) {
6673
                    /* Back up one char, since we've already incremented s. */
6674
4.35k
                    *first_invalid_escape_ptr = s - 1;
6675
4.35k
                }
6676
4.35k
            }
6677
36.1k
            WRITE_ASCII_CHAR('\\');
6678
36.1k
            WRITE_CHAR(c);
6679
36.1k
            continue;
6680
280k
        }
6681
6682
66
      incomplete:
6683
66
        if (consumed) {
6684
0
            *consumed = startinpos;
6685
0
            break;
6686
0
        }
6687
247
      error:;
6688
247
        Py_ssize_t endinpos = s-starts;
6689
247
        writer.min_length = end - s + writer.pos;
6690
247
        if (unicode_decode_call_errorhandler_writer(
6691
247
                errors, &errorHandler,
6692
247
                "unicodeescape", message,
6693
247
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6694
247
                &writer)) {
6695
247
            goto onError;
6696
247
        }
6697
247
        assert(end - s <= writer.size - writer.pos);
6698
6699
0
#undef WRITE_ASCII_CHAR
6700
0
#undef WRITE_CHAR
6701
0
    }
6702
6703
27.2k
    Py_XDECREF(errorHandler);
6704
27.2k
    Py_XDECREF(exc);
6705
27.2k
    return _PyUnicodeWriter_Finish(&writer);
6706
6707
247
  onError:
6708
247
    _PyUnicodeWriter_Dealloc(&writer);
6709
247
    Py_XDECREF(errorHandler);
6710
247
    Py_XDECREF(exc);
6711
247
    return NULL;
6712
27.4k
}
6713
6714
PyObject *
6715
_PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
6716
                              Py_ssize_t size,
6717
                              const char *errors,
6718
                              Py_ssize_t *consumed)
6719
553
{
6720
553
    int first_invalid_escape_char;
6721
553
    const char *first_invalid_escape_ptr;
6722
553
    PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal2(s, size, errors,
6723
553
                                                      consumed,
6724
553
                                                      &first_invalid_escape_char,
6725
553
                                                      &first_invalid_escape_ptr);
6726
553
    if (result == NULL)
6727
121
        return NULL;
6728
432
    if (first_invalid_escape_char != -1) {
6729
295
        if (first_invalid_escape_char > 0xff) {
6730
91
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6731
91
                                 "\"\\%o\" is an invalid octal escape sequence. "
6732
91
                                 "Such sequences will not work in the future. ",
6733
91
                                 first_invalid_escape_char) < 0)
6734
0
            {
6735
0
                Py_DECREF(result);
6736
0
                return NULL;
6737
0
            }
6738
91
        }
6739
204
        else {
6740
204
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6741
204
                                 "\"\\%c\" is an invalid escape sequence. "
6742
204
                                 "Such sequences will not work in the future. ",
6743
204
                                 first_invalid_escape_char) < 0)
6744
0
            {
6745
0
                Py_DECREF(result);
6746
0
                return NULL;
6747
0
            }
6748
204
        }
6749
295
    }
6750
432
    return result;
6751
432
}
6752
6753
PyObject *
6754
PyUnicode_DecodeUnicodeEscape(const char *s,
6755
                              Py_ssize_t size,
6756
                              const char *errors)
6757
0
{
6758
0
    return _PyUnicode_DecodeUnicodeEscapeStateful(s, size, errors, NULL);
6759
0
}
6760
6761
/* Return a Unicode-Escape string version of the Unicode object. */
6762
6763
PyObject *
6764
PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
6765
753k
{
6766
753k
    if (!PyUnicode_Check(unicode)) {
6767
0
        PyErr_BadArgument();
6768
0
        return NULL;
6769
0
    }
6770
6771
753k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
6772
753k
    if (len == 0) {
6773
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
6774
0
    }
6775
753k
    int kind = PyUnicode_KIND(unicode);
6776
753k
    const void *data = PyUnicode_DATA(unicode);
6777
6778
    /* Initial allocation is based on the longest-possible character
6779
     * escape.
6780
     *
6781
     * For UCS1 strings it's '\xxx', 4 bytes per source character.
6782
     * For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6783
     * For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character. */
6784
753k
    Py_ssize_t expandsize = kind * 2 + 2;
6785
753k
    if (len > PY_SSIZE_T_MAX / expandsize) {
6786
0
        return PyErr_NoMemory();
6787
0
    }
6788
6789
753k
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
6790
753k
    if (writer == NULL) {
6791
0
        return NULL;
6792
0
    }
6793
753k
    char *p = PyBytesWriter_GetData(writer);
6794
6795
1.50M
    for (Py_ssize_t i = 0; i < len; i++) {
6796
753k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6797
6798
        /* U+0000-U+00ff range */
6799
753k
        if (ch < 0x100) {
6800
749k
            if (ch >= ' ' && ch < 127) {
6801
43.8k
                if (ch != '\\') {
6802
                    /* Copy printable US ASCII as-is */
6803
0
                    *p++ = (char) ch;
6804
0
                }
6805
                /* Escape backslashes */
6806
43.8k
                else {
6807
43.8k
                    *p++ = '\\';
6808
43.8k
                    *p++ = '\\';
6809
43.8k
                }
6810
43.8k
            }
6811
6812
            /* Map special whitespace to '\t', \n', '\r' */
6813
705k
            else if (ch == '\t') {
6814
3.63k
                *p++ = '\\';
6815
3.63k
                *p++ = 't';
6816
3.63k
            }
6817
701k
            else if (ch == '\n') {
6818
1.60k
                *p++ = '\\';
6819
1.60k
                *p++ = 'n';
6820
1.60k
            }
6821
700k
            else if (ch == '\r') {
6822
508
                *p++ = '\\';
6823
508
                *p++ = 'r';
6824
508
            }
6825
6826
            /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6827
699k
            else {
6828
699k
                *p++ = '\\';
6829
699k
                *p++ = 'x';
6830
699k
                *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6831
699k
                *p++ = Py_hexdigits[ch & 0x000F];
6832
699k
            }
6833
749k
        }
6834
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
6835
4.66k
        else if (ch < 0x10000) {
6836
3.22k
            *p++ = '\\';
6837
3.22k
            *p++ = 'u';
6838
3.22k
            *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6839
3.22k
            *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6840
3.22k
            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6841
3.22k
            *p++ = Py_hexdigits[ch & 0x000F];
6842
3.22k
        }
6843
        /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6844
1.43k
        else {
6845
6846
            /* Make sure that the first two digits are zero */
6847
1.43k
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6848
1.43k
            *p++ = '\\';
6849
1.43k
            *p++ = 'U';
6850
1.43k
            *p++ = '0';
6851
1.43k
            *p++ = '0';
6852
1.43k
            *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6853
1.43k
            *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6854
1.43k
            *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6855
1.43k
            *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6856
1.43k
            *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6857
1.43k
            *p++ = Py_hexdigits[ch & 0x0000000F];
6858
1.43k
        }
6859
753k
    }
6860
6861
753k
    return PyBytesWriter_FinishWithPointer(writer, p);
6862
753k
}
6863
6864
/* --- Raw Unicode Escape Codec ------------------------------------------- */
6865
6866
PyObject *
6867
_PyUnicode_DecodeRawUnicodeEscapeStateful(const char *s,
6868
                                          Py_ssize_t size,
6869
                                          const char *errors,
6870
                                          Py_ssize_t *consumed)
6871
106
{
6872
106
    const char *starts = s;
6873
106
    _PyUnicodeWriter writer;
6874
106
    const char *end;
6875
106
    PyObject *errorHandler = NULL;
6876
106
    PyObject *exc = NULL;
6877
6878
106
    if (size == 0) {
6879
0
        if (consumed) {
6880
0
            *consumed = 0;
6881
0
        }
6882
0
        _Py_RETURN_UNICODE_EMPTY();
6883
0
    }
6884
6885
    /* Escaped strings will always be longer than the resulting
6886
       Unicode string, so we start with size here and then reduce the
6887
       length after conversion to the true value. (But decoding error
6888
       handler might have to resize the string) */
6889
106
    _PyUnicodeWriter_Init(&writer);
6890
106
    writer.min_length = size;
6891
106
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6892
0
        goto onError;
6893
0
    }
6894
6895
106
    end = s + size;
6896
46.3k
    while (s < end) {
6897
46.2k
        unsigned char c = (unsigned char) *s++;
6898
46.2k
        Py_UCS4 ch;
6899
46.2k
        int count;
6900
46.2k
        const char *message;
6901
6902
46.2k
#define WRITE_CHAR(ch)                                                        \
6903
46.2k
            do {                                                              \
6904
46.2k
                if (ch <= writer.maxchar) {                                   \
6905
46.1k
                    assert(writer.pos < writer.size);                         \
6906
46.1k
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6907
46.1k
                }                                                             \
6908
46.2k
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6909
0
                    goto onError;                                             \
6910
0
                }                                                             \
6911
46.2k
            } while(0)
6912
6913
        /* Non-escape characters are interpreted as Unicode ordinals */
6914
46.2k
        if (c != '\\' || (s >= end && !consumed)) {
6915
43.1k
            WRITE_CHAR(c);
6916
43.1k
            continue;
6917
43.1k
        }
6918
6919
3.04k
        Py_ssize_t startinpos = s - starts - 1;
6920
        /* \ - Escapes */
6921
3.04k
        if (s >= end) {
6922
0
            assert(consumed);
6923
            // Set message to silent compiler warning.
6924
            // Actually it is never used.
6925
0
            message = "\\ at end of string";
6926
0
            goto incomplete;
6927
0
        }
6928
6929
3.04k
        c = (unsigned char) *s++;
6930
3.04k
        if (c == 'u') {
6931
404
            count = 4;
6932
404
            message = "truncated \\uXXXX escape";
6933
404
        }
6934
2.64k
        else if (c == 'U') {
6935
537
            count = 8;
6936
537
            message = "truncated \\UXXXXXXXX escape";
6937
537
        }
6938
2.10k
        else {
6939
2.10k
            assert(writer.pos < writer.size);
6940
2.10k
            PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6941
2.10k
            WRITE_CHAR(c);
6942
2.10k
            continue;
6943
2.10k
        }
6944
6945
        /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6946
6.74k
        for (ch = 0; count; ++s, --count) {
6947
5.83k
            if (s >= end) {
6948
7
                goto incomplete;
6949
7
            }
6950
5.82k
            c = (unsigned char)*s;
6951
5.82k
            ch <<= 4;
6952
5.82k
            if (c >= '0' && c <= '9') {
6953
4.97k
                ch += c - '0';
6954
4.97k
            }
6955
849
            else if (c >= 'a' && c <= 'f') {
6956
736
                ch += c - ('a' - 10);
6957
736
            }
6958
113
            else if (c >= 'A' && c <= 'F') {
6959
95
                ch += c - ('A' - 10);
6960
95
            }
6961
18
            else {
6962
18
                goto error;
6963
18
            }
6964
5.82k
        }
6965
916
        if (ch > MAX_UNICODE) {
6966
3
            message = "\\Uxxxxxxxx out of range";
6967
3
            goto error;
6968
3
        }
6969
913
        WRITE_CHAR(ch);
6970
913
        continue;
6971
6972
913
      incomplete:
6973
7
        if (consumed) {
6974
0
            *consumed = startinpos;
6975
0
            break;
6976
0
        }
6977
28
      error:;
6978
28
        Py_ssize_t endinpos = s-starts;
6979
28
        writer.min_length = end - s + writer.pos;
6980
28
        if (unicode_decode_call_errorhandler_writer(
6981
28
                errors, &errorHandler,
6982
28
                "rawunicodeescape", message,
6983
28
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6984
28
                &writer)) {
6985
28
            goto onError;
6986
28
        }
6987
28
        assert(end - s <= writer.size - writer.pos);
6988
6989
0
#undef WRITE_CHAR
6990
0
    }
6991
78
    Py_XDECREF(errorHandler);
6992
78
    Py_XDECREF(exc);
6993
78
    return _PyUnicodeWriter_Finish(&writer);
6994
6995
28
  onError:
6996
28
    _PyUnicodeWriter_Dealloc(&writer);
6997
28
    Py_XDECREF(errorHandler);
6998
28
    Py_XDECREF(exc);
6999
28
    return NULL;
7000
106
}
7001
7002
PyObject *
7003
PyUnicode_DecodeRawUnicodeEscape(const char *s,
7004
                                 Py_ssize_t size,
7005
                                 const char *errors)
7006
0
{
7007
0
    return _PyUnicode_DecodeRawUnicodeEscapeStateful(s, size, errors, NULL);
7008
0
}
7009
7010
7011
PyObject *
7012
PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
7013
247k
{
7014
247k
    if (!PyUnicode_Check(unicode)) {
7015
0
        PyErr_BadArgument();
7016
0
        return NULL;
7017
0
    }
7018
247k
    int kind = PyUnicode_KIND(unicode);
7019
247k
    const void *data = PyUnicode_DATA(unicode);
7020
247k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
7021
247k
    if (len == 0) {
7022
443
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7023
443
    }
7024
247k
    if (kind == PyUnicode_1BYTE_KIND) {
7025
247k
        return PyBytes_FromStringAndSize(data, len);
7026
247k
    }
7027
7028
    /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
7029
       bytes, and 1 byte characters 4. */
7030
315
    Py_ssize_t expandsize = kind * 2 + 2;
7031
315
    if (len > PY_SSIZE_T_MAX / expandsize) {
7032
0
        return PyErr_NoMemory();
7033
0
    }
7034
7035
315
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
7036
315
    if (writer == NULL) {
7037
0
        return NULL;
7038
0
    }
7039
315
    char *p = PyBytesWriter_GetData(writer);
7040
7041
6.45M
    for (Py_ssize_t pos = 0; pos < len; pos++) {
7042
6.45M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7043
7044
        /* U+0000-U+00ff range: Copy 8-bit characters as-is */
7045
6.45M
        if (ch < 0x100) {
7046
6.40M
            *p++ = (char) ch;
7047
6.40M
        }
7048
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
7049
48.3k
        else if (ch < 0x10000) {
7050
47.7k
            *p++ = '\\';
7051
47.7k
            *p++ = 'u';
7052
47.7k
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7053
47.7k
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7054
47.7k
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7055
47.7k
            *p++ = Py_hexdigits[ch & 15];
7056
47.7k
        }
7057
        /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
7058
632
        else {
7059
632
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
7060
632
            *p++ = '\\';
7061
632
            *p++ = 'U';
7062
632
            *p++ = '0';
7063
632
            *p++ = '0';
7064
632
            *p++ = Py_hexdigits[(ch >> 20) & 0xf];
7065
632
            *p++ = Py_hexdigits[(ch >> 16) & 0xf];
7066
632
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7067
632
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7068
632
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7069
632
            *p++ = Py_hexdigits[ch & 15];
7070
632
        }
7071
6.45M
    }
7072
7073
315
    return PyBytesWriter_FinishWithPointer(writer, p);
7074
315
}
7075
7076
/* --- Latin-1 Codec ------------------------------------------------------ */
7077
7078
PyObject *
7079
PyUnicode_DecodeLatin1(const char *s,
7080
                       Py_ssize_t size,
7081
                       const char *errors)
7082
2.98M
{
7083
    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
7084
2.98M
    return _PyUnicode_FromUCS1((const unsigned char*)s, size);
7085
2.98M
}
7086
7087
/* create or adjust a UnicodeEncodeError */
7088
static void
7089
make_encode_exception(PyObject **exceptionObject,
7090
                      const char *encoding,
7091
                      PyObject *unicode,
7092
                      Py_ssize_t startpos, Py_ssize_t endpos,
7093
                      const char *reason)
7094
755k
{
7095
755k
    if (*exceptionObject == NULL) {
7096
755k
        *exceptionObject = PyObject_CallFunction(
7097
755k
            PyExc_UnicodeEncodeError, "sOnns",
7098
755k
            encoding, unicode, startpos, endpos, reason);
7099
755k
    }
7100
0
    else {
7101
0
        if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
7102
0
            goto onError;
7103
0
        if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
7104
0
            goto onError;
7105
0
        if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
7106
0
            goto onError;
7107
0
        return;
7108
0
      onError:
7109
0
        Py_CLEAR(*exceptionObject);
7110
0
    }
7111
755k
}
7112
7113
/* raises a UnicodeEncodeError */
7114
static void
7115
raise_encode_exception(PyObject **exceptionObject,
7116
                       const char *encoding,
7117
                       PyObject *unicode,
7118
                       Py_ssize_t startpos, Py_ssize_t endpos,
7119
                       const char *reason)
7120
565k
{
7121
565k
    make_encode_exception(exceptionObject,
7122
565k
                          encoding, unicode, startpos, endpos, reason);
7123
565k
    if (*exceptionObject != NULL)
7124
565k
        PyCodec_StrictErrors(*exceptionObject);
7125
565k
}
7126
7127
/* error handling callback helper:
7128
   build arguments, call the callback and check the arguments,
7129
   put the result into newpos and return the replacement string, which
7130
   has to be freed by the caller */
7131
static PyObject *
7132
unicode_encode_call_errorhandler(const char *errors,
7133
                                 PyObject **errorHandler,
7134
                                 const char *encoding, const char *reason,
7135
                                 PyObject *unicode, PyObject **exceptionObject,
7136
                                 Py_ssize_t startpos, Py_ssize_t endpos,
7137
                                 Py_ssize_t *newpos)
7138
189k
{
7139
189k
    static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
7140
189k
    Py_ssize_t len;
7141
189k
    PyObject *restuple;
7142
189k
    PyObject *resunicode;
7143
7144
189k
    if (*errorHandler == NULL) {
7145
189k
        *errorHandler = PyCodec_LookupError(errors);
7146
189k
        if (*errorHandler == NULL)
7147
0
            return NULL;
7148
189k
    }
7149
7150
189k
    len = PyUnicode_GET_LENGTH(unicode);
7151
7152
189k
    make_encode_exception(exceptionObject,
7153
189k
                          encoding, unicode, startpos, endpos, reason);
7154
189k
    if (*exceptionObject == NULL)
7155
0
        return NULL;
7156
7157
189k
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
7158
189k
    if (restuple == NULL)
7159
189k
        return NULL;
7160
0
    if (!PyTuple_Check(restuple)) {
7161
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
7162
0
        Py_DECREF(restuple);
7163
0
        return NULL;
7164
0
    }
7165
0
    if (!PyArg_ParseTuple(restuple, argparse,
7166
0
                          &resunicode, newpos)) {
7167
0
        Py_DECREF(restuple);
7168
0
        return NULL;
7169
0
    }
7170
0
    if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
7171
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
7172
0
        Py_DECREF(restuple);
7173
0
        return NULL;
7174
0
    }
7175
0
    if (*newpos<0)
7176
0
        *newpos = len + *newpos;
7177
0
    if (*newpos<0 || *newpos>len) {
7178
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7179
0
        Py_DECREF(restuple);
7180
0
        return NULL;
7181
0
    }
7182
0
    Py_INCREF(resunicode);
7183
0
    Py_DECREF(restuple);
7184
0
    return resunicode;
7185
0
}
7186
7187
static PyObject *
7188
unicode_encode_ucs1(PyObject *unicode,
7189
                    const char *errors,
7190
                    const Py_UCS4 limit)
7191
586k
{
7192
    /* input state */
7193
586k
    Py_ssize_t pos=0, size;
7194
586k
    int kind;
7195
586k
    const void *data;
7196
586k
    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
7197
586k
    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
7198
586k
    PyObject *error_handler_obj = NULL;
7199
586k
    PyObject *exc = NULL;
7200
586k
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7201
586k
    PyObject *rep = NULL;
7202
7203
586k
    size = PyUnicode_GET_LENGTH(unicode);
7204
586k
    kind = PyUnicode_KIND(unicode);
7205
586k
    data = PyUnicode_DATA(unicode);
7206
    /* allocate enough for a simple encoding without
7207
       replacements, if we need more, we'll resize */
7208
586k
    if (size == 0)
7209
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7210
7211
    /* output object */
7212
586k
    PyBytesWriter *writer = PyBytesWriter_Create(size);
7213
586k
    if (writer == NULL) {
7214
0
        return NULL;
7215
0
    }
7216
    /* pointer into the output */
7217
586k
    char *str = PyBytesWriter_GetData(writer);
7218
7219
9.87M
    while (pos < size) {
7220
9.87M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7221
7222
        /* can we encode this? */
7223
9.87M
        if (ch < limit) {
7224
            /* no overflow check, because we know that the space is enough */
7225
9.28M
            *str++ = (char)ch;
7226
9.28M
            ++pos;
7227
9.28M
        }
7228
587k
        else {
7229
587k
            Py_ssize_t newpos, i;
7230
            /* startpos for collecting unencodable chars */
7231
587k
            Py_ssize_t collstart = pos;
7232
587k
            Py_ssize_t collend = collstart + 1;
7233
            /* find all unecodable characters */
7234
7235
2.46M
            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
7236
1.88M
                ++collend;
7237
7238
            /* Only overallocate the buffer if it's not the last write */
7239
587k
            writer->overallocate = (collend < size);
7240
7241
            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
7242
587k
            if (error_handler == _Py_ERROR_UNKNOWN)
7243
586k
                error_handler = _Py_GetErrorHandler(errors);
7244
7245
587k
            switch (error_handler) {
7246
565k
            case _Py_ERROR_STRICT:
7247
565k
                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
7248
565k
                goto onError;
7249
7250
5.99k
            case _Py_ERROR_REPLACE:
7251
5.99k
                memset(str, '?', collend - collstart);
7252
5.99k
                str += (collend - collstart);
7253
5.99k
                _Py_FALLTHROUGH;
7254
5.99k
            case _Py_ERROR_IGNORE:
7255
5.99k
                pos = collend;
7256
5.99k
                break;
7257
7258
0
            case _Py_ERROR_BACKSLASHREPLACE:
7259
                /* subtract preallocated bytes */
7260
0
                writer->size -= (collend - collstart);
7261
0
                str = backslashreplace(writer, str,
7262
0
                                       unicode, collstart, collend);
7263
0
                if (str == NULL)
7264
0
                    goto onError;
7265
0
                pos = collend;
7266
0
                break;
7267
7268
0
            case _Py_ERROR_XMLCHARREFREPLACE:
7269
                /* subtract preallocated bytes */
7270
0
                writer->size -= (collend - collstart);
7271
0
                str = xmlcharrefreplace(writer, str,
7272
0
                                        unicode, collstart, collend);
7273
0
                if (str == NULL)
7274
0
                    goto onError;
7275
0
                pos = collend;
7276
0
                break;
7277
7278
15.2k
            case _Py_ERROR_SURROGATEESCAPE:
7279
15.2k
                for (i = collstart; i < collend; ++i) {
7280
15.2k
                    ch = PyUnicode_READ(kind, data, i);
7281
15.2k
                    if (ch < 0xdc80 || 0xdcff < ch) {
7282
                        /* Not a UTF-8b surrogate */
7283
15.2k
                        break;
7284
15.2k
                    }
7285
0
                    *str++ = (char)(ch - 0xdc00);
7286
0
                    ++pos;
7287
0
                }
7288
15.2k
                if (i >= collend)
7289
0
                    break;
7290
15.2k
                collstart = pos;
7291
15.2k
                assert(collstart != collend);
7292
15.2k
                _Py_FALLTHROUGH;
7293
7294
15.2k
            default:
7295
15.2k
                rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
7296
15.2k
                                                       encoding, reason, unicode, &exc,
7297
15.2k
                                                       collstart, collend, &newpos);
7298
15.2k
                if (rep == NULL)
7299
15.2k
                    goto onError;
7300
7301
0
                if (newpos < collstart) {
7302
0
                    writer->overallocate = 1;
7303
0
                    str = PyBytesWriter_GrowAndUpdatePointer(writer,
7304
0
                                                             collstart - newpos,
7305
0
                                                             str);
7306
0
                    if (str == NULL) {
7307
0
                        goto onError;
7308
0
                    }
7309
0
                }
7310
0
                else {
7311
                    /* subtract preallocated bytes */
7312
0
                    writer->size -= newpos - collstart;
7313
                    /* Only overallocate the buffer if it's not the last write */
7314
0
                    writer->overallocate = (newpos < size);
7315
0
                }
7316
7317
0
                char *rep_str;
7318
0
                Py_ssize_t rep_len;
7319
0
                if (PyBytes_Check(rep)) {
7320
                    /* Directly copy bytes result to output. */
7321
0
                    rep_str = PyBytes_AS_STRING(rep);
7322
0
                    rep_len = PyBytes_GET_SIZE(rep);
7323
0
                }
7324
0
                else {
7325
0
                    assert(PyUnicode_Check(rep));
7326
7327
0
                    if (limit == 256 ?
7328
0
                        PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
7329
0
                        !PyUnicode_IS_ASCII(rep))
7330
0
                    {
7331
                        /* Not all characters are smaller than limit */
7332
0
                        raise_encode_exception(&exc, encoding, unicode,
7333
0
                                               collstart, collend, reason);
7334
0
                        goto onError;
7335
0
                    }
7336
0
                    assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
7337
0
                    rep_str = PyUnicode_DATA(rep);
7338
0
                    rep_len = PyUnicode_GET_LENGTH(rep);
7339
0
                }
7340
7341
0
                str = PyBytesWriter_GrowAndUpdatePointer(writer, rep_len, str);
7342
0
                if (str == NULL) {
7343
0
                    goto onError;
7344
0
                }
7345
0
                memcpy(str, rep_str, rep_len);
7346
0
                str += rep_len;
7347
7348
0
                pos = newpos;
7349
0
                Py_CLEAR(rep);
7350
587k
            }
7351
7352
            /* If overallocation was disabled, ensure that it was the last
7353
               write. Otherwise, we missed an optimization */
7354
587k
            assert(writer->overallocate || pos == size);
7355
5.99k
        }
7356
9.87M
    }
7357
7358
5.87k
    Py_XDECREF(error_handler_obj);
7359
5.87k
    Py_XDECREF(exc);
7360
5.87k
    return PyBytesWriter_FinishWithPointer(writer, str);
7361
7362
581k
  onError:
7363
581k
    Py_XDECREF(rep);
7364
581k
    PyBytesWriter_Discard(writer);
7365
581k
    Py_XDECREF(error_handler_obj);
7366
581k
    Py_XDECREF(exc);
7367
581k
    return NULL;
7368
586k
}
7369
7370
PyObject *
7371
_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
7372
10
{
7373
10
    if (!PyUnicode_Check(unicode)) {
7374
0
        PyErr_BadArgument();
7375
0
        return NULL;
7376
0
    }
7377
    /* Fast path: if it is a one-byte string, construct
7378
       bytes object directly. */
7379
10
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7380
10
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7381
10
                                         PyUnicode_GET_LENGTH(unicode));
7382
    /* Non-Latin-1 characters present. Defer to above function to
7383
       raise the exception. */
7384
0
    return unicode_encode_ucs1(unicode, errors, 256);
7385
10
}
7386
7387
PyObject*
7388
PyUnicode_AsLatin1String(PyObject *unicode)
7389
0
{
7390
0
    return _PyUnicode_AsLatin1String(unicode, NULL);
7391
0
}
7392
7393
/* --- 7-bit ASCII Codec -------------------------------------------------- */
7394
7395
PyObject *
7396
PyUnicode_DecodeASCII(const char *s,
7397
                      Py_ssize_t size,
7398
                      const char *errors)
7399
11.2M
{
7400
11.2M
    const char *starts = s;
7401
11.2M
    const char *e = s + size;
7402
11.2M
    PyObject *error_handler_obj = NULL;
7403
11.2M
    PyObject *exc = NULL;
7404
11.2M
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7405
7406
11.2M
    if (size == 0)
7407
0
        _Py_RETURN_UNICODE_EMPTY();
7408
7409
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
7410
11.2M
    if (size == 1 && (unsigned char)s[0] < 128) {
7411
520k
        return get_latin1_char((unsigned char)s[0]);
7412
520k
    }
7413
7414
    // Shortcut for simple case
7415
10.7M
    PyObject *u = PyUnicode_New(size, 127);
7416
10.7M
    if (u == NULL) {
7417
0
        return NULL;
7418
0
    }
7419
10.7M
    Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
7420
10.7M
    if (outpos == size) {
7421
8.03M
        return u;
7422
8.03M
    }
7423
7424
2.69M
    _PyUnicodeWriter writer;
7425
2.69M
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
7426
2.69M
    writer.pos = outpos;
7427
7428
2.69M
    s += outpos;
7429
2.69M
    int kind = writer.kind;
7430
2.69M
    void *data = writer.data;
7431
2.69M
    Py_ssize_t startinpos, endinpos;
7432
7433
24.1M
    while (s < e) {
7434
23.9M
        unsigned char c = (unsigned char)*s;
7435
23.9M
        if (c < 128) {
7436
7.39M
            PyUnicode_WRITE(kind, data, writer.pos, c);
7437
7.39M
            writer.pos++;
7438
7.39M
            ++s;
7439
7.39M
            continue;
7440
7.39M
        }
7441
7442
        /* byte outsize range 0x00..0x7f: call the error handler */
7443
7444
16.5M
        if (error_handler == _Py_ERROR_UNKNOWN)
7445
2.69M
            error_handler = _Py_GetErrorHandler(errors);
7446
7447
16.5M
        switch (error_handler)
7448
16.5M
        {
7449
800k
        case _Py_ERROR_REPLACE:
7450
14.0M
        case _Py_ERROR_SURROGATEESCAPE:
7451
            /* Fast-path: the error handler only writes one character,
7452
               but we may switch to UCS2 at the first write */
7453
14.0M
            if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7454
0
                goto onError;
7455
14.0M
            kind = writer.kind;
7456
14.0M
            data = writer.data;
7457
7458
14.0M
            if (error_handler == _Py_ERROR_REPLACE)
7459
800k
                PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7460
13.2M
            else
7461
13.2M
                PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7462
14.0M
            writer.pos++;
7463
14.0M
            ++s;
7464
14.0M
            break;
7465
7466
0
        case _Py_ERROR_IGNORE:
7467
0
            ++s;
7468
0
            break;
7469
7470
2.53M
        default:
7471
2.53M
            startinpos = s-starts;
7472
2.53M
            endinpos = startinpos + 1;
7473
2.53M
            if (unicode_decode_call_errorhandler_writer(
7474
2.53M
                    errors, &error_handler_obj,
7475
2.53M
                    "ascii", "ordinal not in range(128)",
7476
2.53M
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
7477
2.53M
                    &writer))
7478
2.53M
                goto onError;
7479
0
            kind = writer.kind;
7480
0
            data = writer.data;
7481
16.5M
        }
7482
16.5M
    }
7483
161k
    Py_XDECREF(error_handler_obj);
7484
161k
    Py_XDECREF(exc);
7485
161k
    return _PyUnicodeWriter_Finish(&writer);
7486
7487
2.53M
  onError:
7488
2.53M
    _PyUnicodeWriter_Dealloc(&writer);
7489
2.53M
    Py_XDECREF(error_handler_obj);
7490
2.53M
    Py_XDECREF(exc);
7491
2.53M
    return NULL;
7492
2.69M
}
7493
7494
PyObject *
7495
_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
7496
960k
{
7497
960k
    if (!PyUnicode_Check(unicode)) {
7498
0
        PyErr_BadArgument();
7499
0
        return NULL;
7500
0
    }
7501
    /* Fast path: if it is an ASCII-only string, construct bytes object
7502
       directly. Else defer to above function to raise the exception. */
7503
960k
    if (PyUnicode_IS_ASCII(unicode))
7504
373k
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7505
373k
                                         PyUnicode_GET_LENGTH(unicode));
7506
586k
    return unicode_encode_ucs1(unicode, errors, 128);
7507
960k
}
7508
7509
PyObject *
7510
PyUnicode_AsASCIIString(PyObject *unicode)
7511
122k
{
7512
122k
    return _PyUnicode_AsASCIIString(unicode, NULL);
7513
122k
}
7514
7515
#ifdef MS_WINDOWS
7516
7517
/* --- MBCS codecs for Windows -------------------------------------------- */
7518
7519
#if SIZEOF_INT < SIZEOF_SIZE_T
7520
#define NEED_RETRY
7521
#endif
7522
7523
/* INT_MAX is the theoretical largest chunk (or INT_MAX / 2 when
7524
   transcoding from UTF-16), but INT_MAX / 4 performs better in
7525
   both cases also and avoids partial characters overrunning the
7526
   length limit in MultiByteToWideChar on Windows */
7527
#define DECODING_CHUNK_SIZE (INT_MAX/4)
7528
7529
#ifndef WC_ERR_INVALID_CHARS
7530
#  define WC_ERR_INVALID_CHARS 0x0080
7531
#endif
7532
7533
static const char*
7534
code_page_name(UINT code_page, PyObject **obj)
7535
{
7536
    *obj = NULL;
7537
    if (code_page == CP_ACP)
7538
        return "mbcs";
7539
7540
    *obj = PyBytes_FromFormat("cp%u", code_page);
7541
    if (*obj == NULL)
7542
        return NULL;
7543
    return PyBytes_AS_STRING(*obj);
7544
}
7545
7546
static DWORD
7547
decode_code_page_flags(UINT code_page)
7548
{
7549
    if (code_page == CP_UTF7) {
7550
        /* The CP_UTF7 decoder only supports flags=0 */
7551
        return 0;
7552
    }
7553
    else
7554
        return MB_ERR_INVALID_CHARS;
7555
}
7556
7557
/*
7558
 * Decode a byte string from a Windows code page into unicode object in strict
7559
 * mode.
7560
 *
7561
 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7562
 * OSError and returns -1 on other error.
7563
 */
7564
static int
7565
decode_code_page_strict(UINT code_page,
7566
                        wchar_t **buf,
7567
                        Py_ssize_t *bufsize,
7568
                        const char *in,
7569
                        int insize)
7570
{
7571
    DWORD flags = MB_ERR_INVALID_CHARS;
7572
    wchar_t *out;
7573
    DWORD outsize;
7574
7575
    /* First get the size of the result */
7576
    assert(insize > 0);
7577
    while ((outsize = MultiByteToWideChar(code_page, flags,
7578
                                          in, insize, NULL, 0)) <= 0)
7579
    {
7580
        if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7581
            goto error;
7582
        }
7583
        /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7584
        flags = 0;
7585
    }
7586
7587
    /* Extend a wchar_t* buffer */
7588
    Py_ssize_t n = *bufsize;   /* Get the current length */
7589
    if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7590
        return -1;
7591
    }
7592
    out = *buf + n;
7593
7594
    /* Do the conversion */
7595
    outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7596
    if (outsize <= 0)
7597
        goto error;
7598
    return insize;
7599
7600
error:
7601
    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7602
        return -2;
7603
    PyErr_SetFromWindowsErr(0);
7604
    return -1;
7605
}
7606
7607
/*
7608
 * Decode a byte string from a code page into unicode object with an error
7609
 * handler.
7610
 *
7611
 * Returns consumed size if succeed, or raise an OSError or
7612
 * UnicodeDecodeError exception and returns -1 on error.
7613
 */
7614
static int
7615
decode_code_page_errors(UINT code_page,
7616
                        wchar_t **buf,
7617
                        Py_ssize_t *bufsize,
7618
                        const char *in, const int size,
7619
                        const char *errors, int final)
7620
{
7621
    const char *startin = in;
7622
    const char *endin = in + size;
7623
    DWORD flags = MB_ERR_INVALID_CHARS;
7624
    /* Ideally, we should get reason from FormatMessage. This is the Windows
7625
       2000 English version of the message. */
7626
    const char *reason = "No mapping for the Unicode character exists "
7627
                         "in the target code page.";
7628
    /* each step cannot decode more than 1 character, but a character can be
7629
       represented as a surrogate pair */
7630
    wchar_t buffer[2], *out;
7631
    int insize;
7632
    Py_ssize_t outsize;
7633
    PyObject *errorHandler = NULL;
7634
    PyObject *exc = NULL;
7635
    PyObject *encoding_obj = NULL;
7636
    const char *encoding;
7637
    DWORD err;
7638
    int ret = -1;
7639
7640
    assert(size > 0);
7641
7642
    encoding = code_page_name(code_page, &encoding_obj);
7643
    if (encoding == NULL)
7644
        return -1;
7645
7646
    if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
7647
        /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7648
           UnicodeDecodeError. */
7649
        make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7650
        if (exc != NULL) {
7651
            PyCodec_StrictErrors(exc);
7652
            Py_CLEAR(exc);
7653
        }
7654
        goto error;
7655
    }
7656
7657
    /* Extend a wchar_t* buffer */
7658
    Py_ssize_t n = *bufsize;   /* Get the current length */
7659
    if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7660
        PyErr_NoMemory();
7661
        goto error;
7662
    }
7663
    if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7664
        goto error;
7665
    }
7666
    out = *buf + n;
7667
7668
    /* Decode the byte string character per character */
7669
    while (in < endin)
7670
    {
7671
        /* Decode a character */
7672
        insize = 1;
7673
        do
7674
        {
7675
            outsize = MultiByteToWideChar(code_page, flags,
7676
                                          in, insize,
7677
                                          buffer, Py_ARRAY_LENGTH(buffer));
7678
            if (outsize > 0)
7679
                break;
7680
            err = GetLastError();
7681
            if (err == ERROR_INVALID_FLAGS && flags) {
7682
                /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7683
                flags = 0;
7684
                continue;
7685
            }
7686
            if (err != ERROR_NO_UNICODE_TRANSLATION
7687
                && err != ERROR_INSUFFICIENT_BUFFER)
7688
            {
7689
                PyErr_SetFromWindowsErr(err);
7690
                goto error;
7691
            }
7692
            insize++;
7693
        }
7694
        /* 4=maximum length of a UTF-8 sequence */
7695
        while (insize <= 4 && (in + insize) <= endin);
7696
7697
        if (outsize <= 0) {
7698
            Py_ssize_t startinpos, endinpos, outpos;
7699
7700
            /* last character in partial decode? */
7701
            if (in + insize >= endin && !final)
7702
                break;
7703
7704
            startinpos = in - startin;
7705
            endinpos = startinpos + 1;
7706
            outpos = out - *buf;
7707
            if (unicode_decode_call_errorhandler_wchar(
7708
                    errors, &errorHandler,
7709
                    encoding, reason,
7710
                    &startin, &endin, &startinpos, &endinpos, &exc, &in,
7711
                    buf, bufsize, &outpos))
7712
            {
7713
                goto error;
7714
            }
7715
            out = *buf + outpos;
7716
        }
7717
        else {
7718
            in += insize;
7719
            memcpy(out, buffer, outsize * sizeof(wchar_t));
7720
            out += outsize;
7721
        }
7722
    }
7723
7724
    /* Shrink the buffer */
7725
    assert(out - *buf <= *bufsize);
7726
    *bufsize = out - *buf;
7727
    /* (in - startin) <= size and size is an int */
7728
    ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
7729
7730
error:
7731
    Py_XDECREF(encoding_obj);
7732
    Py_XDECREF(errorHandler);
7733
    Py_XDECREF(exc);
7734
    return ret;
7735
}
7736
7737
static PyObject *
7738
decode_code_page_stateful(int code_page,
7739
                          const char *s, Py_ssize_t size,
7740
                          const char *errors, Py_ssize_t *consumed)
7741
{
7742
    wchar_t *buf = NULL;
7743
    Py_ssize_t bufsize = 0;
7744
    int chunk_size, final, converted, done;
7745
7746
    if (code_page < 0) {
7747
        PyErr_SetString(PyExc_ValueError, "invalid code page number");
7748
        return NULL;
7749
    }
7750
    if (size < 0) {
7751
        PyErr_BadInternalCall();
7752
        return NULL;
7753
    }
7754
7755
    if (consumed)
7756
        *consumed = 0;
7757
7758
    do
7759
    {
7760
#ifdef NEED_RETRY
7761
        if (size > DECODING_CHUNK_SIZE) {
7762
            chunk_size = DECODING_CHUNK_SIZE;
7763
            final = 0;
7764
            done = 0;
7765
        }
7766
        else
7767
#endif
7768
        {
7769
            chunk_size = (int)size;
7770
            final = (consumed == NULL);
7771
            done = 1;
7772
        }
7773
7774
        if (chunk_size == 0 && done) {
7775
            if (buf != NULL)
7776
                break;
7777
            _Py_RETURN_UNICODE_EMPTY();
7778
        }
7779
7780
        converted = decode_code_page_strict(code_page, &buf, &bufsize,
7781
                                            s, chunk_size);
7782
        if (converted == -2)
7783
            converted = decode_code_page_errors(code_page, &buf, &bufsize,
7784
                                                s, chunk_size,
7785
                                                errors, final);
7786
        assert(converted != 0 || done);
7787
7788
        if (converted < 0) {
7789
            PyMem_Free(buf);
7790
            return NULL;
7791
        }
7792
7793
        if (consumed)
7794
            *consumed += converted;
7795
7796
        s += converted;
7797
        size -= converted;
7798
    } while (!done);
7799
7800
    PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7801
    PyMem_Free(buf);
7802
    return v;
7803
}
7804
7805
PyObject *
7806
PyUnicode_DecodeCodePageStateful(int code_page,
7807
                                 const char *s,
7808
                                 Py_ssize_t size,
7809
                                 const char *errors,
7810
                                 Py_ssize_t *consumed)
7811
{
7812
    return decode_code_page_stateful(code_page, s, size, errors, consumed);
7813
}
7814
7815
PyObject *
7816
PyUnicode_DecodeMBCSStateful(const char *s,
7817
                             Py_ssize_t size,
7818
                             const char *errors,
7819
                             Py_ssize_t *consumed)
7820
{
7821
    return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7822
}
7823
7824
PyObject *
7825
PyUnicode_DecodeMBCS(const char *s,
7826
                     Py_ssize_t size,
7827
                     const char *errors)
7828
{
7829
    return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7830
}
7831
7832
static DWORD
7833
encode_code_page_flags(UINT code_page, const char *errors)
7834
{
7835
    if (code_page == CP_UTF8) {
7836
        return WC_ERR_INVALID_CHARS;
7837
    }
7838
    else if (code_page == CP_UTF7) {
7839
        /* CP_UTF7 only supports flags=0 */
7840
        return 0;
7841
    }
7842
    else {
7843
        if (errors != NULL && strcmp(errors, "replace") == 0)
7844
            return 0;
7845
        else
7846
            return WC_NO_BEST_FIT_CHARS;
7847
    }
7848
}
7849
7850
/*
7851
 * Encode a Unicode string to a Windows code page into a byte string in strict
7852
 * mode.
7853
 *
7854
 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7855
 * an OSError and returns -1 on other error.
7856
 */
7857
static int
7858
encode_code_page_strict(UINT code_page, PyBytesWriter **writer,
7859
                        PyObject *unicode, Py_ssize_t offset, int len,
7860
                        const char* errors)
7861
{
7862
    BOOL usedDefaultChar = FALSE;
7863
    BOOL *pusedDefaultChar = &usedDefaultChar;
7864
    int outsize;
7865
    wchar_t *p;
7866
    Py_ssize_t size;
7867
    const DWORD flags = encode_code_page_flags(code_page, NULL);
7868
    char *out;
7869
    /* Create a substring so that we can get the UTF-16 representation
7870
       of just the slice under consideration. */
7871
    PyObject *substring;
7872
    int ret = -1;
7873
7874
    assert(len > 0);
7875
7876
    if (code_page != CP_UTF8 && code_page != CP_UTF7)
7877
        pusedDefaultChar = &usedDefaultChar;
7878
    else
7879
        pusedDefaultChar = NULL;
7880
7881
    substring = PyUnicode_Substring(unicode, offset, offset+len);
7882
    if (substring == NULL)
7883
        return -1;
7884
    p = PyUnicode_AsWideCharString(substring, &size);
7885
    Py_CLEAR(substring);
7886
    if (p == NULL) {
7887
        return -1;
7888
    }
7889
    assert(size <= INT_MAX);
7890
7891
    /* First get the size of the result */
7892
    outsize = WideCharToMultiByte(code_page, flags,
7893
                                  p, (int)size,
7894
                                  NULL, 0,
7895
                                  NULL, pusedDefaultChar);
7896
    if (outsize <= 0)
7897
        goto error;
7898
    /* If we used a default char, then we failed! */
7899
    if (pusedDefaultChar && *pusedDefaultChar) {
7900
        ret = -2;
7901
        goto done;
7902
    }
7903
7904
    if (*writer == NULL) {
7905
        /* Create string object */
7906
        *writer = PyBytesWriter_Create(outsize);
7907
        if (*writer == NULL) {
7908
            goto done;
7909
        }
7910
        out = PyBytesWriter_GetData(*writer);
7911
    }
7912
    else {
7913
        /* Extend string object */
7914
        Py_ssize_t n = PyBytesWriter_GetSize(*writer);
7915
        if (PyBytesWriter_Grow(*writer, outsize) < 0) {
7916
            goto done;
7917
        }
7918
        out = (char*)PyBytesWriter_GetData(*writer) + n;
7919
    }
7920
7921
    /* Do the conversion */
7922
    outsize = WideCharToMultiByte(code_page, flags,
7923
                                  p, (int)size,
7924
                                  out, outsize,
7925
                                  NULL, pusedDefaultChar);
7926
    if (outsize <= 0)
7927
        goto error;
7928
    if (pusedDefaultChar && *pusedDefaultChar) {
7929
        ret = -2;
7930
        goto done;
7931
    }
7932
    ret = 0;
7933
7934
done:
7935
    PyMem_Free(p);
7936
    return ret;
7937
7938
error:
7939
    if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
7940
        ret = -2;
7941
        goto done;
7942
    }
7943
    PyErr_SetFromWindowsErr(0);
7944
    goto done;
7945
}
7946
7947
/*
7948
 * Encode a Unicode string to a Windows code page into a byte string using an
7949
 * error handler.
7950
 *
7951
 * Returns consumed characters if succeed, or raise an OSError and returns
7952
 * -1 on other error.
7953
 */
7954
static int
7955
encode_code_page_errors(UINT code_page, PyBytesWriter **writer,
7956
                        PyObject *unicode, Py_ssize_t unicode_offset,
7957
                        Py_ssize_t insize, const char* errors)
7958
{
7959
    const DWORD flags = encode_code_page_flags(code_page, errors);
7960
    Py_ssize_t pos = unicode_offset;
7961
    Py_ssize_t endin = unicode_offset + insize;
7962
    /* Ideally, we should get reason from FormatMessage. This is the Windows
7963
       2000 English version of the message. */
7964
    const char *reason = "invalid character";
7965
    /* 4=maximum length of a UTF-8 sequence */
7966
    char buffer[4];
7967
    BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7968
    Py_ssize_t outsize;
7969
    char *out;
7970
    PyObject *errorHandler = NULL;
7971
    PyObject *exc = NULL;
7972
    PyObject *encoding_obj = NULL;
7973
    const char *encoding;
7974
    Py_ssize_t newpos;
7975
    PyObject *rep;
7976
    int ret = -1;
7977
7978
    assert(insize > 0);
7979
7980
    encoding = code_page_name(code_page, &encoding_obj);
7981
    if (encoding == NULL)
7982
        return -1;
7983
7984
    if (errors == NULL || strcmp(errors, "strict") == 0) {
7985
        /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7986
           then we raise a UnicodeEncodeError. */
7987
        make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
7988
        if (exc != NULL) {
7989
            PyCodec_StrictErrors(exc);
7990
            Py_DECREF(exc);
7991
        }
7992
        Py_XDECREF(encoding_obj);
7993
        return -1;
7994
    }
7995
7996
    if (code_page != CP_UTF8 && code_page != CP_UTF7)
7997
        pusedDefaultChar = &usedDefaultChar;
7998
    else
7999
        pusedDefaultChar = NULL;
8000
8001
    if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
8002
        PyErr_NoMemory();
8003
        goto error;
8004
    }
8005
    outsize = insize * Py_ARRAY_LENGTH(buffer);
8006
8007
    if (*writer == NULL) {
8008
        /* Create string object */
8009
        *writer = PyBytesWriter_Create(outsize);
8010
        if (*writer == NULL) {
8011
            goto error;
8012
        }
8013
        out = PyBytesWriter_GetData(*writer);
8014
    }
8015
    else {
8016
        /* Extend string object */
8017
        Py_ssize_t n = PyBytesWriter_GetSize(*writer);
8018
        if (PyBytesWriter_Grow(*writer, outsize) < 0) {
8019
            goto error;
8020
        }
8021
        out = (char*)PyBytesWriter_GetData(*writer) + n;
8022
    }
8023
8024
    /* Encode the string character per character */
8025
    while (pos < endin)
8026
    {
8027
        Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
8028
        wchar_t chars[2];
8029
        int charsize;
8030
        if (ch < 0x10000) {
8031
            chars[0] = (wchar_t)ch;
8032
            charsize = 1;
8033
        }
8034
        else {
8035
            chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
8036
            chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
8037
            charsize = 2;
8038
        }
8039
8040
        outsize = WideCharToMultiByte(code_page, flags,
8041
                                      chars, charsize,
8042
                                      buffer, Py_ARRAY_LENGTH(buffer),
8043
                                      NULL, pusedDefaultChar);
8044
        if (outsize > 0) {
8045
            if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
8046
            {
8047
                pos++;
8048
                memcpy(out, buffer, outsize);
8049
                out += outsize;
8050
                continue;
8051
            }
8052
        }
8053
        else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
8054
            PyErr_SetFromWindowsErr(0);
8055
            goto error;
8056
        }
8057
8058
        rep = unicode_encode_call_errorhandler(
8059
                  errors, &errorHandler, encoding, reason,
8060
                  unicode, &exc,
8061
                  pos, pos + 1, &newpos);
8062
        if (rep == NULL)
8063
            goto error;
8064
8065
        Py_ssize_t morebytes = pos - newpos;
8066
        if (PyBytes_Check(rep)) {
8067
            outsize = PyBytes_GET_SIZE(rep);
8068
            morebytes += outsize;
8069
            if (morebytes > 0) {
8070
                out = PyBytesWriter_GrowAndUpdatePointer(*writer, morebytes, out);
8071
                if (out == NULL) {
8072
                    Py_DECREF(rep);
8073
                    goto error;
8074
                }
8075
            }
8076
            memcpy(out, PyBytes_AS_STRING(rep), outsize);
8077
            out += outsize;
8078
        }
8079
        else {
8080
            Py_ssize_t i;
8081
            int kind;
8082
            const void *data;
8083
8084
            outsize = PyUnicode_GET_LENGTH(rep);
8085
            morebytes += outsize;
8086
            if (morebytes > 0) {
8087
                out = PyBytesWriter_GrowAndUpdatePointer(*writer, morebytes, out);
8088
                if (out == NULL) {
8089
                    Py_DECREF(rep);
8090
                    goto error;
8091
                }
8092
            }
8093
            kind = PyUnicode_KIND(rep);
8094
            data = PyUnicode_DATA(rep);
8095
            for (i=0; i < outsize; i++) {
8096
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8097
                if (ch > 127) {
8098
                    raise_encode_exception(&exc,
8099
                        encoding, unicode,
8100
                        pos, pos + 1,
8101
                        "unable to encode error handler result to ASCII");
8102
                    Py_DECREF(rep);
8103
                    goto error;
8104
                }
8105
                *out = (unsigned char)ch;
8106
                out++;
8107
            }
8108
        }
8109
        pos = newpos;
8110
        Py_DECREF(rep);
8111
    }
8112
    /* write a NUL byte */
8113
    *out = 0;
8114
    outsize = out - (char*)PyBytesWriter_GetData(*writer);
8115
    assert(outsize <= PyBytesWriter_GetSize(*writer));
8116
    if (PyBytesWriter_Resize(*writer, outsize) < 0) {
8117
        goto error;
8118
    }
8119
    ret = 0;
8120
8121
error:
8122
    Py_XDECREF(encoding_obj);
8123
    Py_XDECREF(errorHandler);
8124
    Py_XDECREF(exc);
8125
    return ret;
8126
}
8127
8128
8129
PyObject *
8130
PyUnicode_EncodeCodePage(int code_page,
8131
                         PyObject *unicode,
8132
                         const char *errors)
8133
{
8134
    Py_ssize_t len;
8135
    PyBytesWriter *writer = NULL;
8136
    Py_ssize_t offset;
8137
    int chunk_len, ret, done;
8138
8139
    if (!PyUnicode_Check(unicode)) {
8140
        PyErr_BadArgument();
8141
        return NULL;
8142
    }
8143
8144
    len = PyUnicode_GET_LENGTH(unicode);
8145
8146
    if (code_page < 0) {
8147
        PyErr_SetString(PyExc_ValueError, "invalid code page number");
8148
        return NULL;
8149
    }
8150
8151
    if (len == 0)
8152
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
8153
8154
    offset = 0;
8155
    do
8156
    {
8157
#ifdef NEED_RETRY
8158
        if (len > DECODING_CHUNK_SIZE) {
8159
            chunk_len = DECODING_CHUNK_SIZE;
8160
            done = 0;
8161
        }
8162
        else
8163
#endif
8164
        {
8165
            chunk_len = (int)len;
8166
            done = 1;
8167
        }
8168
8169
        ret = encode_code_page_strict(code_page, &writer,
8170
                                      unicode, offset, chunk_len,
8171
                                      errors);
8172
        if (ret == -2)
8173
            ret = encode_code_page_errors(code_page, &writer,
8174
                                          unicode, offset,
8175
                                          chunk_len, errors);
8176
        if (ret < 0) {
8177
            PyBytesWriter_Discard(writer);
8178
            return NULL;
8179
        }
8180
8181
        offset += chunk_len;
8182
        len -= chunk_len;
8183
    } while (!done);
8184
8185
    return PyBytesWriter_Finish(writer);
8186
}
8187
8188
8189
PyObject *
8190
PyUnicode_AsMBCSString(PyObject *unicode)
8191
{
8192
    return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
8193
}
8194
8195
#undef NEED_RETRY
8196
8197
#endif /* MS_WINDOWS */
8198
8199
/* --- iconv Codec -------------------------------------------------------- */
8200
8201
#ifdef HAVE_ICONV
8202
8203
/* iconv pivot: native-endian UTF-32, a raw array of Py_UCS4.  One input unit is
8204
   one code point, so error handlers get the exact position.  A platform whose
8205
   iconv lacks a UTF-32 endpoint (e.g. UTF-8-only OpenBSD) reports every encoding
8206
   as unavailable. */
8207
#if PY_BIG_ENDIAN
8208
#  define ICONV_PIVOT "UTF-32BE"
8209
#else
8210
2.15k
#  define ICONV_PIVOT "UTF-32LE"
8211
#endif
8212
8213
/* A 2-byte string can be fed to iconv as "UCS-2" only where that is a strict
8214
   array of independent code points.  Some implementations alias "UCS-2" to
8215
   "UTF-16" and would combine an adjacent surrogate pair (a 2-byte string may
8216
   hold one as two code points); there the 2-byte kind is widened to UTF-32.
8217
   glibc and GNU libiconv keep UCS-2 and UTF-16 separate. */
8218
#if defined(__GLIBC__) || defined(_LIBICONV_VERSION)
8219
#  if PY_BIG_ENDIAN
8220
#    define ICONV_UCS2_PIVOT "UCS-2BE"
8221
#  else
8222
0
#    define ICONV_UCS2_PIVOT "UCS-2LE"
8223
#  endif
8224
#endif
8225
8226
static iconv_t
8227
iconv_open_or_set_error(const char *tocode, const char *fromcode,
8228
                        const char *encoding)
8229
70.0k
{
8230
70.0k
    iconv_t cd = iconv_open(tocode, fromcode);
8231
70.0k
    if (cd == (iconv_t)-1) {
8232
67.8k
        if (errno == EINVAL) {
8233
67.8k
            PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding);
8234
67.8k
        }
8235
0
        else {
8236
0
            PyErr_SetFromErrno(PyExc_OSError);
8237
0
        }
8238
67.8k
    }
8239
70.0k
    return cd;
8240
70.0k
}
8241
8242
/*
8243
 * Decode bytes with iconv() into a str.
8244
 *
8245
 * The input is converted to native-endian UTF-32 one chunk at a time and
8246
 * appended to a _PyUnicodeWriter.  If *consumed* is non-NULL the decode is
8247
 * stateful: a trailing incomplete sequence stops and sets *consumed*.
8248
 */
8249
PyObject *
8250
_PyUnicode_DecodeIconv(const char *encoding,
8251
                       const char *s, Py_ssize_t size,
8252
                       const char *errors, Py_ssize_t *consumed)
8253
2.15k
{
8254
2.15k
    if (size < 0) {
8255
0
        PyErr_BadInternalCall();
8256
0
        return NULL;
8257
0
    }
8258
8259
2.15k
    iconv_t cd = iconv_open_or_set_error(ICONV_PIVOT, encoding, encoding);
8260
2.15k
    if (cd == (iconv_t)-1) {
8261
0
        return NULL;
8262
0
    }
8263
8264
    /* Scratch buffer for one iconv() output chunk, as UTF-32 code points. */
8265
2.15k
    Py_UCS4 chunk[1024];
8266
2.15k
    const char *starts = s;
8267
2.15k
    const char *in = s;
8268
2.15k
    const char *inend = s + size;
8269
2.15k
    _PyUnicodeWriter writer;
8270
2.15k
    PyObject *errorHandler = NULL;
8271
2.15k
    PyObject *exc = NULL;
8272
8273
2.15k
    _PyUnicodeWriter_Init(&writer);
8274
2.15k
    writer.min_length = size;
8275
8276
204k
    while (in < inend) {
8277
204k
        char *inptr = (char *)in;
8278
204k
        size_t inleft = (size_t)(inend - in);
8279
204k
        char *outptr = (char *)chunk;
8280
204k
        size_t outleft = sizeof(chunk);
8281
8282
204k
        size_t ret = iconv(cd, &inptr, &inleft, &outptr, &outleft);
8283
204k
        int err = errno;
8284
204k
        in = inptr;
8285
8286
        /* Append whatever code points this call produced. */
8287
204k
        Py_ssize_t nch = (Py_UCS4 *)outptr - chunk;
8288
204k
        if (nch > 0 && PyUnicodeWriter_WriteUCS4((PyUnicodeWriter *)&writer,
8289
10.6k
                                                 chunk, nch) < 0) {
8290
0
            goto error;
8291
0
        }
8292
8293
204k
        if (ret != (size_t)-1) {
8294
1.44k
            assert(in == inend);
8295
1.44k
            break;
8296
1.44k
        }
8297
8298
203k
        if (err == E2BIG) {
8299
            /* The scratch buffer filled up; drain it and continue. */
8300
55
            continue;
8301
55
        }
8302
8303
203k
        const char *reason;
8304
203k
        if (err == EINVAL) {
8305
            /* Incomplete multibyte sequence at the end of the input. */
8306
2
            if (consumed != NULL) {
8307
                /* Stateful decoding: stop and report the consumed bytes. */
8308
0
                break;
8309
0
            }
8310
2
            reason = "incomplete multibyte sequence";
8311
2
        }
8312
203k
        else if (err == EILSEQ) {
8313
203k
            reason = "invalid multibyte sequence";
8314
203k
        }
8315
0
        else {
8316
0
            errno = err;
8317
0
            PyErr_SetFromErrno(PyExc_OSError);
8318
0
            goto error;
8319
0
        }
8320
8321
203k
        Py_ssize_t startinpos = in - starts;
8322
203k
        Py_ssize_t endinpos = startinpos + 1;
8323
203k
        if (unicode_decode_call_errorhandler_writer(
8324
203k
                errors, &errorHandler, encoding, reason,
8325
203k
                &starts, &inend, &startinpos, &endinpos, &exc, &in,
8326
203k
                &writer)) {
8327
444
            goto error;
8328
444
        }
8329
        /* The error handler may have skipped bytes; reset the conversion
8330
           descriptor to the initial shift state before continuing. */
8331
202k
        iconv(cd, NULL, NULL, NULL, NULL);
8332
202k
    }
8333
8334
1.70k
    if (consumed != NULL) {
8335
0
        *consumed = in - starts;
8336
0
    }
8337
1.70k
    iconv_close(cd);
8338
1.70k
    Py_XDECREF(errorHandler);
8339
1.70k
    Py_XDECREF(exc);
8340
1.70k
    return _PyUnicodeWriter_Finish(&writer);
8341
8342
444
error:
8343
444
    iconv_close(cd);
8344
444
    _PyUnicodeWriter_Dealloc(&writer);
8345
444
    Py_XDECREF(errorHandler);
8346
444
    Py_XDECREF(exc);
8347
444
    return NULL;
8348
2.15k
}
8349
8350
/* Grow the output buffer of a PyBytesWriter, keeping the raw cursor *pout and
8351
   the end pointer *poutend valid.  Returns 0 on success, -1 on error. */
8352
static int
8353
iconv_grow_writer(PyBytesWriter *writer, char **pout, char **poutend)
8354
0
{
8355
0
    char *base = PyBytesWriter_GetData(writer);
8356
0
    Py_ssize_t used = *pout - base;
8357
0
    Py_ssize_t cursize = PyBytesWriter_GetSize(writer);
8358
0
    Py_ssize_t growby = cursize > 0 ? cursize : 16;
8359
0
    if (PyBytesWriter_Grow(writer, growby) < 0) {
8360
0
        return -1;
8361
0
    }
8362
0
    base = PyBytesWriter_GetData(writer);
8363
0
    *pout = base + used;
8364
0
    *poutend = base + PyBytesWriter_GetSize(writer);
8365
0
    return 0;
8366
0
}
8367
8368
/*
8369
 * Encode a str to bytes with iconv().
8370
 *
8371
 * The string's own buffer is fed to iconv() using the source encoding for its
8372
 * kind, avoiding a widening copy: Latin-1 for 1-byte (not ASCII: it may hold
8373
 * U+0080..U+00FF), UTF-32 for 4-byte, and UCS-2 -- or a UTF-32 copy where that
8374
 * is unsafe (see ICONV_UCS2_PIVOT) -- for 2-byte.  One input unit is one code
8375
 * point, so the unit index is the string position.
8376
 */
8377
PyObject *
8378
_PyUnicode_EncodeIconv(const char *encoding, PyObject *unicode,
8379
                       const char *errors)
8380
67.8k
{
8381
67.8k
    if (!PyUnicode_Check(unicode)) {
8382
0
        PyErr_BadArgument();
8383
0
        return NULL;
8384
0
    }
8385
8386
67.8k
    Py_ssize_t ulen = PyUnicode_GET_LENGTH(unicode);
8387
67.8k
    const char *source;         /* iconv source encoding for this kind */
8388
67.8k
    const char *data;           /* the units to encode */
8389
67.8k
    Py_ssize_t unit;            /* bytes per code point in *data */
8390
67.8k
    Py_UCS4 *widened = NULL;    /* owned UTF-32 copy of a 2-byte string */
8391
67.8k
    int kind = PyUnicode_KIND(unicode);
8392
67.8k
    if (kind == PyUnicode_1BYTE_KIND) {
8393
67.8k
        source = "ISO-8859-1";
8394
67.8k
        data = (const char *)PyUnicode_1BYTE_DATA(unicode);
8395
67.8k
        unit = 1;
8396
67.8k
    }
8397
0
    else if (kind == PyUnicode_4BYTE_KIND) {
8398
0
        source = ICONV_PIVOT;
8399
0
        data = (const char *)PyUnicode_4BYTE_DATA(unicode);
8400
0
        unit = 4;
8401
0
    }
8402
0
    else {
8403
0
#ifdef ICONV_UCS2_PIVOT
8404
        /* Known-strict UCS-2: feed the 2-byte buffer directly. */
8405
0
        source = ICONV_UCS2_PIVOT;
8406
0
        data = (const char *)PyUnicode_2BYTE_DATA(unicode);
8407
0
        unit = 2;
8408
#else
8409
        /* UCS-2 may be aliased to UTF-16 here; widen to UTF-32 to be safe. */
8410
        widened = PyUnicode_AsUCS4Copy(unicode);
8411
        if (widened == NULL) {
8412
            return NULL;
8413
        }
8414
        source = ICONV_PIVOT;
8415
        data = (const char *)widened;
8416
        unit = 4;
8417
#endif
8418
0
    }
8419
8420
67.8k
    iconv_t cd = iconv_open_or_set_error(encoding, source, encoding);
8421
67.8k
    if (cd == (iconv_t)-1) {
8422
67.8k
        PyMem_Free(widened);
8423
67.8k
        return NULL;
8424
67.8k
    }
8425
8426
63
    PyBytesWriter *writer = NULL;
8427
63
    PyObject *errorHandler = NULL;
8428
63
    PyObject *exc = NULL;
8429
63
    PyObject *result = NULL;
8430
63
    const char *ustart = data;
8431
63
    const char *up = data;
8432
63
    const char *uend = data + (size_t)ulen * unit;
8433
63
    int flushing = 0;
8434
63
    int careful = 0;            /* feed one code point per iconv() call */
8435
8436
    /* A generous initial estimate for the output size. */
8437
63
    writer = PyBytesWriter_Create(ulen + (ulen >> 1) + 16);
8438
63
    if (writer == NULL) {
8439
0
        goto done;
8440
0
    }
8441
63
    char *out = PyBytesWriter_GetData(writer);
8442
63
    char *outend = out + PyBytesWriter_GetSize(writer);
8443
8444
126
    for (;;) {
8445
126
        char *inptr = (char *)up;
8446
126
        size_t inleft = (size_t)(uend - up);
8447
        /* One code point at a time, to pin a substitution to its position. */
8448
126
        if (careful && inleft > (size_t)unit) {
8449
0
            inleft = (size_t)unit;
8450
0
        }
8451
126
        char *out_before = out;
8452
126
        size_t outleft = (size_t)(outend - out);
8453
        /* When the whole string is converted, a final iconv() call with a
8454
           NULL input flushes any pending shift sequence (e.g. ISO-2022). */
8455
126
        size_t ret = iconv(cd, flushing ? NULL : &inptr, &inleft, &out, &outleft);
8456
126
        if (!flushing) {
8457
63
            up = inptr;
8458
63
        }
8459
8460
126
        if (ret != (size_t)-1) {
8461
            /* A positive result counts nonreversible conversions: iconv()
8462
               substituted an unencodable character instead of failing with
8463
               EILSEQ (musl and *BSD citrus do this).  Treat it as unencodable
8464
               and re-run one code point at a time to locate it. */
8465
126
            if (ret > 0) {
8466
0
                if (!careful) {
8467
0
                    careful = 1;
8468
0
                    iconv(cd, NULL, NULL, NULL, NULL);
8469
0
                    out = PyBytesWriter_GetData(writer);
8470
0
                    outend = out + PyBytesWriter_GetSize(writer);
8471
0
                    up = ustart;
8472
0
                    continue;
8473
0
                }
8474
                /* This code point was substituted; drop it and report it. */
8475
0
                out = out_before;
8476
0
                up -= unit;
8477
0
            }
8478
126
            else if (flushing) {
8479
63
                break;
8480
63
            }
8481
63
            else if (careful && up < uend) {
8482
0
                continue;
8483
0
            }
8484
63
            else {
8485
                /* All input consumed; switch to flushing the shift state. */
8486
63
                flushing = 1;
8487
63
                continue;
8488
63
            }
8489
126
        }
8490
0
        else if (errno == E2BIG) {
8491
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8492
0
                goto done;
8493
0
            }
8494
0
            continue;
8495
0
        }
8496
0
        else if (errno != EILSEQ && errno != EINVAL) {
8497
0
            PyErr_SetFromErrno(PyExc_OSError);
8498
0
            goto done;
8499
0
        }
8500
8501
        /* An unencodable code point at *up; one input unit is one code point. */
8502
0
        Py_ssize_t pos = (up - ustart) / unit;
8503
0
        Py_ssize_t newpos;
8504
0
        PyObject *rep = unicode_encode_call_errorhandler(
8505
0
                errors, &errorHandler, encoding, "invalid character",
8506
0
                unicode, &exc, pos, pos + 1, &newpos);
8507
0
        if (rep == NULL) {
8508
0
            goto done;
8509
0
        }
8510
8511
0
        const char *repdata;
8512
0
        Py_ssize_t replen;
8513
0
        PyObject *repbytes = NULL;
8514
0
        if (PyBytes_Check(rep)) {
8515
0
            repdata = PyBytes_AS_STRING(rep);
8516
0
            replen = PyBytes_GET_SIZE(rep);
8517
0
        }
8518
0
        else {
8519
            /* A str replacement is encoded through the same codec. */
8520
0
            assert(PyUnicode_Check(rep));
8521
0
            repbytes = _PyUnicode_EncodeIconv(encoding, rep, errors);
8522
0
            Py_DECREF(rep);
8523
0
            if (repbytes == NULL) {
8524
0
                goto done;
8525
0
            }
8526
0
            repdata = PyBytes_AS_STRING(repbytes);
8527
0
            replen = PyBytes_GET_SIZE(repbytes);
8528
0
        }
8529
8530
0
        while (outend - out < replen) {
8531
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8532
0
                if (repbytes != NULL) {
8533
0
                    Py_DECREF(repbytes);
8534
0
                }
8535
0
                else {
8536
0
                    Py_DECREF(rep);
8537
0
                }
8538
0
                goto done;
8539
0
            }
8540
0
        }
8541
0
        memcpy(out, repdata, replen);
8542
0
        out += replen;
8543
0
        if (repbytes != NULL) {
8544
0
            Py_DECREF(repbytes);
8545
0
        }
8546
0
        else {
8547
0
            Py_DECREF(rep);
8548
0
        }
8549
0
        up = ustart + (size_t)newpos * unit;
8550
        /* Reset the shift state after the injected replacement bytes. */
8551
0
        iconv(cd, NULL, NULL, NULL, NULL);
8552
0
    }
8553
8554
63
    if (PyBytesWriter_Resize(writer, out - (char *)PyBytesWriter_GetData(writer)) < 0) {
8555
0
        goto done;
8556
0
    }
8557
63
    result = PyBytesWriter_Finish(writer);
8558
63
    writer = NULL;
8559
8560
63
done:
8561
63
    if (writer != NULL) {
8562
0
        PyBytesWriter_Discard(writer);
8563
0
    }
8564
63
    iconv_close(cd);
8565
63
    PyMem_Free(widened);
8566
63
    Py_XDECREF(errorHandler);
8567
63
    Py_XDECREF(exc);
8568
63
    return result;
8569
63
}
8570
8571
#endif /* HAVE_ICONV */
8572
8573
/* --- Character Mapping Codec -------------------------------------------- */
8574
8575
static int
8576
charmap_decode_string(const char *s,
8577
                      Py_ssize_t size,
8578
                      PyObject *mapping,
8579
                      const char *errors,
8580
                      _PyUnicodeWriter *writer)
8581
614k
{
8582
614k
    const char *starts = s;
8583
614k
    const char *e;
8584
614k
    Py_ssize_t startinpos, endinpos;
8585
614k
    PyObject *errorHandler = NULL, *exc = NULL;
8586
614k
    Py_ssize_t maplen;
8587
614k
    int mapkind;
8588
614k
    const void *mapdata;
8589
614k
    Py_UCS4 x;
8590
614k
    unsigned char ch;
8591
8592
614k
    maplen = PyUnicode_GET_LENGTH(mapping);
8593
614k
    mapdata = PyUnicode_DATA(mapping);
8594
614k
    mapkind = PyUnicode_KIND(mapping);
8595
8596
614k
    e = s + size;
8597
8598
614k
    if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
8599
        /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
8600
         * is disabled in encoding aliases, latin1 is preferred because
8601
         * its implementation is faster. */
8602
124
        const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
8603
124
        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8604
124
        Py_UCS4 maxchar = writer->maxchar;
8605
8606
124
        assert (writer->kind == PyUnicode_1BYTE_KIND);
8607
7.69k
        while (s < e) {
8608
7.56k
            ch = *s;
8609
7.56k
            x = mapdata_ucs1[ch];
8610
7.56k
            if (x > maxchar) {
8611
119
                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8612
0
                    goto onError;
8613
119
                maxchar = writer->maxchar;
8614
119
                outdata = (Py_UCS1 *)writer->data;
8615
119
            }
8616
7.56k
            outdata[writer->pos] = x;
8617
7.56k
            writer->pos++;
8618
7.56k
            ++s;
8619
7.56k
        }
8620
124
        return 0;
8621
124
    }
8622
8623
725k
    while (s < e) {
8624
709k
        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8625
709k
            int outkind = writer->kind;
8626
709k
            const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
8627
709k
            if (outkind == PyUnicode_1BYTE_KIND) {
8628
650k
                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8629
650k
                Py_UCS4 maxchar = writer->maxchar;
8630
18.7M
                while (s < e) {
8631
18.1M
                    ch = *s;
8632
18.1M
                    x = mapdata_ucs2[ch];
8633
18.1M
                    if (x > maxchar)
8634
75.4k
                        goto Error;
8635
18.1M
                    outdata[writer->pos] = x;
8636
18.1M
                    writer->pos++;
8637
18.1M
                    ++s;
8638
18.1M
                }
8639
574k
                break;
8640
650k
            }
8641
59.5k
            else if (outkind == PyUnicode_2BYTE_KIND) {
8642
59.5k
                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8643
30.5M
                while (s < e) {
8644
30.4M
                    ch = *s;
8645
30.4M
                    x = mapdata_ucs2[ch];
8646
30.4M
                    if (x == 0xFFFE)
8647
35.3k
                        goto Error;
8648
30.4M
                    outdata[writer->pos] = x;
8649
30.4M
                    writer->pos++;
8650
30.4M
                    ++s;
8651
30.4M
                }
8652
24.2k
                break;
8653
59.5k
            }
8654
709k
        }
8655
0
        ch = *s;
8656
8657
0
        if (ch < maplen)
8658
0
            x = PyUnicode_READ(mapkind, mapdata, ch);
8659
0
        else
8660
0
            x = 0xfffe; /* invalid value */
8661
110k
Error:
8662
110k
        if (x == 0xfffe)
8663
56.3k
        {
8664
            /* undefined mapping */
8665
56.3k
            startinpos = s-starts;
8666
56.3k
            endinpos = startinpos+1;
8667
56.3k
            if (unicode_decode_call_errorhandler_writer(
8668
56.3k
                    errors, &errorHandler,
8669
56.3k
                    "charmap", "character maps to <undefined>",
8670
56.3k
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
8671
56.3k
                    writer)) {
8672
16
                goto onError;
8673
16
            }
8674
56.3k
            continue;
8675
56.3k
        }
8676
8677
54.4k
        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8678
0
            goto onError;
8679
54.4k
        ++s;
8680
54.4k
    }
8681
614k
    Py_XDECREF(errorHandler);
8682
614k
    Py_XDECREF(exc);
8683
614k
    return 0;
8684
8685
16
onError:
8686
16
    Py_XDECREF(errorHandler);
8687
16
    Py_XDECREF(exc);
8688
16
    return -1;
8689
614k
}
8690
8691
static int
8692
charmap_decode_mapping(const char *s,
8693
                       Py_ssize_t size,
8694
                       PyObject *mapping,
8695
                       const char *errors,
8696
                       _PyUnicodeWriter *writer)
8697
0
{
8698
0
    const char *starts = s;
8699
0
    const char *e;
8700
0
    Py_ssize_t startinpos, endinpos;
8701
0
    PyObject *errorHandler = NULL, *exc = NULL;
8702
0
    unsigned char ch;
8703
0
    PyObject *key, *item = NULL;
8704
8705
0
    e = s + size;
8706
8707
0
    while (s < e) {
8708
0
        ch = *s;
8709
8710
        /* Get mapping (char ordinal -> integer, Unicode char or None) */
8711
0
        key = PyLong_FromLong((long)ch);
8712
0
        if (key == NULL)
8713
0
            goto onError;
8714
8715
0
        int rc = PyMapping_GetOptionalItem(mapping, key, &item);
8716
0
        Py_DECREF(key);
8717
0
        if (rc == 0) {
8718
            /* No mapping found means: mapping is undefined. */
8719
0
            goto Undefined;
8720
0
        }
8721
0
        if (item == NULL) {
8722
0
            if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8723
                /* No mapping found means: mapping is undefined. */
8724
0
                PyErr_Clear();
8725
0
                goto Undefined;
8726
0
            } else
8727
0
                goto onError;
8728
0
        }
8729
8730
        /* Apply mapping */
8731
0
        if (item == Py_None)
8732
0
            goto Undefined;
8733
0
        if (PyLong_Check(item)) {
8734
0
            long value = PyLong_AsLong(item);
8735
0
            if (value == 0xFFFE)
8736
0
                goto Undefined;
8737
0
            if (value < 0 || value > MAX_UNICODE) {
8738
0
                PyErr_Format(PyExc_TypeError,
8739
0
                             "character mapping must be in range(0x%lx)",
8740
0
                             (unsigned long)MAX_UNICODE + 1);
8741
0
                goto onError;
8742
0
            }
8743
8744
0
            if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8745
0
                goto onError;
8746
0
        }
8747
0
        else if (PyUnicode_Check(item)) {
8748
0
            if (PyUnicode_GET_LENGTH(item) == 1) {
8749
0
                Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8750
0
                if (value == 0xFFFE)
8751
0
                    goto Undefined;
8752
0
                if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8753
0
                    goto onError;
8754
0
            }
8755
0
            else {
8756
0
                writer->overallocate = 1;
8757
0
                if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8758
0
                    goto onError;
8759
0
            }
8760
0
        }
8761
0
        else {
8762
            /* wrong return value */
8763
0
            PyErr_SetString(PyExc_TypeError,
8764
0
                            "character mapping must return integer, None or str");
8765
0
            goto onError;
8766
0
        }
8767
0
        Py_CLEAR(item);
8768
0
        ++s;
8769
0
        continue;
8770
8771
0
Undefined:
8772
        /* undefined mapping */
8773
0
        Py_CLEAR(item);
8774
0
        startinpos = s-starts;
8775
0
        endinpos = startinpos+1;
8776
0
        if (unicode_decode_call_errorhandler_writer(
8777
0
                errors, &errorHandler,
8778
0
                "charmap", "character maps to <undefined>",
8779
0
                &starts, &e, &startinpos, &endinpos, &exc, &s,
8780
0
                writer)) {
8781
0
            goto onError;
8782
0
        }
8783
0
    }
8784
0
    Py_XDECREF(errorHandler);
8785
0
    Py_XDECREF(exc);
8786
0
    return 0;
8787
8788
0
onError:
8789
0
    Py_XDECREF(item);
8790
0
    Py_XDECREF(errorHandler);
8791
0
    Py_XDECREF(exc);
8792
0
    return -1;
8793
0
}
8794
8795
PyObject *
8796
PyUnicode_DecodeCharmap(const char *s,
8797
                        Py_ssize_t size,
8798
                        PyObject *mapping,
8799
                        const char *errors)
8800
614k
{
8801
614k
    _PyUnicodeWriter writer;
8802
8803
    /* Default to Latin-1 */
8804
614k
    if (mapping == NULL)
8805
27
        return PyUnicode_DecodeLatin1(s, size, errors);
8806
8807
614k
    if (size == 0)
8808
0
        _Py_RETURN_UNICODE_EMPTY();
8809
614k
    _PyUnicodeWriter_Init(&writer);
8810
614k
    writer.min_length = size;
8811
614k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
8812
0
        goto onError;
8813
8814
614k
    if (PyUnicode_CheckExact(mapping)) {
8815
614k
        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8816
16
            goto onError;
8817
614k
    }
8818
0
    else {
8819
0
        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8820
0
            goto onError;
8821
0
    }
8822
614k
    return _PyUnicodeWriter_Finish(&writer);
8823
8824
16
  onError:
8825
16
    _PyUnicodeWriter_Dealloc(&writer);
8826
16
    return NULL;
8827
614k
}
8828
8829
/* Charmap encoding: the lookup table */
8830
8831
/*[clinic input]
8832
class EncodingMap "struct encoding_map *" "&EncodingMapType"
8833
[clinic start generated code]*/
8834
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=14e46bbb6c522d22]*/
8835
8836
struct encoding_map {
8837
    PyObject_HEAD
8838
    unsigned char level1[32];
8839
    int count2, count3;
8840
    unsigned char level23[1];
8841
};
8842
8843
/*[clinic input]
8844
EncodingMap.size
8845
8846
Return the size (in bytes) of this object.
8847
[clinic start generated code]*/
8848
8849
static PyObject *
8850
EncodingMap_size_impl(struct encoding_map *self)
8851
/*[clinic end generated code: output=c4c969e4c99342a4 input=004ff13f26bb5366]*/
8852
0
{
8853
0
    return PyLong_FromLong((sizeof(*self) - 1) + 16*self->count2 +
8854
0
                           128*self->count3);
8855
0
}
8856
8857
static PyMethodDef encoding_map_methods[] = {
8858
    ENCODINGMAP_SIZE_METHODDEF
8859
    {NULL, NULL}
8860
};
8861
8862
static PyTypeObject EncodingMapType = {
8863
    PyVarObject_HEAD_INIT(NULL, 0)
8864
    .tp_name = "EncodingMap",
8865
    .tp_basicsize = sizeof(struct encoding_map),
8866
    /* methods */
8867
    .tp_flags = Py_TPFLAGS_DEFAULT,
8868
    .tp_methods = encoding_map_methods,
8869
};
8870
8871
PyObject*
8872
PyUnicode_BuildEncodingMap(PyObject* string)
8873
135
{
8874
135
    PyObject *result;
8875
135
    struct encoding_map *mresult;
8876
135
    int i;
8877
135
    int need_dict = 0;
8878
135
    unsigned char level1[32];
8879
135
    unsigned char level2[512];
8880
135
    unsigned char *mlevel1, *mlevel2, *mlevel3;
8881
135
    int count2 = 0, count3 = 0;
8882
135
    int kind;
8883
135
    const void *data;
8884
135
    int length;
8885
135
    Py_UCS4 ch;
8886
8887
135
    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
8888
0
        PyErr_BadArgument();
8889
0
        return NULL;
8890
0
    }
8891
135
    kind = PyUnicode_KIND(string);
8892
135
    data = PyUnicode_DATA(string);
8893
135
    length = (int)Py_MIN(PyUnicode_GET_LENGTH(string), 256);
8894
135
    memset(level1, 0xFF, sizeof level1);
8895
135
    memset(level2, 0xFF, sizeof level2);
8896
8897
    /* If there isn't a one-to-one mapping of NULL to \0,
8898
       or if there are non-BMP characters, we need to use
8899
       a mapping dictionary. */
8900
135
    if (PyUnicode_READ(kind, data, 0) != 0)
8901
0
        need_dict = 1;
8902
34.5k
    for (i = 1; i < length; i++) {
8903
34.4k
        int l1, l2;
8904
34.4k
        ch = PyUnicode_READ(kind, data, i);
8905
34.4k
        if (ch == 0 || ch > 0xFFFF) {
8906
0
            need_dict = 1;
8907
0
            break;
8908
0
        }
8909
34.4k
        if (ch == 0xFFFE)
8910
            /* unmapped character */
8911
990
            continue;
8912
33.4k
        l1 = ch >> 11;
8913
33.4k
        l2 = ch >> 7;
8914
33.4k
        if (level1[l1] == 0xFF)
8915
246
            level1[l1] = count2++;
8916
33.4k
        if (level2[l2] == 0xFF)
8917
720
            level2[l2] = count3++;
8918
33.4k
    }
8919
8920
135
    if (count2 >= 0xFF || count3 >= 0xFF)
8921
0
        need_dict = 1;
8922
8923
135
    if (need_dict) {
8924
0
        PyObject *result = PyDict_New();
8925
0
        if (!result)
8926
0
            return NULL;
8927
0
        for (i = 0; i < length; i++) {
8928
0
            Py_UCS4 c = PyUnicode_READ(kind, data, i);
8929
0
            PyObject *key = PyLong_FromLong(c);
8930
0
            if (key == NULL) {
8931
0
                Py_DECREF(result);
8932
0
                return NULL;
8933
0
            }
8934
0
            PyObject *value = PyLong_FromLong(i);
8935
0
            if (value == NULL) {
8936
0
                Py_DECREF(key);
8937
0
                Py_DECREF(result);
8938
0
                return NULL;
8939
0
            }
8940
0
            int rc = PyDict_SetItem(result, key, value);
8941
0
            Py_DECREF(key);
8942
0
            Py_DECREF(value);
8943
0
            if (rc < 0) {
8944
0
                Py_DECREF(result);
8945
0
                return NULL;
8946
0
            }
8947
0
        }
8948
0
        return result;
8949
0
    }
8950
8951
    /* Create a three-level trie */
8952
135
    result = PyObject_Malloc(sizeof(struct encoding_map) +
8953
135
                             16*count2 + 128*count3 - 1);
8954
135
    if (!result) {
8955
0
        return PyErr_NoMemory();
8956
0
    }
8957
8958
135
    _PyObject_Init(result, &EncodingMapType);
8959
135
    mresult = (struct encoding_map*)result;
8960
135
    mresult->count2 = count2;
8961
135
    mresult->count3 = count3;
8962
135
    mlevel1 = mresult->level1;
8963
135
    mlevel2 = mresult->level23;
8964
135
    mlevel3 = mresult->level23 + 16*count2;
8965
135
    memcpy(mlevel1, level1, 32);
8966
135
    memset(mlevel2, 0xFF, 16*count2);
8967
135
    memset(mlevel3, 0, 128*count3);
8968
135
    count3 = 0;
8969
34.5k
    for (i = 1; i < length; i++) {
8970
34.4k
        int o1, o2, o3, i2, i3;
8971
34.4k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8972
34.4k
        if (ch == 0xFFFE)
8973
            /* unmapped character */
8974
990
            continue;
8975
33.4k
        o1 = ch>>11;
8976
33.4k
        o2 = (ch>>7) & 0xF;
8977
33.4k
        i2 = 16*mlevel1[o1] + o2;
8978
33.4k
        if (mlevel2[i2] == 0xFF)
8979
720
            mlevel2[i2] = count3++;
8980
33.4k
        o3 = ch & 0x7F;
8981
33.4k
        i3 = 128*mlevel2[i2] + o3;
8982
33.4k
        mlevel3[i3] = i;
8983
33.4k
    }
8984
135
    return result;
8985
135
}
8986
8987
static int
8988
encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
8989
0
{
8990
0
    struct encoding_map *map = (struct encoding_map*)mapping;
8991
0
    int l1 = c>>11;
8992
0
    int l2 = (c>>7) & 0xF;
8993
0
    int l3 = c & 0x7F;
8994
0
    int i;
8995
8996
0
    if (c > 0xFFFF)
8997
0
        return -1;
8998
0
    if (c == 0)
8999
0
        return 0;
9000
    /* level 1*/
9001
0
    i = map->level1[l1];
9002
0
    if (i == 0xFF) {
9003
0
        return -1;
9004
0
    }
9005
    /* level 2*/
9006
0
    i = map->level23[16*i+l2];
9007
0
    if (i == 0xFF) {
9008
0
        return -1;
9009
0
    }
9010
    /* level 3 */
9011
0
    i = map->level23[16*map->count2 + 128*i + l3];
9012
0
    if (i == 0) {
9013
0
        return -1;
9014
0
    }
9015
0
    return i;
9016
0
}
9017
9018
/* Lookup the character in the mapping.
9019
   On success, return PyLong, PyBytes or None (if the character can't be found).
9020
   If the result is PyLong, put its value in replace.
9021
   On error, return NULL.
9022
   */
9023
static PyObject *
9024
charmapencode_lookup(Py_UCS4 c, PyObject *mapping, unsigned char *replace)
9025
0
{
9026
0
    PyObject *w = PyLong_FromLong((long)c);
9027
0
    PyObject *x;
9028
9029
0
    if (w == NULL)
9030
0
        return NULL;
9031
0
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9032
0
    Py_DECREF(w);
9033
0
    if (rc == 0) {
9034
        /* No mapping found means: mapping is undefined. */
9035
0
        Py_RETURN_NONE;
9036
0
    }
9037
0
    if (x == NULL) {
9038
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9039
            /* No mapping found means: mapping is undefined. */
9040
0
            PyErr_Clear();
9041
0
            Py_RETURN_NONE;
9042
0
        } else
9043
0
            return NULL;
9044
0
    }
9045
0
    else if (x == Py_None)
9046
0
        return x;
9047
0
    else if (PyLong_Check(x)) {
9048
0
        long value = PyLong_AsLong(x);
9049
0
        if (value < 0 || value > 255) {
9050
0
            PyErr_SetString(PyExc_TypeError,
9051
0
                            "character mapping must be in range(256)");
9052
0
            Py_DECREF(x);
9053
0
            return NULL;
9054
0
        }
9055
0
        *replace = (unsigned char)value;
9056
0
        return x;
9057
0
    }
9058
0
    else if (PyBytes_Check(x))
9059
0
        return x;
9060
0
    else {
9061
        /* wrong return value */
9062
0
        PyErr_Format(PyExc_TypeError,
9063
0
                     "character mapping must return integer, bytes or None, not %.400s",
9064
0
                     Py_TYPE(x)->tp_name);
9065
0
        Py_DECREF(x);
9066
0
        return NULL;
9067
0
    }
9068
0
}
9069
9070
static int
9071
charmapencode_resize(PyBytesWriter *writer, Py_ssize_t *outpos, Py_ssize_t requiredsize)
9072
0
{
9073
0
    Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9074
    /* exponentially overallocate to minimize reallocations */
9075
0
    if (requiredsize < 2 * outsize)
9076
0
        requiredsize = 2 * outsize;
9077
0
    return PyBytesWriter_Resize(writer, requiredsize);
9078
0
}
9079
9080
typedef enum charmapencode_result {
9081
    enc_SUCCESS, enc_FAILED, enc_EXCEPTION
9082
} charmapencode_result;
9083
/* lookup the character, put the result in the output string and adjust
9084
   various state variables. Resize the output bytes object if not enough
9085
   space is available. Return a new reference to the object that
9086
   was put in the output buffer, or Py_None, if the mapping was undefined
9087
   (in which case no character was written) or NULL, if a
9088
   reallocation error occurred. The caller must decref the result */
9089
static charmapencode_result
9090
charmapencode_output(Py_UCS4 c, PyObject *mapping,
9091
                     PyBytesWriter *writer, Py_ssize_t *outpos)
9092
0
{
9093
0
    PyObject *rep;
9094
0
    unsigned char replace;
9095
0
    char *outstart;
9096
0
    Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9097
9098
0
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9099
0
        int res = encoding_map_lookup(c, mapping);
9100
0
        Py_ssize_t requiredsize = *outpos+1;
9101
0
        if (res == -1) {
9102
0
            return enc_FAILED;
9103
0
        }
9104
9105
0
        if (outsize<requiredsize) {
9106
0
            if (charmapencode_resize(writer, outpos, requiredsize)) {
9107
0
                return enc_EXCEPTION;
9108
0
            }
9109
0
        }
9110
0
        outstart = _PyBytesWriter_GetData(writer);
9111
0
        outstart[(*outpos)++] = (char)res;
9112
0
        return enc_SUCCESS;
9113
0
    }
9114
9115
0
    rep = charmapencode_lookup(c, mapping, &replace);
9116
0
    if (rep==NULL)
9117
0
        return enc_EXCEPTION;
9118
0
    else if (rep==Py_None) {
9119
0
        Py_DECREF(rep);
9120
0
        return enc_FAILED;
9121
0
    } else {
9122
0
        if (PyLong_Check(rep)) {
9123
0
            Py_ssize_t requiredsize = *outpos+1;
9124
0
            if (outsize<requiredsize)
9125
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9126
0
                    Py_DECREF(rep);
9127
0
                    return enc_EXCEPTION;
9128
0
                }
9129
0
            outstart = _PyBytesWriter_GetData(writer);
9130
0
            outstart[(*outpos)++] = (char)replace;
9131
0
        }
9132
0
        else {
9133
0
            const char *repchars = PyBytes_AS_STRING(rep);
9134
0
            Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
9135
0
            Py_ssize_t requiredsize = *outpos+repsize;
9136
0
            if (outsize<requiredsize)
9137
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9138
0
                    Py_DECREF(rep);
9139
0
                    return enc_EXCEPTION;
9140
0
                }
9141
0
            outstart = _PyBytesWriter_GetData(writer);
9142
0
            memcpy(outstart + *outpos, repchars, repsize);
9143
0
            *outpos += repsize;
9144
0
        }
9145
0
    }
9146
0
    Py_DECREF(rep);
9147
0
    return enc_SUCCESS;
9148
0
}
9149
9150
/* handle an error in _PyUnicode_EncodeCharmap()
9151
   Return 0 on success, -1 on error */
9152
static int
9153
charmap_encoding_error(
9154
    PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
9155
    PyObject **exceptionObject,
9156
    _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
9157
    PyBytesWriter *writer, Py_ssize_t *respos)
9158
0
{
9159
0
    PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9160
0
    Py_ssize_t size, repsize;
9161
0
    Py_ssize_t newpos;
9162
0
    int kind;
9163
0
    const void *data;
9164
0
    Py_ssize_t index;
9165
    /* startpos for collecting unencodable chars */
9166
0
    Py_ssize_t collstartpos = *inpos;
9167
0
    Py_ssize_t collendpos = *inpos+1;
9168
0
    Py_ssize_t collpos;
9169
0
    const char *encoding = "charmap";
9170
0
    const char *reason = "character maps to <undefined>";
9171
0
    charmapencode_result x;
9172
0
    Py_UCS4 ch;
9173
0
    int val;
9174
9175
0
    size = PyUnicode_GET_LENGTH(unicode);
9176
    /* find all unencodable characters */
9177
0
    while (collendpos < size) {
9178
0
        PyObject *rep;
9179
0
        unsigned char replace;
9180
0
        if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9181
0
            ch = PyUnicode_READ_CHAR(unicode, collendpos);
9182
0
            val = encoding_map_lookup(ch, mapping);
9183
0
            if (val != -1)
9184
0
                break;
9185
0
            ++collendpos;
9186
0
            continue;
9187
0
        }
9188
9189
0
        ch = PyUnicode_READ_CHAR(unicode, collendpos);
9190
0
        rep = charmapencode_lookup(ch, mapping, &replace);
9191
0
        if (rep==NULL)
9192
0
            return -1;
9193
0
        else if (rep!=Py_None) {
9194
0
            Py_DECREF(rep);
9195
0
            break;
9196
0
        }
9197
0
        Py_DECREF(rep);
9198
0
        ++collendpos;
9199
0
    }
9200
    /* cache callback name lookup
9201
     * (if not done yet, i.e. it's the first error) */
9202
0
    if (*error_handler == _Py_ERROR_UNKNOWN)
9203
0
        *error_handler = _Py_GetErrorHandler(errors);
9204
9205
0
    switch (*error_handler) {
9206
0
    case _Py_ERROR_STRICT:
9207
0
        raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9208
0
        return -1;
9209
9210
0
    case _Py_ERROR_REPLACE:
9211
0
        for (collpos = collstartpos; collpos<collendpos; ++collpos) {
9212
0
            x = charmapencode_output('?', mapping, writer, respos);
9213
0
            if (x==enc_EXCEPTION) {
9214
0
                return -1;
9215
0
            }
9216
0
            else if (x==enc_FAILED) {
9217
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9218
0
                return -1;
9219
0
            }
9220
0
        }
9221
0
        _Py_FALLTHROUGH;
9222
0
    case _Py_ERROR_IGNORE:
9223
0
        *inpos = collendpos;
9224
0
        break;
9225
9226
0
    case _Py_ERROR_XMLCHARREFREPLACE:
9227
        /* generate replacement (temporarily (mis)uses p) */
9228
0
        for (collpos = collstartpos; collpos < collendpos; ++collpos) {
9229
0
            char buffer[2+29+1+1];
9230
0
            char *cp;
9231
0
            sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
9232
0
            for (cp = buffer; *cp; ++cp) {
9233
0
                x = charmapencode_output(*cp, mapping, writer, respos);
9234
0
                if (x==enc_EXCEPTION)
9235
0
                    return -1;
9236
0
                else if (x==enc_FAILED) {
9237
0
                    raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9238
0
                    return -1;
9239
0
                }
9240
0
            }
9241
0
        }
9242
0
        *inpos = collendpos;
9243
0
        break;
9244
9245
0
    default:
9246
0
        repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
9247
0
                                                      encoding, reason, unicode, exceptionObject,
9248
0
                                                      collstartpos, collendpos, &newpos);
9249
0
        if (repunicode == NULL)
9250
0
            return -1;
9251
0
        if (PyBytes_Check(repunicode)) {
9252
            /* Directly copy bytes result to output. */
9253
0
            Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9254
0
            Py_ssize_t requiredsize;
9255
0
            repsize = PyBytes_Size(repunicode);
9256
0
            requiredsize = *respos + repsize;
9257
0
            if (requiredsize > outsize)
9258
                /* Make room for all additional bytes. */
9259
0
                if (charmapencode_resize(writer, respos, requiredsize)) {
9260
0
                    Py_DECREF(repunicode);
9261
0
                    return -1;
9262
0
                }
9263
0
            memcpy((char*)PyBytesWriter_GetData(writer) + *respos,
9264
0
                   PyBytes_AsString(repunicode),  repsize);
9265
0
            *respos += repsize;
9266
0
            *inpos = newpos;
9267
0
            Py_DECREF(repunicode);
9268
0
            break;
9269
0
        }
9270
        /* generate replacement  */
9271
0
        repsize = PyUnicode_GET_LENGTH(repunicode);
9272
0
        data = PyUnicode_DATA(repunicode);
9273
0
        kind = PyUnicode_KIND(repunicode);
9274
0
        for (index = 0; index < repsize; index++) {
9275
0
            Py_UCS4 repch = PyUnicode_READ(kind, data, index);
9276
0
            x = charmapencode_output(repch, mapping, writer, respos);
9277
0
            if (x==enc_EXCEPTION) {
9278
0
                Py_DECREF(repunicode);
9279
0
                return -1;
9280
0
            }
9281
0
            else if (x==enc_FAILED) {
9282
0
                Py_DECREF(repunicode);
9283
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9284
0
                return -1;
9285
0
            }
9286
0
        }
9287
0
        *inpos = newpos;
9288
0
        Py_DECREF(repunicode);
9289
0
    }
9290
0
    return 0;
9291
0
}
9292
9293
PyObject *
9294
_PyUnicode_EncodeCharmap(PyObject *unicode,
9295
                         PyObject *mapping,
9296
                         const char *errors)
9297
0
{
9298
    /* Default to Latin-1 */
9299
0
    if (mapping == NULL) {
9300
0
        return unicode_encode_ucs1(unicode, errors, 256);
9301
0
    }
9302
9303
0
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
9304
0
    if (size == 0) {
9305
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
9306
0
    }
9307
0
    const void *data = PyUnicode_DATA(unicode);
9308
0
    int kind = PyUnicode_KIND(unicode);
9309
9310
0
    PyObject *error_handler_obj = NULL;
9311
0
    PyObject *exc = NULL;
9312
9313
    /* output object */
9314
0
    PyBytesWriter *writer;
9315
    /* allocate enough for a simple encoding without
9316
       replacements, if we need more, we'll resize */
9317
0
    writer = PyBytesWriter_Create(size);
9318
0
    if (writer == NULL) {
9319
0
        goto onError;
9320
0
    }
9321
9322
    /* current input position */
9323
0
    Py_ssize_t inpos = 0;
9324
    /* current output position */
9325
0
    Py_ssize_t respos = 0;
9326
0
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
9327
9328
0
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9329
0
        char *outstart = _PyBytesWriter_GetData(writer);
9330
0
        Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9331
9332
0
        while (inpos<size) {
9333
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9334
9335
            /* try to encode it */
9336
0
            int res = encoding_map_lookup(ch, mapping);
9337
0
            Py_ssize_t requiredsize = respos+1;
9338
0
            if (res == -1) {
9339
0
                goto enc_FAILED;
9340
0
            }
9341
9342
0
            if (outsize<requiredsize) {
9343
0
                if (charmapencode_resize(writer, &respos, requiredsize)) {
9344
0
                    goto onError;
9345
0
                }
9346
0
                outstart = _PyBytesWriter_GetData(writer);
9347
0
                outsize = _PyBytesWriter_GetSize(writer);
9348
0
            }
9349
0
            outstart[respos++] = (char)res;
9350
9351
            /* done with this character => adjust input position */
9352
0
            ++inpos;
9353
0
            continue;
9354
9355
0
enc_FAILED:
9356
0
            if (charmap_encoding_error(unicode, &inpos, mapping,
9357
0
                                       &exc,
9358
0
                                       &error_handler, &error_handler_obj, errors,
9359
0
                                       writer, &respos)) {
9360
0
                goto onError;
9361
0
            }
9362
0
            outstart = _PyBytesWriter_GetData(writer);
9363
0
            outsize = _PyBytesWriter_GetSize(writer);
9364
0
        }
9365
0
    }
9366
0
    else {
9367
0
        while (inpos<size) {
9368
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9369
            /* try to encode it */
9370
0
            charmapencode_result x = charmapencode_output(ch, mapping, writer, &respos);
9371
0
            if (x==enc_EXCEPTION) { /* error */
9372
0
                goto onError;
9373
0
            }
9374
0
            if (x==enc_FAILED) { /* unencodable character */
9375
0
                if (charmap_encoding_error(unicode, &inpos, mapping,
9376
0
                                           &exc,
9377
0
                                           &error_handler, &error_handler_obj, errors,
9378
0
                                           writer, &respos)) {
9379
0
                    goto onError;
9380
0
                }
9381
0
            }
9382
0
            else {
9383
                /* done with this character => adjust input position */
9384
0
                ++inpos;
9385
0
            }
9386
0
        }
9387
0
    }
9388
9389
0
    Py_XDECREF(exc);
9390
0
    Py_XDECREF(error_handler_obj);
9391
9392
    /* Resize if we allocated too much */
9393
0
    return PyBytesWriter_FinishWithSize(writer, respos);
9394
9395
0
  onError:
9396
0
    PyBytesWriter_Discard(writer);
9397
0
    Py_XDECREF(exc);
9398
0
    Py_XDECREF(error_handler_obj);
9399
0
    return NULL;
9400
0
}
9401
9402
PyObject *
9403
PyUnicode_AsCharmapString(PyObject *unicode,
9404
                          PyObject *mapping)
9405
0
{
9406
0
    if (!PyUnicode_Check(unicode) || mapping == NULL) {
9407
0
        PyErr_BadArgument();
9408
0
        return NULL;
9409
0
    }
9410
0
    return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
9411
0
}
9412
9413
/* create or adjust a UnicodeTranslateError */
9414
static void
9415
make_translate_exception(PyObject **exceptionObject,
9416
                         PyObject *unicode,
9417
                         Py_ssize_t startpos, Py_ssize_t endpos,
9418
                         const char *reason)
9419
0
{
9420
0
    if (*exceptionObject == NULL) {
9421
0
        *exceptionObject = _PyUnicodeTranslateError_Create(
9422
0
            unicode, startpos, endpos, reason);
9423
0
    }
9424
0
    else {
9425
0
        if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
9426
0
            goto onError;
9427
0
        if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
9428
0
            goto onError;
9429
0
        if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
9430
0
            goto onError;
9431
0
        return;
9432
0
      onError:
9433
0
        Py_CLEAR(*exceptionObject);
9434
0
    }
9435
0
}
9436
9437
/* error handling callback helper:
9438
   build arguments, call the callback and check the arguments,
9439
   put the result into newpos and return the replacement string, which
9440
   has to be freed by the caller */
9441
static PyObject *
9442
unicode_translate_call_errorhandler(const char *errors,
9443
                                    PyObject **errorHandler,
9444
                                    const char *reason,
9445
                                    PyObject *unicode, PyObject **exceptionObject,
9446
                                    Py_ssize_t startpos, Py_ssize_t endpos,
9447
                                    Py_ssize_t *newpos)
9448
0
{
9449
0
    static const char *argparse = "Un;translating error handler must return (str, int) tuple";
9450
9451
0
    Py_ssize_t i_newpos;
9452
0
    PyObject *restuple;
9453
0
    PyObject *resunicode;
9454
9455
0
    if (*errorHandler == NULL) {
9456
0
        *errorHandler = PyCodec_LookupError(errors);
9457
0
        if (*errorHandler == NULL)
9458
0
            return NULL;
9459
0
    }
9460
9461
0
    make_translate_exception(exceptionObject,
9462
0
                             unicode, startpos, endpos, reason);
9463
0
    if (*exceptionObject == NULL)
9464
0
        return NULL;
9465
9466
0
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
9467
0
    if (restuple == NULL)
9468
0
        return NULL;
9469
0
    if (!PyTuple_Check(restuple)) {
9470
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
9471
0
        Py_DECREF(restuple);
9472
0
        return NULL;
9473
0
    }
9474
0
    if (!PyArg_ParseTuple(restuple, argparse,
9475
0
                          &resunicode, &i_newpos)) {
9476
0
        Py_DECREF(restuple);
9477
0
        return NULL;
9478
0
    }
9479
0
    if (i_newpos<0)
9480
0
        *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
9481
0
    else
9482
0
        *newpos = i_newpos;
9483
0
    if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
9484
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
9485
0
        Py_DECREF(restuple);
9486
0
        return NULL;
9487
0
    }
9488
0
    Py_INCREF(resunicode);
9489
0
    Py_DECREF(restuple);
9490
0
    return resunicode;
9491
0
}
9492
9493
/* Lookup the character ch in the mapping and put the result in result,
9494
   which must be decrefed by the caller.
9495
   The result can be PyLong, PyUnicode, None or NULL.
9496
   If the result is PyLong, put its value in replace.
9497
   Return 0 on success, -1 on error */
9498
static int
9499
charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result, Py_UCS4 *replace)
9500
742
{
9501
742
    PyObject *w = PyLong_FromLong((long)c);
9502
742
    PyObject *x;
9503
9504
742
    if (w == NULL)
9505
0
        return -1;
9506
742
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9507
742
    Py_DECREF(w);
9508
742
    if (rc == 0) {
9509
        /* No mapping found means: use 1:1 mapping. */
9510
326
        *result = NULL;
9511
326
        return 0;
9512
326
    }
9513
416
    if (x == NULL) {
9514
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9515
            /* No mapping found means: use 1:1 mapping. */
9516
0
            PyErr_Clear();
9517
0
            *result = NULL;
9518
0
            return 0;
9519
0
        } else
9520
0
            return -1;
9521
0
    }
9522
416
    else if (x == Py_None) {
9523
0
        *result = x;
9524
0
        return 0;
9525
0
    }
9526
416
    else if (PyLong_Check(x)) {
9527
0
        long value = PyLong_AsLong(x);
9528
0
        if (value < 0 || value > MAX_UNICODE) {
9529
0
            PyErr_Format(PyExc_ValueError,
9530
0
                         "character mapping must be in range(0x%lx)",
9531
0
                         (unsigned long)MAX_UNICODE + 1);
9532
0
            Py_DECREF(x);
9533
0
            return -1;
9534
0
        }
9535
0
        *result = x;
9536
0
        *replace = (Py_UCS4)value;
9537
0
        return 0;
9538
0
    }
9539
416
    else if (PyUnicode_Check(x)) {
9540
416
        *result = x;
9541
416
        return 0;
9542
416
    }
9543
0
    else {
9544
        /* wrong return value */
9545
0
        PyErr_SetString(PyExc_TypeError,
9546
0
                        "character mapping must return integer, None or str");
9547
0
        Py_DECREF(x);
9548
0
        return -1;
9549
0
    }
9550
416
}
9551
9552
/* lookup the character, write the result into the writer.
9553
   Return 1 if the result was written into the writer, return 0 if the mapping
9554
   was undefined, raise an exception return -1 on error. */
9555
static int
9556
charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
9557
                        _PyUnicodeWriter *writer)
9558
381
{
9559
381
    PyObject *item;
9560
381
    Py_UCS4 replace;
9561
9562
381
    if (charmaptranslate_lookup(ch, mapping, &item, &replace))
9563
0
        return -1;
9564
9565
381
    if (item == NULL) {
9566
        /* not found => default to 1:1 mapping */
9567
121
        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
9568
0
            return -1;
9569
0
        }
9570
121
        return 1;
9571
121
    }
9572
9573
260
    if (item == Py_None) {
9574
0
        Py_DECREF(item);
9575
0
        return 0;
9576
0
    }
9577
9578
260
    if (PyLong_Check(item)) {
9579
0
        if (_PyUnicodeWriter_WriteCharInline(writer, replace) < 0) {
9580
0
            Py_DECREF(item);
9581
0
            return -1;
9582
0
        }
9583
0
        Py_DECREF(item);
9584
0
        return 1;
9585
0
    }
9586
9587
260
    if (!PyUnicode_Check(item)) {
9588
0
        Py_DECREF(item);
9589
0
        return -1;
9590
0
    }
9591
9592
260
    if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
9593
0
        Py_DECREF(item);
9594
0
        return -1;
9595
0
    }
9596
9597
260
    Py_DECREF(item);
9598
260
    return 1;
9599
260
}
9600
9601
static int
9602
unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
9603
                              Py_UCS1 *translate)
9604
361
{
9605
361
    PyObject *item = NULL;
9606
361
    Py_UCS4 replace;
9607
361
    int ret = 0;
9608
9609
361
    if (charmaptranslate_lookup(ch, mapping, &item, &replace)) {
9610
0
        return -1;
9611
0
    }
9612
9613
361
    if (item == Py_None) {
9614
        /* deletion */
9615
0
        translate[ch] = 0xfe;
9616
0
    }
9617
361
    else if (item == NULL) {
9618
        /* not found => default to 1:1 mapping */
9619
205
        translate[ch] = ch;
9620
205
        return 1;
9621
205
    }
9622
156
    else if (PyLong_Check(item)) {
9623
0
        if (replace > 127) {
9624
            /* invalid character or character outside ASCII:
9625
               skip the fast translate */
9626
0
            goto exit;
9627
0
        }
9628
0
        translate[ch] = (Py_UCS1)replace;
9629
0
    }
9630
156
    else if (PyUnicode_Check(item)) {
9631
156
        if (PyUnicode_GET_LENGTH(item) != 1)
9632
156
            goto exit;
9633
9634
0
        replace = PyUnicode_READ_CHAR(item, 0);
9635
0
        if (replace > 127)
9636
0
            goto exit;
9637
0
        translate[ch] = (Py_UCS1)replace;
9638
0
    }
9639
0
    else {
9640
        /* not None, NULL, long or unicode */
9641
0
        goto exit;
9642
0
    }
9643
0
    ret = 1;
9644
9645
156
  exit:
9646
156
    Py_DECREF(item);
9647
156
    return ret;
9648
0
}
9649
9650
/* Fast path for ascii => ascii translation. Return 1 if the whole string
9651
   was translated into writer, return 0 if the input string was partially
9652
   translated into writer, raise an exception and return -1 on error. */
9653
static int
9654
unicode_fast_translate(PyObject *input, PyObject *mapping,
9655
                       _PyUnicodeWriter *writer, int ignore,
9656
                       Py_ssize_t *input_pos)
9657
300
{
9658
300
    Py_UCS1 ascii_table[128], ch, ch2;
9659
300
    Py_ssize_t len;
9660
300
    const Py_UCS1 *in, *end;
9661
300
    Py_UCS1 *out;
9662
300
    int res = 0;
9663
9664
300
    len = PyUnicode_GET_LENGTH(input);
9665
9666
300
    memset(ascii_table, 0xff, 128);
9667
9668
300
    in = PyUnicode_1BYTE_DATA(input);
9669
300
    end = in + len;
9670
9671
300
    assert(PyUnicode_IS_ASCII(writer->buffer));
9672
300
    assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9673
300
    out = PyUnicode_1BYTE_DATA(writer->buffer);
9674
9675
547
    for (; in < end; in++) {
9676
403
        ch = *in;
9677
403
        ch2 = ascii_table[ch];
9678
403
        if (ch2 == 0xff) {
9679
361
            int translate = unicode_fast_translate_lookup(mapping, ch,
9680
361
                                                          ascii_table);
9681
361
            if (translate < 0)
9682
0
                return -1;
9683
361
            if (translate == 0)
9684
156
                goto exit;
9685
205
            ch2 = ascii_table[ch];
9686
205
        }
9687
247
        if (ch2 == 0xfe) {
9688
0
            if (ignore)
9689
0
                continue;
9690
0
            goto exit;
9691
0
        }
9692
247
        assert(ch2 < 128);
9693
247
        *out = ch2;
9694
247
        out++;
9695
247
    }
9696
144
    res = 1;
9697
9698
300
exit:
9699
300
    writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
9700
300
    *input_pos = in - PyUnicode_1BYTE_DATA(input);
9701
300
    return res;
9702
144
}
9703
9704
static PyObject *
9705
_PyUnicode_TranslateCharmap(PyObject *input,
9706
                            PyObject *mapping,
9707
                            const char *errors)
9708
300
{
9709
    /* input object */
9710
300
    const void *data;
9711
300
    Py_ssize_t size, i;
9712
300
    int kind;
9713
    /* output buffer */
9714
300
    _PyUnicodeWriter writer;
9715
    /* error handler */
9716
300
    const char *reason = "character maps to <undefined>";
9717
300
    PyObject *errorHandler = NULL;
9718
300
    PyObject *exc = NULL;
9719
300
    int ignore;
9720
300
    int res;
9721
9722
300
    if (mapping == NULL) {
9723
0
        PyErr_BadArgument();
9724
0
        return NULL;
9725
0
    }
9726
9727
300
    data = PyUnicode_DATA(input);
9728
300
    kind = PyUnicode_KIND(input);
9729
300
    size = PyUnicode_GET_LENGTH(input);
9730
9731
300
    if (size == 0)
9732
0
        return PyUnicode_FromObject(input);
9733
9734
    /* allocate enough for a simple 1:1 translation without
9735
       replacements, if we need more, we'll resize */
9736
300
    _PyUnicodeWriter_Init(&writer);
9737
300
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
9738
0
        goto onError;
9739
9740
300
    ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9741
9742
300
    if (PyUnicode_IS_ASCII(input)) {
9743
300
        res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9744
300
        if (res < 0) {
9745
0
            _PyUnicodeWriter_Dealloc(&writer);
9746
0
            return NULL;
9747
0
        }
9748
300
        if (res == 1)
9749
144
            return _PyUnicodeWriter_Finish(&writer);
9750
300
    }
9751
0
    else {
9752
0
        i = 0;
9753
0
    }
9754
9755
537
    while (i<size) {
9756
        /* try to encode it */
9757
381
        int translate;
9758
381
        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9759
381
        Py_ssize_t newpos;
9760
        /* startpos for collecting untranslatable chars */
9761
381
        Py_ssize_t collstart;
9762
381
        Py_ssize_t collend;
9763
381
        Py_UCS4 ch;
9764
9765
381
        ch = PyUnicode_READ(kind, data, i);
9766
381
        translate = charmaptranslate_output(ch, mapping, &writer);
9767
381
        if (translate < 0)
9768
0
            goto onError;
9769
9770
381
        if (translate != 0) {
9771
            /* it worked => adjust input pointer */
9772
381
            ++i;
9773
381
            continue;
9774
381
        }
9775
9776
        /* untranslatable character */
9777
0
        collstart = i;
9778
0
        collend = i+1;
9779
9780
        /* find all untranslatable characters */
9781
0
        while (collend < size) {
9782
0
            PyObject *x;
9783
0
            Py_UCS4 replace;
9784
0
            ch = PyUnicode_READ(kind, data, collend);
9785
0
            if (charmaptranslate_lookup(ch, mapping, &x, &replace))
9786
0
                goto onError;
9787
0
            Py_XDECREF(x);
9788
0
            if (x != Py_None)
9789
0
                break;
9790
0
            ++collend;
9791
0
        }
9792
9793
0
        if (ignore) {
9794
0
            i = collend;
9795
0
        }
9796
0
        else {
9797
0
            repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9798
0
                                                             reason, input, &exc,
9799
0
                                                             collstart, collend, &newpos);
9800
0
            if (repunicode == NULL)
9801
0
                goto onError;
9802
0
            if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
9803
0
                Py_DECREF(repunicode);
9804
0
                goto onError;
9805
0
            }
9806
0
            Py_DECREF(repunicode);
9807
0
            i = newpos;
9808
0
        }
9809
0
    }
9810
156
    Py_XDECREF(exc);
9811
156
    Py_XDECREF(errorHandler);
9812
156
    return _PyUnicodeWriter_Finish(&writer);
9813
9814
0
  onError:
9815
0
    _PyUnicodeWriter_Dealloc(&writer);
9816
0
    Py_XDECREF(exc);
9817
0
    Py_XDECREF(errorHandler);
9818
0
    return NULL;
9819
156
}
9820
9821
PyObject *
9822
PyUnicode_Translate(PyObject *str,
9823
                    PyObject *mapping,
9824
                    const char *errors)
9825
0
{
9826
0
    if (ensure_unicode(str) < 0)
9827
0
        return NULL;
9828
0
    return _PyUnicode_TranslateCharmap(str, mapping, errors);
9829
0
}
9830
9831
PyObject *
9832
_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9833
10.5M
{
9834
10.5M
    if (!PyUnicode_Check(unicode)) {
9835
0
        PyErr_BadInternalCall();
9836
0
        return NULL;
9837
0
    }
9838
10.5M
    if (PyUnicode_IS_ASCII(unicode)) {
9839
        /* If the string is already ASCII, just return the same string */
9840
10.5M
        return Py_NewRef(unicode);
9841
10.5M
    }
9842
9843
2.42k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9844
2.42k
    PyObject *result = PyUnicode_New(len, 127);
9845
2.42k
    if (result == NULL) {
9846
0
        return NULL;
9847
0
    }
9848
9849
2.42k
    Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9850
2.42k
    int kind = PyUnicode_KIND(unicode);
9851
2.42k
    const void *data = PyUnicode_DATA(unicode);
9852
2.42k
    Py_ssize_t i;
9853
110k
    for (i = 0; i < len; ++i) {
9854
108k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9855
108k
        if (ch < 127) {
9856
105k
            out[i] = ch;
9857
105k
        }
9858
2.86k
        else if (Py_UNICODE_ISSPACE(ch)) {
9859
1.24k
            out[i] = ' ';
9860
1.24k
        }
9861
1.61k
        else {
9862
1.61k
            int decimal = Py_UNICODE_TODECIMAL(ch);
9863
1.61k
            if (decimal < 0) {
9864
137
                out[i] = '?';
9865
137
                out[i+1] = '\0';
9866
137
                _PyUnicode_LENGTH(result) = i + 1;
9867
137
                break;
9868
137
            }
9869
1.48k
            out[i] = '0' + decimal;
9870
1.48k
        }
9871
108k
    }
9872
9873
2.42k
    assert(_PyUnicode_CheckConsistency(result, 1));
9874
2.42k
    return result;
9875
2.42k
}
9876
9877
/* --- Helpers ------------------------------------------------------------ */
9878
9879
/* helper macro to fixup start/end slice values */
9880
#define ADJUST_INDICES(start, end, len) \
9881
112M
    do {                                \
9882
112M
        if (end > len) {                \
9883
86.4M
            end = len;                  \
9884
86.4M
        }                               \
9885
112M
        else if (end < 0) {             \
9886
0
            end += len;                 \
9887
0
            if (end < 0) {              \
9888
0
                end = 0;                \
9889
0
            }                           \
9890
0
        }                               \
9891
112M
        if (start < 0) {                \
9892
18.9k
            start += len;               \
9893
18.9k
            if (start < 0) {            \
9894
0
                start = 0;              \
9895
0
            }                           \
9896
18.9k
        }                               \
9897
112M
    } while (0)
9898
9899
static Py_ssize_t
9900
any_find_slice(PyObject* s1, PyObject* s2,
9901
               Py_ssize_t start,
9902
               Py_ssize_t end,
9903
               int direction)
9904
27.2M
{
9905
27.2M
    int kind1, kind2;
9906
27.2M
    const void *buf1, *buf2;
9907
27.2M
    Py_ssize_t len1, len2, result;
9908
9909
27.2M
    kind1 = PyUnicode_KIND(s1);
9910
27.2M
    kind2 = PyUnicode_KIND(s2);
9911
27.2M
    if (kind1 < kind2)
9912
0
        return -1;
9913
9914
27.2M
    len1 = PyUnicode_GET_LENGTH(s1);
9915
27.2M
    len2 = PyUnicode_GET_LENGTH(s2);
9916
27.2M
    ADJUST_INDICES(start, end, len1);
9917
27.2M
    if (end - start < len2)
9918
2.23M
        return -1;
9919
9920
25.0M
    buf1 = PyUnicode_DATA(s1);
9921
25.0M
    buf2 = PyUnicode_DATA(s2);
9922
25.0M
    if (len2 == 1) {
9923
24.2M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9924
24.2M
        result = findchar((const char *)buf1 + kind1*start,
9925
24.2M
                          kind1, end - start, ch, direction);
9926
24.2M
        if (result == -1)
9927
3.68M
            return -1;
9928
20.5M
        else
9929
20.5M
            return start + result;
9930
24.2M
    }
9931
9932
801k
    if (kind2 != kind1) {
9933
184k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
9934
184k
        if (!buf2)
9935
0
            return -2;
9936
184k
    }
9937
9938
801k
    if (direction > 0) {
9939
801k
        switch (kind1) {
9940
617k
        case PyUnicode_1BYTE_KIND:
9941
617k
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9942
367k
                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9943
249k
            else
9944
249k
                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9945
617k
            break;
9946
65.0k
        case PyUnicode_2BYTE_KIND:
9947
65.0k
            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9948
65.0k
            break;
9949
119k
        case PyUnicode_4BYTE_KIND:
9950
119k
            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9951
119k
            break;
9952
0
        default:
9953
0
            Py_UNREACHABLE();
9954
801k
        }
9955
801k
    }
9956
0
    else {
9957
0
        switch (kind1) {
9958
0
        case PyUnicode_1BYTE_KIND:
9959
0
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9960
0
                result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9961
0
            else
9962
0
                result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9963
0
            break;
9964
0
        case PyUnicode_2BYTE_KIND:
9965
0
            result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9966
0
            break;
9967
0
        case PyUnicode_4BYTE_KIND:
9968
0
            result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9969
0
            break;
9970
0
        default:
9971
0
            Py_UNREACHABLE();
9972
0
        }
9973
0
    }
9974
9975
801k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
9976
801k
    if (kind2 != kind1)
9977
184k
        PyMem_Free((void *)buf2);
9978
9979
801k
    return result;
9980
801k
}
9981
9982
9983
Py_ssize_t
9984
PyUnicode_Count(PyObject *str,
9985
                PyObject *substr,
9986
                Py_ssize_t start,
9987
                Py_ssize_t end)
9988
0
{
9989
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
9990
0
        return -1;
9991
9992
0
    return unicode_count_impl(str, substr, start, end);
9993
0
}
9994
9995
Py_ssize_t
9996
PyUnicode_Find(PyObject *str,
9997
               PyObject *substr,
9998
               Py_ssize_t start,
9999
               Py_ssize_t end,
10000
               int direction)
10001
0
{
10002
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10003
0
        return -2;
10004
10005
0
    return any_find_slice(str, substr, start, end, direction);
10006
0
}
10007
10008
Py_ssize_t
10009
PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
10010
                   Py_ssize_t start, Py_ssize_t end,
10011
                   int direction)
10012
1.75M
{
10013
1.75M
    int kind;
10014
1.75M
    Py_ssize_t len, result;
10015
1.75M
    len = PyUnicode_GET_LENGTH(str);
10016
1.75M
    ADJUST_INDICES(start, end, len);
10017
1.75M
    if (end - start < 1)
10018
0
        return -1;
10019
1.75M
    kind = PyUnicode_KIND(str);
10020
1.75M
    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
10021
1.75M
                      kind, end-start, ch, direction);
10022
1.75M
    if (result == -1)
10023
1.02M
        return -1;
10024
724k
    else
10025
724k
        return start + result;
10026
1.75M
}
10027
10028
static int
10029
tailmatch(PyObject *self,
10030
          PyObject *substring,
10031
          Py_ssize_t start,
10032
          Py_ssize_t end,
10033
          int direction)
10034
55.9M
{
10035
55.9M
    int kind_self;
10036
55.9M
    int kind_sub;
10037
55.9M
    const void *data_self;
10038
55.9M
    const void *data_sub;
10039
55.9M
    Py_ssize_t offset;
10040
55.9M
    Py_ssize_t i;
10041
55.9M
    Py_ssize_t end_sub;
10042
10043
55.9M
    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
10044
55.9M
    end -= PyUnicode_GET_LENGTH(substring);
10045
55.9M
    if (end < start)
10046
9.83M
        return 0;
10047
10048
46.1M
    if (PyUnicode_GET_LENGTH(substring) == 0)
10049
0
        return 1;
10050
10051
46.1M
    kind_self = PyUnicode_KIND(self);
10052
46.1M
    data_self = PyUnicode_DATA(self);
10053
46.1M
    kind_sub = PyUnicode_KIND(substring);
10054
46.1M
    data_sub = PyUnicode_DATA(substring);
10055
46.1M
    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
10056
10057
46.1M
    if (direction > 0)
10058
7.56M
        offset = end;
10059
38.5M
    else
10060
38.5M
        offset = start;
10061
10062
46.1M
    if (PyUnicode_READ(kind_self, data_self, offset) ==
10063
46.1M
        PyUnicode_READ(kind_sub, data_sub, 0) &&
10064
32.2M
        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
10065
32.2M
        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
10066
        /* If both are of the same kind, memcmp is sufficient */
10067
13.0M
        if (kind_self == kind_sub) {
10068
6.33M
            return ! memcmp((char *)data_self +
10069
6.33M
                                (offset * PyUnicode_KIND(substring)),
10070
6.33M
                            data_sub,
10071
6.33M
                            PyUnicode_GET_LENGTH(substring) *
10072
6.33M
                                PyUnicode_KIND(substring));
10073
6.33M
        }
10074
        /* otherwise we have to compare each character by first accessing it */
10075
6.66M
        else {
10076
            /* We do not need to compare 0 and len(substring)-1 because
10077
               the if statement above ensured already that they are equal
10078
               when we end up here. */
10079
6.81M
            for (i = 1; i < end_sub; ++i) {
10080
168k
                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
10081
168k
                    PyUnicode_READ(kind_sub, data_sub, i))
10082
21.6k
                    return 0;
10083
168k
            }
10084
6.64M
            return 1;
10085
6.66M
        }
10086
13.0M
    }
10087
10088
33.1M
    return 0;
10089
46.1M
}
10090
10091
Py_ssize_t
10092
PyUnicode_Tailmatch(PyObject *str,
10093
                    PyObject *substr,
10094
                    Py_ssize_t start,
10095
                    Py_ssize_t end,
10096
                    int direction)
10097
558
{
10098
558
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10099
0
        return -1;
10100
10101
558
    return tailmatch(str, substr, start, end, direction);
10102
558
}
10103
10104
static PyObject *
10105
ascii_upper_or_lower(PyObject *self, int lower)
10106
68.0M
{
10107
68.0M
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
10108
68.0M
    const char *data = PyUnicode_DATA(self);
10109
68.0M
    char *resdata;
10110
68.0M
    PyObject *res;
10111
10112
68.0M
    res = PyUnicode_New(len, 127);
10113
68.0M
    if (res == NULL)
10114
0
        return NULL;
10115
68.0M
    resdata = PyUnicode_DATA(res);
10116
68.0M
    if (lower)
10117
67.9M
        _Py_bytes_lower(resdata, data, len);
10118
306
    else
10119
306
        _Py_bytes_upper(resdata, data, len);
10120
68.0M
    return res;
10121
68.0M
}
10122
10123
static Py_UCS4
10124
handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
10125
456k
{
10126
456k
    Py_ssize_t j;
10127
456k
    int final_sigma;
10128
456k
    Py_UCS4 c = 0;   /* initialize to prevent gcc warning */
10129
    /* U+03A3 is in the Final_Sigma context when, it is found like this:
10130
10131
     \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
10132
10133
    where ! is a negation and \p{xxx} is a character with property xxx.
10134
    */
10135
840k
    for (j = i - 1; j >= 0; j--) {
10136
839k
        c = PyUnicode_READ(kind, data, j);
10137
839k
        if (!_PyUnicode_IsCaseIgnorable(c))
10138
454k
            break;
10139
839k
    }
10140
456k
    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
10141
456k
    if (final_sigma) {
10142
706k
        for (j = i + 1; j < length; j++) {
10143
703k
            c = PyUnicode_READ(kind, data, j);
10144
703k
            if (!_PyUnicode_IsCaseIgnorable(c))
10145
352k
                break;
10146
703k
        }
10147
355k
        final_sigma = j == length || !_PyUnicode_IsCased(c);
10148
355k
    }
10149
456k
    return (final_sigma) ? 0x3C2 : 0x3C3;
10150
456k
}
10151
10152
static int
10153
lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
10154
           Py_UCS4 c, Py_UCS4 *mapped)
10155
87.5M
{
10156
    /* Obscure special case. */
10157
87.5M
    if (c == 0x3A3) {
10158
456k
        mapped[0] = handle_capital_sigma(kind, data, length, i);
10159
456k
        return 1;
10160
456k
    }
10161
87.1M
    return _PyUnicode_ToLowerFull(c, mapped);
10162
87.5M
}
10163
10164
static Py_ssize_t
10165
do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10166
0
{
10167
0
    Py_ssize_t i, k = 0;
10168
0
    int n_res, j;
10169
0
    Py_UCS4 c, mapped[3];
10170
10171
0
    c = PyUnicode_READ(kind, data, 0);
10172
0
    n_res = _PyUnicode_ToTitleFull(c, mapped);
10173
0
    for (j = 0; j < n_res; j++) {
10174
0
        *maxchar = Py_MAX(*maxchar, mapped[j]);
10175
0
        res[k++] = mapped[j];
10176
0
    }
10177
0
    for (i = 1; i < length; i++) {
10178
0
        c = PyUnicode_READ(kind, data, i);
10179
0
        n_res = lower_ucs4(kind, data, length, i, c, mapped);
10180
0
        for (j = 0; j < n_res; j++) {
10181
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10182
0
            res[k++] = mapped[j];
10183
0
        }
10184
0
    }
10185
0
    return k;
10186
0
}
10187
10188
static Py_ssize_t
10189
0
do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
10190
0
    Py_ssize_t i, k = 0;
10191
10192
0
    for (i = 0; i < length; i++) {
10193
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10194
0
        int n_res, j;
10195
0
        if (Py_UNICODE_ISUPPER(c)) {
10196
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10197
0
        }
10198
0
        else if (Py_UNICODE_ISLOWER(c)) {
10199
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10200
0
        }
10201
0
        else {
10202
0
            n_res = 1;
10203
0
            mapped[0] = c;
10204
0
        }
10205
0
        for (j = 0; j < n_res; j++) {
10206
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10207
0
            res[k++] = mapped[j];
10208
0
        }
10209
0
    }
10210
0
    return k;
10211
0
}
10212
10213
static Py_ssize_t
10214
do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
10215
                  Py_UCS4 *maxchar, int lower)
10216
4.86M
{
10217
4.86M
    Py_ssize_t i, k = 0;
10218
10219
92.4M
    for (i = 0; i < length; i++) {
10220
87.5M
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10221
87.5M
        int n_res, j;
10222
87.5M
        if (lower)
10223
87.5M
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10224
0
        else
10225
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10226
175M
        for (j = 0; j < n_res; j++) {
10227
87.6M
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10228
87.6M
            res[k++] = mapped[j];
10229
87.6M
        }
10230
87.5M
    }
10231
4.86M
    return k;
10232
4.86M
}
10233
10234
static Py_ssize_t
10235
do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10236
0
{
10237
0
    return do_upper_or_lower(kind, data, length, res, maxchar, 0);
10238
0
}
10239
10240
static Py_ssize_t
10241
do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10242
4.86M
{
10243
4.86M
    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
10244
4.86M
}
10245
10246
static Py_ssize_t
10247
do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10248
0
{
10249
0
    Py_ssize_t i, k = 0;
10250
10251
0
    for (i = 0; i < length; i++) {
10252
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i);
10253
0
        Py_UCS4 mapped[3];
10254
0
        int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
10255
0
        for (j = 0; j < n_res; j++) {
10256
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10257
0
            res[k++] = mapped[j];
10258
0
        }
10259
0
    }
10260
0
    return k;
10261
0
}
10262
10263
static Py_ssize_t
10264
do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10265
0
{
10266
0
    Py_ssize_t i, k = 0;
10267
0
    int previous_is_cased;
10268
10269
0
    previous_is_cased = 0;
10270
0
    for (i = 0; i < length; i++) {
10271
0
        const Py_UCS4 c = PyUnicode_READ(kind, data, i);
10272
0
        Py_UCS4 mapped[3];
10273
0
        int n_res, j;
10274
10275
0
        if (previous_is_cased)
10276
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10277
0
        else
10278
0
            n_res = _PyUnicode_ToTitleFull(c, mapped);
10279
10280
0
        for (j = 0; j < n_res; j++) {
10281
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10282
0
            res[k++] = mapped[j];
10283
0
        }
10284
10285
0
        previous_is_cased = _PyUnicode_IsCased(c);
10286
0
    }
10287
0
    return k;
10288
0
}
10289
10290
static PyObject *
10291
case_operation(PyObject *self,
10292
               Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
10293
4.86M
{
10294
4.86M
    PyObject *res = NULL;
10295
4.86M
    Py_ssize_t length, newlength = 0;
10296
4.86M
    int kind, outkind;
10297
4.86M
    const void *data;
10298
4.86M
    void *outdata;
10299
4.86M
    Py_UCS4 maxchar = 0, *tmp, *tmpend;
10300
10301
4.86M
    kind = PyUnicode_KIND(self);
10302
4.86M
    data = PyUnicode_DATA(self);
10303
4.86M
    length = PyUnicode_GET_LENGTH(self);
10304
4.86M
    if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
10305
0
        PyErr_SetString(PyExc_OverflowError, "string is too long");
10306
0
        return NULL;
10307
0
    }
10308
4.86M
    tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
10309
4.86M
    if (tmp == NULL)
10310
0
        return PyErr_NoMemory();
10311
4.86M
    newlength = perform(kind, data, length, tmp, &maxchar);
10312
4.86M
    res = PyUnicode_New(newlength, maxchar);
10313
4.86M
    if (res == NULL)
10314
0
        goto leave;
10315
4.86M
    tmpend = tmp + newlength;
10316
4.86M
    outdata = PyUnicode_DATA(res);
10317
4.86M
    outkind = PyUnicode_KIND(res);
10318
4.86M
    switch (outkind) {
10319
194k
    case PyUnicode_1BYTE_KIND:
10320
194k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10321
194k
        break;
10322
4.50M
    case PyUnicode_2BYTE_KIND:
10323
4.50M
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10324
4.50M
        break;
10325
161k
    case PyUnicode_4BYTE_KIND:
10326
161k
        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10327
161k
        break;
10328
0
    default:
10329
0
        Py_UNREACHABLE();
10330
4.86M
    }
10331
4.86M
  leave:
10332
4.86M
    PyMem_Free(tmp);
10333
4.86M
    return res;
10334
4.86M
}
10335
10336
PyObject *
10337
PyUnicode_Join(PyObject *separator, PyObject *seq)
10338
27.0M
{
10339
27.0M
    PyObject *res;
10340
27.0M
    PyObject *fseq;
10341
27.0M
    Py_ssize_t seqlen;
10342
27.0M
    PyObject **items;
10343
10344
27.0M
    fseq = PySequence_Fast(seq, "can only join an iterable");
10345
27.0M
    if (fseq == NULL) {
10346
685
        return NULL;
10347
685
    }
10348
10349
27.0M
    Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(seq);
10350
10351
27.0M
    items = PySequence_Fast_ITEMS(fseq);
10352
27.0M
    seqlen = PySequence_Fast_GET_SIZE(fseq);
10353
27.0M
    res = _PyUnicode_JoinArray(separator, items, seqlen);
10354
10355
27.0M
    Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
10356
10357
27.0M
    Py_DECREF(fseq);
10358
27.0M
    return res;
10359
27.0M
}
10360
10361
PyObject *
10362
_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
10363
39.6M
{
10364
39.6M
    PyObject *res = NULL; /* the result */
10365
39.6M
    PyObject *sep = NULL;
10366
39.6M
    Py_ssize_t seplen;
10367
39.6M
    PyObject *item;
10368
39.6M
    Py_ssize_t sz, i, res_offset;
10369
39.6M
    Py_UCS4 maxchar;
10370
39.6M
    Py_UCS4 item_maxchar;
10371
39.6M
    int use_memcpy;
10372
39.6M
    unsigned char *res_data = NULL, *sep_data = NULL;
10373
39.6M
    PyObject *last_obj;
10374
39.6M
    int kind = 0;
10375
10376
    /* If empty sequence, return u"". */
10377
39.6M
    if (seqlen == 0) {
10378
7.21M
        _Py_RETURN_UNICODE_EMPTY();
10379
7.21M
    }
10380
10381
    /* If singleton sequence with an exact Unicode, return that. */
10382
32.4M
    last_obj = NULL;
10383
32.4M
    if (seqlen == 1) {
10384
10.8M
        if (PyUnicode_CheckExact(items[0])) {
10385
9.37M
            res = items[0];
10386
9.37M
            return Py_NewRef(res);
10387
9.37M
        }
10388
1.50M
        seplen = 0;
10389
1.50M
        maxchar = 0;
10390
1.50M
    }
10391
21.5M
    else {
10392
        /* Set up sep and seplen */
10393
21.5M
        if (separator == NULL) {
10394
            /* fall back to a blank space separator */
10395
0
            sep = PyUnicode_FromOrdinal(' ');
10396
0
            if (!sep)
10397
0
                goto onError;
10398
0
            seplen = 1;
10399
0
            maxchar = 32;
10400
0
        }
10401
21.5M
        else {
10402
21.5M
            if (!PyUnicode_Check(separator)) {
10403
0
                PyErr_Format(PyExc_TypeError,
10404
0
                             "separator: expected str instance,"
10405
0
                             " %.80s found",
10406
0
                             Py_TYPE(separator)->tp_name);
10407
0
                goto onError;
10408
0
            }
10409
21.5M
            sep = separator;
10410
21.5M
            seplen = PyUnicode_GET_LENGTH(separator);
10411
21.5M
            maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10412
            /* inc refcount to keep this code path symmetric with the
10413
               above case of a blank separator */
10414
21.5M
            Py_INCREF(sep);
10415
21.5M
        }
10416
21.5M
        last_obj = sep;
10417
21.5M
    }
10418
10419
    /* There are at least two things to join, or else we have a subclass
10420
     * of str in the sequence.
10421
     * Do a pre-pass to figure out the total amount of space we'll
10422
     * need (sz), and see whether all argument are strings.
10423
     */
10424
23.0M
    sz = 0;
10425
#ifdef Py_DEBUG
10426
    use_memcpy = 0;
10427
#else
10428
23.0M
    use_memcpy = 1;
10429
23.0M
#endif
10430
231M
    for (i = 0; i < seqlen; i++) {
10431
208M
        size_t add_sz;
10432
208M
        item = items[i];
10433
208M
        if (!PyUnicode_Check(item)) {
10434
0
            PyErr_Format(PyExc_TypeError,
10435
0
                         "sequence item %zd: expected str instance,"
10436
0
                         " %.80s found",
10437
0
                         i, Py_TYPE(item)->tp_name);
10438
0
            goto onError;
10439
0
        }
10440
208M
        add_sz = PyUnicode_GET_LENGTH(item);
10441
208M
        item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
10442
208M
        maxchar = Py_MAX(maxchar, item_maxchar);
10443
208M
        if (i != 0) {
10444
185M
            add_sz += seplen;
10445
185M
        }
10446
208M
        if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
10447
0
            PyErr_SetString(PyExc_OverflowError,
10448
0
                            "join() result is too long for a Python string");
10449
0
            goto onError;
10450
0
        }
10451
208M
        sz += add_sz;
10452
208M
        if (use_memcpy && last_obj != NULL) {
10453
121M
            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10454
3.82M
                use_memcpy = 0;
10455
121M
        }
10456
208M
        last_obj = item;
10457
208M
    }
10458
10459
23.0M
    res = PyUnicode_New(sz, maxchar);
10460
23.0M
    if (res == NULL)
10461
0
        goto onError;
10462
10463
    /* Catenate everything. */
10464
#ifdef Py_DEBUG
10465
    use_memcpy = 0;
10466
#else
10467
23.0M
    if (use_memcpy) {
10468
19.2M
        res_data = PyUnicode_1BYTE_DATA(res);
10469
19.2M
        kind = PyUnicode_KIND(res);
10470
19.2M
        if (seplen != 0)
10471
213k
            sep_data = PyUnicode_1BYTE_DATA(sep);
10472
19.2M
    }
10473
23.0M
#endif
10474
23.0M
    if (use_memcpy) {
10475
119M
        for (i = 0; i < seqlen; ++i) {
10476
99.8M
            Py_ssize_t itemlen;
10477
99.8M
            item = items[i];
10478
10479
            /* Copy item, and maybe the separator. */
10480
99.8M
            if (i && seplen != 0) {
10481
317k
                memcpy(res_data,
10482
317k
                          sep_data,
10483
317k
                          kind * seplen);
10484
317k
                res_data += kind * seplen;
10485
317k
            }
10486
10487
99.8M
            itemlen = PyUnicode_GET_LENGTH(item);
10488
99.8M
            if (itemlen != 0) {
10489
89.5M
                memcpy(res_data,
10490
89.5M
                          PyUnicode_DATA(item),
10491
89.5M
                          kind * itemlen);
10492
89.5M
                res_data += kind * itemlen;
10493
89.5M
            }
10494
99.8M
        }
10495
19.2M
        assert(res_data == PyUnicode_1BYTE_DATA(res)
10496
19.2M
                           + kind * PyUnicode_GET_LENGTH(res));
10497
19.2M
    }
10498
3.82M
    else {
10499
112M
        for (i = 0, res_offset = 0; i < seqlen; ++i) {
10500
108M
            Py_ssize_t itemlen;
10501
108M
            item = items[i];
10502
10503
            /* Copy item, and maybe the separator. */
10504
108M
            if (i && seplen != 0) {
10505
1.24M
                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10506
1.24M
                res_offset += seplen;
10507
1.24M
            }
10508
10509
108M
            itemlen = PyUnicode_GET_LENGTH(item);
10510
108M
            if (itemlen != 0) {
10511
107M
                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
10512
107M
                res_offset += itemlen;
10513
107M
            }
10514
108M
        }
10515
3.82M
        assert(res_offset == PyUnicode_GET_LENGTH(res));
10516
3.82M
    }
10517
10518
23.0M
    Py_XDECREF(sep);
10519
23.0M
    assert(_PyUnicode_CheckConsistency(res, 1));
10520
23.0M
    return res;
10521
10522
0
  onError:
10523
0
    Py_XDECREF(sep);
10524
0
    Py_XDECREF(res);
10525
0
    return NULL;
10526
23.0M
}
10527
10528
void
10529
_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10530
                    Py_UCS4 fill_char)
10531
673
{
10532
673
    const int kind = PyUnicode_KIND(unicode);
10533
673
    void *data = PyUnicode_DATA(unicode);
10534
673
    assert(_PyUnicode_IsModifiable(unicode));
10535
673
    assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10536
673
    assert(start >= 0);
10537
673
    assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10538
673
    _PyUnicode_Fill(kind, data, fill_char, start, length);
10539
673
}
10540
10541
Py_ssize_t
10542
PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10543
               Py_UCS4 fill_char)
10544
673
{
10545
673
    Py_ssize_t maxlen;
10546
10547
673
    if (!PyUnicode_Check(unicode)) {
10548
0
        PyErr_BadInternalCall();
10549
0
        return -1;
10550
0
    }
10551
673
    if (unicode_check_modifiable(unicode))
10552
0
        return -1;
10553
10554
673
    if (start < 0) {
10555
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
10556
0
        return -1;
10557
0
    }
10558
673
    if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10559
0
        PyErr_SetString(PyExc_ValueError,
10560
0
                         "fill character is bigger than "
10561
0
                         "the string maximum character");
10562
0
        return -1;
10563
0
    }
10564
10565
673
    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10566
673
    length = Py_MIN(maxlen, length);
10567
673
    if (length <= 0)
10568
0
        return 0;
10569
10570
673
    _PyUnicode_FastFill(unicode, start, length, fill_char);
10571
673
    return length;
10572
673
}
10573
10574
static PyObject *
10575
pad(PyObject *self,
10576
    Py_ssize_t left,
10577
    Py_ssize_t right,
10578
    Py_UCS4 fill)
10579
0
{
10580
0
    PyObject *u;
10581
0
    Py_UCS4 maxchar;
10582
0
    int kind;
10583
0
    void *data;
10584
10585
0
    if (left < 0)
10586
0
        left = 0;
10587
0
    if (right < 0)
10588
0
        right = 0;
10589
10590
0
    if (left == 0 && right == 0)
10591
0
        return unicode_result_unchanged(self);
10592
10593
0
    if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10594
0
        right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
10595
0
        PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10596
0
        return NULL;
10597
0
    }
10598
0
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10599
0
    maxchar = Py_MAX(maxchar, fill);
10600
0
    u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
10601
0
    if (!u)
10602
0
        return NULL;
10603
10604
0
    kind = PyUnicode_KIND(u);
10605
0
    data = PyUnicode_DATA(u);
10606
0
    if (left)
10607
0
        _PyUnicode_Fill(kind, data, fill, 0, left);
10608
0
    if (right)
10609
0
        _PyUnicode_Fill(kind, data, fill,
10610
0
                        left + _PyUnicode_LENGTH(self), right);
10611
0
    _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
10612
0
    assert(_PyUnicode_CheckConsistency(u, 1));
10613
0
    return u;
10614
0
}
10615
10616
PyObject *
10617
PyUnicode_Splitlines(PyObject *string, int keepends)
10618
17.5k
{
10619
17.5k
    PyObject *list;
10620
10621
17.5k
    if (ensure_unicode(string) < 0)
10622
0
        return NULL;
10623
10624
17.5k
    switch (PyUnicode_KIND(string)) {
10625
5.23k
    case PyUnicode_1BYTE_KIND:
10626
5.23k
        if (PyUnicode_IS_ASCII(string))
10627
4.20k
            list = asciilib_splitlines(
10628
4.20k
                string, PyUnicode_1BYTE_DATA(string),
10629
4.20k
                PyUnicode_GET_LENGTH(string), keepends);
10630
1.03k
        else
10631
1.03k
            list = ucs1lib_splitlines(
10632
1.03k
                string, PyUnicode_1BYTE_DATA(string),
10633
1.03k
                PyUnicode_GET_LENGTH(string), keepends);
10634
5.23k
        break;
10635
8.85k
    case PyUnicode_2BYTE_KIND:
10636
8.85k
        list = ucs2lib_splitlines(
10637
8.85k
            string, PyUnicode_2BYTE_DATA(string),
10638
8.85k
            PyUnicode_GET_LENGTH(string), keepends);
10639
8.85k
        break;
10640
3.50k
    case PyUnicode_4BYTE_KIND:
10641
3.50k
        list = ucs4lib_splitlines(
10642
3.50k
            string, PyUnicode_4BYTE_DATA(string),
10643
3.50k
            PyUnicode_GET_LENGTH(string), keepends);
10644
3.50k
        break;
10645
0
    default:
10646
0
        Py_UNREACHABLE();
10647
17.5k
    }
10648
17.5k
    return list;
10649
17.5k
}
10650
10651
static PyObject *
10652
split(PyObject *self,
10653
      PyObject *substring,
10654
      Py_ssize_t maxcount)
10655
22.2M
{
10656
22.2M
    int kind1, kind2;
10657
22.2M
    const void *buf1, *buf2;
10658
22.2M
    Py_ssize_t len1, len2;
10659
22.2M
    PyObject* out;
10660
22.2M
    len1 = PyUnicode_GET_LENGTH(self);
10661
22.2M
    kind1 = PyUnicode_KIND(self);
10662
10663
22.2M
    if (substring == NULL) {
10664
201k
        if (maxcount < 0) {
10665
179k
            maxcount = (len1 - 1) / 2 + 1;
10666
179k
        }
10667
201k
        switch (kind1) {
10668
121k
        case PyUnicode_1BYTE_KIND:
10669
121k
            if (PyUnicode_IS_ASCII(self))
10670
91.6k
                return asciilib_split_whitespace(
10671
91.6k
                    self,  PyUnicode_1BYTE_DATA(self),
10672
91.6k
                    len1, maxcount
10673
91.6k
                    );
10674
29.9k
            else
10675
29.9k
                return ucs1lib_split_whitespace(
10676
29.9k
                    self,  PyUnicode_1BYTE_DATA(self),
10677
29.9k
                    len1, maxcount
10678
29.9k
                    );
10679
69.8k
        case PyUnicode_2BYTE_KIND:
10680
69.8k
            return ucs2lib_split_whitespace(
10681
69.8k
                self,  PyUnicode_2BYTE_DATA(self),
10682
69.8k
                len1, maxcount
10683
69.8k
                );
10684
10.0k
        case PyUnicode_4BYTE_KIND:
10685
10.0k
            return ucs4lib_split_whitespace(
10686
10.0k
                self,  PyUnicode_4BYTE_DATA(self),
10687
10.0k
                len1, maxcount
10688
10.0k
                );
10689
0
        default:
10690
0
            Py_UNREACHABLE();
10691
201k
        }
10692
201k
    }
10693
10694
22.0M
    kind2 = PyUnicode_KIND(substring);
10695
22.0M
    len2 = PyUnicode_GET_LENGTH(substring);
10696
22.0M
    if (maxcount < 0) {
10697
        // if len2 == 0, it will raise ValueError.
10698
15.7M
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10699
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10700
15.7M
        maxcount = maxcount < 0 ? len1 : maxcount;
10701
15.7M
    }
10702
22.0M
    if (kind1 < kind2 || len1 < len2) {
10703
1.93M
        out = PyList_New(1);
10704
1.93M
        if (out == NULL)
10705
0
            return NULL;
10706
1.93M
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10707
1.93M
        return out;
10708
1.93M
    }
10709
20.1M
    buf1 = PyUnicode_DATA(self);
10710
20.1M
    buf2 = PyUnicode_DATA(substring);
10711
20.1M
    if (kind2 != kind1) {
10712
274k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10713
274k
        if (!buf2)
10714
0
            return NULL;
10715
274k
    }
10716
10717
20.1M
    switch (kind1) {
10718
19.8M
    case PyUnicode_1BYTE_KIND:
10719
19.8M
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10720
18.6M
            out = asciilib_split(
10721
18.6M
                self,  buf1, len1, buf2, len2, maxcount);
10722
1.17M
        else
10723
1.17M
            out = ucs1lib_split(
10724
1.17M
                self,  buf1, len1, buf2, len2, maxcount);
10725
19.8M
        break;
10726
238k
    case PyUnicode_2BYTE_KIND:
10727
238k
        out = ucs2lib_split(
10728
238k
            self,  buf1, len1, buf2, len2, maxcount);
10729
238k
        break;
10730
35.8k
    case PyUnicode_4BYTE_KIND:
10731
35.8k
        out = ucs4lib_split(
10732
35.8k
            self,  buf1, len1, buf2, len2, maxcount);
10733
35.8k
        break;
10734
0
    default:
10735
0
        out = NULL;
10736
20.1M
    }
10737
20.1M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10738
20.1M
    if (kind2 != kind1)
10739
274k
        PyMem_Free((void *)buf2);
10740
20.1M
    return out;
10741
20.1M
}
10742
10743
static PyObject *
10744
rsplit(PyObject *self,
10745
       PyObject *substring,
10746
       Py_ssize_t maxcount)
10747
66
{
10748
66
    int kind1, kind2;
10749
66
    const void *buf1, *buf2;
10750
66
    Py_ssize_t len1, len2;
10751
66
    PyObject* out;
10752
10753
66
    len1 = PyUnicode_GET_LENGTH(self);
10754
66
    kind1 = PyUnicode_KIND(self);
10755
10756
66
    if (substring == NULL) {
10757
0
        if (maxcount < 0) {
10758
0
            maxcount = (len1 - 1) / 2 + 1;
10759
0
        }
10760
0
        switch (kind1) {
10761
0
        case PyUnicode_1BYTE_KIND:
10762
0
            if (PyUnicode_IS_ASCII(self))
10763
0
                return asciilib_rsplit_whitespace(
10764
0
                    self,  PyUnicode_1BYTE_DATA(self),
10765
0
                    len1, maxcount
10766
0
                    );
10767
0
            else
10768
0
                return ucs1lib_rsplit_whitespace(
10769
0
                    self,  PyUnicode_1BYTE_DATA(self),
10770
0
                    len1, maxcount
10771
0
                    );
10772
0
        case PyUnicode_2BYTE_KIND:
10773
0
            return ucs2lib_rsplit_whitespace(
10774
0
                self,  PyUnicode_2BYTE_DATA(self),
10775
0
                len1, maxcount
10776
0
                );
10777
0
        case PyUnicode_4BYTE_KIND:
10778
0
            return ucs4lib_rsplit_whitespace(
10779
0
                self,  PyUnicode_4BYTE_DATA(self),
10780
0
                len1, maxcount
10781
0
                );
10782
0
        default:
10783
0
            Py_UNREACHABLE();
10784
0
        }
10785
0
    }
10786
66
    kind2 = PyUnicode_KIND(substring);
10787
66
    len2 = PyUnicode_GET_LENGTH(substring);
10788
66
    if (maxcount < 0) {
10789
        // if len2 == 0, it will raise ValueError.
10790
0
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10791
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10792
0
        maxcount = maxcount < 0 ? len1 : maxcount;
10793
0
    }
10794
66
    if (kind1 < kind2 || len1 < len2) {
10795
0
        out = PyList_New(1);
10796
0
        if (out == NULL)
10797
0
            return NULL;
10798
0
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10799
0
        return out;
10800
0
    }
10801
66
    buf1 = PyUnicode_DATA(self);
10802
66
    buf2 = PyUnicode_DATA(substring);
10803
66
    if (kind2 != kind1) {
10804
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10805
0
        if (!buf2)
10806
0
            return NULL;
10807
0
    }
10808
10809
66
    switch (kind1) {
10810
66
    case PyUnicode_1BYTE_KIND:
10811
66
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10812
66
            out = asciilib_rsplit(
10813
66
                self,  buf1, len1, buf2, len2, maxcount);
10814
0
        else
10815
0
            out = ucs1lib_rsplit(
10816
0
                self,  buf1, len1, buf2, len2, maxcount);
10817
66
        break;
10818
0
    case PyUnicode_2BYTE_KIND:
10819
0
        out = ucs2lib_rsplit(
10820
0
            self,  buf1, len1, buf2, len2, maxcount);
10821
0
        break;
10822
0
    case PyUnicode_4BYTE_KIND:
10823
0
        out = ucs4lib_rsplit(
10824
0
            self,  buf1, len1, buf2, len2, maxcount);
10825
0
        break;
10826
0
    default:
10827
0
        out = NULL;
10828
66
    }
10829
66
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10830
66
    if (kind2 != kind1)
10831
0
        PyMem_Free((void *)buf2);
10832
66
    return out;
10833
66
}
10834
10835
static Py_ssize_t
10836
anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
10837
            PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
10838
21.4M
{
10839
21.4M
    switch (kind) {
10840
8.35M
    case PyUnicode_1BYTE_KIND:
10841
8.35M
        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10842
3.85M
            return asciilib_find(buf1, len1, buf2, len2, offset);
10843
4.50M
        else
10844
4.50M
            return ucs1lib_find(buf1, len1, buf2, len2, offset);
10845
5.50M
    case PyUnicode_2BYTE_KIND:
10846
5.50M
        return ucs2lib_find(buf1, len1, buf2, len2, offset);
10847
7.56M
    case PyUnicode_4BYTE_KIND:
10848
7.56M
        return ucs4lib_find(buf1, len1, buf2, len2, offset);
10849
21.4M
    }
10850
21.4M
    Py_UNREACHABLE();
10851
21.4M
}
10852
10853
static Py_ssize_t
10854
anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
10855
             PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
10856
11.1M
{
10857
11.1M
    switch (kind) {
10858
10.4M
    case PyUnicode_1BYTE_KIND:
10859
10.4M
        return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10860
691k
    case PyUnicode_2BYTE_KIND:
10861
691k
        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10862
82.2k
    case PyUnicode_4BYTE_KIND:
10863
82.2k
        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10864
11.1M
    }
10865
11.1M
    Py_UNREACHABLE();
10866
11.1M
}
10867
10868
static void
10869
replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10870
                      Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10871
63.9k
{
10872
63.9k
    int kind = PyUnicode_KIND(u);
10873
63.9k
    void *data = PyUnicode_DATA(u);
10874
63.9k
    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10875
63.9k
    if (kind == PyUnicode_1BYTE_KIND) {
10876
38.8k
        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10877
38.8k
                                      (Py_UCS1 *)data + len,
10878
38.8k
                                      u1, u2, maxcount);
10879
38.8k
    }
10880
25.0k
    else if (kind == PyUnicode_2BYTE_KIND) {
10881
19.9k
        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10882
19.9k
                                      (Py_UCS2 *)data + len,
10883
19.9k
                                      u1, u2, maxcount);
10884
19.9k
    }
10885
5.15k
    else {
10886
5.15k
        assert(kind == PyUnicode_4BYTE_KIND);
10887
5.15k
        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10888
5.15k
                                      (Py_UCS4 *)data + len,
10889
5.15k
                                      u1, u2, maxcount);
10890
5.15k
    }
10891
63.9k
}
10892
10893
static PyObject *
10894
replace(PyObject *self, PyObject *str1,
10895
        PyObject *str2, Py_ssize_t maxcount)
10896
20.2M
{
10897
20.2M
    PyObject *u;
10898
20.2M
    const char *sbuf = PyUnicode_DATA(self);
10899
20.2M
    const void *buf1 = PyUnicode_DATA(str1);
10900
20.2M
    const void *buf2 = PyUnicode_DATA(str2);
10901
20.2M
    int srelease = 0, release1 = 0, release2 = 0;
10902
20.2M
    int skind = PyUnicode_KIND(self);
10903
20.2M
    int kind1 = PyUnicode_KIND(str1);
10904
20.2M
    int kind2 = PyUnicode_KIND(str2);
10905
20.2M
    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10906
20.2M
    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10907
20.2M
    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
10908
20.2M
    int mayshrink;
10909
20.2M
    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
10910
10911
20.2M
    if (slen < len1)
10912
8.59M
        goto nothing;
10913
10914
11.6M
    if (maxcount < 0)
10915
11.6M
        maxcount = PY_SSIZE_T_MAX;
10916
0
    else if (maxcount == 0)
10917
0
        goto nothing;
10918
10919
11.6M
    if (str1 == str2)
10920
0
        goto nothing;
10921
10922
11.6M
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10923
11.6M
    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10924
11.6M
    if (maxchar < maxchar_str1)
10925
        /* substring too wide to be present */
10926
0
        goto nothing;
10927
11.6M
    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10928
    /* Replacing str1 with str2 may cause a maxchar reduction in the
10929
       result string. */
10930
11.6M
    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
10931
11.6M
    maxchar = Py_MAX(maxchar, maxchar_str2);
10932
10933
11.6M
    if (len1 == len2) {
10934
        /* same length */
10935
505k
        if (len1 == 0)
10936
0
            goto nothing;
10937
505k
        if (len1 == 1) {
10938
            /* replace characters */
10939
497k
            Py_UCS4 u1, u2;
10940
497k
            Py_ssize_t pos;
10941
10942
497k
            u1 = PyUnicode_READ(kind1, buf1, 0);
10943
497k
            pos = findchar(sbuf, skind, slen, u1, 1);
10944
497k
            if (pos < 0)
10945
434k
                goto nothing;
10946
63.9k
            u2 = PyUnicode_READ(kind2, buf2, 0);
10947
63.9k
            u = PyUnicode_New(slen, maxchar);
10948
63.9k
            if (!u)
10949
0
                goto error;
10950
10951
63.9k
            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10952
63.9k
            replace_1char_inplace(u, pos, u1, u2, maxcount);
10953
63.9k
        }
10954
7.08k
        else {
10955
7.08k
            int rkind = skind;
10956
7.08k
            char *res;
10957
7.08k
            Py_ssize_t i;
10958
10959
7.08k
            if (kind1 < rkind) {
10960
                /* widen substring */
10961
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
10962
0
                if (!buf1) goto error;
10963
0
                release1 = 1;
10964
0
            }
10965
7.08k
            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
10966
7.08k
            if (i < 0)
10967
7.08k
                goto nothing;
10968
0
            if (rkind > kind2) {
10969
                /* widen replacement */
10970
0
                buf2 = unicode_askind(kind2, buf2, len2, rkind);
10971
0
                if (!buf2) goto error;
10972
0
                release2 = 1;
10973
0
            }
10974
0
            else if (rkind < kind2) {
10975
                /* widen self and buf1 */
10976
0
                rkind = kind2;
10977
0
                if (release1) {
10978
0
                    assert(buf1 != PyUnicode_DATA(str1));
10979
0
                    PyMem_Free((void *)buf1);
10980
0
                    buf1 = PyUnicode_DATA(str1);
10981
0
                    release1 = 0;
10982
0
                }
10983
0
                sbuf = unicode_askind(skind, sbuf, slen, rkind);
10984
0
                if (!sbuf) goto error;
10985
0
                srelease = 1;
10986
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
10987
0
                if (!buf1) goto error;
10988
0
                release1 = 1;
10989
0
            }
10990
0
            u = PyUnicode_New(slen, maxchar);
10991
0
            if (!u)
10992
0
                goto error;
10993
0
            assert(PyUnicode_KIND(u) == rkind);
10994
0
            res = PyUnicode_DATA(u);
10995
10996
0
            memcpy(res, sbuf, rkind * slen);
10997
            /* change everything in-place, starting with this one */
10998
0
            memcpy(res + rkind * i,
10999
0
                   buf2,
11000
0
                   rkind * len2);
11001
0
            i += len1;
11002
11003
0
            while ( --maxcount > 0) {
11004
0
                i = anylib_find(rkind, self,
11005
0
                                sbuf+rkind*i, slen-i,
11006
0
                                str1, buf1, len1, i);
11007
0
                if (i == -1)
11008
0
                    break;
11009
0
                memcpy(res + rkind * i,
11010
0
                       buf2,
11011
0
                       rkind * len2);
11012
0
                i += len1;
11013
0
            }
11014
0
        }
11015
505k
    }
11016
11.1M
    else {
11017
11.1M
        Py_ssize_t n, i, j, ires;
11018
11.1M
        Py_ssize_t new_size;
11019
11.1M
        int rkind = skind;
11020
11.1M
        char *res;
11021
11022
11.1M
        if (kind1 < rkind) {
11023
            /* widen substring */
11024
774k
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11025
774k
            if (!buf1) goto error;
11026
774k
            release1 = 1;
11027
774k
        }
11028
11.1M
        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
11029
11.1M
        if (n == 0)
11030
9.89M
            goto nothing;
11031
1.29M
        if (kind2 < rkind) {
11032
            /* widen replacement */
11033
45.8k
            buf2 = unicode_askind(kind2, buf2, len2, rkind);
11034
45.8k
            if (!buf2) goto error;
11035
45.8k
            release2 = 1;
11036
45.8k
        }
11037
1.25M
        else if (kind2 > rkind) {
11038
            /* widen self and buf1 */
11039
0
            rkind = kind2;
11040
0
            sbuf = unicode_askind(skind, sbuf, slen, rkind);
11041
0
            if (!sbuf) goto error;
11042
0
            srelease = 1;
11043
0
            if (release1) {
11044
0
                assert(buf1 != PyUnicode_DATA(str1));
11045
0
                PyMem_Free((void *)buf1);
11046
0
                buf1 = PyUnicode_DATA(str1);
11047
0
                release1 = 0;
11048
0
            }
11049
0
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11050
0
            if (!buf1) goto error;
11051
0
            release1 = 1;
11052
0
        }
11053
        /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
11054
           PyUnicode_GET_LENGTH(str1)); */
11055
1.29M
        if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
11056
0
                PyErr_SetString(PyExc_OverflowError,
11057
0
                                "replace string is too long");
11058
0
                goto error;
11059
0
        }
11060
1.29M
        new_size = slen + n * (len2 - len1);
11061
1.29M
        if (new_size == 0) {
11062
0
            u = _PyUnicode_GetEmpty();
11063
0
            goto done;
11064
0
        }
11065
1.29M
        if (new_size > (PY_SSIZE_T_MAX / rkind)) {
11066
0
            PyErr_SetString(PyExc_OverflowError,
11067
0
                            "replace string is too long");
11068
0
            goto error;
11069
0
        }
11070
1.29M
        u = PyUnicode_New(new_size, maxchar);
11071
1.29M
        if (!u)
11072
0
            goto error;
11073
1.29M
        assert(PyUnicode_KIND(u) == rkind);
11074
1.29M
        res = PyUnicode_DATA(u);
11075
1.29M
        ires = i = 0;
11076
1.29M
        if (len1 > 0) {
11077
22.7M
            while (n-- > 0) {
11078
                /* look for next match */
11079
21.4M
                j = anylib_find(rkind, self,
11080
21.4M
                                sbuf + rkind * i, slen-i,
11081
21.4M
                                str1, buf1, len1, i);
11082
21.4M
                if (j == -1)
11083
0
                    break;
11084
21.4M
                else if (j > i) {
11085
                    /* copy unchanged part [i:j] */
11086
4.33M
                    memcpy(res + rkind * ires,
11087
4.33M
                           sbuf + rkind * i,
11088
4.33M
                           rkind * (j-i));
11089
4.33M
                    ires += j - i;
11090
4.33M
                }
11091
                /* copy substitution string */
11092
21.4M
                if (len2 > 0) {
11093
21.4M
                    memcpy(res + rkind * ires,
11094
21.4M
                           buf2,
11095
21.4M
                           rkind * len2);
11096
21.4M
                    ires += len2;
11097
21.4M
                }
11098
21.4M
                i = j + len1;
11099
21.4M
            }
11100
1.29M
            if (i < slen)
11101
                /* copy tail [i:] */
11102
1.29M
                memcpy(res + rkind * ires,
11103
1.29M
                       sbuf + rkind * i,
11104
1.29M
                       rkind * (slen-i));
11105
1.29M
        }
11106
0
        else {
11107
            /* interleave */
11108
0
            while (n > 0) {
11109
0
                memcpy(res + rkind * ires,
11110
0
                       buf2,
11111
0
                       rkind * len2);
11112
0
                ires += len2;
11113
0
                if (--n <= 0)
11114
0
                    break;
11115
0
                memcpy(res + rkind * ires,
11116
0
                       sbuf + rkind * i,
11117
0
                       rkind);
11118
0
                ires++;
11119
0
                i++;
11120
0
            }
11121
0
            memcpy(res + rkind * ires,
11122
0
                   sbuf + rkind * i,
11123
0
                   rkind * (slen-i));
11124
0
        }
11125
1.29M
    }
11126
11127
1.36M
    if (mayshrink) {
11128
0
        unicode_adjust_maxchar(&u);
11129
0
        if (u == NULL)
11130
0
            goto error;
11131
0
    }
11132
11133
1.36M
  done:
11134
1.36M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11135
1.36M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11136
1.36M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11137
1.36M
    if (srelease)
11138
0
        PyMem_Free((void *)sbuf);
11139
1.36M
    if (release1)
11140
45.8k
        PyMem_Free((void *)buf1);
11141
1.36M
    if (release2)
11142
45.8k
        PyMem_Free((void *)buf2);
11143
1.36M
    assert(_PyUnicode_CheckConsistency(u, 1));
11144
1.36M
    return u;
11145
11146
18.9M
  nothing:
11147
    /* nothing to replace; return original string (when possible) */
11148
18.9M
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11149
18.9M
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11150
18.9M
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11151
18.9M
    if (srelease)
11152
0
        PyMem_Free((void *)sbuf);
11153
18.9M
    if (release1)
11154
728k
        PyMem_Free((void *)buf1);
11155
18.9M
    if (release2)
11156
0
        PyMem_Free((void *)buf2);
11157
18.9M
    return unicode_result_unchanged(self);
11158
11159
0
  error:
11160
0
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11161
0
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11162
0
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11163
0
    if (srelease)
11164
0
        PyMem_Free((void *)sbuf);
11165
0
    if (release1)
11166
0
        PyMem_Free((void *)buf1);
11167
0
    if (release2)
11168
0
        PyMem_Free((void *)buf2);
11169
0
    return NULL;
11170
1.36M
}
11171
11172
/* --- Unicode Object Methods --------------------------------------------- */
11173
11174
/*[clinic input]
11175
str.title as unicode_title
11176
11177
Return a version of the string where each word is titlecased.
11178
11179
More specifically, words start with uppercased characters and all
11180
remaining cased characters have lower case.
11181
[clinic start generated code]*/
11182
11183
static PyObject *
11184
unicode_title_impl(PyObject *self)
11185
/*[clinic end generated code: output=c75ae03809574902 input=2a07e2c7df94627a]*/
11186
0
{
11187
0
    return case_operation(self, do_title);
11188
0
}
11189
11190
/*[clinic input]
11191
str.capitalize as unicode_capitalize
11192
11193
Return a capitalized version of the string.
11194
11195
More specifically, make the first character have upper case and the
11196
rest lower case.
11197
[clinic start generated code]*/
11198
11199
static PyObject *
11200
unicode_capitalize_impl(PyObject *self)
11201
/*[clinic end generated code: output=e49a4c333cdb7667 input=e50e50ed45a654cf]*/
11202
0
{
11203
0
    if (PyUnicode_GET_LENGTH(self) == 0)
11204
0
        return unicode_result_unchanged(self);
11205
0
    return case_operation(self, do_capitalize);
11206
0
}
11207
11208
/*[clinic input]
11209
str.casefold as unicode_casefold
11210
11211
Return a version of the string suitable for caseless comparisons.
11212
[clinic start generated code]*/
11213
11214
static PyObject *
11215
unicode_casefold_impl(PyObject *self)
11216
/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
11217
0
{
11218
0
    if (PyUnicode_IS_ASCII(self))
11219
0
        return ascii_upper_or_lower(self, 1);
11220
0
    return case_operation(self, do_casefold);
11221
0
}
11222
11223
11224
/* Argument converter. Accepts a single Unicode character. */
11225
11226
static int
11227
convert_uc(PyObject *obj, void *addr)
11228
0
{
11229
0
    Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
11230
11231
0
    if (!PyUnicode_Check(obj)) {
11232
0
        PyErr_Format(PyExc_TypeError,
11233
0
                     "The fill character must be a unicode character, "
11234
0
                     "not %.100s", Py_TYPE(obj)->tp_name);
11235
0
        return 0;
11236
0
    }
11237
0
    if (PyUnicode_GET_LENGTH(obj) != 1) {
11238
0
        PyErr_SetString(PyExc_TypeError,
11239
0
                        "The fill character must be exactly one character long");
11240
0
        return 0;
11241
0
    }
11242
0
    *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
11243
0
    return 1;
11244
0
}
11245
11246
/*[clinic input]
11247
str.center as unicode_center
11248
11249
    width: Py_ssize_t
11250
    fillchar: Py_UCS4 = ' '
11251
    /
11252
11253
Return a centered string of length width.
11254
11255
Padding is done using the specified fill character (default is
11256
a space).
11257
[clinic start generated code]*/
11258
11259
static PyObject *
11260
unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
11261
/*[clinic end generated code: output=420c8859effc7c0c input=df91017dfd186a78]*/
11262
0
{
11263
0
    Py_ssize_t marg, left;
11264
11265
0
    if (PyUnicode_GET_LENGTH(self) >= width)
11266
0
        return unicode_result_unchanged(self);
11267
11268
0
    marg = width - PyUnicode_GET_LENGTH(self);
11269
0
    left = marg / 2 + (marg & width & 1);
11270
11271
0
    return pad(self, left, marg - left, fillchar);
11272
0
}
11273
11274
/* This function assumes that str1 and str2 are readied by the caller. */
11275
11276
static int
11277
unicode_compare(PyObject *str1, PyObject *str2)
11278
32.1M
{
11279
32.1M
#define COMPARE(TYPE1, TYPE2) \
11280
32.1M
    do { \
11281
29.8M
        TYPE1* p1 = (TYPE1 *)data1; \
11282
29.8M
        TYPE2* p2 = (TYPE2 *)data2; \
11283
29.8M
        TYPE1* end = p1 + len; \
11284
29.8M
        Py_UCS4 c1, c2; \
11285
29.8M
        for (; p1 != end; p1++, p2++) { \
11286
29.8M
            c1 = *p1; \
11287
29.8M
            c2 = *p2; \
11288
29.8M
            if (c1 != c2) \
11289
29.8M
                return (c1 < c2) ? -1 : 1; \
11290
29.8M
        } \
11291
29.8M
    } \
11292
29.8M
    while (0)
11293
11294
32.1M
    int kind1, kind2;
11295
32.1M
    const void *data1, *data2;
11296
32.1M
    Py_ssize_t len1, len2, len;
11297
11298
32.1M
    kind1 = PyUnicode_KIND(str1);
11299
32.1M
    kind2 = PyUnicode_KIND(str2);
11300
32.1M
    data1 = PyUnicode_DATA(str1);
11301
32.1M
    data2 = PyUnicode_DATA(str2);
11302
32.1M
    len1 = PyUnicode_GET_LENGTH(str1);
11303
32.1M
    len2 = PyUnicode_GET_LENGTH(str2);
11304
32.1M
    len = Py_MIN(len1, len2);
11305
11306
32.1M
    switch(kind1) {
11307
4.36M
    case PyUnicode_1BYTE_KIND:
11308
4.36M
    {
11309
4.36M
        switch(kind2) {
11310
257k
        case PyUnicode_1BYTE_KIND:
11311
257k
        {
11312
257k
            int cmp = memcmp(data1, data2, len);
11313
            /* normalize result of memcmp() into the range [-1; 1] */
11314
257k
            if (cmp < 0)
11315
195k
                return -1;
11316
62.3k
            if (cmp > 0)
11317
56.4k
                return 1;
11318
5.92k
            break;
11319
62.3k
        }
11320
3.61M
        case PyUnicode_2BYTE_KIND:
11321
3.61M
            COMPARE(Py_UCS1, Py_UCS2);
11322
0
            break;
11323
496k
        case PyUnicode_4BYTE_KIND:
11324
496k
            COMPARE(Py_UCS1, Py_UCS4);
11325
0
            break;
11326
0
        default:
11327
0
            Py_UNREACHABLE();
11328
4.36M
        }
11329
5.92k
        break;
11330
4.36M
    }
11331
25.3M
    case PyUnicode_2BYTE_KIND:
11332
25.3M
    {
11333
25.3M
        switch(kind2) {
11334
81.7k
        case PyUnicode_1BYTE_KIND:
11335
81.7k
            COMPARE(Py_UCS2, Py_UCS1);
11336
0
            break;
11337
24.6M
        case PyUnicode_2BYTE_KIND:
11338
24.6M
        {
11339
24.6M
            COMPARE(Py_UCS2, Py_UCS2);
11340
0
            break;
11341
24.6M
        }
11342
589k
        case PyUnicode_4BYTE_KIND:
11343
589k
            COMPARE(Py_UCS2, Py_UCS4);
11344
0
            break;
11345
0
        default:
11346
0
            Py_UNREACHABLE();
11347
25.3M
        }
11348
0
        break;
11349
25.3M
    }
11350
2.48M
    case PyUnicode_4BYTE_KIND:
11351
2.48M
    {
11352
2.48M
        switch(kind2) {
11353
9.03k
        case PyUnicode_1BYTE_KIND:
11354
9.03k
            COMPARE(Py_UCS4, Py_UCS1);
11355
0
            break;
11356
363k
        case PyUnicode_2BYTE_KIND:
11357
363k
            COMPARE(Py_UCS4, Py_UCS2);
11358
0
            break;
11359
2.11M
        case PyUnicode_4BYTE_KIND:
11360
2.11M
        {
11361
2.11M
#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11362
2.11M
            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11363
            /* normalize result of wmemcmp() into the range [-1; 1] */
11364
2.11M
            if (cmp < 0)
11365
1.04M
                return -1;
11366
1.06M
            if (cmp > 0)
11367
1.06M
                return 1;
11368
#else
11369
            COMPARE(Py_UCS4, Py_UCS4);
11370
#endif
11371
0
            break;
11372
1.06M
        }
11373
0
        default:
11374
0
            Py_UNREACHABLE();
11375
2.48M
        }
11376
0
        break;
11377
2.48M
    }
11378
0
    default:
11379
0
        Py_UNREACHABLE();
11380
32.1M
    }
11381
11382
5.92k
    if (len1 == len2)
11383
5.88k
        return 0;
11384
37
    if (len1 < len2)
11385
11
        return -1;
11386
26
    else
11387
26
        return 1;
11388
11389
37
#undef COMPARE
11390
37
}
11391
11392
11393
int
11394
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
11395
600M
{
11396
600M
    assert(PyUnicode_Check(str1));
11397
600M
    assert(PyUnicode_Check(str2));
11398
600M
    if (str1 == str2) {
11399
76.6M
        return 1;
11400
76.6M
    }
11401
523M
    return unicode_eq(str1, str2);
11402
600M
}
11403
11404
11405
int
11406
PyUnicode_Equal(PyObject *str1, PyObject *str2)
11407
0
{
11408
0
    if (!PyUnicode_Check(str1)) {
11409
0
        PyErr_Format(PyExc_TypeError,
11410
0
                     "first argument must be str, not %T", str1);
11411
0
        return -1;
11412
0
    }
11413
0
    if (!PyUnicode_Check(str2)) {
11414
0
        PyErr_Format(PyExc_TypeError,
11415
0
                     "second argument must be str, not %T", str2);
11416
0
        return -1;
11417
0
    }
11418
11419
0
    return _PyUnicode_Equal(str1, str2);
11420
0
}
11421
11422
11423
int
11424
PyUnicode_Compare(PyObject *left, PyObject *right)
11425
89.0k
{
11426
89.0k
    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11427
        /* a string is equal to itself */
11428
89.0k
        if (left == right)
11429
0
            return 0;
11430
11431
89.0k
        return unicode_compare(left, right);
11432
89.0k
    }
11433
0
    PyErr_Format(PyExc_TypeError,
11434
0
                 "Can't compare %.100s and %.100s",
11435
0
                 Py_TYPE(left)->tp_name,
11436
0
                 Py_TYPE(right)->tp_name);
11437
0
    return -1;
11438
89.0k
}
11439
11440
int
11441
PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11442
10.7M
{
11443
10.7M
    Py_ssize_t i;
11444
10.7M
    int kind;
11445
10.7M
    Py_UCS4 chr;
11446
11447
10.7M
    assert(_PyUnicode_CHECK(uni));
11448
10.7M
    kind = PyUnicode_KIND(uni);
11449
10.7M
    if (kind == PyUnicode_1BYTE_KIND) {
11450
10.7M
        const void *data = PyUnicode_1BYTE_DATA(uni);
11451
10.7M
        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
11452
10.7M
        size_t len, len2 = strlen(str);
11453
10.7M
        int cmp;
11454
11455
10.7M
        len = Py_MIN(len1, len2);
11456
10.7M
        cmp = memcmp(data, str, len);
11457
10.7M
        if (cmp != 0) {
11458
6.62M
            if (cmp < 0)
11459
51.3k
                return -1;
11460
6.57M
            else
11461
6.57M
                return 1;
11462
6.62M
        }
11463
4.16M
        if (len1 > len2)
11464
201
            return 1; /* uni is longer */
11465
4.16M
        if (len1 < len2)
11466
1.01k
            return -1; /* str is longer */
11467
4.16M
        return 0;
11468
4.16M
    }
11469
2.44k
    else {
11470
2.44k
        const void *data = PyUnicode_DATA(uni);
11471
        /* Compare Unicode string and source character set string */
11472
4.32k
        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
11473
4.04k
            if (chr != (unsigned char)str[i])
11474
2.16k
                return (chr < (unsigned char)(str[i])) ? -1 : 1;
11475
        /* This check keeps Python strings that end in '\0' from comparing equal
11476
         to C strings identical up to that point. */
11477
277
        if (PyUnicode_GET_LENGTH(uni) != i || chr)
11478
277
            return 1; /* uni is longer */
11479
0
        if (str[i])
11480
0
            return -1; /* str is longer */
11481
0
        return 0;
11482
0
    }
11483
10.7M
}
11484
11485
int
11486
PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
11487
24
{
11488
24
    return PyUnicode_EqualToUTF8AndSize(unicode, str, strlen(str));
11489
24
}
11490
11491
int
11492
PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t size)
11493
24
{
11494
24
    assert(_PyUnicode_CHECK(unicode));
11495
24
    assert(str);
11496
11497
24
    if (PyUnicode_IS_ASCII(unicode)) {
11498
24
        Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11499
24
        return size == len &&
11500
0
            memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11501
24
    }
11502
0
    if (PyUnicode_UTF8(unicode) != NULL) {
11503
0
        Py_ssize_t len = PyUnicode_UTF8_LENGTH(unicode);
11504
0
        return size == len &&
11505
0
            memcmp(PyUnicode_UTF8(unicode), str, len) == 0;
11506
0
    }
11507
11508
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11509
0
    if ((size_t)len >= (size_t)size || (size_t)len < (size_t)size / 4) {
11510
0
        return 0;
11511
0
    }
11512
0
    const unsigned char *s = (const unsigned char *)str;
11513
0
    const unsigned char *ends = s + (size_t)size;
11514
0
    int kind = PyUnicode_KIND(unicode);
11515
0
    const void *data = PyUnicode_DATA(unicode);
11516
    /* Compare Unicode string and UTF-8 string */
11517
0
    for (Py_ssize_t i = 0; i < len; i++) {
11518
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11519
0
        if (ch < 0x80) {
11520
0
            if (ends == s || s[0] != ch) {
11521
0
                return 0;
11522
0
            }
11523
0
            s += 1;
11524
0
        }
11525
0
        else if (ch < 0x800) {
11526
0
            if ((ends - s) < 2 ||
11527
0
                s[0] != (0xc0 | (ch >> 6)) ||
11528
0
                s[1] != (0x80 | (ch & 0x3f)))
11529
0
            {
11530
0
                return 0;
11531
0
            }
11532
0
            s += 2;
11533
0
        }
11534
0
        else if (ch < 0x10000) {
11535
0
            if (Py_UNICODE_IS_SURROGATE(ch) ||
11536
0
                (ends - s) < 3 ||
11537
0
                s[0] != (0xe0 | (ch >> 12)) ||
11538
0
                s[1] != (0x80 | ((ch >> 6) & 0x3f)) ||
11539
0
                s[2] != (0x80 | (ch & 0x3f)))
11540
0
            {
11541
0
                return 0;
11542
0
            }
11543
0
            s += 3;
11544
0
        }
11545
0
        else {
11546
0
            assert(ch <= MAX_UNICODE);
11547
0
            if ((ends - s) < 4 ||
11548
0
                s[0] != (0xf0 | (ch >> 18)) ||
11549
0
                s[1] != (0x80 | ((ch >> 12) & 0x3f)) ||
11550
0
                s[2] != (0x80 | ((ch >> 6) & 0x3f)) ||
11551
0
                s[3] != (0x80 | (ch & 0x3f)))
11552
0
            {
11553
0
                return 0;
11554
0
            }
11555
0
            s += 4;
11556
0
        }
11557
0
    }
11558
0
    return s == ends;
11559
0
}
11560
11561
int
11562
_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11563
37.6M
{
11564
37.6M
    size_t len;
11565
37.6M
    assert(_PyUnicode_CHECK(unicode));
11566
37.6M
    assert(str);
11567
#ifndef NDEBUG
11568
    for (const char *p = str; *p; p++) {
11569
        assert((unsigned char)*p < 128);
11570
    }
11571
#endif
11572
37.6M
    if (!PyUnicode_IS_ASCII(unicode))
11573
185k
        return 0;
11574
37.4M
    len = (size_t)PyUnicode_GET_LENGTH(unicode);
11575
37.4M
    return strlen(str) == len &&
11576
479k
           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11577
37.6M
}
11578
11579
PyObject *
11580
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
11581
66.5M
{
11582
66.5M
    int result;
11583
11584
66.5M
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11585
180k
        Py_RETURN_NOTIMPLEMENTED;
11586
11587
66.3M
    if (left == right) {
11588
4.91k
        switch (op) {
11589
4.70k
        case Py_EQ:
11590
4.70k
        case Py_LE:
11591
4.70k
        case Py_GE:
11592
            /* a string is equal to itself */
11593
4.70k
            Py_RETURN_TRUE;
11594
211
        case Py_NE:
11595
211
        case Py_LT:
11596
211
        case Py_GT:
11597
211
            Py_RETURN_FALSE;
11598
0
        default:
11599
0
            PyErr_BadArgument();
11600
0
            return NULL;
11601
4.91k
        }
11602
4.91k
    }
11603
66.3M
    else if (op == Py_EQ || op == Py_NE) {
11604
34.2M
        result = unicode_eq(left, right);
11605
34.2M
        result ^= (op == Py_NE);
11606
34.2M
        return PyBool_FromLong(result);
11607
34.2M
    }
11608
32.0M
    else {
11609
32.0M
        result = unicode_compare(left, right);
11610
32.0M
        Py_RETURN_RICHCOMPARE(result, 0, op);
11611
32.0M
    }
11612
66.3M
}
11613
11614
int
11615
PyUnicode_Contains(PyObject *str, PyObject *substr)
11616
229M
{
11617
229M
    int kind1, kind2;
11618
229M
    const void *buf1, *buf2;
11619
229M
    Py_ssize_t len1, len2;
11620
229M
    int result;
11621
11622
229M
    if (!PyUnicode_Check(substr)) {
11623
0
        PyErr_Format(PyExc_TypeError,
11624
0
                     "'in <string>' requires string as left operand, not %.100s",
11625
0
                     Py_TYPE(substr)->tp_name);
11626
0
        return -1;
11627
0
    }
11628
229M
    if (ensure_unicode(str) < 0)
11629
0
        return -1;
11630
11631
229M
    kind1 = PyUnicode_KIND(str);
11632
229M
    kind2 = PyUnicode_KIND(substr);
11633
229M
    if (kind1 < kind2)
11634
13.6M
        return 0;
11635
215M
    len1 = PyUnicode_GET_LENGTH(str);
11636
215M
    len2 = PyUnicode_GET_LENGTH(substr);
11637
215M
    if (len1 < len2)
11638
188k
        return 0;
11639
215M
    buf1 = PyUnicode_DATA(str);
11640
215M
    buf2 = PyUnicode_DATA(substr);
11641
215M
    if (len2 == 1) {
11642
200M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11643
200M
        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11644
200M
        return result;
11645
200M
    }
11646
14.7M
    if (kind2 != kind1) {
11647
21.1k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11648
21.1k
        if (!buf2)
11649
0
            return -1;
11650
21.1k
    }
11651
11652
14.7M
    switch (kind1) {
11653
14.6M
    case PyUnicode_1BYTE_KIND:
11654
14.6M
        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11655
14.6M
        break;
11656
14.5k
    case PyUnicode_2BYTE_KIND:
11657
14.5k
        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11658
14.5k
        break;
11659
6.59k
    case PyUnicode_4BYTE_KIND:
11660
6.59k
        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11661
6.59k
        break;
11662
0
    default:
11663
0
        Py_UNREACHABLE();
11664
14.7M
    }
11665
11666
14.7M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
11667
14.7M
    if (kind2 != kind1)
11668
21.1k
        PyMem_Free((void *)buf2);
11669
11670
14.7M
    return result;
11671
14.7M
}
11672
11673
/* Concat to string or Unicode object giving a new Unicode object. */
11674
11675
PyObject *
11676
PyUnicode_Concat(PyObject *left, PyObject *right)
11677
26.0M
{
11678
26.0M
    PyObject *result;
11679
26.0M
    Py_UCS4 maxchar, maxchar2;
11680
26.0M
    Py_ssize_t left_len, right_len, new_len;
11681
11682
26.0M
    if (ensure_unicode(left) < 0)
11683
0
        return NULL;
11684
11685
26.0M
    if (!PyUnicode_Check(right)) {
11686
0
        PyErr_Format(PyExc_TypeError,
11687
0
            "can only concatenate str (not \"%.200s\") to str",
11688
0
            Py_TYPE(right)->tp_name);
11689
0
        return NULL;
11690
0
    }
11691
11692
    /* Shortcuts */
11693
26.0M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11694
26.0M
    if (left == empty) {
11695
431k
        return PyUnicode_FromObject(right);
11696
431k
    }
11697
25.6M
    if (right == empty) {
11698
1.60M
        return PyUnicode_FromObject(left);
11699
1.60M
    }
11700
11701
24.0M
    left_len = PyUnicode_GET_LENGTH(left);
11702
24.0M
    right_len = PyUnicode_GET_LENGTH(right);
11703
24.0M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11704
0
        PyErr_SetString(PyExc_OverflowError,
11705
0
                        "strings are too large to concat");
11706
0
        return NULL;
11707
0
    }
11708
24.0M
    new_len = left_len + right_len;
11709
11710
24.0M
    maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11711
24.0M
    maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11712
24.0M
    maxchar = Py_MAX(maxchar, maxchar2);
11713
11714
    /* Concat the two Unicode strings */
11715
24.0M
    result = PyUnicode_New(new_len, maxchar);
11716
24.0M
    if (result == NULL)
11717
0
        return NULL;
11718
24.0M
    _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11719
24.0M
    _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11720
24.0M
    assert(_PyUnicode_CheckConsistency(result, 1));
11721
24.0M
    return result;
11722
24.0M
}
11723
11724
void
11725
PyUnicode_Append(PyObject **p_left, PyObject *right)
11726
6.18M
{
11727
6.18M
    PyObject *left, *res;
11728
6.18M
    Py_UCS4 maxchar, maxchar2;
11729
6.18M
    Py_ssize_t left_len, right_len, new_len;
11730
11731
6.18M
    if (p_left == NULL) {
11732
0
        if (!PyErr_Occurred())
11733
0
            PyErr_BadInternalCall();
11734
0
        return;
11735
0
    }
11736
6.18M
    left = *p_left;
11737
6.18M
    if (right == NULL || left == NULL
11738
6.18M
        || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
11739
0
        if (!PyErr_Occurred())
11740
0
            PyErr_BadInternalCall();
11741
0
        goto error;
11742
0
    }
11743
11744
    /* Shortcuts */
11745
6.18M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11746
6.18M
    if (left == empty) {
11747
463k
        Py_DECREF(left);
11748
463k
        *p_left = Py_NewRef(right);
11749
463k
        return;
11750
463k
    }
11751
5.72M
    if (right == empty) {
11752
2.28k
        return;
11753
2.28k
    }
11754
11755
5.72M
    left_len = PyUnicode_GET_LENGTH(left);
11756
5.72M
    right_len = PyUnicode_GET_LENGTH(right);
11757
5.72M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11758
0
        PyErr_SetString(PyExc_OverflowError,
11759
0
                        "strings are too large to concat");
11760
0
        goto error;
11761
0
    }
11762
5.72M
    new_len = left_len + right_len;
11763
11764
5.72M
    if (_PyUnicode_IsModifiable(left)
11765
5.72M
        && PyUnicode_CheckExact(right)
11766
5.72M
        && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
11767
        /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11768
           to change the structure size, but characters are stored just after
11769
           the structure, and so it requires to move all characters which is
11770
           not so different than duplicating the string. */
11771
2.27M
        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11772
2.27M
    {
11773
        /* append inplace */
11774
2.27M
        if (unicode_resize(p_left, new_len) != 0)
11775
0
            goto error;
11776
11777
        /* copy 'right' into the newly allocated area of 'left' */
11778
2.27M
        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
11779
2.27M
    }
11780
3.44M
    else {
11781
3.44M
        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11782
3.44M
        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11783
3.44M
        maxchar = Py_MAX(maxchar, maxchar2);
11784
11785
        /* Concat the two Unicode strings */
11786
3.44M
        res = PyUnicode_New(new_len, maxchar);
11787
3.44M
        if (res == NULL)
11788
0
            goto error;
11789
3.44M
        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11790
3.44M
        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
11791
3.44M
        Py_DECREF(left);
11792
3.44M
        *p_left = res;
11793
3.44M
    }
11794
5.72M
    assert(_PyUnicode_CheckConsistency(*p_left, 1));
11795
5.72M
    return;
11796
11797
0
error:
11798
0
    Py_CLEAR(*p_left);
11799
0
}
11800
11801
void
11802
PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11803
8
{
11804
8
    PyUnicode_Append(pleft, right);
11805
8
    Py_XDECREF(right);
11806
8
}
11807
11808
/*[clinic input]
11809
@permit_long_summary
11810
@text_signature "($self, sub[, start[, end]], /)"
11811
str.count as unicode_count -> Py_ssize_t
11812
11813
    self as str: self
11814
    sub as substr: unicode
11815
    start: slice_index(accept={int, NoneType}, c_default='0') = None
11816
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
11817
    /
11818
11819
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
11820
11821
Optional arguments start and end are interpreted as in slice
11822
notation.
11823
[clinic start generated code]*/
11824
11825
static Py_ssize_t
11826
unicode_count_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
11827
                   Py_ssize_t end)
11828
/*[clinic end generated code: output=8fcc3aef0b18edbf input=c9209e05438cc352]*/
11829
27.4M
{
11830
27.4M
    assert(PyUnicode_Check(str));
11831
27.4M
    assert(PyUnicode_Check(substr));
11832
11833
27.4M
    Py_ssize_t result;
11834
27.4M
    int kind1, kind2;
11835
27.4M
    const void *buf1 = NULL, *buf2 = NULL;
11836
27.4M
    Py_ssize_t len1, len2;
11837
11838
27.4M
    kind1 = PyUnicode_KIND(str);
11839
27.4M
    kind2 = PyUnicode_KIND(substr);
11840
27.4M
    if (kind1 < kind2)
11841
0
        return 0;
11842
11843
27.4M
    len1 = PyUnicode_GET_LENGTH(str);
11844
27.4M
    len2 = PyUnicode_GET_LENGTH(substr);
11845
27.4M
    ADJUST_INDICES(start, end, len1);
11846
27.4M
    if (end - start < len2)
11847
4.95M
        return 0;
11848
11849
22.4M
    buf1 = PyUnicode_DATA(str);
11850
22.4M
    buf2 = PyUnicode_DATA(substr);
11851
22.4M
    if (kind2 != kind1) {
11852
6.06M
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11853
6.06M
        if (!buf2)
11854
0
            goto onError;
11855
6.06M
    }
11856
11857
    // We don't reuse `anylib_count` here because of the explicit casts.
11858
22.4M
    switch (kind1) {
11859
16.4M
    case PyUnicode_1BYTE_KIND:
11860
16.4M
        result = ucs1lib_count(
11861
16.4M
            ((const Py_UCS1*)buf1) + start, end - start,
11862
16.4M
            buf2, len2, PY_SSIZE_T_MAX
11863
16.4M
            );
11864
16.4M
        break;
11865
3.71M
    case PyUnicode_2BYTE_KIND:
11866
3.71M
        result = ucs2lib_count(
11867
3.71M
            ((const Py_UCS2*)buf1) + start, end - start,
11868
3.71M
            buf2, len2, PY_SSIZE_T_MAX
11869
3.71M
            );
11870
3.71M
        break;
11871
2.35M
    case PyUnicode_4BYTE_KIND:
11872
2.35M
        result = ucs4lib_count(
11873
2.35M
            ((const Py_UCS4*)buf1) + start, end - start,
11874
2.35M
            buf2, len2, PY_SSIZE_T_MAX
11875
2.35M
            );
11876
2.35M
        break;
11877
0
    default:
11878
0
        Py_UNREACHABLE();
11879
22.4M
    }
11880
11881
22.4M
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11882
22.4M
    if (kind2 != kind1)
11883
6.06M
        PyMem_Free((void *)buf2);
11884
11885
22.4M
    return result;
11886
0
  onError:
11887
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11888
0
    if (kind2 != kind1)
11889
0
        PyMem_Free((void *)buf2);
11890
0
    return -1;
11891
22.4M
}
11892
11893
/*[clinic input]
11894
str.encode as unicode_encode
11895
11896
    encoding: str(c_default="NULL") = 'utf-8'
11897
        The encoding in which to encode the string.
11898
    errors: str(c_default="NULL") = 'strict'
11899
        The error handling scheme to use for encoding errors.
11900
        The default is 'strict' meaning that encoding errors raise a
11901
        UnicodeEncodeError.  Other possible values are 'ignore', 'replace'
11902
        and 'xmlcharrefreplace' as well as any other name registered with
11903
        codecs.register_error that can handle UnicodeEncodeErrors.
11904
11905
Encode the string using the codec registered for encoding.
11906
[clinic start generated code]*/
11907
11908
static PyObject *
11909
unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
11910
/*[clinic end generated code: output=bf78b6e2a9470e3c input=b85a9645cb33b729]*/
11911
19.7M
{
11912
19.7M
    return PyUnicode_AsEncodedString(self, encoding, errors);
11913
19.7M
}
11914
11915
/*[clinic input]
11916
str.expandtabs as unicode_expandtabs
11917
11918
    tabsize: int = 8
11919
11920
Return a copy where all tab characters are expanded using spaces.
11921
11922
If tabsize is not given, a tab size of 8 characters is assumed.
11923
[clinic start generated code]*/
11924
11925
static PyObject *
11926
unicode_expandtabs_impl(PyObject *self, int tabsize)
11927
/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
11928
1.24M
{
11929
1.24M
    Py_ssize_t i, j, line_pos, src_len, incr;
11930
1.24M
    Py_UCS4 ch;
11931
1.24M
    PyObject *u;
11932
1.24M
    const void *src_data;
11933
1.24M
    void *dest_data;
11934
1.24M
    int kind;
11935
1.24M
    int found;
11936
11937
    /* First pass: determine size of output string */
11938
1.24M
    src_len = PyUnicode_GET_LENGTH(self);
11939
1.24M
    i = j = line_pos = 0;
11940
1.24M
    kind = PyUnicode_KIND(self);
11941
1.24M
    src_data = PyUnicode_DATA(self);
11942
1.24M
    found = 0;
11943
2.76M
    for (; i < src_len; i++) {
11944
1.52M
        ch = PyUnicode_READ(kind, src_data, i);
11945
1.52M
        if (ch == '\t') {
11946
396k
            found = 1;
11947
396k
            if (tabsize > 0) {
11948
396k
                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
11949
396k
                if (j > PY_SSIZE_T_MAX - incr)
11950
0
                    goto overflow;
11951
396k
                line_pos += incr;
11952
396k
                j += incr;
11953
396k
            }
11954
396k
        }
11955
1.12M
        else {
11956
1.12M
            if (j > PY_SSIZE_T_MAX - 1)
11957
0
                goto overflow;
11958
1.12M
            line_pos++;
11959
1.12M
            j++;
11960
1.12M
            if (ch == '\n' || ch == '\r')
11961
2.63k
                line_pos = 0;
11962
1.12M
        }
11963
1.52M
    }
11964
1.24M
    if (!found)
11965
1.20M
        return unicode_result_unchanged(self);
11966
11967
    /* Second pass: create output string and fill it */
11968
36.4k
    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
11969
36.4k
    if (!u)
11970
0
        return NULL;
11971
36.4k
    dest_data = PyUnicode_DATA(u);
11972
11973
36.4k
    i = j = line_pos = 0;
11974
11975
745k
    for (; i < src_len; i++) {
11976
708k
        ch = PyUnicode_READ(kind, src_data, i);
11977
708k
        if (ch == '\t') {
11978
396k
            if (tabsize > 0) {
11979
396k
                incr = tabsize - (line_pos % tabsize);
11980
396k
                line_pos += incr;
11981
396k
                _PyUnicode_Fill(kind, dest_data, ' ', j, incr);
11982
396k
                j += incr;
11983
396k
            }
11984
396k
        }
11985
311k
        else {
11986
311k
            line_pos++;
11987
311k
            PyUnicode_WRITE(kind, dest_data, j, ch);
11988
311k
            j++;
11989
311k
            if (ch == '\n' || ch == '\r')
11990
0
                line_pos = 0;
11991
311k
        }
11992
708k
    }
11993
36.4k
    assert (j == PyUnicode_GET_LENGTH(u));
11994
36.4k
    return unicode_result(u);
11995
11996
0
  overflow:
11997
0
    PyErr_SetString(PyExc_OverflowError, "new string is too long");
11998
0
    return NULL;
11999
36.4k
}
12000
12001
/*[clinic input]
12002
@permit_long_summary
12003
str.find as unicode_find = str.count
12004
12005
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12006
12007
Optional arguments start and end are interpreted as in slice
12008
notation.  Return -1 on failure.
12009
[clinic start generated code]*/
12010
12011
static Py_ssize_t
12012
unicode_find_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12013
                  Py_ssize_t end)
12014
/*[clinic end generated code: output=51dbe6255712e278 input=f57e93c59d1ee927]*/
12015
26.9M
{
12016
26.9M
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12017
26.9M
    if (result < 0) {
12018
5.90M
        return -1;
12019
5.90M
    }
12020
21.0M
    return result;
12021
26.9M
}
12022
12023
static PyObject *
12024
unicode_getitem(PyObject *self, Py_ssize_t index)
12025
61.6M
{
12026
61.6M
    const void *data;
12027
61.6M
    int kind;
12028
61.6M
    Py_UCS4 ch;
12029
12030
61.6M
    if (!PyUnicode_Check(self)) {
12031
0
        PyErr_BadArgument();
12032
0
        return NULL;
12033
0
    }
12034
61.6M
    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
12035
5.42k
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12036
5.42k
        return NULL;
12037
5.42k
    }
12038
61.6M
    kind = PyUnicode_KIND(self);
12039
61.6M
    data = PyUnicode_DATA(self);
12040
61.6M
    ch = PyUnicode_READ(kind, data, index);
12041
61.6M
    return unicode_char(ch);
12042
61.6M
}
12043
12044
/* Believe it or not, this produces the same value for ASCII strings
12045
   as bytes_hash(). */
12046
static Py_hash_t
12047
unicode_hash(PyObject *self)
12048
121M
{
12049
121M
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
12050
12051
#ifdef Py_DEBUG
12052
    assert(_Py_HashSecret_Initialized);
12053
#endif
12054
121M
    Py_hash_t hash = PyUnicode_HASH(self);
12055
121M
    if (hash != -1) {
12056
75.2M
        return hash;
12057
75.2M
    }
12058
46.5M
    x = Py_HashBuffer(PyUnicode_DATA(self),
12059
46.5M
                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
12060
12061
46.5M
    PyUnicode_SET_HASH(self, x);
12062
46.5M
    return x;
12063
121M
}
12064
12065
/*[clinic input]
12066
@permit_long_summary
12067
str.index as unicode_index = str.count
12068
12069
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12070
12071
Optional arguments start and end are interpreted as in slice
12072
notation.  Raises ValueError when the substring is not found.
12073
[clinic start generated code]*/
12074
12075
static Py_ssize_t
12076
unicode_index_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12077
                   Py_ssize_t end)
12078
/*[clinic end generated code: output=77558288837cdf40 input=5900ab84de55e628]*/
12079
0
{
12080
0
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12081
0
    if (result == -1) {
12082
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
12083
0
    }
12084
0
    else if (result < 0) {
12085
0
        return -1;
12086
0
    }
12087
0
    return result;
12088
0
}
12089
12090
/*[clinic input]
12091
@permit_long_summary
12092
str.isascii as unicode_isascii
12093
12094
Return True if all characters in the string are ASCII, False otherwise.
12095
12096
ASCII characters have code points in the range U+0000-U+007F.
12097
Empty string is ASCII too.
12098
[clinic start generated code]*/
12099
12100
static PyObject *
12101
unicode_isascii_impl(PyObject *self)
12102
/*[clinic end generated code: output=c5910d64b5a8003f input=dc74e1ced821159f]*/
12103
5.34k
{
12104
5.34k
    return PyBool_FromLong(PyUnicode_IS_ASCII(self));
12105
5.34k
}
12106
12107
/*[clinic input]
12108
str.islower as unicode_islower
12109
12110
Return True if the string is a lowercase string, False otherwise.
12111
12112
A string is lowercase if all cased characters in the string are
12113
lowercase and there is at least one cased character in the string.
12114
[clinic start generated code]*/
12115
12116
static PyObject *
12117
unicode_islower_impl(PyObject *self)
12118
/*[clinic end generated code: output=dbd41995bd005b81 input=1879b48dfc628366]*/
12119
0
{
12120
0
    Py_ssize_t i, length;
12121
0
    int kind;
12122
0
    const void *data;
12123
0
    int cased;
12124
12125
0
    length = PyUnicode_GET_LENGTH(self);
12126
0
    kind = PyUnicode_KIND(self);
12127
0
    data = PyUnicode_DATA(self);
12128
12129
    /* Shortcut for single character strings */
12130
0
    if (length == 1)
12131
0
        return PyBool_FromLong(
12132
0
            Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
12133
12134
    /* Special case for empty strings */
12135
0
    if (length == 0)
12136
0
        Py_RETURN_FALSE;
12137
12138
0
    cased = 0;
12139
0
    for (i = 0; i < length; i++) {
12140
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12141
12142
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
12143
0
            Py_RETURN_FALSE;
12144
0
        else if (!cased && Py_UNICODE_ISLOWER(ch))
12145
0
            cased = 1;
12146
0
    }
12147
0
    return PyBool_FromLong(cased);
12148
0
}
12149
12150
/*[clinic input]
12151
str.isupper as unicode_isupper
12152
12153
Return True if the string is an uppercase string, False otherwise.
12154
12155
A string is uppercase if all cased characters in the string are
12156
uppercase and there is at least one cased character in the string.
12157
[clinic start generated code]*/
12158
12159
static PyObject *
12160
unicode_isupper_impl(PyObject *self)
12161
/*[clinic end generated code: output=049209c8e7f15f59 input=77d29904aef0e3a0]*/
12162
10.7k
{
12163
10.7k
    Py_ssize_t i, length;
12164
10.7k
    int kind;
12165
10.7k
    const void *data;
12166
10.7k
    int cased;
12167
12168
10.7k
    length = PyUnicode_GET_LENGTH(self);
12169
10.7k
    kind = PyUnicode_KIND(self);
12170
10.7k
    data = PyUnicode_DATA(self);
12171
12172
    /* Shortcut for single character strings */
12173
10.7k
    if (length == 1)
12174
0
        return PyBool_FromLong(
12175
0
            Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
12176
12177
    /* Special case for empty strings */
12178
10.7k
    if (length == 0)
12179
0
        Py_RETURN_FALSE;
12180
12181
10.7k
    cased = 0;
12182
135k
    for (i = 0; i < length; i++) {
12183
126k
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12184
12185
126k
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
12186
1.36k
            Py_RETURN_FALSE;
12187
124k
        else if (!cased && Py_UNICODE_ISUPPER(ch))
12188
9.56k
            cased = 1;
12189
126k
    }
12190
9.42k
    return PyBool_FromLong(cased);
12191
10.7k
}
12192
12193
/*[clinic input]
12194
str.istitle as unicode_istitle
12195
12196
Return True if the string is a title-cased string, False otherwise.
12197
12198
In a title-cased string, upper- and title-case characters may only
12199
follow uncased characters and lowercase characters only cased ones.
12200
[clinic start generated code]*/
12201
12202
static PyObject *
12203
unicode_istitle_impl(PyObject *self)
12204
/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
12205
0
{
12206
0
    Py_ssize_t i, length;
12207
0
    int kind;
12208
0
    const void *data;
12209
0
    int cased, previous_is_cased;
12210
12211
0
    length = PyUnicode_GET_LENGTH(self);
12212
0
    kind = PyUnicode_KIND(self);
12213
0
    data = PyUnicode_DATA(self);
12214
12215
    /* Shortcut for single character strings */
12216
0
    if (length == 1) {
12217
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12218
0
        return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
12219
0
                               (Py_UNICODE_ISUPPER(ch) != 0));
12220
0
    }
12221
12222
    /* Special case for empty strings */
12223
0
    if (length == 0)
12224
0
        Py_RETURN_FALSE;
12225
12226
0
    cased = 0;
12227
0
    previous_is_cased = 0;
12228
0
    for (i = 0; i < length; i++) {
12229
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12230
12231
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
12232
0
            if (previous_is_cased)
12233
0
                Py_RETURN_FALSE;
12234
0
            previous_is_cased = 1;
12235
0
            cased = 1;
12236
0
        }
12237
0
        else if (Py_UNICODE_ISLOWER(ch)) {
12238
0
            if (!previous_is_cased)
12239
0
                Py_RETURN_FALSE;
12240
0
            previous_is_cased = 1;
12241
0
            cased = 1;
12242
0
        }
12243
0
        else
12244
0
            previous_is_cased = 0;
12245
0
    }
12246
0
    return PyBool_FromLong(cased);
12247
0
}
12248
12249
/*[clinic input]
12250
str.isspace as unicode_isspace
12251
12252
Return True if the string is a whitespace string, False otherwise.
12253
12254
A string is whitespace if all characters in the string are
12255
whitespace and there is at least one character in the string.
12256
[clinic start generated code]*/
12257
12258
static PyObject *
12259
unicode_isspace_impl(PyObject *self)
12260
/*[clinic end generated code: output=163a63bfa08ac2b9 input=29e09560fc23fbeb]*/
12261
1.61M
{
12262
1.61M
    Py_ssize_t i, length;
12263
1.61M
    int kind;
12264
1.61M
    const void *data;
12265
12266
1.61M
    length = PyUnicode_GET_LENGTH(self);
12267
1.61M
    kind = PyUnicode_KIND(self);
12268
1.61M
    data = PyUnicode_DATA(self);
12269
12270
    /* Shortcut for single character strings */
12271
1.61M
    if (length == 1)
12272
1.61M
        return PyBool_FromLong(
12273
1.61M
            Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
12274
12275
    /* Special case for empty strings */
12276
1.33k
    if (length == 0)
12277
284
        Py_RETURN_FALSE;
12278
12279
7.60k
    for (i = 0; i < length; i++) {
12280
7.50k
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12281
7.50k
        if (!Py_UNICODE_ISSPACE(ch))
12282
944
            Py_RETURN_FALSE;
12283
7.50k
    }
12284
1.04k
    Py_RETURN_TRUE;
12285
1.04k
}
12286
12287
/*[clinic input]
12288
str.isalpha as unicode_isalpha
12289
12290
Return True if the string is an alphabetic string, False otherwise.
12291
12292
A string is alphabetic if all characters in the string are
12293
alphabetic and there is at least one character in the string.
12294
[clinic start generated code]*/
12295
12296
static PyObject *
12297
unicode_isalpha_impl(PyObject *self)
12298
/*[clinic end generated code: output=cc81b9ac3883ec4f input=9906a07f3e04892e]*/
12299
18
{
12300
18
    Py_ssize_t i, length;
12301
18
    int kind;
12302
18
    const void *data;
12303
12304
18
    length = PyUnicode_GET_LENGTH(self);
12305
18
    kind = PyUnicode_KIND(self);
12306
18
    data = PyUnicode_DATA(self);
12307
12308
    /* Shortcut for single character strings */
12309
18
    if (length == 1)
12310
14
        return PyBool_FromLong(
12311
14
            Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
12312
12313
    /* Special case for empty strings */
12314
4
    if (length == 0)
12315
0
        Py_RETURN_FALSE;
12316
12317
4
    for (i = 0; i < length; i++) {
12318
4
        if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
12319
4
            Py_RETURN_FALSE;
12320
4
    }
12321
4
    Py_RETURN_TRUE;
12322
4
}
12323
12324
/*[clinic input]
12325
@permit_long_summary
12326
str.isalnum as unicode_isalnum
12327
12328
Return True if the string is an alpha-numeric string, False otherwise.
12329
12330
A string is alpha-numeric if all characters in the string are
12331
alpha-numeric and there is at least one character in the string.
12332
[clinic start generated code]*/
12333
12334
static PyObject *
12335
unicode_isalnum_impl(PyObject *self)
12336
/*[clinic end generated code: output=a5a23490ffc3660c input=892f64ebc171fd4f]*/
12337
0
{
12338
0
    int kind;
12339
0
    const void *data;
12340
0
    Py_ssize_t len, i;
12341
12342
0
    kind = PyUnicode_KIND(self);
12343
0
    data = PyUnicode_DATA(self);
12344
0
    len = PyUnicode_GET_LENGTH(self);
12345
12346
    /* Shortcut for single character strings */
12347
0
    if (len == 1) {
12348
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12349
0
        return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12350
0
    }
12351
12352
    /* Special case for empty strings */
12353
0
    if (len == 0)
12354
0
        Py_RETURN_FALSE;
12355
12356
0
    for (i = 0; i < len; i++) {
12357
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12358
0
        if (!Py_UNICODE_ISALNUM(ch))
12359
0
            Py_RETURN_FALSE;
12360
0
    }
12361
0
    Py_RETURN_TRUE;
12362
0
}
12363
12364
/*[clinic input]
12365
str.isdecimal as unicode_isdecimal
12366
12367
Return True if the string is a decimal string, False otherwise.
12368
12369
A string is a decimal string if all characters in the string are
12370
decimal and there is at least one character in the string.
12371
[clinic start generated code]*/
12372
12373
static PyObject *
12374
unicode_isdecimal_impl(PyObject *self)
12375
/*[clinic end generated code: output=fb2dcdb62d3fc548 input=63b0453c48cad0af]*/
12376
1.26k
{
12377
1.26k
    Py_ssize_t i, length;
12378
1.26k
    int kind;
12379
1.26k
    const void *data;
12380
12381
1.26k
    length = PyUnicode_GET_LENGTH(self);
12382
1.26k
    kind = PyUnicode_KIND(self);
12383
1.26k
    data = PyUnicode_DATA(self);
12384
12385
    /* Shortcut for single character strings */
12386
1.26k
    if (length == 1)
12387
186
        return PyBool_FromLong(
12388
186
            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
12389
12390
    /* Special case for empty strings */
12391
1.08k
    if (length == 0)
12392
0
        Py_RETURN_FALSE;
12393
12394
7.56k
    for (i = 0; i < length; i++) {
12395
6.96k
        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
12396
477
            Py_RETURN_FALSE;
12397
6.96k
    }
12398
1.08k
    Py_RETURN_TRUE;
12399
1.08k
}
12400
12401
/*[clinic input]
12402
str.isdigit as unicode_isdigit
12403
12404
Return True if the string is a digit string, False otherwise.
12405
12406
A string is a digit string if all characters in the string are
12407
digits and there is at least one character in the string.
12408
[clinic start generated code]*/
12409
12410
static PyObject *
12411
unicode_isdigit_impl(PyObject *self)
12412
/*[clinic end generated code: output=10a6985311da6858 input=353b03747b062e4b]*/
12413
1.26M
{
12414
1.26M
    Py_ssize_t i, length;
12415
1.26M
    int kind;
12416
1.26M
    const void *data;
12417
12418
1.26M
    length = PyUnicode_GET_LENGTH(self);
12419
1.26M
    kind = PyUnicode_KIND(self);
12420
1.26M
    data = PyUnicode_DATA(self);
12421
12422
    /* Shortcut for single character strings */
12423
1.26M
    if (length == 1) {
12424
1.26M
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12425
1.26M
        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12426
1.26M
    }
12427
12428
    /* Special case for empty strings */
12429
408
    if (length == 0)
12430
0
        Py_RETURN_FALSE;
12431
12432
1.45k
    for (i = 0; i < length; i++) {
12433
1.04k
        if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
12434
0
            Py_RETURN_FALSE;
12435
1.04k
    }
12436
408
    Py_RETURN_TRUE;
12437
408
}
12438
12439
/*[clinic input]
12440
str.isnumeric as unicode_isnumeric
12441
12442
Return True if the string is a numeric string, False otherwise.
12443
12444
A string is numeric if all characters in the string are numeric and
12445
there is at least one character in the string.
12446
[clinic start generated code]*/
12447
12448
static PyObject *
12449
unicode_isnumeric_impl(PyObject *self)
12450
/*[clinic end generated code: output=9172a32d9013051a input=83b2a072ed7aff48]*/
12451
0
{
12452
0
    Py_ssize_t i, length;
12453
0
    int kind;
12454
0
    const void *data;
12455
12456
0
    length = PyUnicode_GET_LENGTH(self);
12457
0
    kind = PyUnicode_KIND(self);
12458
0
    data = PyUnicode_DATA(self);
12459
12460
    /* Shortcut for single character strings */
12461
0
    if (length == 1)
12462
0
        return PyBool_FromLong(
12463
0
            Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
12464
12465
    /* Special case for empty strings */
12466
0
    if (length == 0)
12467
0
        Py_RETURN_FALSE;
12468
12469
0
    for (i = 0; i < length; i++) {
12470
0
        if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
12471
0
            Py_RETURN_FALSE;
12472
0
    }
12473
0
    Py_RETURN_TRUE;
12474
0
}
12475
12476
Py_ssize_t
12477
_PyUnicode_ScanIdentifier(PyObject *self)
12478
62.1k
{
12479
62.1k
    Py_ssize_t i;
12480
62.1k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12481
62.1k
    if (len == 0) {
12482
        /* an empty string is not a valid identifier */
12483
0
        return 0;
12484
0
    }
12485
12486
62.1k
    int kind = PyUnicode_KIND(self);
12487
62.1k
    const void *data = PyUnicode_DATA(self);
12488
62.1k
    Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12489
    /* PEP 3131 says that the first character must be in
12490
       XID_Start and subsequent characters in XID_Continue,
12491
       and for the ASCII range, the 2.x rules apply (i.e
12492
       start with letters and underscore, continue with
12493
       letters, digits, underscore). However, given the current
12494
       definition of XID_Start and XID_Continue, it is sufficient
12495
       to check just for these, except that _ must be allowed
12496
       as starting an identifier.  */
12497
62.1k
    if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12498
720
        return 0;
12499
720
    }
12500
12501
508k
    for (i = 1; i < len; i++) {
12502
447k
        ch = PyUnicode_READ(kind, data, i);
12503
447k
        if (!_PyUnicode_IsXidContinue(ch)) {
12504
300
            return i;
12505
300
        }
12506
447k
    }
12507
61.1k
    return i;
12508
61.4k
}
12509
12510
int
12511
PyUnicode_IsIdentifier(PyObject *self)
12512
49.3k
{
12513
49.3k
    Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12514
49.3k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12515
    /* an empty string is not a valid identifier */
12516
49.3k
    return len && i == len;
12517
49.3k
}
12518
12519
/*[clinic input]
12520
@permit_long_summary
12521
str.isidentifier as unicode_isidentifier
12522
12523
Return True if the string is a valid Python identifier, False otherwise.
12524
12525
Call keyword.iskeyword(s) to test whether string s is a reserved
12526
identifier, such as "def" or "class".
12527
[clinic start generated code]*/
12528
12529
static PyObject *
12530
unicode_isidentifier_impl(PyObject *self)
12531
/*[clinic end generated code: output=fe585a9666572905 input=cabde62c20a3be6b]*/
12532
47.0k
{
12533
47.0k
    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12534
47.0k
}
12535
12536
/*[clinic input]
12537
@permit_long_summary
12538
str.isprintable as unicode_isprintable
12539
12540
Return True if all characters in the string are printable, False otherwise.
12541
12542
A character is printable if repr() may use it in its output.
12543
[clinic start generated code]*/
12544
12545
static PyObject *
12546
unicode_isprintable_impl(PyObject *self)
12547
/*[clinic end generated code: output=3ab9626cd32dd1a0 input=18345ba847084ec5]*/
12548
2.24M
{
12549
2.24M
    Py_ssize_t i, length;
12550
2.24M
    int kind;
12551
2.24M
    const void *data;
12552
12553
2.24M
    length = PyUnicode_GET_LENGTH(self);
12554
2.24M
    kind = PyUnicode_KIND(self);
12555
2.24M
    data = PyUnicode_DATA(self);
12556
12557
    /* Shortcut for single character strings */
12558
2.24M
    if (length == 1)
12559
2.24M
        return PyBool_FromLong(
12560
2.24M
            Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
12561
12562
0
    for (i = 0; i < length; i++) {
12563
0
        if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
12564
0
            Py_RETURN_FALSE;
12565
0
        }
12566
0
    }
12567
0
    Py_RETURN_TRUE;
12568
0
}
12569
12570
/*[clinic input]
12571
str.join as unicode_join
12572
12573
    iterable: object
12574
    /
12575
12576
Concatenate any number of strings.
12577
12578
The string whose method is called is inserted in between each given
12579
string.  The result is returned as a new string.
12580
12581
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12582
[clinic start generated code]*/
12583
12584
static PyObject *
12585
unicode_join(PyObject *self, PyObject *iterable)
12586
/*[clinic end generated code: output=6857e7cecfe7bf98 input=fd330a11ee845fb2]*/
12587
19.7M
{
12588
19.7M
    return PyUnicode_Join(self, iterable);
12589
19.7M
}
12590
12591
static Py_ssize_t
12592
unicode_length(PyObject *self)
12593
32.4M
{
12594
32.4M
    return PyUnicode_GET_LENGTH(self);
12595
32.4M
}
12596
12597
/*[clinic input]
12598
str.ljust as unicode_ljust
12599
12600
    width: Py_ssize_t
12601
    fillchar: Py_UCS4 = ' '
12602
    /
12603
12604
Return a left-justified string of length width.
12605
12606
Padding is done using the specified fill character (default is
12607
a space).
12608
[clinic start generated code]*/
12609
12610
static PyObject *
12611
unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12612
/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=8a55f06694c20ed6]*/
12613
0
{
12614
0
    if (PyUnicode_GET_LENGTH(self) >= width)
12615
0
        return unicode_result_unchanged(self);
12616
12617
0
    return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
12618
0
}
12619
12620
/*[clinic input]
12621
str.lower as unicode_lower
12622
12623
Return a copy of the string converted to lowercase.
12624
[clinic start generated code]*/
12625
12626
static PyObject *
12627
unicode_lower_impl(PyObject *self)
12628
/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
12629
72.8M
{
12630
72.8M
    if (PyUnicode_IS_ASCII(self))
12631
67.9M
        return ascii_upper_or_lower(self, 1);
12632
4.86M
    return case_operation(self, do_lower);
12633
72.8M
}
12634
12635
48.0M
#define LEFTSTRIP 0
12636
52.8M
#define RIGHTSTRIP 1
12637
36.9M
#define BOTHSTRIP 2
12638
12639
/* Arrays indexed by above */
12640
static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
12641
12642
0
#define STRIPNAME(i) (stripfuncnames[i])
12643
12644
/* externally visible for str.strip(unicode) */
12645
PyObject *
12646
_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
12647
4.27M
{
12648
4.27M
    const void *data;
12649
4.27M
    int kind;
12650
4.27M
    Py_ssize_t i, j, len;
12651
4.27M
    BLOOM_MASK sepmask;
12652
4.27M
    Py_ssize_t seplen;
12653
12654
4.27M
    kind = PyUnicode_KIND(self);
12655
4.27M
    data = PyUnicode_DATA(self);
12656
4.27M
    len = PyUnicode_GET_LENGTH(self);
12657
4.27M
    seplen = PyUnicode_GET_LENGTH(sepobj);
12658
4.27M
    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12659
4.27M
                              PyUnicode_DATA(sepobj),
12660
4.27M
                              seplen);
12661
12662
4.27M
    i = 0;
12663
4.27M
    if (striptype != RIGHTSTRIP) {
12664
468k
        while (i < len) {
12665
465k
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12666
465k
            if (!BLOOM(sepmask, ch))
12667
428k
                break;
12668
37.2k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12669
2.69k
                break;
12670
34.5k
            i++;
12671
34.5k
        }
12672
434k
    }
12673
12674
4.27M
    j = len;
12675
4.27M
    if (striptype != LEFTSTRIP) {
12676
3.84M
        j--;
12677
4.45M
        while (j >= i) {
12678
3.37M
            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12679
3.37M
            if (!BLOOM(sepmask, ch))
12680
2.64M
                break;
12681
733k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12682
119k
                break;
12683
614k
            j--;
12684
614k
        }
12685
12686
3.84M
        j++;
12687
3.84M
    }
12688
12689
4.27M
    return PyUnicode_Substring(self, i, j);
12690
4.27M
}
12691
12692
PyObject*
12693
_PyUnicode_BinarySlice(PyObject *container, PyObject *start_o, PyObject *stop_o)
12694
30.6M
{
12695
30.6M
    assert(PyUnicode_CheckExact(container));
12696
30.6M
    Py_ssize_t len = PyUnicode_GET_LENGTH(container);
12697
30.6M
    Py_ssize_t istart, istop;
12698
30.6M
    if (!_PyEval_UnpackIndices(start_o, stop_o, len, &istart, &istop)) {
12699
0
        return NULL;
12700
0
    }
12701
30.6M
    return PyUnicode_Substring(container, istart, istop);
12702
30.6M
}
12703
12704
PyObject*
12705
PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12706
243M
{
12707
243M
    const unsigned char *data;
12708
243M
    int kind;
12709
243M
    Py_ssize_t length;
12710
12711
243M
    length = PyUnicode_GET_LENGTH(self);
12712
243M
    end = Py_MIN(end, length);
12713
12714
243M
    if (start == 0 && end == length)
12715
46.3M
        return unicode_result_unchanged(self);
12716
12717
197M
    if (start < 0 || end < 0) {
12718
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12719
0
        return NULL;
12720
0
    }
12721
197M
    if (start >= length || end < start)
12722
1.47M
        _Py_RETURN_UNICODE_EMPTY();
12723
12724
195M
    length = end - start;
12725
195M
    if (PyUnicode_IS_ASCII(self)) {
12726
55.9M
        data = PyUnicode_1BYTE_DATA(self);
12727
55.9M
        return _PyUnicode_FromASCII((const char*)(data + start), length);
12728
55.9M
    }
12729
139M
    else {
12730
139M
        kind = PyUnicode_KIND(self);
12731
139M
        data = PyUnicode_1BYTE_DATA(self);
12732
139M
        return PyUnicode_FromKindAndData(kind,
12733
139M
                                         data + kind * start,
12734
139M
                                         length);
12735
139M
    }
12736
195M
}
12737
12738
static PyObject *
12739
do_strip(PyObject *self, int striptype)
12740
41.6M
{
12741
41.6M
    Py_ssize_t len, i, j;
12742
12743
41.6M
    len = PyUnicode_GET_LENGTH(self);
12744
12745
41.6M
    if (PyUnicode_IS_ASCII(self)) {
12746
32.7M
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12747
12748
32.7M
        i = 0;
12749
32.7M
        if (striptype != RIGHTSTRIP) {
12750
31.3M
            while (i < len) {
12751
26.6M
                Py_UCS1 ch = data[i];
12752
26.6M
                if (!_Py_ascii_whitespace[ch])
12753
25.3M
                    break;
12754
1.26M
                i++;
12755
1.26M
            }
12756
30.0M
        }
12757
12758
32.7M
        j = len;
12759
32.7M
        if (striptype != LEFTSTRIP) {
12760
32.3M
            j--;
12761
34.3M
            while (j >= i) {
12762
28.5M
                Py_UCS1 ch = data[j];
12763
28.5M
                if (!_Py_ascii_whitespace[ch])
12764
26.5M
                    break;
12765
1.93M
                j--;
12766
1.93M
            }
12767
32.3M
            j++;
12768
32.3M
        }
12769
32.7M
    }
12770
8.91M
    else {
12771
8.91M
        int kind = PyUnicode_KIND(self);
12772
8.91M
        const void *data = PyUnicode_DATA(self);
12773
12774
8.91M
        i = 0;
12775
8.91M
        if (striptype != RIGHTSTRIP) {
12776
9.87M
            while (i < len) {
12777
9.86M
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12778
9.86M
                if (!Py_UNICODE_ISSPACE(ch))
12779
8.58M
                    break;
12780
1.28M
                i++;
12781
1.28M
            }
12782
8.58M
        }
12783
12784
8.91M
        j = len;
12785
8.91M
        if (striptype != LEFTSTRIP) {
12786
7.58M
            j--;
12787
8.47M
            while (j >= i) {
12788
8.45M
                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12789
8.45M
                if (!Py_UNICODE_ISSPACE(ch))
12790
7.56M
                    break;
12791
891k
                j--;
12792
891k
            }
12793
7.58M
            j++;
12794
7.58M
        }
12795
8.91M
    }
12796
12797
41.6M
    return PyUnicode_Substring(self, i, j);
12798
41.6M
}
12799
12800
12801
static PyObject *
12802
do_argstrip(PyObject *self, int striptype, PyObject *sep)
12803
45.9M
{
12804
45.9M
    if (sep != Py_None) {
12805
4.27M
        if (PyUnicode_Check(sep))
12806
4.27M
            return _PyUnicode_XStrip(self, striptype, sep);
12807
0
        else {
12808
0
            PyErr_Format(PyExc_TypeError,
12809
0
                         "%s arg must be None or str",
12810
0
                         STRIPNAME(striptype));
12811
0
            return NULL;
12812
0
        }
12813
4.27M
    }
12814
12815
41.6M
    return do_strip(self, striptype);
12816
45.9M
}
12817
12818
12819
/*[clinic input]
12820
@permit_long_summary
12821
str.strip as unicode_strip
12822
12823
    chars: object = None
12824
    /
12825
12826
Return a copy of the string with leading and trailing whitespace removed.
12827
12828
If chars is given and not None, remove characters in chars instead.
12829
[clinic start generated code]*/
12830
12831
static PyObject *
12832
unicode_strip_impl(PyObject *self, PyObject *chars)
12833
/*[clinic end generated code: output=ca19018454345d57 input=8bc6353450345fbd]*/
12834
36.9M
{
12835
36.9M
    return do_argstrip(self, BOTHSTRIP, chars);
12836
36.9M
}
12837
12838
12839
/*[clinic input]
12840
str.lstrip as unicode_lstrip
12841
12842
    chars: object = None
12843
    /
12844
12845
Return a copy of the string with leading whitespace removed.
12846
12847
If chars is given and not None, remove characters in chars instead.
12848
[clinic start generated code]*/
12849
12850
static PyObject *
12851
unicode_lstrip_impl(PyObject *self, PyObject *chars)
12852
/*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
12853
2.14M
{
12854
2.14M
    return do_argstrip(self, LEFTSTRIP, chars);
12855
2.14M
}
12856
12857
12858
/*[clinic input]
12859
str.rstrip as unicode_rstrip
12860
12861
    chars: object = None
12862
    /
12863
12864
Return a copy of the string with trailing whitespace removed.
12865
12866
If chars is given and not None, remove characters in chars instead.
12867
[clinic start generated code]*/
12868
12869
static PyObject *
12870
unicode_rstrip_impl(PyObject *self, PyObject *chars)
12871
/*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
12872
6.85M
{
12873
6.85M
    return do_argstrip(self, RIGHTSTRIP, chars);
12874
6.85M
}
12875
12876
12877
PyObject *
12878
_PyUnicode_Repeat(PyObject *str, Py_ssize_t len)
12879
284k
{
12880
284k
    PyObject *u;
12881
284k
    Py_ssize_t nchars, n;
12882
12883
284k
    if (len < 1)
12884
38.3k
        _Py_RETURN_UNICODE_EMPTY();
12885
12886
    /* no repeat, return original string */
12887
246k
    if (len == 1)
12888
27.8k
        return unicode_result_unchanged(str);
12889
12890
218k
    if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
12891
0
        PyErr_SetString(PyExc_OverflowError,
12892
0
                        "repeated string is too long");
12893
0
        return NULL;
12894
0
    }
12895
218k
    nchars = len * PyUnicode_GET_LENGTH(str);
12896
12897
218k
    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
12898
218k
    if (!u)
12899
0
        return NULL;
12900
218k
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
12901
12902
218k
    if (PyUnicode_GET_LENGTH(str) == 1) {
12903
215k
        int kind = PyUnicode_KIND(str);
12904
215k
        Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12905
215k
        if (kind == PyUnicode_1BYTE_KIND) {
12906
215k
            void *to = PyUnicode_DATA(u);
12907
215k
            memset(to, (unsigned char)fill_char, len);
12908
215k
        }
12909
0
        else if (kind == PyUnicode_2BYTE_KIND) {
12910
0
            Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
12911
0
            for (n = 0; n < len; ++n)
12912
0
                ucs2[n] = fill_char;
12913
0
        } else {
12914
0
            Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12915
0
            assert(kind == PyUnicode_4BYTE_KIND);
12916
0
            for (n = 0; n < len; ++n)
12917
0
                ucs4[n] = fill_char;
12918
0
        }
12919
215k
    }
12920
2.22k
    else {
12921
2.22k
        Py_ssize_t char_size = PyUnicode_KIND(str);
12922
2.22k
        char *to = (char *) PyUnicode_DATA(u);
12923
2.22k
        _PyBytes_RepeatBuffer(to, nchars * char_size, PyUnicode_DATA(str),
12924
2.22k
            PyUnicode_GET_LENGTH(str) * char_size);
12925
2.22k
    }
12926
12927
218k
    assert(_PyUnicode_CheckConsistency(u, 1));
12928
218k
    return u;
12929
218k
}
12930
12931
PyObject *
12932
PyUnicode_Replace(PyObject *str,
12933
                  PyObject *substr,
12934
                  PyObject *replstr,
12935
                  Py_ssize_t maxcount)
12936
0
{
12937
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12938
0
            ensure_unicode(replstr) < 0)
12939
0
        return NULL;
12940
0
    return replace(str, substr, replstr, maxcount);
12941
0
}
12942
12943
/*[clinic input]
12944
str.replace as unicode_replace
12945
12946
    old: unicode
12947
    new: unicode
12948
    /
12949
    count: Py_ssize_t = -1
12950
        Maximum number of occurrences to replace.
12951
        -1 (the default value) means replace all occurrences.
12952
12953
Return a copy with all occurrences of substring old replaced by new.
12954
12955
If count is given, only the first count occurrences are replaced.
12956
If count is not specified or -1, then all occurrences are replaced.
12957
[clinic start generated code]*/
12958
12959
static PyObject *
12960
unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12961
                     Py_ssize_t count)
12962
/*[clinic end generated code: output=b63f1a8b5eebf448 input=d15a6886b05e2edc]*/
12963
20.2M
{
12964
20.2M
    return replace(self, old, new, count);
12965
20.2M
}
12966
12967
/*[clinic input]
12968
str.removeprefix as unicode_removeprefix
12969
12970
    prefix: unicode
12971
    /
12972
12973
Return a str with the given prefix string removed if present.
12974
12975
If the string starts with the prefix string, return
12976
string[len(prefix):].  Otherwise, return a copy of the original
12977
string.
12978
[clinic start generated code]*/
12979
12980
static PyObject *
12981
unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
12982
/*[clinic end generated code: output=f1e5945e9763bcb9 input=90d162724944bfa7]*/
12983
28
{
12984
28
    int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
12985
28
    if (match == -1) {
12986
0
        return NULL;
12987
0
    }
12988
28
    if (match) {
12989
28
        return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
12990
28
                                   PyUnicode_GET_LENGTH(self));
12991
28
    }
12992
0
    return unicode_result_unchanged(self);
12993
28
}
12994
12995
/*[clinic input]
12996
str.removesuffix as unicode_removesuffix
12997
12998
    suffix: unicode
12999
    /
13000
13001
Return a str with the given suffix string removed if present.
13002
13003
If the string ends with the suffix string and that suffix is not
13004
empty, return string[:-len(suffix)].  Otherwise, return a copy of
13005
the original string.
13006
[clinic start generated code]*/
13007
13008
static PyObject *
13009
unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
13010
/*[clinic end generated code: output=d36629e227636822 input=6efc96152d4bfcd5]*/
13011
0
{
13012
0
    int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
13013
0
    if (match == -1) {
13014
0
        return NULL;
13015
0
    }
13016
0
    if (match) {
13017
0
        return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
13018
0
                                            - PyUnicode_GET_LENGTH(suffix));
13019
0
    }
13020
0
    return unicode_result_unchanged(self);
13021
0
}
13022
13023
static PyObject *
13024
unicode_repr(PyObject *unicode)
13025
7.36M
{
13026
7.36M
    Py_ssize_t isize = PyUnicode_GET_LENGTH(unicode);
13027
7.36M
    const void *idata = PyUnicode_DATA(unicode);
13028
13029
    /* Compute length of output, quote characters, and
13030
       maximum character */
13031
7.36M
    Py_ssize_t osize = 0;
13032
7.36M
    Py_UCS4 maxch = 127;
13033
7.36M
    Py_ssize_t squote = 0;
13034
7.36M
    Py_ssize_t dquote = 0;
13035
7.36M
    int ikind = PyUnicode_KIND(unicode);
13036
223M
    for (Py_ssize_t i = 0; i < isize; i++) {
13037
215M
        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
13038
215M
        Py_ssize_t incr = 1;
13039
215M
        switch (ch) {
13040
283k
        case '\'': squote++; break;
13041
491k
        case '"':  dquote++; break;
13042
470k
        case '\\': case '\t': case '\r': case '\n':
13043
470k
            incr = 2;
13044
470k
            break;
13045
214M
        default:
13046
            /* Fast-path ASCII */
13047
214M
            if (ch < ' ' || ch == 0x7f)
13048
132M
                incr = 4; /* \xHH */
13049
81.9M
            else if (ch < 0x7f)
13050
71.0M
                ;
13051
10.8M
            else if (Py_UNICODE_ISPRINTABLE(ch))
13052
10.6M
                maxch = (ch > maxch) ? ch : maxch;
13053
176k
            else if (ch < 0x100)
13054
70.8k
                incr = 4; /* \xHH */
13055
105k
            else if (ch < 0x10000)
13056
64.5k
                incr = 6; /* \uHHHH */
13057
41.3k
            else
13058
41.3k
                incr = 10; /* \uHHHHHHHH */
13059
215M
        }
13060
215M
        if (osize > PY_SSIZE_T_MAX - incr) {
13061
0
            PyErr_SetString(PyExc_OverflowError,
13062
0
                            "string is too long to generate repr");
13063
0
            return NULL;
13064
0
        }
13065
215M
        osize += incr;
13066
215M
    }
13067
13068
7.36M
    Py_UCS4 quote = '\'';
13069
7.36M
    int changed = (osize != isize);
13070
7.36M
    if (squote) {
13071
85.1k
        changed = 1;
13072
85.1k
        if (dquote)
13073
            /* Both squote and dquote present. Use squote,
13074
               and escape them */
13075
7.06k
            osize += squote;
13076
78.0k
        else
13077
78.0k
            quote = '"';
13078
85.1k
    }
13079
7.36M
    osize += 2;   /* quotes */
13080
13081
7.36M
    PyObject *repr = PyUnicode_New(osize, maxch);
13082
7.36M
    if (repr == NULL)
13083
0
        return NULL;
13084
7.36M
    int okind = PyUnicode_KIND(repr);
13085
7.36M
    void *odata = PyUnicode_DATA(repr);
13086
13087
7.36M
    if (!changed) {
13088
5.14M
        PyUnicode_WRITE(okind, odata, 0, quote);
13089
13090
5.14M
        _PyUnicode_FastCopyCharacters(repr, 1,
13091
5.14M
                                      unicode, 0,
13092
5.14M
                                      isize);
13093
13094
5.14M
        PyUnicode_WRITE(okind, odata, osize-1, quote);
13095
5.14M
    }
13096
2.22M
    else {
13097
2.22M
        switch (okind) {
13098
2.00M
        case PyUnicode_1BYTE_KIND:
13099
2.00M
            ucs1lib_repr(unicode, quote, odata);
13100
2.00M
            break;
13101
213k
        case PyUnicode_2BYTE_KIND:
13102
213k
            ucs2lib_repr(unicode, quote, odata);
13103
213k
            break;
13104
3.97k
        default:
13105
3.97k
            assert(okind == PyUnicode_4BYTE_KIND);
13106
3.97k
            ucs4lib_repr(unicode, quote, odata);
13107
2.22M
        }
13108
2.22M
    }
13109
13110
7.36M
    assert(_PyUnicode_CheckConsistency(repr, 1));
13111
7.36M
    return repr;
13112
7.36M
}
13113
13114
/*[clinic input]
13115
@permit_long_summary
13116
str.rfind as unicode_rfind = str.count
13117
13118
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13119
13120
Optional arguments start and end are interpreted as in slice
13121
notation.  Return -1 on failure.
13122
[clinic start generated code]*/
13123
13124
static Py_ssize_t
13125
unicode_rfind_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13126
                   Py_ssize_t end)
13127
/*[clinic end generated code: output=880b29f01dd014c8 input=2e67789533baf2f5]*/
13128
202k
{
13129
202k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13130
202k
    if (result < 0) {
13131
9.98k
        return -1;
13132
9.98k
    }
13133
192k
    return result;
13134
202k
}
13135
13136
/*[clinic input]
13137
@permit_long_summary
13138
str.rindex as unicode_rindex = str.count
13139
13140
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13141
13142
Optional arguments start and end are interpreted as in slice
13143
notation.  Raises ValueError when the substring is not found.
13144
[clinic start generated code]*/
13145
13146
static Py_ssize_t
13147
unicode_rindex_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13148
                    Py_ssize_t end)
13149
/*[clinic end generated code: output=5f3aef124c867fe1 input=e29d446c8234c9d9]*/
13150
163k
{
13151
163k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13152
163k
    if (result == -1) {
13153
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
13154
0
    }
13155
163k
    else if (result < 0) {
13156
0
        return -1;
13157
0
    }
13158
163k
    return result;
13159
163k
}
13160
13161
/*[clinic input]
13162
str.rjust as unicode_rjust
13163
13164
    width: Py_ssize_t
13165
    fillchar: Py_UCS4 = ' '
13166
    /
13167
13168
Return a right-justified string of length width.
13169
13170
Padding is done using the specified fill character (default is
13171
a space).
13172
[clinic start generated code]*/
13173
13174
static PyObject *
13175
unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
13176
/*[clinic end generated code: output=804a1a57fbe8d5cf input=1256a8d659589907]*/
13177
0
{
13178
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13179
0
        return unicode_result_unchanged(self);
13180
13181
0
    return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
13182
0
}
13183
13184
PyObject *
13185
PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13186
0
{
13187
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13188
0
        return NULL;
13189
13190
0
    return split(s, sep, maxsplit);
13191
0
}
13192
13193
/*[clinic input]
13194
@permit_long_summary
13195
str.split as unicode_split
13196
13197
    sep: object = None
13198
        The separator used to split the string.
13199
13200
        When set to None (the default value), will split on any
13201
        whitespace character (including \n \r \t \f and spaces) and
13202
        will discard empty strings from the result.
13203
    maxsplit: Py_ssize_t = -1
13204
        Maximum number of splits.
13205
        -1 (the default value) means no limit.
13206
13207
Return a list of the substrings in the string, using sep as the separator string.
13208
13209
Splitting starts at the front of the string and works to the end.
13210
13211
Note, str.split() is mainly useful for data that has been
13212
intentionally delimited.  With natural text that includes
13213
punctuation, consider using the regular expression module.
13214
13215
[clinic start generated code]*/
13216
13217
static PyObject *
13218
unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13219
/*[clinic end generated code: output=3a65b1db356948dc input=288cfd6bc8828f5a]*/
13220
22.2M
{
13221
22.2M
    if (sep == Py_None)
13222
201k
        return split(self, NULL, maxsplit);
13223
22.0M
    if (PyUnicode_Check(sep))
13224
22.0M
        return split(self, sep, maxsplit);
13225
13226
0
    PyErr_Format(PyExc_TypeError,
13227
0
                 "must be str or None, not %.100s",
13228
0
                 Py_TYPE(sep)->tp_name);
13229
0
    return NULL;
13230
22.0M
}
13231
13232
PyObject *
13233
PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
13234
8.70M
{
13235
8.70M
    PyObject* out;
13236
8.70M
    int kind1, kind2;
13237
8.70M
    const void *buf1, *buf2;
13238
8.70M
    Py_ssize_t len1, len2;
13239
13240
8.70M
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13241
0
        return NULL;
13242
13243
8.70M
    kind1 = PyUnicode_KIND(str_obj);
13244
8.70M
    kind2 = PyUnicode_KIND(sep_obj);
13245
8.70M
    len1 = PyUnicode_GET_LENGTH(str_obj);
13246
8.70M
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13247
8.70M
    if (kind1 < kind2 || len1 < len2) {
13248
1.41k
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13249
1.41k
        return PyTuple_Pack(3, str_obj, empty, empty);
13250
1.41k
    }
13251
8.69M
    buf1 = PyUnicode_DATA(str_obj);
13252
8.69M
    buf2 = PyUnicode_DATA(sep_obj);
13253
8.69M
    if (kind2 != kind1) {
13254
96.2k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13255
96.2k
        if (!buf2)
13256
0
            return NULL;
13257
96.2k
    }
13258
13259
8.69M
    switch (kind1) {
13260
8.60M
    case PyUnicode_1BYTE_KIND:
13261
8.60M
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13262
3.02M
            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13263
5.57M
        else
13264
5.57M
            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13265
8.60M
        break;
13266
82.7k
    case PyUnicode_2BYTE_KIND:
13267
82.7k
        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13268
82.7k
        break;
13269
13.4k
    case PyUnicode_4BYTE_KIND:
13270
13.4k
        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13271
13.4k
        break;
13272
0
    default:
13273
0
        Py_UNREACHABLE();
13274
8.69M
    }
13275
13276
8.69M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13277
8.69M
    if (kind2 != kind1)
13278
96.2k
        PyMem_Free((void *)buf2);
13279
13280
8.69M
    return out;
13281
8.69M
}
13282
13283
13284
PyObject *
13285
PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
13286
54.5k
{
13287
54.5k
    PyObject* out;
13288
54.5k
    int kind1, kind2;
13289
54.5k
    const void *buf1, *buf2;
13290
54.5k
    Py_ssize_t len1, len2;
13291
13292
54.5k
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13293
0
        return NULL;
13294
13295
54.5k
    kind1 = PyUnicode_KIND(str_obj);
13296
54.5k
    kind2 = PyUnicode_KIND(sep_obj);
13297
54.5k
    len1 = PyUnicode_GET_LENGTH(str_obj);
13298
54.5k
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13299
54.5k
    if (kind1 < kind2 || len1 < len2) {
13300
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13301
0
        return PyTuple_Pack(3, empty, empty, str_obj);
13302
0
    }
13303
54.5k
    buf1 = PyUnicode_DATA(str_obj);
13304
54.5k
    buf2 = PyUnicode_DATA(sep_obj);
13305
54.5k
    if (kind2 != kind1) {
13306
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13307
0
        if (!buf2)
13308
0
            return NULL;
13309
0
    }
13310
13311
54.5k
    switch (kind1) {
13312
54.5k
    case PyUnicode_1BYTE_KIND:
13313
54.5k
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13314
54.5k
            out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13315
0
        else
13316
0
            out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13317
54.5k
        break;
13318
0
    case PyUnicode_2BYTE_KIND:
13319
0
        out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13320
0
        break;
13321
0
    case PyUnicode_4BYTE_KIND:
13322
0
        out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13323
0
        break;
13324
0
    default:
13325
0
        Py_UNREACHABLE();
13326
54.5k
    }
13327
13328
54.5k
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13329
54.5k
    if (kind2 != kind1)
13330
0
        PyMem_Free((void *)buf2);
13331
13332
54.5k
    return out;
13333
54.5k
}
13334
13335
/*[clinic input]
13336
str.partition as unicode_partition
13337
13338
    sep: object
13339
    /
13340
13341
Partition the string into three parts using the given separator.
13342
13343
This will search for the separator in the string.  If the separator
13344
is found, returns a 3-tuple containing the part before the
13345
separator, the separator itself, and the part after it.
13346
13347
If the separator is not found, returns a 3-tuple containing
13348
the original string and two empty strings.
13349
[clinic start generated code]*/
13350
13351
static PyObject *
13352
unicode_partition(PyObject *self, PyObject *sep)
13353
/*[clinic end generated code: output=e4ced7bd253ca3c4 input=e45faa8c26270cb1]*/
13354
8.70M
{
13355
8.70M
    return PyUnicode_Partition(self, sep);
13356
8.70M
}
13357
13358
/*[clinic input]
13359
str.rpartition as unicode_rpartition = str.partition
13360
13361
Partition the string into three parts using the given separator.
13362
13363
This will search for the separator in the string, starting at the
13364
end.  If the separator is found, returns a 3-tuple containing the
13365
part before the separator, the separator itself, and the part after
13366
it.
13367
13368
If the separator is not found, returns a 3-tuple containing two
13369
empty strings and the original string.
13370
[clinic start generated code]*/
13371
13372
static PyObject *
13373
unicode_rpartition(PyObject *self, PyObject *sep)
13374
/*[clinic end generated code: output=1aa13cf1156572aa input=53a7f8cb19975b7c]*/
13375
54.5k
{
13376
54.5k
    return PyUnicode_RPartition(self, sep);
13377
54.5k
}
13378
13379
PyObject *
13380
PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13381
0
{
13382
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13383
0
        return NULL;
13384
13385
0
    return rsplit(s, sep, maxsplit);
13386
0
}
13387
13388
/*[clinic input]
13389
@permit_long_summary
13390
str.rsplit as unicode_rsplit = str.split
13391
13392
Return a list of the substrings in the string, using sep as the separator string.
13393
13394
Splitting starts at the end of the string and works to the front.
13395
[clinic start generated code]*/
13396
13397
static PyObject *
13398
unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13399
/*[clinic end generated code: output=c2b815c63bcabffc input=0f762e30d267fa83]*/
13400
66
{
13401
66
    if (sep == Py_None)
13402
0
        return rsplit(self, NULL, maxsplit);
13403
66
    if (PyUnicode_Check(sep))
13404
66
        return rsplit(self, sep, maxsplit);
13405
13406
0
    PyErr_Format(PyExc_TypeError,
13407
0
                 "must be str or None, not %.100s",
13408
0
                 Py_TYPE(sep)->tp_name);
13409
0
    return NULL;
13410
66
}
13411
13412
/*[clinic input]
13413
@permit_long_summary
13414
str.splitlines as unicode_splitlines
13415
13416
    keepends: bool = False
13417
13418
Return a list of the lines in the string, breaking at line boundaries.
13419
13420
Line breaks are not included in the resulting list unless keepends
13421
is given and true.
13422
[clinic start generated code]*/
13423
13424
static PyObject *
13425
unicode_splitlines_impl(PyObject *self, int keepends)
13426
/*[clinic end generated code: output=f664dcdad153ec40 input=b45ea0f87645a06d]*/
13427
17.5k
{
13428
17.5k
    return PyUnicode_Splitlines(self, keepends);
13429
17.5k
}
13430
13431
static
13432
PyObject *unicode_str(PyObject *self)
13433
3.19M
{
13434
3.19M
    return unicode_result_unchanged(self);
13435
3.19M
}
13436
13437
/*[clinic input]
13438
@permit_long_summary
13439
str.swapcase as unicode_swapcase
13440
13441
Convert uppercase characters to lowercase and lowercase characters to uppercase.
13442
[clinic start generated code]*/
13443
13444
static PyObject *
13445
unicode_swapcase_impl(PyObject *self)
13446
/*[clinic end generated code: output=5d28966bf6d7b2af input=85bc39a9b4e8ee91]*/
13447
0
{
13448
0
    return case_operation(self, do_swapcase);
13449
0
}
13450
13451
static int
13452
unicode_maketrans_from_dict(PyObject *x, PyObject *newdict)
13453
0
{
13454
0
    PyObject *key, *value;
13455
0
    Py_ssize_t i = 0;
13456
0
    int res;
13457
0
    while (PyDict_Next(x, &i, &key, &value)) {
13458
0
        if (PyUnicode_Check(key)) {
13459
0
            PyObject *newkey;
13460
0
            int kind;
13461
0
            const void *data;
13462
0
            if (PyUnicode_GET_LENGTH(key) != 1) {
13463
0
                PyErr_SetString(PyExc_ValueError, "string keys in translate"
13464
0
                                "table must be of length 1");
13465
0
                return -1;
13466
0
            }
13467
0
            kind = PyUnicode_KIND(key);
13468
0
            data = PyUnicode_DATA(key);
13469
0
            newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
13470
0
            if (!newkey)
13471
0
                return -1;
13472
0
            res = PyDict_SetItem(newdict, newkey, value);
13473
0
            Py_DECREF(newkey);
13474
0
            if (res < 0)
13475
0
                return -1;
13476
0
        }
13477
0
        else if (PyLong_Check(key)) {
13478
0
            if (PyDict_SetItem(newdict, key, value) < 0)
13479
0
                return -1;
13480
0
        }
13481
0
        else {
13482
0
            PyErr_SetString(PyExc_TypeError, "keys in translate table must"
13483
0
                            "be strings or integers");
13484
0
            return -1;
13485
0
        }
13486
0
    }
13487
0
    return 0;
13488
0
}
13489
13490
/*[clinic input]
13491
13492
@staticmethod
13493
str.maketrans as unicode_maketrans
13494
13495
  x: object
13496
13497
  y: unicode=NULL
13498
13499
  z: unicode=NULL
13500
13501
  /
13502
13503
Return a translation table usable for str.translate().
13504
13505
If there is only one argument, it must be a dictionary mapping
13506
Unicode ordinals (integers) or characters to Unicode ordinals,
13507
strings or None.  Character keys will be then converted to ordinals.
13508
If there are two arguments, they must be strings of equal length,
13509
and in the resulting dictionary, each character in x will be mapped
13510
to the character at the same position in y.  If there is a third
13511
argument, it must be a string, whose characters will be mapped to
13512
None in the result.
13513
[clinic start generated code]*/
13514
13515
static PyObject *
13516
unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
13517
/*[clinic end generated code: output=a925c89452bd5881 input=66bc00a1b4258a6e]*/
13518
4
{
13519
4
    PyObject *new = NULL, *key, *value;
13520
4
    Py_ssize_t i = 0;
13521
4
    int res;
13522
13523
4
    new = PyDict_New();
13524
4
    if (!new)
13525
0
        return NULL;
13526
4
    if (y != NULL) {
13527
4
        int x_kind, y_kind, z_kind;
13528
4
        const void *x_data, *y_data, *z_data;
13529
13530
        /* x must be a string too, of equal length */
13531
4
        if (!PyUnicode_Check(x)) {
13532
0
            PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13533
0
                            "be a string if there is a second argument");
13534
0
            goto err;
13535
0
        }
13536
4
        if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
13537
0
            PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13538
0
                            "arguments must have equal length");
13539
0
            goto err;
13540
0
        }
13541
        /* create entries for translating chars in x to those in y */
13542
4
        x_kind = PyUnicode_KIND(x);
13543
4
        y_kind = PyUnicode_KIND(y);
13544
4
        x_data = PyUnicode_DATA(x);
13545
4
        y_data = PyUnicode_DATA(y);
13546
36
        for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13547
32
            key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
13548
32
            if (!key)
13549
0
                goto err;
13550
32
            value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
13551
32
            if (!value) {
13552
0
                Py_DECREF(key);
13553
0
                goto err;
13554
0
            }
13555
32
            res = PyDict_SetItem(new, key, value);
13556
32
            Py_DECREF(key);
13557
32
            Py_DECREF(value);
13558
32
            if (res < 0)
13559
0
                goto err;
13560
32
        }
13561
        /* create entries for deleting chars in z */
13562
4
        if (z != NULL) {
13563
0
            z_kind = PyUnicode_KIND(z);
13564
0
            z_data = PyUnicode_DATA(z);
13565
0
            for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
13566
0
                key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
13567
0
                if (!key)
13568
0
                    goto err;
13569
0
                res = PyDict_SetItem(new, key, Py_None);
13570
0
                Py_DECREF(key);
13571
0
                if (res < 0)
13572
0
                    goto err;
13573
0
            }
13574
0
        }
13575
4
    } else {
13576
        /* x must be a dict */
13577
0
        if (!PyAnyDict_CheckExact(x)) {
13578
0
            PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13579
0
                            "to maketrans it must be a dict");
13580
0
            goto err;
13581
0
        }
13582
        /* copy entries into the new dict, converting string keys to int keys */
13583
0
        int errcode;
13584
0
        Py_BEGIN_CRITICAL_SECTION(x);
13585
0
        errcode = unicode_maketrans_from_dict(x, new);
13586
0
        Py_END_CRITICAL_SECTION();
13587
0
        if (errcode < 0)
13588
0
            goto err;
13589
0
    }
13590
4
    return new;
13591
0
  err:
13592
0
    Py_DECREF(new);
13593
0
    return NULL;
13594
4
}
13595
13596
/*[clinic input]
13597
@permit_long_summary
13598
str.translate as unicode_translate
13599
13600
    table: object
13601
        Translation table, which must be a mapping of Unicode ordinals
13602
        to Unicode ordinals, strings, or None.
13603
    /
13604
13605
Replace each character in the string using the given translation table.
13606
13607
The table must implement lookup/indexing via __getitem__, for
13608
instance a dictionary or list.  If this operation raises
13609
LookupError, the character is left untouched.  Characters mapped to
13610
None are deleted.
13611
[clinic start generated code]*/
13612
13613
static PyObject *
13614
unicode_translate(PyObject *self, PyObject *table)
13615
/*[clinic end generated code: output=3cb448ff2fd96bf3 input=48cf0efe06bc1b75]*/
13616
300
{
13617
300
    return _PyUnicode_TranslateCharmap(self, table, "ignore");
13618
300
}
13619
13620
/*[clinic input]
13621
str.upper as unicode_upper
13622
13623
Return a copy of the string converted to uppercase.
13624
[clinic start generated code]*/
13625
13626
static PyObject *
13627
unicode_upper_impl(PyObject *self)
13628
/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
13629
306
{
13630
306
    if (PyUnicode_IS_ASCII(self))
13631
306
        return ascii_upper_or_lower(self, 0);
13632
0
    return case_operation(self, do_upper);
13633
306
}
13634
13635
/*[clinic input]
13636
@permit_long_summary
13637
str.zfill as unicode_zfill
13638
13639
    width: Py_ssize_t
13640
    /
13641
13642
Pad a numeric string with zeros on the left, to fill a field of the given width.
13643
13644
The string is never truncated.
13645
[clinic start generated code]*/
13646
13647
static PyObject *
13648
unicode_zfill_impl(PyObject *self, Py_ssize_t width)
13649
/*[clinic end generated code: output=e13fb6bdf8e3b9df input=25a4ee0ea3e58ce0]*/
13650
0
{
13651
0
    Py_ssize_t fill;
13652
0
    PyObject *u;
13653
0
    int kind;
13654
0
    const void *data;
13655
0
    Py_UCS4 chr;
13656
13657
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13658
0
        return unicode_result_unchanged(self);
13659
13660
0
    fill = width - PyUnicode_GET_LENGTH(self);
13661
13662
0
    u = pad(self, fill, 0, '0');
13663
13664
0
    if (u == NULL)
13665
0
        return NULL;
13666
13667
0
    kind = PyUnicode_KIND(u);
13668
0
    data = PyUnicode_DATA(u);
13669
0
    chr = PyUnicode_READ(kind, data, fill);
13670
13671
0
    if (chr == '+' || chr == '-') {
13672
        /* move sign to beginning of string */
13673
0
        PyUnicode_WRITE(kind, data, 0, chr);
13674
0
        PyUnicode_WRITE(kind, data, fill, '0');
13675
0
    }
13676
13677
0
    assert(_PyUnicode_CheckConsistency(u, 1));
13678
0
    return u;
13679
0
}
13680
13681
/*[clinic input]
13682
@permit_long_summary
13683
@text_signature "($self, prefix[, start[, end]], /)"
13684
str.startswith as unicode_startswith
13685
13686
    prefix as subobj: object
13687
        A string or a tuple of strings to try.
13688
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13689
        Optional start position. Default: start of the string.
13690
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13691
        Optional stop position. Default: end of the string.
13692
    /
13693
13694
Return True if the string starts with the specified prefix, False otherwise.
13695
[clinic start generated code]*/
13696
13697
static PyObject *
13698
unicode_startswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13699
                        Py_ssize_t end)
13700
/*[clinic end generated code: output=4bd7cfd0803051d4 input=766bdbd33df251dc]*/
13701
41.9M
{
13702
41.9M
    if (PyTuple_Check(subobj)) {
13703
1.64M
        Py_ssize_t i;
13704
6.02M
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13705
4.39M
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13706
4.39M
            if (!PyUnicode_Check(substring)) {
13707
0
                PyErr_Format(PyExc_TypeError,
13708
0
                             "tuple for startswith must only contain str, "
13709
0
                             "not %.100s",
13710
0
                             Py_TYPE(substring)->tp_name);
13711
0
                return NULL;
13712
0
            }
13713
4.39M
            int result = tailmatch(self, substring, start, end, -1);
13714
4.39M
            if (result < 0) {
13715
0
                return NULL;
13716
0
            }
13717
4.39M
            if (result) {
13718
19.1k
                Py_RETURN_TRUE;
13719
19.1k
            }
13720
4.39M
        }
13721
        /* nothing matched */
13722
1.64M
        Py_RETURN_FALSE;
13723
1.64M
    }
13724
40.2M
    if (!PyUnicode_Check(subobj)) {
13725
0
        PyErr_Format(PyExc_TypeError,
13726
0
                     "startswith first arg must be str or "
13727
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13728
0
        return NULL;
13729
0
    }
13730
40.2M
    int result = tailmatch(self, subobj, start, end, -1);
13731
40.2M
    if (result < 0) {
13732
0
        return NULL;
13733
0
    }
13734
40.2M
    return PyBool_FromLong(result);
13735
40.2M
}
13736
13737
13738
/*[clinic input]
13739
@permit_long_summary
13740
@text_signature "($self, suffix[, start[, end]], /)"
13741
str.endswith as unicode_endswith
13742
13743
    suffix as subobj: object
13744
        A string or a tuple of strings to try.
13745
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13746
        Optional start position. Default: start of the string.
13747
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13748
        Optional stop position. Default: end of the string.
13749
    /
13750
13751
Return True if the string ends with the specified suffix, False otherwise.
13752
[clinic start generated code]*/
13753
13754
static PyObject *
13755
unicode_endswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13756
                      Py_ssize_t end)
13757
/*[clinic end generated code: output=cce6f8ceb0102ca9 input=b66bf6d5547ba1aa]*/
13758
11.1M
{
13759
11.1M
    if (PyTuple_Check(subobj)) {
13760
180k
        Py_ssize_t i;
13761
349k
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13762
319k
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13763
319k
            if (!PyUnicode_Check(substring)) {
13764
0
                PyErr_Format(PyExc_TypeError,
13765
0
                             "tuple for endswith must only contain str, "
13766
0
                             "not %.100s",
13767
0
                             Py_TYPE(substring)->tp_name);
13768
0
                return NULL;
13769
0
            }
13770
319k
            int result = tailmatch(self, substring, start, end, +1);
13771
319k
            if (result < 0) {
13772
0
                return NULL;
13773
0
            }
13774
319k
            if (result) {
13775
150k
                Py_RETURN_TRUE;
13776
150k
            }
13777
319k
        }
13778
180k
        Py_RETURN_FALSE;
13779
180k
    }
13780
10.9M
    if (!PyUnicode_Check(subobj)) {
13781
0
        PyErr_Format(PyExc_TypeError,
13782
0
                     "endswith first arg must be str or "
13783
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13784
0
        return NULL;
13785
0
    }
13786
10.9M
    int result = tailmatch(self, subobj, start, end, +1);
13787
10.9M
    if (result < 0) {
13788
0
        return NULL;
13789
0
    }
13790
10.9M
    return PyBool_FromLong(result);
13791
10.9M
}
13792
13793
13794
#include "stringlib/unicode_format.h"
13795
13796
PyDoc_STRVAR(format__doc__,
13797
             "format($self, /, *args, **kwargs)\n\
13798
--\n\
13799
\n\
13800
Return a formatted version of the string, using substitutions from args and kwargs.\n\
13801
The substitutions are identified by braces ('{' and '}').");
13802
13803
PyDoc_STRVAR(format_map__doc__,
13804
             "format_map($self, mapping, /)\n\
13805
--\n\
13806
\n\
13807
Return a formatted version of the string, using substitutions from mapping.\n\
13808
The substitutions are identified by braces ('{' and '}').");
13809
13810
/*[clinic input]
13811
@permit_long_summary
13812
str.__format__ as unicode___format__
13813
13814
    format_spec: unicode
13815
    /
13816
13817
Return a formatted version of the string as described by format_spec.
13818
[clinic start generated code]*/
13819
13820
static PyObject *
13821
unicode___format___impl(PyObject *self, PyObject *format_spec)
13822
/*[clinic end generated code: output=45fceaca6d2ba4c8 input=77a2a19f3f7969f2]*/
13823
0
{
13824
0
    _PyUnicodeWriter writer;
13825
0
    int ret;
13826
13827
0
    _PyUnicodeWriter_Init(&writer);
13828
0
    ret = _PyUnicode_FormatAdvancedWriter(&writer,
13829
0
                                          self, format_spec, 0,
13830
0
                                          PyUnicode_GET_LENGTH(format_spec));
13831
0
    if (ret == -1) {
13832
0
        _PyUnicodeWriter_Dealloc(&writer);
13833
0
        return NULL;
13834
0
    }
13835
0
    return _PyUnicodeWriter_Finish(&writer);
13836
0
}
13837
13838
/*[clinic input]
13839
str.__sizeof__ as unicode_sizeof
13840
13841
Return the size of the string in memory, in bytes.
13842
[clinic start generated code]*/
13843
13844
static PyObject *
13845
unicode_sizeof_impl(PyObject *self)
13846
/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
13847
0
{
13848
0
    Py_ssize_t size;
13849
13850
    /* If it's a compact object, account for base structure +
13851
       character data. */
13852
0
    if (PyUnicode_IS_COMPACT_ASCII(self)) {
13853
0
        size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13854
0
    }
13855
0
    else if (PyUnicode_IS_COMPACT(self)) {
13856
0
        size = sizeof(PyCompactUnicodeObject) +
13857
0
            (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
13858
0
    }
13859
0
    else {
13860
        /* If it is a two-block object, account for base object, and
13861
           for character block if present. */
13862
0
        size = sizeof(PyUnicodeObject);
13863
0
        if (_PyUnicode_DATA_ANY(self))
13864
0
            size += (PyUnicode_GET_LENGTH(self) + 1) *
13865
0
                PyUnicode_KIND(self);
13866
0
    }
13867
0
    if (_PyUnicode_HAS_UTF8_MEMORY(self))
13868
0
        size += PyUnicode_UTF8_LENGTH(self) + 1;
13869
13870
0
    return PyLong_FromSsize_t(size);
13871
0
}
13872
13873
static PyObject *
13874
unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
13875
0
{
13876
0
    PyObject *copy = _PyUnicode_Copy(v);
13877
0
    if (!copy)
13878
0
        return NULL;
13879
0
    return Py_BuildValue("(N)", copy);
13880
0
}
13881
13882
/*
13883
This function searchs the longest common leading whitespace
13884
of all lines in the [src, end).
13885
It returns the length of the common leading whitespace and sets `output` to
13886
point to the beginning of the common leading whitespace if length > 0.
13887
*/
13888
static Py_ssize_t
13889
search_longest_common_leading_whitespace(
13890
    const char *const src,
13891
    const char *const end,
13892
    const char **output)
13893
0
{
13894
    // [_start, _start + _len)
13895
    // describes the current longest common leading whitespace
13896
0
    const char *_start = NULL;
13897
0
    Py_ssize_t _len = 0;
13898
13899
0
    for (const char *iter = src; iter < end; ++iter) {
13900
0
        const char *line_start = iter;
13901
0
        const char *leading_whitespace_end = NULL;
13902
13903
        // scan the whole line
13904
0
        while (iter < end && *iter != '\n') {
13905
0
            if (!leading_whitespace_end && *iter != ' ' && *iter != '\t') {
13906
                /* `iter` points to the first non-whitespace character
13907
                   in this line */
13908
0
                if (iter == line_start) {
13909
                    // some line has no indent, fast exit!
13910
0
                    return 0;
13911
0
                }
13912
0
                leading_whitespace_end = iter;
13913
0
            }
13914
0
            ++iter;
13915
0
        }
13916
13917
        // if this line has all white space, skip it
13918
0
        if (!leading_whitespace_end) {
13919
0
            continue;
13920
0
        }
13921
13922
0
        if (!_start) {
13923
            // update the first leading whitespace
13924
0
            _start = line_start;
13925
0
            _len = leading_whitespace_end - line_start;
13926
0
            assert(_len > 0);
13927
0
        }
13928
0
        else {
13929
            /* We then compare with the current longest leading whitespace.
13930
13931
               [line_start, leading_whitespace_end) is the leading
13932
               whitespace of this line,
13933
13934
               [_start, _start + _len) is the leading whitespace of the
13935
               current longest leading whitespace. */
13936
0
            Py_ssize_t new_len = 0;
13937
0
            const char *_iter = _start, *line_iter = line_start;
13938
13939
0
            while (_iter < _start + _len && line_iter < leading_whitespace_end
13940
0
                   && *_iter == *line_iter)
13941
0
            {
13942
0
                ++_iter;
13943
0
                ++line_iter;
13944
0
                ++new_len;
13945
0
            }
13946
13947
0
            _len = new_len;
13948
0
            if (_len == 0) {
13949
                // No common things now, fast exit!
13950
0
                return 0;
13951
0
            }
13952
0
        }
13953
0
    }
13954
13955
0
    assert(_len >= 0);
13956
0
    if (_len > 0) {
13957
0
        *output = _start;
13958
0
    }
13959
0
    return _len;
13960
0
}
13961
13962
/* Dedent a string.
13963
   Intended to dedent Python source. Unlike `textwrap.dedent`, this
13964
   only supports spaces and tabs and doesn't normalize empty lines.
13965
   Return a new reference on success, NULL with exception set on error.
13966
   */
13967
PyObject *
13968
_PyUnicode_Dedent(PyObject *unicode)
13969
0
{
13970
0
    Py_ssize_t src_len = 0;
13971
0
    const char *src = PyUnicode_AsUTF8AndSize(unicode, &src_len);
13972
0
    if (!src) {
13973
0
        return NULL;
13974
0
    }
13975
0
    assert(src_len >= 0);
13976
0
    if (src_len == 0) {
13977
0
        return Py_NewRef(unicode);
13978
0
    }
13979
13980
0
    const char *const end = src + src_len;
13981
13982
    // [whitespace_start, whitespace_start + whitespace_len)
13983
    // describes the current longest common leading whitespace
13984
0
    const char *whitespace_start = NULL;
13985
0
    Py_ssize_t whitespace_len = search_longest_common_leading_whitespace(
13986
0
        src, end, &whitespace_start);
13987
13988
0
    if (whitespace_len == 0) {
13989
0
        return Py_NewRef(unicode);
13990
0
    }
13991
13992
    // now we should trigger a dedent
13993
0
    char *dest = PyMem_Malloc(src_len);
13994
0
    if (!dest) {
13995
0
        PyErr_NoMemory();
13996
0
        return NULL;
13997
0
    }
13998
0
    char *dest_iter = dest;
13999
14000
0
    for (const char *iter = src; iter < end; ++iter) {
14001
0
        const char *line_start = iter;
14002
0
        bool in_leading_space = true;
14003
14004
        // iterate over a line to find the end of a line
14005
0
        while (iter < end && *iter != '\n') {
14006
0
            if (in_leading_space && *iter != ' ' && *iter != '\t') {
14007
0
                in_leading_space = false;
14008
0
            }
14009
0
            ++iter;
14010
0
        }
14011
14012
        // invariant: *iter == '\n' or iter == end
14013
0
        bool append_newline = iter < end;
14014
14015
        // if this line has all white space, write '\n' and continue
14016
0
        if (in_leading_space && append_newline) {
14017
0
            *dest_iter++ = '\n';
14018
0
            continue;
14019
0
        }
14020
14021
        /* copy [new_line_start + whitespace_len, iter) to buffer, then
14022
            conditionally append '\n' */
14023
14024
0
        Py_ssize_t new_line_len = iter - line_start - whitespace_len;
14025
0
        assert(new_line_len >= 0);
14026
0
        memcpy(dest_iter, line_start + whitespace_len, new_line_len);
14027
14028
0
        dest_iter += new_line_len;
14029
14030
0
        if (append_newline) {
14031
0
            *dest_iter++ = '\n';
14032
0
        }
14033
0
    }
14034
14035
0
    PyObject *res = PyUnicode_FromStringAndSize(dest, dest_iter - dest);
14036
0
    PyMem_Free(dest);
14037
0
    return res;
14038
0
}
14039
14040
static PyMethodDef unicode_methods[] = {
14041
    UNICODE_ENCODE_METHODDEF
14042
    UNICODE_REPLACE_METHODDEF
14043
    UNICODE_SPLIT_METHODDEF
14044
    UNICODE_RSPLIT_METHODDEF
14045
    UNICODE_JOIN_METHODDEF
14046
    UNICODE_CAPITALIZE_METHODDEF
14047
    UNICODE_CASEFOLD_METHODDEF
14048
    UNICODE_TITLE_METHODDEF
14049
    UNICODE_CENTER_METHODDEF
14050
    UNICODE_COUNT_METHODDEF
14051
    UNICODE_EXPANDTABS_METHODDEF
14052
    UNICODE_FIND_METHODDEF
14053
    UNICODE_PARTITION_METHODDEF
14054
    UNICODE_INDEX_METHODDEF
14055
    UNICODE_LJUST_METHODDEF
14056
    UNICODE_LOWER_METHODDEF
14057
    UNICODE_LSTRIP_METHODDEF
14058
    UNICODE_RFIND_METHODDEF
14059
    UNICODE_RINDEX_METHODDEF
14060
    UNICODE_RJUST_METHODDEF
14061
    UNICODE_RSTRIP_METHODDEF
14062
    UNICODE_RPARTITION_METHODDEF
14063
    UNICODE_SPLITLINES_METHODDEF
14064
    UNICODE_STRIP_METHODDEF
14065
    UNICODE_SWAPCASE_METHODDEF
14066
    UNICODE_TRANSLATE_METHODDEF
14067
    UNICODE_UPPER_METHODDEF
14068
    UNICODE_STARTSWITH_METHODDEF
14069
    UNICODE_ENDSWITH_METHODDEF
14070
    UNICODE_REMOVEPREFIX_METHODDEF
14071
    UNICODE_REMOVESUFFIX_METHODDEF
14072
    UNICODE_ISASCII_METHODDEF
14073
    UNICODE_ISLOWER_METHODDEF
14074
    UNICODE_ISUPPER_METHODDEF
14075
    UNICODE_ISTITLE_METHODDEF
14076
    UNICODE_ISSPACE_METHODDEF
14077
    UNICODE_ISDECIMAL_METHODDEF
14078
    UNICODE_ISDIGIT_METHODDEF
14079
    UNICODE_ISNUMERIC_METHODDEF
14080
    UNICODE_ISALPHA_METHODDEF
14081
    UNICODE_ISALNUM_METHODDEF
14082
    UNICODE_ISIDENTIFIER_METHODDEF
14083
    UNICODE_ISPRINTABLE_METHODDEF
14084
    UNICODE_ZFILL_METHODDEF
14085
    {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
14086
    {"format_map", do_string_format_map, METH_O, format_map__doc__},
14087
    UNICODE___FORMAT___METHODDEF
14088
    UNICODE_MAKETRANS_METHODDEF
14089
    UNICODE_SIZEOF_METHODDEF
14090
    {"__getnewargs__",  unicode_getnewargs, METH_NOARGS},
14091
    {NULL, NULL}
14092
};
14093
14094
static PyObject *
14095
unicode_mod(PyObject *v, PyObject *w)
14096
12.1M
{
14097
12.1M
    if (!PyUnicode_Check(v))
14098
0
        Py_RETURN_NOTIMPLEMENTED;
14099
12.1M
    return PyUnicode_Format(v, w);
14100
12.1M
}
14101
14102
static PyNumberMethods unicode_as_number = {
14103
    0,              /*nb_add*/
14104
    0,              /*nb_subtract*/
14105
    0,              /*nb_multiply*/
14106
    unicode_mod,            /*nb_remainder*/
14107
};
14108
14109
static PySequenceMethods unicode_as_sequence = {
14110
    unicode_length,     /* sq_length */
14111
    PyUnicode_Concat,   /* sq_concat */
14112
    _PyUnicode_Repeat,  /* sq_repeat */
14113
    unicode_getitem,    /* sq_item */
14114
    0,                  /* sq_slice */
14115
    0,                  /* sq_ass_item */
14116
    0,                  /* sq_ass_slice */
14117
    PyUnicode_Contains, /* sq_contains */
14118
};
14119
14120
static PyObject*
14121
unicode_subscript(PyObject* self, PyObject* item)
14122
82.3M
{
14123
82.3M
    if (_PyIndex_Check(item)) {
14124
61.6M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
14125
61.6M
        if (i == -1 && PyErr_Occurred())
14126
0
            return NULL;
14127
61.6M
        if (i < 0)
14128
65.3k
            i += PyUnicode_GET_LENGTH(self);
14129
61.6M
        return unicode_getitem(self, i);
14130
61.6M
    } else if (PySlice_Check(item)) {
14131
20.6M
        Py_ssize_t start, stop, step, slicelength, i;
14132
20.6M
        size_t cur;
14133
20.6M
        PyObject *result;
14134
20.6M
        const void *src_data;
14135
20.6M
        void *dest_data;
14136
20.6M
        int src_kind, dest_kind;
14137
20.6M
        Py_UCS4 ch, max_char, kind_limit;
14138
14139
20.6M
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
14140
0
            return NULL;
14141
0
        }
14142
20.6M
        slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14143
20.6M
                                            &start, &stop, step);
14144
14145
20.6M
        if (slicelength <= 0) {
14146
1.20M
            _Py_RETURN_UNICODE_EMPTY();
14147
19.4M
        } else if (start == 0 && step == 1 &&
14148
6.80M
                   slicelength == PyUnicode_GET_LENGTH(self)) {
14149
5.04M
            return unicode_result_unchanged(self);
14150
14.3M
        } else if (step == 1) {
14151
14.3M
            return PyUnicode_Substring(self,
14152
14.3M
                                       start, start + slicelength);
14153
14.3M
        }
14154
        /* General case */
14155
0
        src_kind = PyUnicode_KIND(self);
14156
0
        src_data = PyUnicode_DATA(self);
14157
0
        if (!PyUnicode_IS_ASCII(self)) {
14158
0
            kind_limit = kind_maxchar_limit(src_kind);
14159
0
            max_char = 0;
14160
0
            for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14161
0
                ch = PyUnicode_READ(src_kind, src_data, cur);
14162
0
                if (ch > max_char) {
14163
0
                    max_char = ch;
14164
0
                    if (max_char >= kind_limit)
14165
0
                        break;
14166
0
                }
14167
0
            }
14168
0
        }
14169
0
        else
14170
0
            max_char = 127;
14171
0
        result = PyUnicode_New(slicelength, max_char);
14172
0
        if (result == NULL)
14173
0
            return NULL;
14174
0
        dest_kind = PyUnicode_KIND(result);
14175
0
        dest_data = PyUnicode_DATA(result);
14176
14177
0
        for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14178
0
            Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14179
0
            PyUnicode_WRITE(dest_kind, dest_data, i, ch);
14180
0
        }
14181
0
        assert(_PyUnicode_CheckConsistency(result, 1));
14182
0
        return result;
14183
0
    } else {
14184
0
        PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
14185
0
                     Py_TYPE(item)->tp_name);
14186
0
        return NULL;
14187
0
    }
14188
82.3M
}
14189
14190
static PyMappingMethods unicode_as_mapping = {
14191
    unicode_length,     /* mp_length */
14192
    unicode_subscript,  /* mp_subscript */
14193
    0,                  /* mp_ass_subscript */
14194
};
14195
14196
14197
static PyObject *
14198
unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
14199
14200
/*[clinic input]
14201
@classmethod
14202
str.__new__ as unicode_new
14203
14204
    object as x: object = NULL
14205
    encoding: str = NULL
14206
    errors: str = NULL
14207
14208
[clinic start generated code]*/
14209
14210
static PyObject *
14211
unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
14212
                 const char *errors)
14213
/*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
14214
11.1M
{
14215
11.1M
    PyObject *unicode;
14216
11.1M
    if (x == NULL) {
14217
0
        unicode = _PyUnicode_GetEmpty();
14218
0
    }
14219
11.1M
    else if (encoding == NULL && errors == NULL) {
14220
11.1M
        unicode = PyObject_Str(x);
14221
11.1M
    }
14222
0
    else {
14223
0
        unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
14224
0
    }
14225
14226
11.1M
    if (unicode != NULL && type != &PyUnicode_Type) {
14227
11.1M
        Py_SETREF(unicode, unicode_subtype_new(type, unicode));
14228
11.1M
    }
14229
11.1M
    return unicode;
14230
11.1M
}
14231
14232
static const char *
14233
arg_as_utf8(PyObject *obj, const char *name)
14234
2.84M
{
14235
2.84M
    if (!PyUnicode_Check(obj)) {
14236
0
        PyErr_Format(PyExc_TypeError,
14237
0
                     "str() argument '%s' must be str, not %T",
14238
0
                     name, obj);
14239
0
        return NULL;
14240
0
    }
14241
2.84M
    return _PyUnicode_AsUTF8NoNUL(obj);
14242
2.84M
}
14243
14244
static PyObject *
14245
unicode_vectorcall(PyObject *type, PyObject *const *args,
14246
                   size_t nargsf, PyObject *kwnames)
14247
2.51M
{
14248
2.51M
    assert(Py_Is(_PyType_CAST(type), &PyUnicode_Type));
14249
14250
2.51M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
14251
2.51M
    if (kwnames != NULL && PyTuple_GET_SIZE(kwnames) != 0) {
14252
        // Fallback to unicode_new()
14253
0
        PyObject *tuple = PyTuple_FromArray(args, nargs);
14254
0
        if (tuple == NULL) {
14255
0
            return NULL;
14256
0
        }
14257
0
        PyObject *dict = _PyStack_AsDict(args + nargs, kwnames);
14258
0
        if (dict == NULL) {
14259
0
            Py_DECREF(tuple);
14260
0
            return NULL;
14261
0
        }
14262
0
        PyObject *ret = unicode_new(_PyType_CAST(type), tuple, dict);
14263
0
        Py_DECREF(tuple);
14264
0
        Py_DECREF(dict);
14265
0
        return ret;
14266
0
    }
14267
2.51M
    if (!_PyArg_CheckPositional("str", nargs, 0, 3)) {
14268
0
        return NULL;
14269
0
    }
14270
2.51M
    if (nargs == 0) {
14271
4.30k
        return _PyUnicode_GetEmpty();
14272
4.30k
    }
14273
2.50M
    PyObject *object = args[0];
14274
2.50M
    if (nargs == 1) {
14275
1.13k
        return PyObject_Str(object);
14276
1.13k
    }
14277
2.50M
    const char *encoding = arg_as_utf8(args[1], "encoding");
14278
2.50M
    if (encoding == NULL) {
14279
0
        return NULL;
14280
0
    }
14281
2.50M
    const char *errors = NULL;
14282
2.50M
    if (nargs == 3) {
14283
335k
        errors = arg_as_utf8(args[2], "errors");
14284
335k
        if (errors == NULL) {
14285
0
            return NULL;
14286
0
        }
14287
335k
    }
14288
2.50M
    return PyUnicode_FromEncodedObject(object, encoding, errors);
14289
2.50M
}
14290
14291
static PyObject *
14292
unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
14293
11.1M
{
14294
11.1M
    PyObject *self;
14295
11.1M
    Py_ssize_t length, char_size;
14296
11.1M
    int share_utf8;
14297
11.1M
    int kind;
14298
11.1M
    void *data;
14299
14300
11.1M
    assert(PyType_IsSubtype(type, &PyUnicode_Type));
14301
11.1M
    assert(_PyUnicode_CHECK(unicode));
14302
14303
11.1M
    self = type->tp_alloc(type, 0);
14304
11.1M
    if (self == NULL) {
14305
0
        return NULL;
14306
0
    }
14307
11.1M
    kind = PyUnicode_KIND(unicode);
14308
11.1M
    length = PyUnicode_GET_LENGTH(unicode);
14309
14310
11.1M
    _PyUnicode_LENGTH(self) = length;
14311
#ifdef Py_DEBUG
14312
    _PyUnicode_HASH(self) = -1;
14313
#else
14314
11.1M
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14315
11.1M
#endif
14316
11.1M
    _PyUnicode_STATE(self).interned = 0;
14317
11.1M
    _PyUnicode_STATE(self).kind = kind;
14318
11.1M
    _PyUnicode_STATE(self).compact = 0;
14319
11.1M
    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
14320
11.1M
    _PyUnicode_STATE(self).statically_allocated = 0;
14321
11.1M
    PyUnicode_SET_UTF8_LENGTH(self, 0);
14322
11.1M
    PyUnicode_SET_UTF8(self, NULL);
14323
11.1M
    _PyUnicode_DATA_ANY(self) = NULL;
14324
14325
11.1M
    share_utf8 = 0;
14326
11.1M
    if (kind == PyUnicode_1BYTE_KIND) {
14327
9.86M
        char_size = 1;
14328
9.86M
        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14329
9.83M
            share_utf8 = 1;
14330
9.86M
    }
14331
1.23M
    else if (kind == PyUnicode_2BYTE_KIND) {
14332
1.18M
        char_size = 2;
14333
1.18M
    }
14334
49.5k
    else {
14335
49.5k
        assert(kind == PyUnicode_4BYTE_KIND);
14336
49.5k
        char_size = 4;
14337
49.5k
    }
14338
14339
    /* Ensure we won't overflow the length. */
14340
11.1M
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14341
0
        PyErr_NoMemory();
14342
0
        goto onError;
14343
0
    }
14344
11.1M
    data = PyMem_Malloc((length + 1) * char_size);
14345
11.1M
    if (data == NULL) {
14346
0
        PyErr_NoMemory();
14347
0
        goto onError;
14348
0
    }
14349
14350
11.1M
    _PyUnicode_DATA_ANY(self) = data;
14351
11.1M
    if (share_utf8) {
14352
9.83M
        PyUnicode_SET_UTF8_LENGTH(self, length);
14353
9.83M
        PyUnicode_SET_UTF8(self, data);
14354
9.83M
    }
14355
14356
11.1M
    memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
14357
11.1M
    assert(_PyUnicode_CheckConsistency(self, 1));
14358
#ifdef Py_DEBUG
14359
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14360
#endif
14361
11.1M
    return self;
14362
14363
0
onError:
14364
0
    Py_DECREF(self);
14365
0
    return NULL;
14366
11.1M
}
14367
14368
static _PyObjectIndexPair
14369
unicode_iteritem(PyObject *obj, Py_ssize_t index)
14370
47.0M
{
14371
47.0M
    if (index >= PyUnicode_GET_LENGTH(obj)) {
14372
3.91M
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
14373
3.91M
    }
14374
43.1M
    const void *data = PyUnicode_DATA(obj);
14375
43.1M
    int kind = PyUnicode_KIND(obj);
14376
43.1M
    Py_UCS4 ch = PyUnicode_READ(kind, data, index);
14377
43.1M
    PyObject *result = unicode_char(ch);
14378
43.1M
    index = (result == NULL) ? -1 : index + 1;
14379
43.1M
    return (_PyObjectIndexPair) { .object = result, .index = index };
14380
47.0M
}
14381
14382
void
14383
_PyUnicode_ExactDealloc(PyObject *op)
14384
73.0M
{
14385
73.0M
    assert(PyUnicode_CheckExact(op));
14386
73.0M
    unicode_dealloc(op);
14387
73.0M
}
14388
14389
PyDoc_STRVAR(unicode_doc,
14390
"str(object='') -> str\n\
14391
str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
14392
\n\
14393
Create a new string object from the given object. If encoding or\n\
14394
errors is specified, then the object must expose a data buffer\n\
14395
that will be decoded using the given encoding and error handler.\n\
14396
Otherwise, returns the result of object.__str__() (if defined)\n\
14397
or repr(object).\n\
14398
encoding defaults to 'utf-8'.\n\
14399
errors defaults to 'strict'.");
14400
14401
static PyObject *unicode_iter(PyObject *seq);
14402
14403
PyTypeObject PyUnicode_Type = {
14404
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
14405
    "str",                        /* tp_name */
14406
    sizeof(PyUnicodeObject),      /* tp_basicsize */
14407
    0,                            /* tp_itemsize */
14408
    /* Slots */
14409
    unicode_dealloc,              /* tp_dealloc */
14410
    0,                            /* tp_vectorcall_offset */
14411
    0,                            /* tp_getattr */
14412
    0,                            /* tp_setattr */
14413
    0,                            /* tp_as_async */
14414
    unicode_repr,                 /* tp_repr */
14415
    &unicode_as_number,           /* tp_as_number */
14416
    &unicode_as_sequence,         /* tp_as_sequence */
14417
    &unicode_as_mapping,          /* tp_as_mapping */
14418
    unicode_hash,                 /* tp_hash*/
14419
    0,                            /* tp_call*/
14420
    unicode_str,                  /* tp_str */
14421
    PyObject_GenericGetAttr,      /* tp_getattro */
14422
    0,                            /* tp_setattro */
14423
    0,                            /* tp_as_buffer */
14424
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
14425
        Py_TPFLAGS_UNICODE_SUBCLASS |
14426
        _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
14427
    unicode_doc,                  /* tp_doc */
14428
    0,                            /* tp_traverse */
14429
    0,                            /* tp_clear */
14430
    PyUnicode_RichCompare,        /* tp_richcompare */
14431
    0,                            /* tp_weaklistoffset */
14432
    unicode_iter,                 /* tp_iter */
14433
    0,                            /* tp_iternext */
14434
    unicode_methods,              /* tp_methods */
14435
    0,                            /* tp_members */
14436
    0,                            /* tp_getset */
14437
    0,                            /* tp_base */
14438
    0,                            /* tp_dict */
14439
    0,                            /* tp_descr_get */
14440
    0,                            /* tp_descr_set */
14441
    0,                            /* tp_dictoffset */
14442
    0,                            /* tp_init */
14443
    0,                            /* tp_alloc */
14444
    unicode_new,                  /* tp_new */
14445
    PyObject_Free,                /* tp_free */
14446
    .tp_vectorcall = unicode_vectorcall,
14447
    ._tp_iteritem = unicode_iteritem,
14448
};
14449
14450
/* Initialize the Unicode implementation */
14451
14452
static void
14453
_init_global_state(void)
14454
36
{
14455
36
    static int initialized = 0;
14456
36
    if (initialized) {
14457
0
        return;
14458
0
    }
14459
36
    initialized = 1;
14460
14461
    /* initialize the linebreak bloom filter */
14462
36
    const Py_UCS2 linebreak[] = {
14463
36
        0x000A, /* LINE FEED */
14464
36
        0x000D, /* CARRIAGE RETURN */
14465
36
        0x001C, /* FILE SEPARATOR */
14466
36
        0x001D, /* GROUP SEPARATOR */
14467
36
        0x001E, /* RECORD SEPARATOR */
14468
36
        0x0085, /* NEXT LINE */
14469
36
        0x2028, /* LINE SEPARATOR */
14470
36
        0x2029, /* PARAGRAPH SEPARATOR */
14471
36
    };
14472
36
    bloom_linebreak = make_bloom_mask(
14473
36
        PyUnicode_2BYTE_KIND, linebreak,
14474
36
        Py_ARRAY_LENGTH(linebreak));
14475
36
}
14476
14477
void
14478
_PyUnicode_InitState(PyInterpreterState *interp)
14479
36
{
14480
36
    if (!_Py_IsMainInterpreter(interp)) {
14481
0
        return;
14482
0
    }
14483
36
    _init_global_state();
14484
36
}
14485
14486
14487
PyStatus
14488
_PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
14489
36
{
14490
36
    if (_Py_IsMainInterpreter(interp)) {
14491
36
        PyStatus status = init_global_interned_strings(interp);
14492
36
        if (_PyStatus_EXCEPTION(status)) {
14493
0
            return status;
14494
0
        }
14495
36
    }
14496
36
    assert(INTERNED_STRINGS);
14497
14498
36
    if (init_interned_dict(interp)) {
14499
0
        PyErr_Clear();
14500
0
        return _PyStatus_ERR("failed to create interned dict");
14501
0
    }
14502
14503
36
    return _PyStatus_OK();
14504
36
}
14505
14506
14507
PyStatus
14508
_PyUnicode_InitTypes(PyInterpreterState *interp)
14509
36
{
14510
36
    if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
14511
0
        goto error;
14512
0
    }
14513
36
    if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
14514
0
        goto error;
14515
0
    }
14516
36
    if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
14517
0
        goto error;
14518
0
    }
14519
36
    return _PyStatus_OK();
14520
14521
0
error:
14522
0
    return _PyStatus_ERR("Can't initialize unicode types");
14523
36
}
14524
14525
static /* non-null */ PyObject*
14526
intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
14527
40.4k
{
14528
    // Note that this steals a reference to `s`, but in many cases that
14529
    // stolen ref is returned, requiring no decref/incref.
14530
14531
40.4k
    assert(s != NULL);
14532
40.4k
    assert(_PyUnicode_CHECK(s));
14533
40.4k
    assert(_PyUnicode_STATE(s).statically_allocated);
14534
40.4k
    assert(!PyUnicode_CHECK_INTERNED(s));
14535
14536
#ifdef Py_DEBUG
14537
    /* We must not add process-global interned string if there's already a
14538
     * per-interpreter interned_dict, which might contain duplicates.
14539
     */
14540
    PyObject *interned = get_interned_dict(interp);
14541
    assert(interned == NULL);
14542
#endif
14543
14544
    /* Look in the global cache first. */
14545
40.4k
    PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14546
    /* We should only init each string once */
14547
40.4k
    assert(r == NULL);
14548
    /* but just in case (for the non-debug build), handle this */
14549
40.4k
    if (r != NULL && r != s) {
14550
0
        assert(_PyUnicode_STATE(r).interned == SSTATE_INTERNED_IMMORTAL_STATIC);
14551
0
        assert(_PyUnicode_CHECK(r));
14552
0
        Py_DECREF(s);
14553
0
        return Py_NewRef(r);
14554
0
    }
14555
14556
40.4k
    if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < -1) {
14557
0
        Py_FatalError("failed to intern static string");
14558
0
    }
14559
14560
40.4k
    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
14561
40.4k
    return s;
14562
40.4k
}
14563
14564
void
14565
_PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
14566
40.4k
{
14567
    // This should only be called as part of runtime initialization
14568
40.4k
    assert(!Py_IsInitialized());
14569
14570
40.4k
    *p = intern_static(interp, *p);
14571
40.4k
    assert(*p);
14572
40.4k
}
14573
14574
static void
14575
immortalize_interned(PyObject *s)
14576
281k
{
14577
281k
    assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
14578
281k
    assert(!_Py_IsImmortal(s));
14579
#ifdef Py_REF_DEBUG
14580
    /* The reference count value should be excluded from the RefTotal.
14581
       The decrements to these objects will not be registered so they
14582
       need to be accounted for in here. */
14583
    for (Py_ssize_t i = 0; i < Py_REFCNT(s); i++) {
14584
        _Py_DecRefTotal(_PyThreadState_GET());
14585
    }
14586
#endif
14587
281k
    _Py_SetImmortal(s);
14588
    // The switch to SSTATE_INTERNED_IMMORTAL must be the last thing done here
14589
    // to synchronize with the check in intern_common() that avoids locking if
14590
    // the string is already immortal.
14591
281k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_IMMORTAL);
14592
281k
}
14593
14594
#ifdef Py_GIL_DISABLED
14595
static bool
14596
can_immortalize_safely(PyObject *s)
14597
{
14598
    if (_Py_IsOwnedByCurrentThread(s) || _Py_IsImmortal(s)) {
14599
        return true;
14600
    }
14601
    Py_ssize_t shared = _Py_atomic_load_ssize(&s->ob_ref_shared);
14602
    return _Py_REF_IS_MERGED(shared);
14603
}
14604
#endif
14605
14606
static /* non-null */ PyObject*
14607
intern_common(PyInterpreterState *interp, PyObject *s /* stolen */,
14608
              bool immortalize)
14609
69.6M
{
14610
    // Note that this steals a reference to `s`, but in many cases that
14611
    // stolen ref is returned, requiring no decref/incref.
14612
14613
#ifdef Py_DEBUG
14614
    assert(s != NULL);
14615
    assert(_PyUnicode_CHECK(s));
14616
#else
14617
69.6M
    if (s == NULL || !PyUnicode_Check(s)) {
14618
0
        return s;
14619
0
    }
14620
69.6M
#endif
14621
14622
    /* If it's a subclass, we don't really know what putting
14623
       it in the interned dict might do. */
14624
69.6M
    if (!PyUnicode_CheckExact(s)) {
14625
0
        return s;
14626
0
    }
14627
14628
    /* Is it already interned? */
14629
69.6M
    switch (PyUnicode_CHECK_INTERNED(s)) {
14630
6.26M
        case SSTATE_NOT_INTERNED:
14631
            // no, go on
14632
6.26M
            break;
14633
27.8k
        case SSTATE_INTERNED_MORTAL:
14634
27.8k
#ifndef Py_GIL_DISABLED
14635
            // yes but we might need to make it immortal
14636
27.8k
            if (immortalize) {
14637
1.86k
                immortalize_interned(s);
14638
1.86k
            }
14639
27.8k
            return s;
14640
#else
14641
            // not fully interned yet; fall through to the locking path
14642
            break;
14643
#endif
14644
63.3M
        default:
14645
            // all done
14646
63.3M
            return s;
14647
69.6M
    }
14648
14649
    /* Statically allocated strings must be already interned. */
14650
69.6M
    assert(!_PyUnicode_STATE(s).statically_allocated);
14651
14652
#if Py_GIL_DISABLED
14653
    /* In the free-threaded build, all interned strings are immortal */
14654
    immortalize = 1;
14655
#endif
14656
14657
    /* If it's already immortal, intern it as such */
14658
6.26M
    if (_Py_IsImmortal(s)) {
14659
0
        immortalize = 1;
14660
0
    }
14661
14662
    /* if it's a short string, get the singleton */
14663
6.26M
    if (PyUnicode_GET_LENGTH(s) == 1 &&
14664
20.5k
                PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) {
14665
0
        PyObject *r = LATIN1(*(unsigned char*)PyUnicode_DATA(s));
14666
0
        assert(PyUnicode_CHECK_INTERNED(r));
14667
0
        Py_DECREF(s);
14668
0
        return r;
14669
0
    }
14670
#ifdef Py_DEBUG
14671
    assert(!unicode_is_singleton(s));
14672
#endif
14673
14674
    /* Look in the global cache now. */
14675
6.26M
    {
14676
6.26M
        PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14677
6.26M
        if (r != NULL) {
14678
492k
            assert(_PyUnicode_STATE(r).statically_allocated);
14679
492k
            assert(r != s);  // r must be statically_allocated; s is not
14680
492k
            Py_DECREF(s);
14681
492k
            return Py_NewRef(r);
14682
492k
        }
14683
6.26M
    }
14684
14685
    /* Do a setdefault on the per-interpreter cache. */
14686
5.77M
    PyObject *interned = get_interned_dict(interp);
14687
5.77M
    assert(interned != NULL);
14688
#ifdef Py_GIL_DISABLED
14689
#  define INTERN_MUTEX &_Py_INTERP_CACHED_OBJECT(interp, interned_mutex)
14690
    // Lock-free fast path: check if there's already an interned copy that
14691
    // is in its final immortal state.
14692
    PyObject *r;
14693
    int res = PyDict_GetItemRef(interned, s, &r);
14694
    if (res < 0) {
14695
        PyErr_Clear();
14696
        return s;
14697
    }
14698
    if (res > 0) {
14699
        unsigned int state = _Py_atomic_load_uint8(&_PyUnicode_STATE(r).interned);
14700
        if (state == SSTATE_INTERNED_IMMORTAL) {
14701
            Py_DECREF(s);
14702
            return r;
14703
        }
14704
        // Not yet fully interned; fall through to the locking path.
14705
        Py_DECREF(r);
14706
    }
14707
#endif
14708
14709
#ifdef Py_GIL_DISABLED
14710
    // Immortalization writes to the refcount fields non-atomically. That
14711
    // races with Py_INCREF / Py_DECREF on the thread that owns `s`. If we
14712
    // don't own it (and its refcount hasn't been merged), intern a copy
14713
    // we own instead.
14714
    if (!can_immortalize_safely(s)) {
14715
        PyObject *copy = _PyUnicode_Copy(s);
14716
        if (copy == NULL) {
14717
            PyErr_Clear();
14718
            return s;
14719
        }
14720
        Py_DECREF(s);
14721
        s = copy;
14722
    }
14723
#endif
14724
14725
5.77M
    FT_MUTEX_LOCK(INTERN_MUTEX);
14726
5.77M
    PyObject *t;
14727
5.77M
    {
14728
5.77M
        int res = PyDict_SetDefaultRef(interned, s, s, &t);
14729
5.77M
        if (res < 0) {
14730
0
            PyErr_Clear();
14731
0
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14732
0
            return s;
14733
0
        }
14734
5.77M
        else if (res == 1) {
14735
            // value was already present (not inserted)
14736
5.11M
            Py_DECREF(s);
14737
5.11M
            if (immortalize &&
14738
1.11M
                    PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
14739
9.77k
                immortalize_interned(t);
14740
9.77k
            }
14741
5.11M
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14742
5.11M
            return t;
14743
5.11M
        }
14744
651k
        else {
14745
            // value was newly inserted
14746
651k
            assert (s == t);
14747
651k
            Py_DECREF(t);
14748
651k
        }
14749
5.77M
    }
14750
14751
    /* NOT_INTERNED -> INTERNED_MORTAL */
14752
14753
5.77M
    assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
14754
14755
651k
    if (!_Py_IsImmortal(s)) {
14756
        /* The two references in interned dict (key and value) are not counted.
14757
        unicode_dealloc() and _PyUnicode_ClearInterned() take care of this. */
14758
651k
        Py_DECREF(s);
14759
651k
        Py_DECREF(s);
14760
651k
    }
14761
651k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_MORTAL);
14762
14763
    /* INTERNED_MORTAL -> INTERNED_IMMORTAL (if needed) */
14764
14765
#ifdef Py_DEBUG
14766
    if (_Py_IsImmortal(s)) {
14767
        assert(immortalize);
14768
    }
14769
#endif
14770
651k
    if (immortalize) {
14771
269k
        immortalize_interned(s);
14772
269k
    }
14773
14774
651k
    FT_MUTEX_UNLOCK(INTERN_MUTEX);
14775
651k
    return s;
14776
5.77M
}
14777
14778
void
14779
_PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
14780
15.1M
{
14781
15.1M
    *p = intern_common(interp, *p, 1);
14782
15.1M
    assert(*p);
14783
15.1M
}
14784
14785
void
14786
_PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
14787
54.4M
{
14788
54.4M
    *p = intern_common(interp, *p, 0);
14789
54.4M
    assert(*p);
14790
54.4M
}
14791
14792
14793
void
14794
_PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
14795
0
{
14796
0
    _PyUnicode_InternImmortal(interp, p);
14797
0
    return;
14798
0
}
14799
14800
void
14801
PyUnicode_InternInPlace(PyObject **p)
14802
8
{
14803
8
    PyInterpreterState *interp = _PyInterpreterState_GET();
14804
8
    _PyUnicode_InternMortal(interp, p);
14805
8
}
14806
14807
// Public-looking name kept for the stable ABI; user should not call this:
14808
PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
14809
void
14810
PyUnicode_InternImmortal(PyObject **p)
14811
0
{
14812
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14813
0
    _PyUnicode_InternImmortal(interp, p);
14814
0
}
14815
14816
PyObject *
14817
PyUnicode_InternFromString(const char *cp)
14818
1.43M
{
14819
1.43M
    PyObject *s = PyUnicode_FromString(cp);
14820
1.43M
    if (s == NULL) {
14821
0
        return NULL;
14822
0
    }
14823
1.43M
    PyInterpreterState *interp = _PyInterpreterState_GET();
14824
1.43M
    _PyUnicode_InternMortal(interp, &s);
14825
1.43M
    return s;
14826
1.43M
}
14827
14828
14829
void
14830
_PyUnicode_ClearInterned(PyInterpreterState *interp)
14831
0
{
14832
0
    PyObject *interned = get_interned_dict(interp);
14833
0
    if (interned == NULL) {
14834
0
        return;
14835
0
    }
14836
0
    assert(PyDict_CheckExact(interned));
14837
14838
0
    if (has_shared_intern_dict(interp)) {
14839
        // the dict doesn't belong to this interpreter, skip the debug
14840
        // checks on it and just clear the pointer to it
14841
0
        clear_interned_dict(interp);
14842
0
        return;
14843
0
    }
14844
14845
#ifdef INTERNED_STATS
14846
    fprintf(stderr, "releasing %zd interned strings\n",
14847
            PyDict_GET_SIZE(interned));
14848
14849
    Py_ssize_t total_length = 0;
14850
#endif
14851
0
    Py_ssize_t pos = 0;
14852
0
    PyObject *s, *ignored_value;
14853
0
    while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
14854
0
        int shared = 0;
14855
0
        switch (PyUnicode_CHECK_INTERNED(s)) {
14856
0
        case SSTATE_INTERNED_IMMORTAL:
14857
            /* Make immortal interned strings mortal again. */
14858
            // Skip the Immortal Instance check and restore
14859
            // the two references (key and value) ignored
14860
            // by PyUnicode_InternInPlace().
14861
0
            _Py_SetMortal(s, 2);
14862
#ifdef Py_REF_DEBUG
14863
            /* let's be pedantic with the ref total */
14864
            _Py_IncRefTotal(_PyThreadState_GET());
14865
            _Py_IncRefTotal(_PyThreadState_GET());
14866
#endif
14867
#ifdef INTERNED_STATS
14868
            total_length += PyUnicode_GET_LENGTH(s);
14869
#endif
14870
0
            break;
14871
0
        case SSTATE_INTERNED_IMMORTAL_STATIC:
14872
            /* It is shared between interpreters, so we should unmark it
14873
               only when this is the last interpreter in which it's
14874
               interned.  We immortalize all the statically initialized
14875
               strings during startup, so we can rely on the
14876
               main interpreter to be the last one. */
14877
0
            if (!_Py_IsMainInterpreter(interp)) {
14878
0
                shared = 1;
14879
0
            }
14880
0
            break;
14881
0
        case SSTATE_INTERNED_MORTAL:
14882
            // Restore 2 references held by the interned dict; these will
14883
            // be decref'd by clear_interned_dict's PyDict_Clear.
14884
0
            _Py_RefcntAdd(s, 2);
14885
#ifdef Py_REF_DEBUG
14886
            /* let's be pedantic with the ref total */
14887
            _Py_IncRefTotal(_PyThreadState_GET());
14888
            _Py_IncRefTotal(_PyThreadState_GET());
14889
#endif
14890
0
            break;
14891
0
        case SSTATE_NOT_INTERNED:
14892
0
            _Py_FALLTHROUGH;
14893
0
        default:
14894
0
            Py_UNREACHABLE();
14895
0
        }
14896
0
        if (!shared) {
14897
0
            FT_ATOMIC_STORE_UINT8_RELAXED(_PyUnicode_STATE(s).interned, SSTATE_NOT_INTERNED);
14898
0
        }
14899
0
    }
14900
#ifdef INTERNED_STATS
14901
    fprintf(stderr,
14902
            "total length of all interned strings: %zd characters\n",
14903
            total_length);
14904
#endif
14905
14906
0
    struct _Py_unicode_state *state = &interp->unicode;
14907
0
    struct _Py_unicode_ids *ids = &state->ids;
14908
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
14909
0
        Py_XINCREF(ids->array[i]);
14910
0
    }
14911
0
    clear_interned_dict(interp);
14912
0
    if (_Py_IsMainInterpreter(interp)) {
14913
0
        clear_global_interned_strings();
14914
0
    }
14915
0
}
14916
14917
14918
/********************* Unicode Iterator **************************/
14919
14920
typedef struct {
14921
    PyObject_HEAD
14922
    Py_ssize_t it_index;
14923
    PyObject *it_seq;    /* Set to NULL when iterator is exhausted */
14924
} unicodeiterobject;
14925
14926
static void
14927
unicodeiter_dealloc(PyObject *op)
14928
3.00M
{
14929
3.00M
    unicodeiterobject *it = (unicodeiterobject *)op;
14930
3.00M
    _PyObject_GC_UNTRACK(it);
14931
3.00M
    Py_XDECREF(it->it_seq);
14932
3.00M
    PyObject_GC_Del(it);
14933
3.00M
}
14934
14935
static int
14936
unicodeiter_traverse(PyObject *op, visitproc visit, void *arg)
14937
8
{
14938
8
    unicodeiterobject *it = (unicodeiterobject *)op;
14939
8
    Py_VISIT(it->it_seq);
14940
8
    return 0;
14941
8
}
14942
14943
static PyObject *
14944
unicodeiter_next(PyObject *op)
14945
60.9M
{
14946
60.9M
    unicodeiterobject *it = (unicodeiterobject *)op;
14947
60.9M
    PyObject *seq;
14948
14949
60.9M
    assert(it != NULL);
14950
60.9M
    seq = it->it_seq;
14951
60.9M
    if (seq == NULL)
14952
0
        return NULL;
14953
60.9M
    assert(_PyUnicode_CHECK(seq));
14954
14955
60.9M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14956
60.0M
        int kind = PyUnicode_KIND(seq);
14957
60.0M
        const void *data = PyUnicode_DATA(seq);
14958
60.0M
        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14959
60.0M
        it->it_index++;
14960
60.0M
        return unicode_char(chr);
14961
60.0M
    }
14962
14963
846k
    it->it_seq = NULL;
14964
846k
    Py_DECREF(seq);
14965
846k
    return NULL;
14966
60.9M
}
14967
14968
static PyObject *
14969
unicode_ascii_iter_next(PyObject *op)
14970
9.62M
{
14971
9.62M
    unicodeiterobject *it = (unicodeiterobject *)op;
14972
9.62M
    assert(it != NULL);
14973
9.62M
    PyObject *seq = it->it_seq;
14974
9.62M
    if (seq == NULL) {
14975
0
        return NULL;
14976
0
    }
14977
9.62M
    assert(_PyUnicode_CHECK(seq));
14978
9.62M
    assert(PyUnicode_IS_COMPACT_ASCII(seq));
14979
9.62M
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14980
7.48M
        const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
14981
7.48M
        Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
14982
7.48M
                                              data, it->it_index);
14983
7.48M
        it->it_index++;
14984
7.48M
        return (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
14985
7.48M
    }
14986
2.14M
    it->it_seq = NULL;
14987
2.14M
    Py_DECREF(seq);
14988
2.14M
    return NULL;
14989
9.62M
}
14990
14991
static PyObject *
14992
unicodeiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
14993
2.60M
{
14994
2.60M
    unicodeiterobject *it = (unicodeiterobject *)op;
14995
2.60M
    Py_ssize_t len = 0;
14996
2.60M
    if (it->it_seq)
14997
2.60M
        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
14998
2.60M
    return PyLong_FromSsize_t(len);
14999
2.60M
}
15000
15001
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15002
15003
static PyObject *
15004
unicodeiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
15005
0
{
15006
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15007
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
15008
15009
    /* _PyEval_GetBuiltin can invoke arbitrary code,
15010
     * call must be before access of iterator pointers.
15011
     * see issue #101765 */
15012
15013
0
    if (it->it_seq != NULL) {
15014
0
        return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
15015
0
    } else {
15016
0
        PyObject *u = _PyUnicode_GetEmpty();
15017
0
        if (u == NULL) {
15018
0
            Py_XDECREF(iter);
15019
0
            return NULL;
15020
0
        }
15021
0
        return Py_BuildValue("N(N)", iter, u);
15022
0
    }
15023
0
}
15024
15025
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15026
15027
static PyObject *
15028
unicodeiter_setstate(PyObject *op, PyObject *state)
15029
0
{
15030
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15031
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
15032
0
    if (index == -1 && PyErr_Occurred())
15033
0
        return NULL;
15034
0
    if (it->it_seq != NULL) {
15035
0
        if (index < 0)
15036
0
            index = 0;
15037
0
        else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15038
0
            index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15039
0
        it->it_index = index;
15040
0
    }
15041
0
    Py_RETURN_NONE;
15042
0
}
15043
15044
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15045
15046
static PyMethodDef unicodeiter_methods[] = {
15047
    {"__length_hint__", unicodeiter_len, METH_NOARGS, length_hint_doc},
15048
    {"__reduce__",      unicodeiter_reduce, METH_NOARGS, reduce_doc},
15049
    {"__setstate__",    unicodeiter_setstate, METH_O, setstate_doc},
15050
    {NULL,      NULL}       /* sentinel */
15051
};
15052
15053
PyTypeObject PyUnicodeIter_Type = {
15054
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15055
    "str_iterator",         /* tp_name */
15056
    sizeof(unicodeiterobject),      /* tp_basicsize */
15057
    0,                  /* tp_itemsize */
15058
    /* methods */
15059
    unicodeiter_dealloc,/* tp_dealloc */
15060
    0,                  /* tp_vectorcall_offset */
15061
    0,                  /* tp_getattr */
15062
    0,                  /* tp_setattr */
15063
    0,                  /* tp_as_async */
15064
    0,                  /* tp_repr */
15065
    0,                  /* tp_as_number */
15066
    0,                  /* tp_as_sequence */
15067
    0,                  /* tp_as_mapping */
15068
    0,                  /* tp_hash */
15069
    0,                  /* tp_call */
15070
    0,                  /* tp_str */
15071
    PyObject_GenericGetAttr,        /* tp_getattro */
15072
    0,                  /* tp_setattro */
15073
    0,                  /* tp_as_buffer */
15074
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15075
    0,                  /* tp_doc */
15076
    unicodeiter_traverse, /* tp_traverse */
15077
    0,                  /* tp_clear */
15078
    0,                  /* tp_richcompare */
15079
    0,                  /* tp_weaklistoffset */
15080
    PyObject_SelfIter,          /* tp_iter */
15081
    unicodeiter_next,   /* tp_iternext */
15082
    unicodeiter_methods,            /* tp_methods */
15083
    0,
15084
};
15085
15086
PyTypeObject _PyUnicodeASCIIIter_Type = {
15087
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15088
    .tp_name = "str_ascii_iterator",
15089
    .tp_basicsize = sizeof(unicodeiterobject),
15090
    .tp_dealloc = unicodeiter_dealloc,
15091
    .tp_getattro = PyObject_GenericGetAttr,
15092
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
15093
    .tp_traverse = unicodeiter_traverse,
15094
    .tp_iter = PyObject_SelfIter,
15095
    .tp_iternext = unicode_ascii_iter_next,
15096
    .tp_methods = unicodeiter_methods,
15097
};
15098
15099
static PyObject *
15100
unicode_iter(PyObject *seq)
15101
3.00M
{
15102
3.00M
    unicodeiterobject *it;
15103
15104
3.00M
    if (!PyUnicode_Check(seq)) {
15105
0
        PyErr_BadInternalCall();
15106
0
        return NULL;
15107
0
    }
15108
3.00M
    if (PyUnicode_IS_COMPACT_ASCII(seq)) {
15109
2.15M
        it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
15110
2.15M
    }
15111
846k
    else {
15112
846k
        it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15113
846k
    }
15114
3.00M
    if (it == NULL)
15115
0
        return NULL;
15116
3.00M
    it->it_index = 0;
15117
3.00M
    it->it_seq = Py_NewRef(seq);
15118
3.00M
    _PyObject_GC_TRACK(it);
15119
3.00M
    return (PyObject *)it;
15120
3.00M
}
15121
15122
static int
15123
encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
15124
144
{
15125
144
    int res;
15126
144
    res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
15127
144
    if (res == -2) {
15128
0
        PyErr_Format(PyExc_RuntimeError, "cannot encode %s", name);
15129
0
        return -1;
15130
0
    }
15131
144
    if (res < 0) {
15132
0
        PyErr_NoMemory();
15133
0
        return -1;
15134
0
    }
15135
144
    return 0;
15136
144
}
15137
15138
15139
static int
15140
config_get_codec_name(wchar_t **config_encoding)
15141
72
{
15142
72
    char *encoding;
15143
72
    if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15144
0
        return -1;
15145
0
    }
15146
15147
72
    PyObject *name_obj = NULL;
15148
72
    PyObject *codec = _PyCodec_Lookup(encoding);
15149
72
    PyMem_RawFree(encoding);
15150
15151
72
    if (!codec)
15152
0
        goto error;
15153
15154
72
    name_obj = PyObject_GetAttrString(codec, "name");
15155
72
    Py_CLEAR(codec);
15156
72
    if (!name_obj) {
15157
0
        goto error;
15158
0
    }
15159
15160
72
    wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
15161
72
    Py_DECREF(name_obj);
15162
72
    if (wname == NULL) {
15163
0
        goto error;
15164
0
    }
15165
15166
72
    wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
15167
72
    if (raw_wname == NULL) {
15168
0
        PyMem_Free(wname);
15169
0
        PyErr_NoMemory();
15170
0
        goto error;
15171
0
    }
15172
15173
72
    PyMem_RawFree(*config_encoding);
15174
72
    *config_encoding = raw_wname;
15175
15176
72
    PyMem_Free(wname);
15177
72
    return 0;
15178
15179
0
error:
15180
0
    Py_XDECREF(codec);
15181
0
    Py_XDECREF(name_obj);
15182
0
    return -1;
15183
72
}
15184
15185
15186
static PyStatus
15187
init_stdio_encoding(PyInterpreterState *interp)
15188
36
{
15189
    /* Update the stdio encoding to the normalized Python codec name. */
15190
36
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15191
36
    if (config_get_codec_name(&config->stdio_encoding) < 0) {
15192
0
        return _PyStatus_ERR("failed to get the Python codec name "
15193
0
                             "of the stdio encoding");
15194
0
    }
15195
36
    return _PyStatus_OK();
15196
36
}
15197
15198
15199
static int
15200
init_fs_codec(PyInterpreterState *interp)
15201
36
{
15202
36
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
15203
15204
36
    _Py_error_handler error_handler;
15205
36
    error_handler = get_error_handler_wide(config->filesystem_errors);
15206
36
    if (error_handler == _Py_ERROR_UNKNOWN) {
15207
0
        PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
15208
0
        return -1;
15209
0
    }
15210
15211
36
    char *encoding, *errors;
15212
36
    if (encode_wstr_utf8(config->filesystem_encoding,
15213
36
                         &encoding,
15214
36
                         "filesystem_encoding") < 0) {
15215
0
        return -1;
15216
0
    }
15217
15218
36
    if (encode_wstr_utf8(config->filesystem_errors,
15219
36
                         &errors,
15220
36
                         "filesystem_errors") < 0) {
15221
0
        PyMem_RawFree(encoding);
15222
0
        return -1;
15223
0
    }
15224
15225
36
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
15226
36
    PyMem_RawFree(fs_codec->encoding);
15227
36
    fs_codec->encoding = encoding;
15228
    /* encoding has been normalized by init_fs_encoding() */
15229
36
    fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
15230
36
    PyMem_RawFree(fs_codec->errors);
15231
36
    fs_codec->errors = errors;
15232
36
    fs_codec->error_handler = error_handler;
15233
15234
#ifdef _Py_FORCE_UTF8_FS_ENCODING
15235
    assert(fs_codec->utf8 == 1);
15236
#endif
15237
15238
    /* At this point, PyUnicode_EncodeFSDefault() and
15239
       PyUnicode_DecodeFSDefault() can now use the Python codec rather than
15240
       the C implementation of the filesystem encoding. */
15241
15242
    /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
15243
       global configuration variables. */
15244
36
    if (_Py_IsMainInterpreter(interp)) {
15245
15246
36
        if (_Py_SetFileSystemEncoding(fs_codec->encoding,
15247
36
                                      fs_codec->errors) < 0) {
15248
0
            PyErr_NoMemory();
15249
0
            return -1;
15250
0
        }
15251
36
    }
15252
36
    return 0;
15253
36
}
15254
15255
15256
static PyStatus
15257
init_fs_encoding(PyThreadState *tstate)
15258
36
{
15259
36
    PyInterpreterState *interp = tstate->interp;
15260
15261
    /* Update the filesystem encoding to the normalized Python codec name.
15262
       For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
15263
       (Python codec name). */
15264
36
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15265
36
    if (config_get_codec_name(&config->filesystem_encoding) < 0) {
15266
0
        _Py_DumpPathConfig(tstate);
15267
0
        return _PyStatus_ERR("failed to get the Python codec "
15268
0
                             "of the filesystem encoding");
15269
0
    }
15270
15271
36
    if (init_fs_codec(interp) < 0) {
15272
0
        return _PyStatus_ERR("cannot initialize filesystem codec");
15273
0
    }
15274
36
    return _PyStatus_OK();
15275
36
}
15276
15277
15278
PyStatus
15279
_PyUnicode_InitEncodings(PyThreadState *tstate)
15280
36
{
15281
36
    PyStatus status = _PyCodec_InitRegistry(tstate->interp);
15282
36
    if (_PyStatus_EXCEPTION(status)) {
15283
0
        return status;
15284
0
    }
15285
36
    status = init_fs_encoding(tstate);
15286
36
    if (_PyStatus_EXCEPTION(status)) {
15287
0
        return status;
15288
0
    }
15289
15290
36
    return init_stdio_encoding(tstate->interp);
15291
36
}
15292
15293
15294
static void
15295
_PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
15296
0
{
15297
0
    PyMem_RawFree(fs_codec->encoding);
15298
0
    fs_codec->encoding = NULL;
15299
0
    fs_codec->utf8 = 0;
15300
0
    PyMem_RawFree(fs_codec->errors);
15301
0
    fs_codec->errors = NULL;
15302
0
    fs_codec->error_handler = _Py_ERROR_UNKNOWN;
15303
0
}
15304
15305
15306
#ifdef Py_DEBUG
15307
static inline int
15308
unicode_is_finalizing(void)
15309
{
15310
    return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
15311
}
15312
#endif
15313
15314
15315
void
15316
_PyUnicode_FiniTypes(PyInterpreterState *interp)
15317
0
{
15318
0
    _PyStaticType_FiniBuiltin(interp, &EncodingMapType);
15319
0
    _PyStaticType_FiniBuiltin(interp, &PyFieldNameIter_Type);
15320
0
    _PyStaticType_FiniBuiltin(interp, &PyFormatterIter_Type);
15321
0
}
15322
15323
15324
void
15325
_PyUnicode_Fini(PyInterpreterState *interp)
15326
0
{
15327
0
    struct _Py_unicode_state *state = &interp->unicode;
15328
15329
0
    if (!has_shared_intern_dict(interp)) {
15330
        // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
15331
0
        assert(get_interned_dict(interp) == NULL);
15332
0
    }
15333
15334
0
    _PyUnicode_FiniEncodings(&state->fs_codec);
15335
15336
    // bpo-47182: force a unicodedata CAPI capsule re-import on
15337
    // subsequent initialization of interpreter.
15338
0
    interp->unicode.ucnhash_capi = NULL;
15339
15340
0
    unicode_clear_identifiers(state);
15341
0
}
15342
15343
/* A _string module, to export formatter_parser and formatter_field_name_split
15344
   to the string.Formatter class implemented in Python. */
15345
15346
static PyMethodDef _string_methods[] = {
15347
    {"formatter_field_name_split", formatter_field_name_split,
15348
     METH_O, PyDoc_STR("split the argument as a field name")},
15349
    {"formatter_parser", formatter_parser,
15350
     METH_O, PyDoc_STR("parse the argument as a format string")},
15351
    {NULL, NULL}
15352
};
15353
15354
static PyModuleDef_Slot module_slots[] = {
15355
    _Py_ABI_SLOT,
15356
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
15357
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
15358
    {0, NULL}
15359
};
15360
15361
static struct PyModuleDef _string_module = {
15362
    PyModuleDef_HEAD_INIT,
15363
    .m_name = "_string",
15364
    .m_doc = PyDoc_STR("string helper module"),
15365
    .m_size = 0,
15366
    .m_methods = _string_methods,
15367
    .m_slots = module_slots,
15368
};
15369
15370
PyMODINIT_FUNC
15371
PyInit__string(void)
15372
8
{
15373
8
    return PyModuleDef_Init(&_string_module);
15374
8
}
15375
15376
15377
#undef PyUnicode_KIND
15378
int PyUnicode_KIND(PyObject *op)
15379
0
{
15380
0
    if (!PyUnicode_Check(op)) {
15381
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15382
0
        return -1;
15383
0
    }
15384
0
    return _PyASCIIObject_CAST(op)->state.kind;
15385
0
}
15386
15387
#undef PyUnicode_DATA
15388
void* PyUnicode_DATA(PyObject *op)
15389
0
{
15390
0
    if (!PyUnicode_Check(op)) {
15391
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15392
0
        return NULL;
15393
0
    }
15394
0
    return _PyUnicode_DATA(op);
15395
0
}