Coverage Report

Created: 2026-07-16 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Objects/unicodeobject.c
Line
Count
Source
1
/*
2
3
Unicode implementation based on original code by Fredrik Lundh,
4
modified by Marc-Andre Lemburg <mal@lemburg.com>.
5
6
Major speed upgrades to the method implementations at the Reykjavik
7
NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
9
Copyright (c) Corporation for National Research Initiatives.
10
11
--------------------------------------------------------------------
12
The original string type implementation is:
13
14
  Copyright (c) 1999 by Secret Labs AB
15
  Copyright (c) 1999 by Fredrik Lundh
16
17
By obtaining, using, and/or copying this software and/or its
18
associated documentation, you agree that you have read, understood,
19
and will comply with the following terms and conditions:
20
21
Permission to use, copy, modify, and distribute this software and its
22
associated documentation for any purpose and without fee is hereby
23
granted, provided that the above copyright notice appears in all
24
copies, and that both that copyright notice and this permission notice
25
appear in supporting documentation, and that the name of Secret Labs
26
AB or the author not be used in advertising or publicity pertaining to
27
distribution of the software without specific, written prior
28
permission.
29
30
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32
FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37
--------------------------------------------------------------------
38
39
*/
40
41
#include "Python.h"
42
#include "pycore_abstract.h"      // _PyIndex_Check()
43
#include "pycore_bytes_methods.h" // _Py_bytes_lower()
44
#include "pycore_bytesobject.h"   // _PyBytes_RepeatBuffer()
45
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
46
#include "pycore_codecs.h"        // _PyCodec_Lookup()
47
#include "pycore_critical_section.h" // Py_*_CRITICAL_SECTION_SEQUENCE_FAST
48
#include "pycore_format.h"        // F_LJUST
49
#include "pycore_initconfig.h"    // _PyStatus_OK()
50
#include "pycore_interp.h"        // PyInterpreterState.fs_codec
51
#include "pycore_long.h"          // _PyLong_FormatWriter()
52
#include "pycore_object.h"        // _PyObject_GC_TRACK(), _Py_FatalRefcountError()
53
#include "pycore_pathconfig.h"    // _Py_DumpPathConfig()
54
#include "pycore_pyerrors.h"      // _PyUnicodeTranslateError_Create()
55
#include "pycore_pyhash.h"        // _Py_HashSecret_t
56
#include "pycore_pylifecycle.h"   // _Py_SetFileSystemEncoding()
57
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
58
#include "pycore_ucnhash.h"       // _PyUnicode_Name_CAPI
59
#include "pycore_unicodectype.h"  // _PyUnicode_IsXidStart
60
#include "pycore_unicodeobject.h" // struct _Py_unicode_state
61
#include "pycore_unicodeobject_generated.h"  // _PyUnicode_InitStaticStrings()
62
63
#include "stringlib/eq.h"         // unicode_eq()
64
#include <stddef.h>               // ptrdiff_t
65
66
#ifdef MS_WINDOWS
67
#include <windows.h>
68
#endif
69
70
#ifdef 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
536k
#define MAX_UNICODE _Py_MAX_UNICODE
109
114M
#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
8.50M
{
119
8.50M
    return FT_ATOMIC_LOAD_PTR_ACQUIRE(_PyCompactUnicodeObject_CAST(op)->utf8);
120
8.50M
}
121
122
static inline char* PyUnicode_UTF8(PyObject *op)
123
611k
{
124
611k
    assert(_PyUnicode_CHECK(op));
125
611k
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
126
611k
        return ((char*)(_PyASCIIObject_CAST(op) + 1));
127
611k
    }
128
196
    else {
129
196
         return _PyUnicode_UTF8(op);
130
196
    }
131
611k
}
132
133
static inline void PyUnicode_SET_UTF8(PyObject *op, char *utf8)
134
126
{
135
126
    FT_ATOMIC_STORE_PTR_RELEASE(_PyCompactUnicodeObject_CAST(op)->utf8, utf8);
136
126
}
137
138
static inline Py_ssize_t PyUnicode_UTF8_LENGTH(PyObject *op)
139
252k
{
140
252k
    assert(_PyUnicode_CHECK(op));
141
252k
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
142
252k
         return _PyASCIIObject_CAST(op)->length;
143
252k
    }
144
40
    else {
145
40
         return _PyCompactUnicodeObject_CAST(op)->utf8_length;
146
40
    }
147
252k
}
148
149
static inline void PyUnicode_SET_UTF8_LENGTH(PyObject *op, Py_ssize_t length)
150
126
{
151
126
    _PyCompactUnicodeObject_CAST(op)->utf8_length = length;
152
126
}
153
154
#define _PyUnicode_LENGTH(op)                           \
155
13.4M
    (_PyASCIIObject_CAST(op)->length)
156
#define _PyUnicode_STATE(op)                            \
157
45.3M
    (_PyASCIIObject_CAST(op)->state)
158
#define _PyUnicode_HASH(op)                             \
159
6.62M
    (_PyASCIIObject_CAST(op)->hash)
160
161
26.8M
#define PyUnicode_HASH PyUnstable_Unicode_GET_CACHED_HASH
162
163
static inline void PyUnicode_SET_HASH(PyObject *op, Py_hash_t hash)
164
3.06M
{
165
3.06M
    FT_ATOMIC_STORE_SSIZE_RELAXED(_PyASCIIObject_CAST(op)->hash, hash);
166
3.06M
}
167
168
#define _PyUnicode_DATA_ANY(op)                         \
169
70
    (_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
12.9M
{
182
12.9M
    return (!PyUnicode_IS_COMPACT_ASCII(op)
183
1.67M
            && _PyUnicode_UTF8(op) != NULL
184
56
            && _PyUnicode_UTF8(op) != PyUnicode_DATA(op));
185
12.9M
}
186
187
188
3.71M
#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
38.0M
{
208
38.0M
    _Py_DECLARE_STR(empty, "");
209
38.0M
    return &_Py_STR(empty);
210
38.0M
}
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
505k
{
217
505k
    return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
218
505k
}
219
220
/* This hashtable holds statically allocated interned strings.
221
 * See InternalDocs/string_interning.md for details.
222
 */
223
453k
#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
517k
{
260
517k
    return unicode_hash((PyObject *)key);
261
517k
}
262
263
static int
264
hashtable_unicode_compare(const void *key1, const void *key2)
265
62.5k
{
266
62.5k
    PyObject *obj1 = (PyObject *)key1;
267
62.5k
    PyObject *obj2 = (PyObject *)key2;
268
62.5k
    if (obj1 != NULL && obj2 != NULL) {
269
62.5k
        return unicode_eq(obj1, obj2);
270
62.5k
    }
271
0
    else {
272
0
        return obj1 == obj2;
273
0
    }
274
62.5k
}
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
20
{
289
20
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
290
20
    return interp != main_interp  && interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC;
291
20
}
292
293
static int
294
init_interned_dict(PyInterpreterState *interp)
295
20
{
296
20
    assert(get_interned_dict(interp) == NULL);
297
20
    PyObject *interned;
298
20
    if (has_shared_intern_dict(interp)) {
299
0
        interned = get_interned_dict(_PyInterpreterState_Main());
300
0
        Py_INCREF(interned);
301
0
    }
302
20
    else {
303
20
        interned = PyDict_New();
304
20
        if (interned == NULL) {
305
0
            return -1;
306
0
        }
307
20
    }
308
20
    _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
309
20
    return 0;
310
20
}
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
20
{
329
20
    assert(INTERNED_STRINGS == NULL);
330
20
    _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
331
332
20
    INTERNED_STRINGS = _Py_hashtable_new_full(
333
20
        hashtable_unicode_hash,
334
20
        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
20
        NULL,
338
20
        NULL,
339
20
        &hashtable_alloc
340
20
    );
341
20
    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
20
    _PyUnicode_InitStaticStrings(interp);
354
355
5.14k
    for (int i = 0; i < 256; i++) {
356
5.12k
        PyObject *s = LATIN1(i);
357
5.12k
        _PyUnicode_InternStatic(interp, &s);
358
5.12k
        assert(s == LATIN1(i));
359
5.12k
    }
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
20
    return _PyStatus_OK();
368
20
}
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
22.0M
    do {                             \
380
22.0M
        return _PyUnicode_GetEmpty();\
381
22.0M
    } 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
1.21k
{
475
1.21k
    if (errors == NULL || strcmp(errors, "strict") == 0) {
476
0
        return _Py_ERROR_STRICT;
477
0
    }
478
1.21k
    if (strcmp(errors, "surrogateescape") == 0) {
479
425
        return _Py_ERROR_SURROGATEESCAPE;
480
425
    }
481
789
    if (strcmp(errors, "replace") == 0) {
482
0
        return _Py_ERROR_REPLACE;
483
0
    }
484
789
    if (strcmp(errors, "ignore") == 0) {
485
0
        return _Py_ERROR_IGNORE;
486
0
    }
487
789
    if (strcmp(errors, "backslashreplace") == 0) {
488
281
        return _Py_ERROR_BACKSLASHREPLACE;
489
281
    }
490
508
    if (strcmp(errors, "surrogatepass") == 0) {
491
508
        return _Py_ERROR_SURROGATEPASS;
492
508
    }
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
240
{
503
240
    if (errors == NULL || wcscmp(errors, L"strict") == 0) {
504
0
        return _Py_ERROR_STRICT;
505
0
    }
506
240
    if (wcscmp(errors, L"surrogateescape") == 0) {
507
240
        return _Py_ERROR_SURROGATEESCAPE;
508
240
    }
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
17.3k
{
531
17.3k
    if (encoding == NULL && errors == NULL) {
532
0
        return 0;
533
0
    }
534
535
17.3k
    PyInterpreterState *interp = _PyInterpreterState_GET();
536
17.3k
#ifndef Py_DEBUG
537
    /* In release mode, only check in development mode (-X dev) */
538
17.3k
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
539
17.3k
        return 0;
540
17.3k
    }
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
35.4M
{
594
35.4M
#define CHECK(expr) \
595
126M
    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
35.4M
# define CHECK_IF_GIL(expr) CHECK(expr)
601
35.4M
# define CHECK_IF_FT(expr) (void)(expr)
602
35.4M
#endif
603
604
605
35.4M
    assert(op != NULL);
606
35.4M
    CHECK(PyUnicode_Check(op));
607
608
35.4M
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
609
0
    int kind = ascii->state.kind;
610
611
35.4M
    if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
612
32.0M
        CHECK(kind == PyUnicode_1BYTE_KIND);
613
32.0M
    }
614
3.41M
    else {
615
3.41M
        PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
616
0
        void *data;
617
618
3.41M
        if (ascii->state.compact == 1) {
619
3.41M
            data = compact + 1;
620
3.41M
            CHECK(kind == PyUnicode_1BYTE_KIND
621
3.41M
                                 || kind == PyUnicode_2BYTE_KIND
622
3.41M
                                 || kind == PyUnicode_4BYTE_KIND);
623
3.41M
            CHECK(ascii->state.ascii == 0);
624
3.41M
            CHECK(_PyUnicode_UTF8(op) != data);
625
3.41M
        }
626
35
        else {
627
35
            PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
628
629
0
            data = unicode->data.any;
630
35
            CHECK(kind == PyUnicode_1BYTE_KIND
631
35
                     || kind == PyUnicode_2BYTE_KIND
632
35
                     || kind == PyUnicode_4BYTE_KIND);
633
35
            CHECK(ascii->state.compact == 0);
634
35
            CHECK(data != NULL);
635
35
            if (ascii->state.ascii) {
636
35
                CHECK(_PyUnicode_UTF8(op) == data);
637
35
                CHECK(compact->utf8_length == ascii->length);
638
35
            }
639
0
            else {
640
0
                CHECK(_PyUnicode_UTF8(op) != data);
641
0
            }
642
35
        }
643
3.41M
#ifndef Py_GIL_DISABLED
644
3.41M
        if (_PyUnicode_UTF8(op) == NULL)
645
3.41M
            CHECK(compact->utf8_length == 0);
646
3.41M
#endif
647
3.41M
    }
648
649
    /* check that the best kind is used: O(n) operation */
650
35.4M
    if (check_content) {
651
21.9M
        Py_ssize_t i;
652
21.9M
        Py_UCS4 maxchar = 0;
653
21.9M
        const void *data;
654
21.9M
        Py_UCS4 ch;
655
656
21.9M
        data = PyUnicode_DATA(ascii);
657
24.8G
        for (i=0; i < ascii->length; i++)
658
24.8G
        {
659
24.8G
            ch = PyUnicode_READ(kind, data, i);
660
24.8G
            if (ch > maxchar)
661
34.6M
                maxchar = ch;
662
24.8G
        }
663
21.9M
        if (kind == PyUnicode_1BYTE_KIND) {
664
21.6M
            if (ascii->state.ascii == 0) {
665
1.42M
                CHECK(maxchar >= 128);
666
1.42M
                CHECK(maxchar <= 255);
667
1.42M
            }
668
20.2M
            else
669
20.2M
                CHECK(maxchar < 128);
670
21.6M
        }
671
320k
        else if (kind == PyUnicode_2BYTE_KIND) {
672
130k
            CHECK(maxchar >= 0x100);
673
130k
            CHECK(maxchar <= 0xFFFF);
674
130k
        }
675
189k
        else {
676
189k
            CHECK(maxchar >= 0x10000);
677
189k
            CHECK(maxchar <= MAX_UNICODE);
678
189k
        }
679
21.9M
        CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
680
21.9M
    }
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
35.4M
    return 1;
717
718
35.4M
#undef CHECK
719
35.4M
}
720
721
PyObject*
722
_PyUnicode_Result(PyObject *unicode)
723
1.81M
{
724
1.81M
    assert(_PyUnicode_CHECK(unicode));
725
726
1.81M
    Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
727
1.81M
    if (length == 0) {
728
1
        PyObject *empty = _PyUnicode_GetEmpty();
729
1
        if (unicode != empty) {
730
0
            Py_DECREF(unicode);
731
0
        }
732
1
        return empty;
733
1
    }
734
735
1.81M
    if (length == 1) {
736
387k
        int kind = PyUnicode_KIND(unicode);
737
387k
        if (kind == PyUnicode_1BYTE_KIND) {
738
303k
            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
739
303k
            Py_UCS1 ch = data[0];
740
303k
            PyObject *latin1_char = LATIN1(ch);
741
303k
            if (unicode != latin1_char) {
742
303k
                Py_DECREF(unicode);
743
303k
            }
744
303k
            return latin1_char;
745
303k
        }
746
387k
    }
747
748
1.81M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
749
1.51M
    return unicode;
750
1.51M
}
751
2.14k
#define unicode_result _PyUnicode_Result
752
753
static PyObject*
754
unicode_result_unchanged(PyObject *unicode)
755
42.3k
{
756
42.3k
    if (PyUnicode_CheckExact(unicode)) {
757
42.3k
        return Py_NewRef(unicode);
758
42.3k
    }
759
0
    else
760
        /* Subtype -- return genuine unicode string with the same value. */
761
0
        return _PyUnicode_Copy(unicode);
762
42.3k
}
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
15.7k
{
770
15.7k
    Py_ssize_t size, i;
771
15.7k
    Py_UCS4 ch;
772
15.7k
    int kind;
773
15.7k
    const void *data;
774
775
15.7k
    kind = PyUnicode_KIND(unicode);
776
15.7k
    data = PyUnicode_DATA(unicode);
777
778
15.7k
    size = 0;
779
    /* determine replacement size */
780
156k
    for (i = collstart; i < collend; ++i) {
781
140k
        Py_ssize_t incr;
782
783
140k
        ch = PyUnicode_READ(kind, data, i);
784
140k
        if (ch < 0x100)
785
140k
            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
140k
        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
140k
        size += incr;
798
140k
    }
799
800
15.7k
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
801
15.7k
    if (str == NULL) {
802
0
        return NULL;
803
0
    }
804
805
    /* generate replacement */
806
156k
    for (i = collstart; i < collend; ++i) {
807
140k
        ch = PyUnicode_READ(kind, data, i);
808
140k
        *str++ = '\\';
809
140k
        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
140k
        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
140k
        else
824
140k
            *str++ = 'x';
825
140k
        *str++ = Py_hexdigits[(ch>>4)&0xf];
826
140k
        *str++ = Py_hexdigits[ch&0xf];
827
140k
    }
828
15.7k
    return str;
829
15.7k
}
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
6.92k
#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
6.70k
#define BLOOM_MASK unsigned long
910
911
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
912
913
3.38k
#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
914
915
#define BLOOM_LINEBREAK(ch)                                             \
916
0
    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
917
0
     (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
3.36k
{
922
3.36k
#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
923
3.36k
    do {                                               \
924
3.36k
        TYPE *data = (TYPE *)PTR;                      \
925
3.36k
        TYPE *end = data + LEN;                        \
926
3.36k
        Py_UCS4 ch;                                    \
927
6.90k
        for (; data != end; data++) {                  \
928
3.54k
            ch = *data;                                \
929
3.54k
            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
930
3.54k
        }                                              \
931
3.36k
        break;                                         \
932
3.36k
    } while (0)
933
934
    /* calculate simple bloom-style bitmask for a given unicode string */
935
936
3.36k
    BLOOM_MASK mask;
937
938
3.36k
    mask = 0;
939
3.36k
    switch (kind) {
940
3.34k
    case PyUnicode_1BYTE_KIND:
941
3.34k
        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
942
3.34k
        break;
943
20
    case PyUnicode_2BYTE_KIND:
944
20
        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
945
20
        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
3.36k
    }
952
3.36k
    return mask;
953
954
3.36k
#undef BLOOM_UPDATE
955
3.36k
}
956
957
/* Compilation of templated routines */
958
959
1.45k
#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
26.7M
{
1012
26.7M
    switch (kind) {
1013
26.7M
    case PyUnicode_1BYTE_KIND:
1014
26.7M
        if ((Py_UCS1) ch != ch)
1015
1.69k
            return -1;
1016
26.7M
        if (direction > 0)
1017
26.7M
            return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1018
3.23k
        else
1019
3.23k
            return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1020
915
    case PyUnicode_2BYTE_KIND:
1021
915
        if ((Py_UCS2) ch != ch)
1022
0
            return -1;
1023
915
        if (direction > 0)
1024
0
            return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1025
915
        else
1026
915
            return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1027
1.35k
    case PyUnicode_4BYTE_KIND:
1028
1.35k
        if (direction > 0)
1029
0
            return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
1030
1.35k
        else
1031
1.35k
            return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
1032
0
    default:
1033
0
        Py_UNREACHABLE();
1034
26.7M
    }
1035
26.7M
}
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
6.85M
{
1074
6.85M
    Py_ssize_t char_size;
1075
6.85M
    Py_ssize_t struct_size;
1076
6.85M
    Py_ssize_t new_size;
1077
6.85M
    PyObject *new_unicode;
1078
#ifdef Py_DEBUG
1079
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1080
#endif
1081
1082
6.85M
    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
6.85M
    assert(PyUnicode_IS_COMPACT(unicode));
1091
1092
6.85M
    char_size = PyUnicode_KIND(unicode);
1093
6.85M
    if (PyUnicode_IS_ASCII(unicode))
1094
5.71M
        struct_size = sizeof(PyASCIIObject);
1095
1.13M
    else
1096
1.13M
        struct_size = sizeof(PyCompactUnicodeObject);
1097
1098
6.85M
    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1099
0
        PyErr_NoMemory();
1100
0
        return NULL;
1101
0
    }
1102
6.85M
    new_size = (struct_size + (length + 1) * char_size);
1103
1104
6.85M
    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
6.85M
    _PyReftracerTrack(unicode, PyRefTracer_DESTROY);
1113
1114
6.85M
    new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
1115
6.85M
    if (new_unicode == NULL) {
1116
0
        _Py_NewReferenceNoTotal(unicode);
1117
0
        PyErr_NoMemory();
1118
0
        return NULL;
1119
0
    }
1120
6.85M
    unicode = new_unicode;
1121
6.85M
    _Py_NewReferenceNoTotal(unicode);
1122
1123
6.85M
    _PyUnicode_LENGTH(unicode) = length;
1124
#ifdef Py_DEBUG
1125
    unicode_fill_invalid(unicode, old_length);
1126
#endif
1127
6.85M
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1128
6.85M
                    length, 0);
1129
6.85M
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1130
6.85M
    return unicode;
1131
6.85M
}
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
16.1M
{
1278
    /* Optimization for empty strings */
1279
16.1M
    if (size == 0) {
1280
9.56M
        return _PyUnicode_GetEmpty();
1281
9.56M
    }
1282
1283
6.62M
    PyObject *obj;
1284
6.62M
    PyCompactUnicodeObject *unicode;
1285
6.62M
    void *data;
1286
6.62M
    int kind;
1287
6.62M
    int is_ascii;
1288
6.62M
    Py_ssize_t char_size;
1289
6.62M
    Py_ssize_t struct_size;
1290
1291
6.62M
    is_ascii = 0;
1292
6.62M
    struct_size = sizeof(PyCompactUnicodeObject);
1293
6.62M
    if (maxchar < 128) {
1294
6.08M
        kind = PyUnicode_1BYTE_KIND;
1295
6.08M
        char_size = 1;
1296
6.08M
        is_ascii = 1;
1297
6.08M
        struct_size = sizeof(PyASCIIObject);
1298
6.08M
    }
1299
534k
    else if (maxchar < 256) {
1300
330k
        kind = PyUnicode_1BYTE_KIND;
1301
330k
        char_size = 1;
1302
330k
    }
1303
203k
    else if (maxchar < 65536) {
1304
103k
        kind = PyUnicode_2BYTE_KIND;
1305
103k
        char_size = 2;
1306
103k
    }
1307
99.9k
    else {
1308
99.9k
        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
99.9k
        kind = PyUnicode_4BYTE_KIND;
1314
99.9k
        char_size = 4;
1315
99.9k
    }
1316
1317
    /* Ensure we won't overflow the size. */
1318
6.62M
    if (size < 0) {
1319
0
        PyErr_SetString(PyExc_SystemError,
1320
0
                        "Negative size passed to PyUnicode_New");
1321
0
        return NULL;
1322
0
    }
1323
6.62M
    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
6.62M
    obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
1331
6.62M
    if (obj == NULL) {
1332
0
        return PyErr_NoMemory();
1333
0
    }
1334
6.62M
    _PyObject_Init(obj, &PyUnicode_Type);
1335
1336
6.62M
    unicode = (PyCompactUnicodeObject *)obj;
1337
6.62M
    if (is_ascii)
1338
6.08M
        data = ((PyASCIIObject*)obj) + 1;
1339
534k
    else
1340
534k
        data = unicode + 1;
1341
6.62M
    _PyUnicode_LENGTH(unicode) = size;
1342
6.62M
    _PyUnicode_HASH(unicode) = -1;
1343
6.62M
    _PyUnicode_STATE(unicode).interned = 0;
1344
6.62M
    _PyUnicode_STATE(unicode).kind = kind;
1345
6.62M
    _PyUnicode_STATE(unicode).compact = 1;
1346
6.62M
    _PyUnicode_STATE(unicode).ascii = is_ascii;
1347
6.62M
    _PyUnicode_STATE(unicode).statically_allocated = 0;
1348
6.62M
    if (is_ascii) {
1349
6.08M
        ((char*)data)[size] = 0;
1350
6.08M
    }
1351
534k
    else if (kind == PyUnicode_1BYTE_KIND) {
1352
330k
        ((char*)data)[size] = 0;
1353
330k
        unicode->utf8 = NULL;
1354
330k
        unicode->utf8_length = 0;
1355
330k
    }
1356
203k
    else {
1357
203k
        unicode->utf8 = NULL;
1358
203k
        unicode->utf8_length = 0;
1359
203k
        if (kind == PyUnicode_2BYTE_KIND)
1360
103k
            ((Py_UCS2*)data)[size] = 0;
1361
99.9k
        else /* kind == PyUnicode_4BYTE_KIND */
1362
99.9k
            ((Py_UCS4*)data)[size] = 0;
1363
203k
    }
1364
#ifdef Py_DEBUG
1365
    unicode_fill_invalid((PyObject*)unicode, 0);
1366
#endif
1367
6.62M
    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
1368
6.62M
    return obj;
1369
6.62M
}
1370
1371
static int
1372
unicode_check_modifiable(PyObject *unicode)
1373
9
{
1374
9
    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
9
    return 0;
1380
9
}
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
9.70M
{
1387
9.70M
    int from_kind, to_kind;
1388
9.70M
    const void *from_data;
1389
9.70M
    void *to_data;
1390
1391
9.70M
    assert(0 <= how_many);
1392
9.70M
    assert(0 <= from_start);
1393
9.70M
    assert(0 <= to_start);
1394
9.70M
    assert(PyUnicode_Check(from));
1395
9.70M
    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
1396
1397
9.70M
    assert(to == NULL || PyUnicode_Check(to));
1398
1399
9.70M
    if (how_many == 0) {
1400
1.11k
        return 0;
1401
1.11k
    }
1402
1403
9.70M
    assert(to != NULL);
1404
9.70M
    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1405
1406
9.70M
    from_kind = PyUnicode_KIND(from);
1407
9.70M
    from_data = PyUnicode_DATA(from);
1408
9.70M
    to_kind = PyUnicode_KIND(to);
1409
9.70M
    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
9.70M
    if (from_kind == to_kind) {
1426
9.55M
        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
9.55M
        memcpy((char*)to_data + to_kind * to_start,
1438
9.55M
                  (const char*)from_data + from_kind * from_start,
1439
9.55M
                  to_kind * how_many);
1440
9.55M
    }
1441
155k
    else if (from_kind == PyUnicode_1BYTE_KIND
1442
40.1k
             && to_kind == PyUnicode_2BYTE_KIND)
1443
30.6k
    {
1444
30.6k
        _PyUnicode_CONVERT_BYTES(
1445
30.6k
            Py_UCS1, Py_UCS2,
1446
30.6k
            PyUnicode_1BYTE_DATA(from) + from_start,
1447
30.6k
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448
30.6k
            PyUnicode_2BYTE_DATA(to) + to_start
1449
30.6k
            );
1450
30.6k
    }
1451
125k
    else if (from_kind == PyUnicode_1BYTE_KIND
1452
9.47k
             && to_kind == PyUnicode_4BYTE_KIND)
1453
9.47k
    {
1454
9.47k
        _PyUnicode_CONVERT_BYTES(
1455
9.47k
            Py_UCS1, Py_UCS4,
1456
9.47k
            PyUnicode_1BYTE_DATA(from) + from_start,
1457
9.47k
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458
9.47k
            PyUnicode_4BYTE_DATA(to) + to_start
1459
9.47k
            );
1460
9.47k
    }
1461
115k
    else if (from_kind == PyUnicode_2BYTE_KIND
1462
39.7k
             && to_kind == PyUnicode_4BYTE_KIND)
1463
32.0k
    {
1464
32.0k
        _PyUnicode_CONVERT_BYTES(
1465
32.0k
            Py_UCS2, Py_UCS4,
1466
32.0k
            PyUnicode_2BYTE_DATA(from) + from_start,
1467
32.0k
            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468
32.0k
            PyUnicode_4BYTE_DATA(to) + to_start
1469
32.0k
            );
1470
32.0k
    }
1471
83.6k
    else {
1472
83.6k
        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
1474
83.6k
        if (!check_maxchar) {
1475
83.6k
            if (from_kind == PyUnicode_2BYTE_KIND
1476
7.70k
                && to_kind == PyUnicode_1BYTE_KIND)
1477
7.70k
            {
1478
7.70k
                _PyUnicode_CONVERT_BYTES(
1479
7.70k
                    Py_UCS2, Py_UCS1,
1480
7.70k
                    PyUnicode_2BYTE_DATA(from) + from_start,
1481
7.70k
                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482
7.70k
                    PyUnicode_1BYTE_DATA(to) + to_start
1483
7.70k
                    );
1484
7.70k
            }
1485
75.9k
            else if (from_kind == PyUnicode_4BYTE_KIND
1486
75.9k
                     && to_kind == PyUnicode_1BYTE_KIND)
1487
47.7k
            {
1488
47.7k
                _PyUnicode_CONVERT_BYTES(
1489
47.7k
                    Py_UCS4, Py_UCS1,
1490
47.7k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1491
47.7k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492
47.7k
                    PyUnicode_1BYTE_DATA(to) + to_start
1493
47.7k
                    );
1494
47.7k
            }
1495
28.1k
            else if (from_kind == PyUnicode_4BYTE_KIND
1496
28.1k
                     && to_kind == PyUnicode_2BYTE_KIND)
1497
28.1k
            {
1498
28.1k
                _PyUnicode_CONVERT_BYTES(
1499
28.1k
                    Py_UCS4, Py_UCS2,
1500
28.1k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1501
28.1k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502
28.1k
                    PyUnicode_2BYTE_DATA(to) + to_start
1503
28.1k
                    );
1504
28.1k
            }
1505
0
            else {
1506
0
                Py_UNREACHABLE();
1507
0
            }
1508
83.6k
        }
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
83.6k
    }
1522
9.70M
    return 0;
1523
9.70M
}
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
9.70M
{
1530
9.70M
    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1531
9.70M
}
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
1.24k
{
1593
1.24k
    const wchar_t *iter;
1594
1.24k
    Py_UCS4 ch;
1595
1596
1.24k
    assert(num_surrogates != NULL && maxchar != NULL);
1597
1.24k
    *num_surrogates = 0;
1598
1.24k
    *maxchar = 0;
1599
1600
46.6k
    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
45.4k
        {
1613
45.4k
            ch = *iter;
1614
45.4k
            iter++;
1615
45.4k
        }
1616
45.4k
        if (ch > *maxchar) {
1617
3.94k
            *maxchar = ch;
1618
3.94k
            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
3.94k
        }
1625
45.4k
    }
1626
1.24k
    return 0;
1627
1.24k
}
1628
1629
static void
1630
unicode_dealloc(PyObject *unicode)
1631
6.12M
{
1632
#ifdef Py_DEBUG
1633
    if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
1634
        _Py_FatalRefcountError("deallocating an Unicode singleton");
1635
    }
1636
#endif
1637
12.2M
    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
6.12M
    switch (_PyUnicode_STATE(unicode).interned) {
1649
5.96M
        case SSTATE_NOT_INTERNED:
1650
5.96M
            break;
1651
159k
        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
159k
            assert(Py_REFCNT(unicode) == 0);
1657
159k
            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
159k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1664
159k
            PyObject *interned = get_interned_dict(interp);
1665
159k
            assert(interned != NULL);
1666
159k
            PyObject *popped;
1667
159k
            int r = PyDict_Pop(interned, unicode, &popped);
1668
159k
            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
159k
            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
159k
            assert(popped == unicode);
1691
            // Only our `popped` reference should be left; remove it too.
1692
159k
            assert(Py_REFCNT(unicode) == 1);
1693
159k
            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
159k
            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
6.12M
    }
1707
6.12M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1708
56
        PyMem_Free(_PyUnicode_UTF8(unicode));
1709
56
    }
1710
6.12M
    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
1711
0
        PyMem_Free(_PyUnicode_DATA_ANY(unicode));
1712
0
    }
1713
1714
6.12M
    Py_TYPE(unicode)->tp_free(unicode);
1715
6.12M
}
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
18.0M
{
1739
18.0M
    assert(_PyUnicode_CHECK(unicode));
1740
18.0M
    if (!_PyObject_IsUniquelyReferenced(unicode))
1741
430k
        return 0;
1742
17.6M
    if (PyUnicode_HASH(unicode) != -1)
1743
0
        return 0;
1744
17.6M
    if (PyUnicode_CHECK_INTERNED(unicode))
1745
0
        return 0;
1746
17.6M
    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
17.6M
    return 1;
1753
17.6M
}
1754
1755
static int
1756
unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1757
5.39M
{
1758
5.39M
    PyObject *unicode;
1759
5.39M
    Py_ssize_t old_length;
1760
1761
5.39M
    assert(p_unicode != NULL);
1762
5.39M
    unicode = *p_unicode;
1763
1764
5.39M
    assert(unicode != NULL);
1765
5.39M
    assert(PyUnicode_Check(unicode));
1766
5.39M
    assert(0 <= length);
1767
1768
5.39M
    old_length = PyUnicode_GET_LENGTH(unicode);
1769
5.39M
    if (old_length == length)
1770
0
        return 0;
1771
1772
5.39M
    if (length == 0) {
1773
0
        PyObject *empty = _PyUnicode_GetEmpty();
1774
0
        Py_SETREF(*p_unicode, empty);
1775
0
        return 0;
1776
0
    }
1777
1778
5.39M
    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
5.39M
    if (PyUnicode_IS_COMPACT(unicode)) {
1787
5.39M
        PyObject *new_unicode = _PyUnicode_ResizeCompact(unicode, length);
1788
5.39M
        if (new_unicode == NULL)
1789
0
            return -1;
1790
5.39M
        *p_unicode = new_unicode;
1791
5.39M
        return 0;
1792
5.39M
    }
1793
0
    return resize_inplace(unicode, length);
1794
5.39M
}
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
3.40M
{
1816
3.40M
    PyObject *o = LATIN1(ch);
1817
3.40M
    return o;
1818
3.40M
}
1819
1820
static PyObject*
1821
unicode_char(Py_UCS4 ch)
1822
3.32M
{
1823
3.32M
    PyObject *unicode;
1824
1825
3.32M
    assert(ch <= MAX_UNICODE);
1826
1827
3.32M
    if (ch < 256) {
1828
3.27M
        return get_latin1_char(ch);
1829
3.27M
    }
1830
1831
54.9k
    unicode = PyUnicode_New(1, ch);
1832
54.9k
    if (unicode == NULL)
1833
0
        return NULL;
1834
1835
54.9k
    assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1836
109k
    if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
1837
52.4k
        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1838
52.4k
    } else {
1839
2.57k
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1840
2.57k
        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1841
2.57k
    }
1842
54.9k
    assert(_PyUnicode_CheckConsistency(unicode, 1));
1843
54.9k
    return unicode;
1844
54.9k
}
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
1.24k
{
1852
1.24k
    switch (kind) {
1853
1.24k
    case PyUnicode_1BYTE_KIND:
1854
1.24k
        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, u, u + size, data);
1855
1.24k
        break;
1856
1857
0
    case PyUnicode_2BYTE_KIND:
1858
#if SIZEOF_WCHAR_T == 2
1859
        memcpy(data, u, size * 2);
1860
#else
1861
0
        _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2, u, u + size, data);
1862
0
#endif
1863
0
        break;
1864
1865
0
    case PyUnicode_4BYTE_KIND:
1866
0
    {
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
0
        assert(num_surrogates == 0);
1892
0
        memcpy(data, u, size * 4);
1893
0
#endif
1894
0
        break;
1895
0
    }
1896
0
    default:
1897
0
        Py_UNREACHABLE();
1898
1.24k
    }
1899
1.24k
}
1900
1901
1902
PyObject *
1903
PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
1904
1.28k
{
1905
1.28k
    PyObject *unicode;
1906
1.28k
    Py_UCS4 maxchar = 0;
1907
1.28k
    Py_ssize_t num_surrogates;
1908
1909
1.28k
    if (u == NULL && size != 0) {
1910
0
        PyErr_BadInternalCall();
1911
0
        return NULL;
1912
0
    }
1913
1914
1.28k
    if (size == -1) {
1915
820
        size = wcslen(u);
1916
820
    }
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
1.28k
    if (size == 0)
1923
40
        _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
1.24k
    if (size == 1 && (Py_UCS4)*u < 256)
1942
0
        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
1.24k
    if (find_maxchar_surrogates(u, u + size,
1947
1.24k
                                &maxchar, &num_surrogates) == -1)
1948
0
        return NULL;
1949
1950
1.24k
    unicode = PyUnicode_New(size - num_surrogates, maxchar);
1951
1.24k
    if (!unicode)
1952
0
        return NULL;
1953
1954
1.24k
    unicode_write_widechar(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1955
1.24k
                           u, size, num_surrogates);
1956
1957
1.24k
    return unicode_result(unicode);
1958
1.24k
}
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
41.3k
{
2014
41.3k
    if (size < 0) {
2015
0
        PyErr_SetString(PyExc_SystemError,
2016
0
                        "Negative size passed to PyUnicode_FromStringAndSize");
2017
0
        return NULL;
2018
0
    }
2019
41.3k
    if (u != NULL) {
2020
41.3k
        return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2021
41.3k
    }
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
1.73M
{
2033
1.73M
    size_t size = strlen(u);
2034
1.73M
    if (size > PY_SSIZE_T_MAX) {
2035
0
        PyErr_SetString(PyExc_OverflowError, "input too long");
2036
0
        return NULL;
2037
0
    }
2038
1.73M
    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
2039
1.73M
}
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
10.1M
{
2128
10.1M
    const unsigned char *s = (const unsigned char *)buffer;
2129
10.1M
    PyObject *unicode;
2130
10.1M
    if (size == 1) {
2131
#ifdef Py_DEBUG
2132
        assert((unsigned char)s[0] < 128);
2133
#endif
2134
120k
        return get_latin1_char(s[0]);
2135
120k
    }
2136
10.0M
    unicode = PyUnicode_New(size, 127);
2137
10.0M
    if (!unicode)
2138
0
        return NULL;
2139
10.0M
    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2140
10.0M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
2141
10.0M
    return unicode;
2142
10.0M
}
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
9.96M
{
2162
9.96M
    PyObject *res;
2163
9.96M
    unsigned char max_char;
2164
2165
9.96M
    if (size == 0) {
2166
9.80M
        _Py_RETURN_UNICODE_EMPTY();
2167
9.80M
    }
2168
9.96M
    assert(size > 0);
2169
153k
    if (size == 1) {
2170
11.6k
        return get_latin1_char(u[0]);
2171
11.6k
    }
2172
2173
141k
    max_char = ucs1lib_find_max_char(u, u + size);
2174
141k
    res = PyUnicode_New(size, max_char);
2175
141k
    if (!res)
2176
0
        return NULL;
2177
141k
    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
2178
141k
    assert(_PyUnicode_CheckConsistency(res, 1));
2179
141k
    return res;
2180
141k
}
2181
2182
static PyObject*
2183
_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
2184
5.11M
{
2185
5.11M
    PyObject *res;
2186
5.11M
    Py_UCS2 max_char;
2187
2188
5.11M
    if (size == 0)
2189
4.87M
        _Py_RETURN_UNICODE_EMPTY();
2190
5.11M
    assert(size > 0);
2191
238k
    if (size == 1)
2192
42.5k
        return unicode_char(u[0]);
2193
2194
195k
    max_char = ucs2lib_find_max_char(u, u + size);
2195
195k
    res = PyUnicode_New(size, max_char);
2196
195k
    if (!res)
2197
0
        return NULL;
2198
195k
    if (max_char >= 256)
2199
1.80k
        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
2200
193k
    else {
2201
193k
        _PyUnicode_CONVERT_BYTES(
2202
193k
            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2203
193k
    }
2204
195k
    assert(_PyUnicode_CheckConsistency(res, 1));
2205
195k
    return res;
2206
195k
}
2207
2208
static PyObject*
2209
_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
2210
7.89M
{
2211
7.89M
    PyObject *res;
2212
7.89M
    Py_UCS4 max_char;
2213
2214
7.89M
    if (size == 0)
2215
7.35M
        _Py_RETURN_UNICODE_EMPTY();
2216
7.89M
    assert(size > 0);
2217
542k
    if (size == 1)
2218
92.8k
        return unicode_char(u[0]);
2219
2220
449k
    max_char = ucs4lib_find_max_char(u, u + size);
2221
449k
    res = PyUnicode_New(size, max_char);
2222
449k
    if (!res)
2223
0
        return NULL;
2224
449k
    if (max_char < 256)
2225
432k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2226
449k
                                 PyUnicode_1BYTE_DATA(res));
2227
17.3k
    else if (max_char < 0x10000)
2228
12.7k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2229
17.3k
                                 PyUnicode_2BYTE_DATA(res));
2230
4.65k
    else
2231
4.65k
        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
2232
449k
    assert(_PyUnicode_CheckConsistency(res, 1));
2233
449k
    return res;
2234
449k
}
2235
2236
2237
int
2238
PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *pub_writer,
2239
                          const Py_UCS4 *str,
2240
                          Py_ssize_t size)
2241
0
{
2242
0
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
2243
2244
0
    if (size < 0) {
2245
0
        PyErr_SetString(PyExc_ValueError,
2246
0
                        "size must be positive");
2247
0
        return -1;
2248
0
    }
2249
2250
0
    if (size == 0) {
2251
0
        return 0;
2252
0
    }
2253
2254
0
    Py_UCS4 max_char = ucs4lib_find_max_char(str, str + size);
2255
2256
0
    if (_PyUnicodeWriter_Prepare(writer, size, max_char) < 0) {
2257
0
        return -1;
2258
0
    }
2259
2260
0
    int kind = writer->kind;
2261
0
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2262
0
    if (kind == PyUnicode_1BYTE_KIND) {
2263
0
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1,
2264
0
                                 str, str + size,
2265
0
                                 data);
2266
0
    }
2267
0
    else if (kind == PyUnicode_2BYTE_KIND) {
2268
0
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2,
2269
0
                                 str, str + size,
2270
0
                                 data);
2271
0
    }
2272
0
    else {
2273
0
        memcpy(data, str, size * sizeof(Py_UCS4));
2274
0
    }
2275
0
    writer->pos += size;
2276
2277
0
    return 0;
2278
0
}
2279
2280
2281
PyObject*
2282
PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2283
1.85M
{
2284
1.85M
    if (size < 0) {
2285
0
        PyErr_SetString(PyExc_ValueError, "size must be positive");
2286
0
        return NULL;
2287
0
    }
2288
1.85M
    switch (kind) {
2289
146k
    case PyUnicode_1BYTE_KIND:
2290
146k
        return _PyUnicode_FromUCS1(buffer, size);
2291
169k
    case PyUnicode_2BYTE_KIND:
2292
169k
        return _PyUnicode_FromUCS2(buffer, size);
2293
1.53M
    case PyUnicode_4BYTE_KIND:
2294
1.53M
        return _PyUnicode_FromUCS4(buffer, size);
2295
0
    default:
2296
0
        PyErr_SetString(PyExc_SystemError, "invalid kind");
2297
0
        return NULL;
2298
1.85M
    }
2299
1.85M
}
2300
2301
Py_UCS4
2302
_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2303
1.44M
{
2304
1.44M
    int kind;
2305
1.44M
    const void *startptr, *endptr;
2306
2307
1.44M
    assert(0 <= start);
2308
1.44M
    assert(end <= PyUnicode_GET_LENGTH(unicode));
2309
1.44M
    assert(start <= end);
2310
2311
1.44M
    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2312
0
        return PyUnicode_MAX_CHAR_VALUE(unicode);
2313
2314
1.44M
    if (start == end)
2315
0
        return 127;
2316
2317
1.44M
    if (PyUnicode_IS_ASCII(unicode))
2318
1.34M
        return 127;
2319
2320
92.3k
    kind = PyUnicode_KIND(unicode);
2321
92.3k
    startptr = PyUnicode_DATA(unicode);
2322
92.3k
    endptr = (char *)startptr + end * kind;
2323
92.3k
    startptr = (char *)startptr + start * kind;
2324
92.3k
    switch(kind) {
2325
4.28k
    case PyUnicode_1BYTE_KIND:
2326
4.28k
        return ucs1lib_find_max_char(startptr, endptr);
2327
8.54k
    case PyUnicode_2BYTE_KIND:
2328
8.54k
        return ucs2lib_find_max_char(startptr, endptr);
2329
79.5k
    case PyUnicode_4BYTE_KIND:
2330
79.5k
        return ucs4lib_find_max_char(startptr, endptr);
2331
0
    default:
2332
0
        Py_UNREACHABLE();
2333
92.3k
    }
2334
92.3k
}
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
0
{
2385
0
    Py_ssize_t length;
2386
0
    PyObject *copy;
2387
2388
0
    if (!PyUnicode_Check(unicode)) {
2389
0
        PyErr_BadInternalCall();
2390
0
        return NULL;
2391
0
    }
2392
2393
0
    length = PyUnicode_GET_LENGTH(unicode);
2394
0
    copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
2395
0
    if (!copy)
2396
0
        return NULL;
2397
0
    assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2398
2399
0
    memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2400
0
              length * PyUnicode_KIND(unicode));
2401
0
    assert(_PyUnicode_CheckConsistency(copy, 1));
2402
0
    return copy;
2403
0
}
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
3.30k
{
2412
3.30k
    void *result;
2413
2414
3.30k
    assert(skind < kind);
2415
3.30k
    switch (kind) {
2416
1.44k
    case PyUnicode_2BYTE_KIND:
2417
1.44k
        result = PyMem_New(Py_UCS2, len);
2418
1.44k
        if (!result)
2419
0
            return PyErr_NoMemory();
2420
1.44k
        assert(skind == PyUnicode_1BYTE_KIND);
2421
1.44k
        _PyUnicode_CONVERT_BYTES(
2422
1.44k
            Py_UCS1, Py_UCS2,
2423
1.44k
            (const Py_UCS1 *)data,
2424
1.44k
            ((const Py_UCS1 *)data) + len,
2425
1.44k
            result);
2426
1.44k
        return result;
2427
1.86k
    case PyUnicode_4BYTE_KIND:
2428
1.86k
        result = PyMem_New(Py_UCS4, len);
2429
1.86k
        if (!result)
2430
0
            return PyErr_NoMemory();
2431
1.86k
        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
1.86k
        else {
2439
1.86k
            assert(skind == PyUnicode_1BYTE_KIND);
2440
1.86k
            _PyUnicode_CONVERT_BYTES(
2441
1.86k
                Py_UCS1, Py_UCS4,
2442
1.86k
                (const Py_UCS1 *)data,
2443
1.86k
                ((const Py_UCS1 *)data) + len,
2444
1.86k
                result);
2445
1.86k
        }
2446
1.86k
        return result;
2447
0
    default:
2448
0
        Py_UNREACHABLE();
2449
0
        return NULL;
2450
3.30k
    }
2451
3.30k
}
2452
2453
static Py_UCS4*
2454
as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2455
        int copy_null)
2456
0
{
2457
0
    int kind;
2458
0
    const void *data;
2459
0
    Py_ssize_t len, targetlen;
2460
0
    kind = PyUnicode_KIND(string);
2461
0
    data = PyUnicode_DATA(string);
2462
0
    len = PyUnicode_GET_LENGTH(string);
2463
0
    targetlen = len;
2464
0
    if (copy_null)
2465
0
        targetlen++;
2466
0
    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
0
    else {
2474
0
        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
0
    }
2482
0
    if (kind == PyUnicode_1BYTE_KIND) {
2483
0
        const Py_UCS1 *start = (const Py_UCS1 *) data;
2484
0
        _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
2485
0
    }
2486
0
    else if (kind == PyUnicode_2BYTE_KIND) {
2487
0
        const Py_UCS2 *start = (const Py_UCS2 *) data;
2488
0
        _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2489
0
    }
2490
0
    else if (kind == PyUnicode_4BYTE_KIND) {
2491
0
        memcpy(target, data, len * sizeof(Py_UCS4));
2492
0
    }
2493
0
    else {
2494
0
        Py_UNREACHABLE();
2495
0
    }
2496
0
    if (copy_null)
2497
0
        target[len] = 0;
2498
0
    return target;
2499
0
}
2500
2501
Py_UCS4*
2502
PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2503
                 int copy_null)
2504
0
{
2505
0
    if (target == NULL || targetsize < 0) {
2506
0
        PyErr_BadInternalCall();
2507
0
        return NULL;
2508
0
    }
2509
0
    return as_ucs4(string, target, targetsize, copy_null);
2510
0
}
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.39k
{
2528
7.39k
    Py_ssize_t length, fill, arglen;
2529
7.39k
    Py_UCS4 maxchar;
2530
2531
7.39k
    length = PyUnicode_GET_LENGTH(str);
2532
7.39k
    if ((precision == -1 || precision >= length)
2533
5.93k
        && width <= length)
2534
5.93k
        return _PyUnicodeWriter_WriteStr(writer, str);
2535
2536
1.46k
    if (precision != -1)
2537
1.46k
        length = Py_MIN(precision, length);
2538
2539
1.46k
    arglen = Py_MAX(length, width);
2540
1.46k
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2541
361
        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2542
1.10k
    else
2543
1.10k
        maxchar = writer->maxchar;
2544
2545
1.46k
    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2546
0
        return -1;
2547
2548
1.46k
    fill = Py_MAX(width - length, 0);
2549
1.46k
    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
1.46k
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2556
1.46k
                                  str, 0, length);
2557
1.46k
    writer->pos += length;
2558
2559
1.46k
    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
1.46k
    return 0;
2566
1.46k
}
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
5.14k
{
2572
    /* UTF-8 */
2573
5.14k
    Py_ssize_t *pconsumed = NULL;
2574
5.14k
    Py_ssize_t length;
2575
5.14k
    if (precision == -1) {
2576
1.00k
        length = strlen(str);
2577
1.00k
    }
2578
4.13k
    else {
2579
4.13k
        length = 0;
2580
60.9k
        while (length < precision && str[length]) {
2581
56.8k
            length++;
2582
56.8k
        }
2583
4.13k
        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
66
            pconsumed = &length;
2590
66
        }
2591
4.13k
    }
2592
2593
5.14k
    if (width < 0) {
2594
5.14k
        return _PyUnicode_DecodeUTF8Writer(writer, str, length,
2595
5.14k
                                           _Py_ERROR_REPLACE, "replace", pconsumed);
2596
5.14k
    }
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
1.07k
#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
17.8k
{
2648
17.8k
    const char *p;
2649
17.8k
    Py_ssize_t len;
2650
17.8k
    int flags = 0;
2651
17.8k
    Py_ssize_t width;
2652
17.8k
    Py_ssize_t precision;
2653
2654
17.8k
    p = f;
2655
17.8k
    f++;
2656
17.8k
    if (*f == '%') {
2657
0
        if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
2658
0
            return NULL;
2659
0
        f++;
2660
0
        return f;
2661
0
    }
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
17.8k
    while (1) {
2669
17.8k
        switch (*f++) {
2670
0
        case '-': flags |= F_LJUST; continue;
2671
12
        case '0': flags |= F_ZERO; continue;
2672
0
        case '#': flags |= F_ALT; continue;
2673
17.8k
        }
2674
17.8k
        f--;
2675
17.8k
        break;
2676
17.8k
    }
2677
2678
    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2679
17.8k
    width = -1;
2680
17.8k
    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
17.8k
    else if (Py_ISDIGIT((unsigned)*f)) {
2689
12
        width = *f - '0';
2690
12
        f++;
2691
12
        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
12
    }
2701
17.8k
    precision = -1;
2702
17.8k
    if (*f == '.') {
2703
8.68k
        f++;
2704
8.68k
        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
8.68k
        else if (Py_ISDIGIT((unsigned)*f)) {
2712
8.68k
            precision = (*f - '0');
2713
8.68k
            f++;
2714
26.0k
            while (Py_ISDIGIT((unsigned)*f)) {
2715
17.3k
                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
17.3k
                precision = (precision * 10) + (*f - '0');
2721
17.3k
                f++;
2722
17.3k
            }
2723
8.68k
        }
2724
8.68k
    }
2725
2726
17.8k
    int sizemod = 0;
2727
17.8k
    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
17.8k
    else if (*f == 'z') {
2738
536
        sizemod = F_SIZE;
2739
536
        ++f;
2740
536
    }
2741
17.3k
    else if (*f == 't') {
2742
0
        sizemod = F_PTRDIFF;
2743
0
        ++f;
2744
0
    }
2745
17.3k
    else if (*f == 'j') {
2746
0
        sizemod = F_INTMAX;
2747
0
        ++f;
2748
0
    }
2749
17.8k
    if (f[0] != '\0' && f[1] == '\0')
2750
6.81k
        writer->overallocate = 0;
2751
2752
17.8k
    switch (*f) {
2753
5.27k
    case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
2754
5.27k
        break;
2755
50
    case 'c': case 'p':
2756
50
        if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
2757
50
        break;
2758
5.14k
    case 's':
2759
5.14k
    case 'V':
2760
5.14k
        if (sizemod && sizemod != F_LONG) goto invalid_format;
2761
5.14k
        break;
2762
7.39k
    default:
2763
7.39k
        if (sizemod) goto invalid_format;
2764
7.39k
        break;
2765
17.8k
    }
2766
2767
17.8k
    switch (*f) {
2768
50
    case 'c':
2769
50
    {
2770
50
        int ordinal = va_arg(*vargs, int);
2771
50
        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
50
        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
2777
0
            return NULL;
2778
50
        break;
2779
50
    }
2780
2781
5.26k
    case 'd': case 'i':
2782
5.27k
    case 'o': case 'u': case 'x': case 'X':
2783
5.27k
    {
2784
5.27k
        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
5.27k
        #define SPRINT(SIZE_SPEC, FMT_CHAR, TYPE) \
2798
5.27k
            sprintf(buffer, "%" SIZE_SPEC FMT_CHAR, va_arg(*vargs, TYPE))
2799
2800
        // One inner switch to handle all format variants
2801
5.27k
        #define DO_SPRINTS(SIZE_SPEC, SIGNED_TYPE, UNSIGNED_TYPE)             \
2802
5.27k
            switch (*f) {                                                     \
2803
0
                case 'o': len = SPRINT(SIZE_SPEC, "o", UNSIGNED_TYPE); break; \
2804
0
                case 'u': len = SPRINT(SIZE_SPEC, "u", UNSIGNED_TYPE); break; \
2805
0
                case 'x': len = SPRINT(SIZE_SPEC, "x", UNSIGNED_TYPE); break; \
2806
12
                case 'X': len = SPRINT(SIZE_SPEC, "X", UNSIGNED_TYPE); break; \
2807
5.26k
                default:  len = SPRINT(SIZE_SPEC, "d", SIGNED_TYPE); break;   \
2808
5.27k
            }
2809
2810
        // Outer switch to handle all the sizes/types
2811
5.27k
        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
536
            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
4.74k
            default:         DO_SPRINTS("", int, unsigned int); break;
2818
5.27k
        }
2819
5.27k
        #undef SPRINT
2820
5.27k
        #undef DO_SPRINTS
2821
2822
5.27k
        assert(len >= 0);
2823
2824
5.27k
        int sign = (buffer[0] == '-');
2825
5.27k
        len -= sign;
2826
2827
5.27k
        precision = Py_MAX(precision, len);
2828
5.27k
        width = Py_MAX(width, precision + sign);
2829
5.27k
        if ((flags & F_ZERO) && !(flags & F_LJUST)) {
2830
12
            precision = width - sign;
2831
12
        }
2832
2833
5.27k
        Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
2834
5.27k
        Py_ssize_t zeropad = Py_MAX(precision - len, 0);
2835
2836
5.27k
        if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1)
2837
0
            return NULL;
2838
2839
5.27k
        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
5.27k
        if (sign) {
2846
0
            if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
2847
0
                return NULL;
2848
0
        }
2849
2850
5.27k
        if (zeropad) {
2851
9
            if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
2852
0
                return NULL;
2853
9
            writer->pos += zeropad;
2854
9
        }
2855
2856
5.27k
        if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
2857
0
            return NULL;
2858
2859
5.27k
        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
5.27k
        break;
2865
5.27k
    }
2866
2867
5.27k
    case 'p':
2868
0
    {
2869
0
        char number[MAX_INTMAX_CHARS];
2870
2871
0
        len = sprintf(number, "%p", va_arg(*vargs, void*));
2872
0
        assert(len >= 0);
2873
2874
        /* %p is ill-defined:  ensure leading 0x. */
2875
0
        if (number[1] == 'X')
2876
0
            number[1] = 'x';
2877
0
        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
0
        if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
2886
0
            return NULL;
2887
0
        break;
2888
0
    }
2889
2890
5.14k
    case 's':
2891
5.14k
    {
2892
5.14k
        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
5.14k
        else {
2898
            /* UTF-8 */
2899
5.14k
            const char *s = va_arg(*vargs, const char*);
2900
5.14k
            if (unicode_fromformat_write_utf8(writer, s, width, precision, flags) < 0)
2901
0
                return NULL;
2902
5.14k
        }
2903
5.14k
        break;
2904
5.14k
    }
2905
2906
5.14k
    case 'U':
2907
776
    {
2908
776
        PyObject *obj = va_arg(*vargs, PyObject *);
2909
776
        assert(obj && _PyUnicode_CHECK(obj));
2910
2911
776
        if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2912
0
            return NULL;
2913
776
        break;
2914
776
    }
2915
2916
776
    case 'V':
2917
0
    {
2918
0
        PyObject *obj = va_arg(*vargs, PyObject *);
2919
0
        const char *str;
2920
0
        const wchar_t *wstr;
2921
0
        if (sizemod) {
2922
0
            wstr = va_arg(*vargs, const wchar_t*);
2923
0
        }
2924
0
        else {
2925
0
            str = va_arg(*vargs, const char *);
2926
0
        }
2927
0
        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
0
        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
0
        else {
2938
0
            assert(str != NULL);
2939
0
            if (unicode_fromformat_write_utf8(writer, str, width, precision, flags) < 0)
2940
0
                return NULL;
2941
0
        }
2942
0
        break;
2943
0
    }
2944
2945
60
    case 'S':
2946
60
    {
2947
60
        PyObject *obj = va_arg(*vargs, PyObject *);
2948
60
        PyObject *str;
2949
60
        assert(obj);
2950
60
        str = PyObject_Str(obj);
2951
60
        if (!str)
2952
0
            return NULL;
2953
60
        if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
2954
0
            Py_DECREF(str);
2955
0
            return NULL;
2956
0
        }
2957
60
        Py_DECREF(str);
2958
60
        break;
2959
60
    }
2960
2961
6.56k
    case 'R':
2962
6.56k
    {
2963
6.56k
        PyObject *obj = va_arg(*vargs, PyObject *);
2964
6.56k
        PyObject *repr;
2965
6.56k
        assert(obj);
2966
6.56k
        repr = PyObject_Repr(obj);
2967
6.56k
        if (!repr)
2968
0
            return NULL;
2969
6.56k
        if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
2970
0
            Py_DECREF(repr);
2971
0
            return NULL;
2972
0
        }
2973
6.56k
        Py_DECREF(repr);
2974
6.56k
        break;
2975
6.56k
    }
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
0
    case 'T':
2994
0
    {
2995
0
        PyObject *obj = va_arg(*vargs, PyObject *);
2996
0
        PyTypeObject *type = (PyTypeObject *)Py_NewRef(Py_TYPE(obj));
2997
2998
0
        PyObject *type_name;
2999
0
        if (flags & F_ALT) {
3000
0
            type_name = _PyType_GetFullyQualifiedName(type, ':');
3001
0
        }
3002
0
        else {
3003
0
            type_name = PyType_GetFullyQualifiedName(type);
3004
0
        }
3005
0
        Py_DECREF(type);
3006
0
        if (!type_name) {
3007
0
            return NULL;
3008
0
        }
3009
3010
0
        if (unicode_fromformat_write_str(writer, type_name,
3011
0
                                         width, precision, flags) == -1) {
3012
0
            Py_DECREF(type_name);
3013
0
            return NULL;
3014
0
        }
3015
0
        Py_DECREF(type_name);
3016
0
        break;
3017
0
    }
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
17.8k
    }
3054
3055
17.8k
    f++;
3056
17.8k
    return f;
3057
17.8k
}
3058
3059
static int
3060
unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
3061
27.0k
{
3062
27.0k
    Py_ssize_t len = strlen(format);
3063
27.0k
    writer->min_length += len + 100;
3064
27.0k
    writer->overallocate = 1;
3065
3066
    // Copy varags to be able to pass a reference to a subfunction.
3067
27.0k
    va_list vargs2;
3068
27.0k
    va_copy(vargs2, vargs);
3069
3070
    // _PyUnicodeWriter_WriteASCIIString() below requires the format string
3071
    // to be encoded to ASCII.
3072
27.0k
    int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)format, (Py_UCS1*)format + len) < 128);
3073
27.0k
    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
82.4k
    for (const char *f = format; *f; ) {
3084
55.4k
        if (*f == '%') {
3085
17.8k
            f = unicode_fromformat_arg(writer, f, &vargs2);
3086
17.8k
            if (f == NULL)
3087
0
                goto fail;
3088
17.8k
        }
3089
37.5k
        else {
3090
37.5k
            const char *p = strchr(f, '%');
3091
37.5k
            if (p != NULL) {
3092
17.3k
                len = p - f;
3093
17.3k
            }
3094
20.1k
            else {
3095
20.1k
                len = strlen(f);
3096
20.1k
                writer->overallocate = 0;
3097
20.1k
            }
3098
3099
37.5k
            if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
3100
0
                goto fail;
3101
0
            }
3102
37.5k
            f += len;
3103
37.5k
        }
3104
55.4k
    }
3105
27.0k
    va_end(vargs2);
3106
27.0k
    return 0;
3107
3108
0
  fail:
3109
0
    va_end(vargs2);
3110
0
    return -1;
3111
27.0k
}
3112
3113
PyObject *
3114
PyUnicode_FromFormatV(const char *format, va_list vargs)
3115
27.0k
{
3116
27.0k
    _PyUnicodeWriter writer;
3117
27.0k
    _PyUnicodeWriter_Init(&writer);
3118
3119
27.0k
    if (unicode_from_format(&writer, format, vargs) < 0) {
3120
0
        _PyUnicodeWriter_Dealloc(&writer);
3121
0
        return NULL;
3122
0
    }
3123
27.0k
    return _PyUnicodeWriter_Finish(&writer);
3124
27.0k
}
3125
3126
PyObject *
3127
PyUnicode_FromFormat(const char *format, ...)
3128
183
{
3129
183
    PyObject* ret;
3130
183
    va_list vargs;
3131
3132
183
    va_start(vargs, format);
3133
183
    ret = PyUnicode_FromFormatV(format, vargs);
3134
183
    va_end(vargs);
3135
183
    return ret;
3136
183
}
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
1.30k
{
3166
1.30k
    Py_ssize_t res;
3167
3168
1.30k
    assert(unicode != NULL);
3169
1.30k
    assert(_PyUnicode_CHECK(unicode));
3170
3171
1.30k
    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
0
    return res;
3184
1.30k
}
3185
3186
static void
3187
unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3188
1.30k
{
3189
1.30k
    assert(unicode != NULL);
3190
1.30k
    assert(_PyUnicode_CHECK(unicode));
3191
3192
2.61k
    if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
3193
0
        memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
3194
0
        return;
3195
0
    }
3196
3197
2.61k
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3198
1.30k
        const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3199
51.3k
        for (; size--; ++s, ++w) {
3200
50.0k
            *w = *s;
3201
50.0k
        }
3202
1.30k
    }
3203
0
    else {
3204
0
#if SIZEOF_WCHAR_T == 4
3205
0
        assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3206
0
        const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3207
0
        for (; size--; ++s, ++w) {
3208
0
            *w = *s;
3209
0
        }
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
0
    }
3229
1.30k
}
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
5
{
3246
5
    Py_ssize_t res;
3247
3248
5
    if (unicode == NULL) {
3249
0
        PyErr_BadInternalCall();
3250
0
        return -1;
3251
0
    }
3252
5
    if (!PyUnicode_Check(unicode)) {
3253
0
        PyErr_BadArgument();
3254
0
        return -1;
3255
0
    }
3256
3257
5
    res = unicode_get_widechar_size(unicode);
3258
5
    if (w == NULL) {
3259
0
        return res + 1;
3260
0
    }
3261
3262
5
    if (size > res) {
3263
5
        size = res + 1;
3264
5
    }
3265
0
    else {
3266
0
        res = size;
3267
0
    }
3268
5
    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
5
    return res;
3281
5
}
3282
3283
wchar_t*
3284
PyUnicode_AsWideCharString(PyObject *unicode,
3285
                           Py_ssize_t *size)
3286
1.30k
{
3287
1.30k
    wchar_t *buffer;
3288
1.30k
    Py_ssize_t buflen;
3289
3290
1.30k
    if (unicode == NULL) {
3291
0
        PyErr_BadInternalCall();
3292
0
        return NULL;
3293
0
    }
3294
1.30k
    if (!PyUnicode_Check(unicode)) {
3295
0
        PyErr_BadArgument();
3296
0
        return NULL;
3297
0
    }
3298
3299
1.30k
    buflen = unicode_get_widechar_size(unicode);
3300
1.30k
    buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
3301
1.30k
    if (buffer == NULL) {
3302
0
        PyErr_NoMemory();
3303
0
        return NULL;
3304
0
    }
3305
1.30k
    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
1.30k
    if (size != NULL) {
3318
800
        *size = buflen;
3319
800
    }
3320
500
    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
1.30k
    return buffer;
3327
1.30k
}
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
50.7k
{
3382
50.7k
    if (ordinal < 0 || ordinal > MAX_UNICODE) {
3383
0
        PyErr_SetString(PyExc_ValueError,
3384
0
                        "chr() arg not in range(0x110000)");
3385
0
        return NULL;
3386
0
    }
3387
3388
50.7k
    return unicode_char((Py_UCS4)ordinal);
3389
50.7k
}
3390
3391
PyObject *
3392
PyUnicode_FromObject(PyObject *obj)
3393
29
{
3394
    /* XXX Perhaps we should make this API an alias of
3395
       PyObject_Str() instead ?! */
3396
29
    if (PyUnicode_CheckExact(obj)) {
3397
29
        return Py_NewRef(obj);
3398
29
    }
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
15.0k
{
3415
15.0k
    Py_buffer buffer;
3416
15.0k
    PyObject *v;
3417
3418
15.0k
    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
15.0k
    if (PyBytes_Check(obj)) {
3425
15.0k
        if (PyBytes_GET_SIZE(obj) == 0) {
3426
34
            if (unicode_check_encoding_errors(encoding, errors) < 0) {
3427
0
                return NULL;
3428
0
            }
3429
34
            _Py_RETURN_UNICODE_EMPTY();
3430
34
        }
3431
14.9k
        return PyUnicode_Decode(
3432
14.9k
                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3433
14.9k
                encoding, errors);
3434
15.0k
    }
3435
3436
0
    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
0
    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
0
    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
0
    v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
3459
0
    PyBuffer_Release(&buffer);
3460
0
    return v;
3461
0
}
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
17.3k
{
3472
17.3k
    const char *e;
3473
17.3k
    char *l;
3474
17.3k
    char *l_end;
3475
17.3k
    int punct;
3476
3477
17.3k
    assert(encoding != NULL);
3478
3479
17.3k
    e = encoding;
3480
17.3k
    l = lower;
3481
17.3k
    l_end = &lower[lower_len - 1];
3482
17.3k
    punct = 0;
3483
113k
    while (1) {
3484
113k
        char c = *e;
3485
113k
        if (c == 0) {
3486
17.3k
            break;
3487
17.3k
        }
3488
3489
96.3k
        if (Py_ISALNUM(c) || c == '.') {
3490
86.5k
            if (punct && l != lower) {
3491
9.80k
                if (l == l_end) {
3492
0
                    return 0;
3493
0
                }
3494
9.80k
                *l++ = '_';
3495
9.80k
            }
3496
86.5k
            punct = 0;
3497
3498
86.5k
            if (l == l_end) {
3499
0
                return 0;
3500
0
            }
3501
86.5k
            *l++ = to_lower ? Py_TOLOWER(c) : c;
3502
86.5k
        }
3503
9.80k
        else {
3504
9.80k
            punct = 1;
3505
9.80k
        }
3506
3507
96.3k
        e++;
3508
96.3k
    }
3509
17.3k
    *l = '\0';
3510
17.3k
    return 1;
3511
17.3k
}
3512
3513
PyObject *
3514
PyUnicode_Decode(const char *s,
3515
                 Py_ssize_t size,
3516
                 const char *encoding,
3517
                 const char *errors)
3518
14.9k
{
3519
14.9k
    PyObject *buffer = NULL, *unicode;
3520
14.9k
    Py_buffer info;
3521
14.9k
    char buflower[11];   /* strlen("iso-8859-1\0") == 11, longest shortcut */
3522
3523
14.9k
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3524
0
        return NULL;
3525
0
    }
3526
3527
14.9k
    if (size == 0) {
3528
0
        _Py_RETURN_UNICODE_EMPTY();
3529
0
    }
3530
3531
14.9k
    if (encoding == NULL) {
3532
0
        return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3533
0
    }
3534
3535
    /* Shortcuts for common default encodings */
3536
14.9k
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3537
14.9k
        char *lower = buflower;
3538
3539
        /* Fast paths */
3540
14.9k
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3541
8.45k
            lower += 3;
3542
8.45k
            if (*lower == '_') {
3543
                /* Match "utf8" and "utf_8" */
3544
8.45k
                lower++;
3545
8.45k
            }
3546
3547
8.45k
            if (lower[0] == '8' && lower[1] == 0) {
3548
7.12k
                return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3549
7.12k
            }
3550
1.32k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3551
45
                return PyUnicode_DecodeUTF16(s, size, errors, 0);
3552
45
            }
3553
1.27k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3554
13
                return PyUnicode_DecodeUTF32(s, size, errors, 0);
3555
13
            }
3556
8.45k
        }
3557
6.54k
        else {
3558
6.54k
            if (strcmp(lower, "ascii") == 0
3559
4.59k
                || strcmp(lower, "us_ascii") == 0) {
3560
1.94k
                return PyUnicode_DecodeASCII(s, size, errors);
3561
1.94k
            }
3562
    #ifdef MS_WINDOWS
3563
            else if (strcmp(lower, "mbcs") == 0) {
3564
                return PyUnicode_DecodeMBCS(s, size, errors);
3565
            }
3566
    #endif
3567
4.59k
            else if (strcmp(lower, "latin1") == 0
3568
0
                     || strcmp(lower, "latin_1") == 0
3569
0
                     || strcmp(lower, "iso_8859_1") == 0
3570
4.59k
                     || strcmp(lower, "iso8859_1") == 0) {
3571
4.59k
                return PyUnicode_DecodeLatin1(s, size, errors);
3572
4.59k
            }
3573
6.54k
        }
3574
14.9k
    }
3575
3576
    /* Decode via the codec registry */
3577
1.26k
    buffer = NULL;
3578
1.26k
    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
3579
0
        goto onError;
3580
1.26k
    buffer = PyMemoryView_FromBuffer(&info);
3581
1.26k
    if (buffer == NULL)
3582
0
        goto onError;
3583
1.26k
    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
3584
1.26k
    if (unicode == NULL)
3585
362
        goto onError;
3586
904
    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
904
    Py_DECREF(buffer);
3596
904
    return unicode_result(unicode);
3597
3598
362
  onError:
3599
362
    Py_XDECREF(buffer);
3600
362
    return NULL;
3601
904
}
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
200
{
3684
200
    Py_ssize_t wlen;
3685
200
    wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3686
200
    if (wstr == NULL) {
3687
0
        return NULL;
3688
0
    }
3689
3690
200
    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
200
    char *str;
3697
200
    size_t error_pos;
3698
200
    const char *reason;
3699
200
    int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
3700
200
                                 current_locale, error_handler);
3701
200
    PyMem_Free(wstr);
3702
3703
200
    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
200
    PyObject *bytes = PyBytes_FromString(str);
3726
200
    PyMem_RawFree(str);
3727
200
    return bytes;
3728
200
}
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
1.22k
{
3740
1.22k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3741
1.22k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3742
1.22k
    if (fs_codec->utf8) {
3743
1.02k
        return unicode_encode_utf8(unicode,
3744
1.02k
                                   fs_codec->error_handler,
3745
1.02k
                                   fs_codec->errors);
3746
1.02k
    }
3747
200
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3748
200
    else if (fs_codec->encoding) {
3749
0
        return PyUnicode_AsEncodedString(unicode,
3750
0
                                         fs_codec->encoding,
3751
0
                                         fs_codec->errors);
3752
0
    }
3753
200
#endif
3754
200
    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
200
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3759
200
        const wchar_t *filesystem_errors = config->filesystem_errors;
3760
200
        assert(filesystem_errors != NULL);
3761
200
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3762
200
        assert(errors != _Py_ERROR_UNKNOWN);
3763
#ifdef _Py_FORCE_UTF8_FS_ENCODING
3764
        return unicode_encode_utf8(unicode, errors, NULL);
3765
#else
3766
200
        return unicode_encode_locale(unicode, errors, 0);
3767
200
#endif
3768
200
    }
3769
1.22k
}
3770
3771
PyObject *
3772
PyUnicode_AsEncodedString(PyObject *unicode,
3773
                          const char *encoding,
3774
                          const char *errors)
3775
2.30k
{
3776
2.30k
    PyObject *v;
3777
2.30k
    char buflower[11];   /* strlen("iso_8859_1\0") == 11, longest shortcut */
3778
3779
2.30k
    if (!PyUnicode_Check(unicode)) {
3780
0
        PyErr_BadArgument();
3781
0
        return NULL;
3782
0
    }
3783
3784
2.30k
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3785
0
        return NULL;
3786
0
    }
3787
3788
2.30k
    if (encoding == NULL) {
3789
0
        return _PyUnicode_AsUTF8String(unicode, errors);
3790
0
    }
3791
3792
    /* Shortcuts for common default encodings */
3793
2.30k
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3794
2.30k
        char *lower = buflower;
3795
3796
        /* Fast paths */
3797
2.30k
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3798
60
            lower += 3;
3799
60
            if (*lower == '_') {
3800
                /* Match "utf8" and "utf_8" */
3801
60
                lower++;
3802
60
            }
3803
3804
60
            if (lower[0] == '8' && lower[1] == 0) {
3805
60
                return _PyUnicode_AsUTF8String(unicode, errors);
3806
60
            }
3807
0
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3808
0
                return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3809
0
            }
3810
0
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3811
0
                return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3812
0
            }
3813
60
        }
3814
2.24k
        else {
3815
2.24k
            if (strcmp(lower, "ascii") == 0
3816
2.24k
                || strcmp(lower, "us_ascii") == 0) {
3817
2.24k
                return _PyUnicode_AsASCIIString(unicode, errors);
3818
2.24k
            }
3819
#ifdef MS_WINDOWS
3820
            else if (strcmp(lower, "mbcs") == 0) {
3821
                return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3822
            }
3823
#endif
3824
0
            else if (strcmp(lower, "latin1") == 0 ||
3825
0
                     strcmp(lower, "latin_1") == 0 ||
3826
0
                     strcmp(lower, "iso_8859_1") == 0 ||
3827
0
                     strcmp(lower, "iso8859_1") == 0) {
3828
0
                return _PyUnicode_AsLatin1String(unicode, errors);
3829
0
            }
3830
2.24k
        }
3831
2.30k
    }
3832
3833
    /* Encode via the codec registry */
3834
0
    v = _PyCodec_EncodeText(unicode, encoding, errors);
3835
0
    if (v == NULL)
3836
0
        return NULL;
3837
3838
    /* The normal path */
3839
0
    if (PyBytes_Check(v))
3840
0
        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
264
{
3909
264
    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
264
    wchar_t *wstr;
3915
264
    size_t wlen;
3916
264
    const char *reason;
3917
264
    int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
3918
264
                                 current_locale, errors);
3919
264
    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
264
    PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3942
264
    PyMem_RawFree(wstr);
3943
264
    return unicode;
3944
264
}
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
244
{
3957
244
    Py_ssize_t size = (Py_ssize_t)strlen(str);
3958
244
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3959
244
    return unicode_decode_locale(str, size, error_handler, 1);
3960
244
}
3961
3962
3963
PyObject*
3964
0
PyUnicode_DecodeFSDefault(const char *s) {
3965
0
    Py_ssize_t size = (Py_ssize_t)strlen(s);
3966
0
    return PyUnicode_DecodeFSDefaultAndSize(s, size);
3967
0
}
3968
3969
PyObject*
3970
PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3971
5.71k
{
3972
5.71k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3973
5.71k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3974
5.71k
    if (fs_codec->utf8) {
3975
5.69k
        return unicode_decode_utf8(s, size,
3976
5.69k
                                   fs_codec->error_handler,
3977
5.69k
                                   fs_codec->errors,
3978
5.69k
                                   NULL);
3979
5.69k
    }
3980
20
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3981
20
    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
20
#endif
3987
20
    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
20
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3992
20
        const wchar_t *filesystem_errors = config->filesystem_errors;
3993
20
        assert(filesystem_errors != NULL);
3994
20
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3995
20
        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
20
        return unicode_decode_locale(s, size, errors, 0);
4000
20
#endif
4001
20
    }
4002
5.71k
}
4003
4004
4005
int
4006
PyUnicode_FSConverter(PyObject* arg, void* addr)
4007
212
{
4008
212
    PyObject *path = NULL;
4009
212
    PyObject *output = NULL;
4010
212
    Py_ssize_t size;
4011
212
    const char *data;
4012
212
    if (arg == NULL) {
4013
0
        Py_DECREF(*(PyObject**)addr);
4014
0
        *(PyObject**)addr = NULL;
4015
0
        return 1;
4016
0
    }
4017
212
    path = PyOS_FSPath(arg);
4018
212
    if (path == NULL) {
4019
0
        return 0;
4020
0
    }
4021
212
    if (PyBytes_Check(path)) {
4022
0
        output = path;
4023
0
    }
4024
212
    else {  // PyOS_FSPath() guarantees its returned value is bytes or str.
4025
212
        output = PyUnicode_EncodeFSDefault(path);
4026
212
        Py_DECREF(path);
4027
212
        if (!output) {
4028
0
            return 0;
4029
0
        }
4030
212
        assert(PyBytes_Check(output));
4031
212
    }
4032
4033
212
    size = PyBytes_GET_SIZE(output);
4034
212
    data = PyBytes_AS_STRING(output);
4035
212
    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
212
    *(PyObject**)addr = output;
4041
212
    return Py_CLEANUP_SUPPORTED;
4042
212
}
4043
4044
4045
int
4046
PyUnicode_FSDecoder(PyObject* arg, void* addr)
4047
43
{
4048
43
    if (arg == NULL) {
4049
0
        Py_DECREF(*(PyObject**)addr);
4050
0
        *(PyObject**)addr = NULL;
4051
0
        return 1;
4052
0
    }
4053
4054
43
    PyObject *path = PyOS_FSPath(arg);
4055
43
    if (path == NULL) {
4056
0
        return 0;
4057
0
    }
4058
4059
43
    PyObject *output = NULL;
4060
43
    if (PyUnicode_Check(path)) {
4061
43
        output = path;
4062
43
    }
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
43
    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
4080
43
                 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
43
    *(PyObject**)addr = output;
4086
43
    return Py_CLEANUP_SUPPORTED;
4087
43
}
4088
4089
4090
static int unicode_fill_utf8(PyObject *unicode);
4091
4092
4093
static int
4094
unicode_ensure_utf8(PyObject *unicode)
4095
304k
{
4096
304k
    int err = 0;
4097
304k
    if (PyUnicode_UTF8(unicode) == NULL) {
4098
56
        Py_BEGIN_CRITICAL_SECTION(unicode);
4099
56
        if (PyUnicode_UTF8(unicode) == NULL) {
4100
56
            err = unicode_fill_utf8(unicode);
4101
56
        }
4102
56
        Py_END_CRITICAL_SECTION();
4103
56
    }
4104
304k
    return err;
4105
304k
}
4106
4107
const char *
4108
PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
4109
304k
{
4110
304k
    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
304k
    if (unicode_ensure_utf8(unicode) == -1) {
4119
0
        if (psize) {
4120
0
            *psize = -1;
4121
0
        }
4122
0
        return NULL;
4123
0
    }
4124
4125
304k
    if (psize) {
4126
251k
        *psize = PyUnicode_UTF8_LENGTH(unicode);
4127
251k
    }
4128
304k
    return PyUnicode_UTF8(unicode);
4129
304k
}
4130
4131
const char *
4132
PyUnicode_AsUTF8(PyObject *unicode)
4133
53.2k
{
4134
53.2k
    return PyUnicode_AsUTF8AndSize(unicode, NULL);
4135
53.2k
}
4136
4137
const char *
4138
_PyUnicode_AsUTF8NoNUL(PyObject *unicode)
4139
6.26k
{
4140
6.26k
    Py_ssize_t size;
4141
6.26k
    const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
4142
6.26k
    if (s && strlen(s) != (size_t)size) {
4143
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4144
0
        return NULL;
4145
0
    }
4146
6.26k
    return s;
4147
6.26k
}
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
568
{
4168
568
    if (!PyUnicode_Check(unicode)) {
4169
0
        PyErr_BadArgument();
4170
0
        return -1;
4171
0
    }
4172
568
    return PyUnicode_GET_LENGTH(unicode);
4173
568
}
4174
4175
Py_UCS4
4176
PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4177
0
{
4178
0
    const void *data;
4179
0
    int kind;
4180
4181
0
    if (!PyUnicode_Check(unicode)) {
4182
0
        PyErr_BadArgument();
4183
0
        return (Py_UCS4)-1;
4184
0
    }
4185
0
    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
0
    data = PyUnicode_DATA(unicode);
4190
0
    kind = PyUnicode_KIND(unicode);
4191
0
    return PyUnicode_READ(kind, data, index);
4192
0
}
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
53.4k
{
4230
53.4k
    if (*exceptionObject == NULL) {
4231
3.25k
        *exceptionObject = PyUnicodeDecodeError_Create(
4232
3.25k
            encoding, input, length, startpos, endpos, reason);
4233
3.25k
    }
4234
50.1k
    else {
4235
50.1k
        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4236
0
            goto onError;
4237
50.1k
        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4238
0
            goto onError;
4239
50.1k
        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4240
0
            goto onError;
4241
50.1k
    }
4242
53.4k
    return;
4243
4244
53.4k
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
53.4k
{
4383
53.4k
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4384
4385
53.4k
    PyObject *restuple = NULL;
4386
53.4k
    PyObject *repunicode = NULL;
4387
53.4k
    Py_ssize_t insize;
4388
53.4k
    Py_ssize_t newpos;
4389
53.4k
    Py_ssize_t replen;
4390
53.4k
    Py_ssize_t remain;
4391
53.4k
    PyObject *inputobj = NULL;
4392
53.4k
    int need_to_grow = 0;
4393
53.4k
    const char *new_inptr;
4394
4395
53.4k
    if (*errorHandler == NULL) {
4396
3.25k
        *errorHandler = PyCodec_LookupError(errors);
4397
3.25k
        if (*errorHandler == NULL)
4398
0
            goto onError;
4399
3.25k
    }
4400
4401
53.4k
    make_decode_exception(exceptionObject,
4402
53.4k
        encoding,
4403
53.4k
        *input, *inend - *input,
4404
53.4k
        *startinpos, *endinpos,
4405
53.4k
        reason);
4406
53.4k
    if (*exceptionObject == NULL)
4407
0
        goto onError;
4408
4409
53.4k
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4410
53.4k
    if (restuple == NULL)
4411
2.89k
        goto onError;
4412
50.5k
    if (!PyTuple_Check(restuple)) {
4413
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4414
0
        goto onError;
4415
0
    }
4416
50.5k
    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
50.5k
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4422
50.5k
    if (!inputobj)
4423
0
        goto onError;
4424
50.5k
    remain = *inend - *input - *endinpos;
4425
50.5k
    *input = PyBytes_AS_STRING(inputobj);
4426
50.5k
    insize = PyBytes_GET_SIZE(inputobj);
4427
50.5k
    *inend = *input + insize;
4428
    /* we can DECREF safely, as the exception has another reference,
4429
       so the object won't go away. */
4430
50.5k
    Py_DECREF(inputobj);
4431
4432
50.5k
    if (newpos<0)
4433
0
        newpos = insize+newpos;
4434
50.5k
    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
50.5k
    replen = PyUnicode_GET_LENGTH(repunicode);
4440
50.5k
    if (replen > 1) {
4441
0
        writer->min_length += replen - 1;
4442
0
        need_to_grow = 1;
4443
0
    }
4444
50.5k
    new_inptr = *input + newpos;
4445
50.5k
    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
50
        writer->min_length += *inend - new_inptr - remain;
4452
50
        need_to_grow = 1;
4453
50
    }
4454
50.5k
    if (need_to_grow) {
4455
50
        writer->overallocate = 1;
4456
50
        if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
4457
50
                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4458
0
            goto onError;
4459
50
    }
4460
50.5k
    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4461
0
        goto onError;
4462
4463
50.5k
    *endinpos = newpos;
4464
50.5k
    *inptr = new_inptr;
4465
4466
    /* we made it! */
4467
50.5k
    Py_DECREF(restuple);
4468
50.5k
    return 0;
4469
4470
2.89k
  onError:
4471
2.89k
    Py_XDECREF(restuple);
4472
2.89k
    return -1;
4473
50.5k
}
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
0
    (((c) >= 'A' && (c) <= 'Z') ||     \
4485
0
     ((c) >= 'a' && (c) <= 'z') ||     \
4486
0
     ((c) >= '0' && (c) <= '9') ||     \
4487
0
     (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
0
    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
4493
0
     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
4494
0
     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
4495
0
     (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
0
    ((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
0
{
4574
0
    const char *starts = s;
4575
0
    Py_ssize_t startinpos;
4576
0
    Py_ssize_t endinpos;
4577
0
    const char *e;
4578
0
    _PyUnicodeWriter writer;
4579
0
    const char *errmsg = "";
4580
0
    int inShift = 0;
4581
0
    Py_ssize_t shiftOutStart;
4582
0
    unsigned int base64bits = 0;
4583
0
    unsigned long base64buffer = 0;
4584
0
    Py_UCS4 surrogate = 0;
4585
0
    PyObject *errorHandler = NULL;
4586
0
    PyObject *exc = NULL;
4587
4588
0
    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
0
    _PyUnicodeWriter_Init(&writer);
4596
0
    writer.min_length = size;
4597
4598
0
    shiftOutStart = 0;
4599
0
    e = s + size;
4600
4601
0
    while (s < e) {
4602
0
        Py_UCS4 ch;
4603
0
      restart:
4604
0
        ch = (unsigned char) *s;
4605
4606
0
        if (inShift) { /* in a base-64 section */
4607
0
            if (IS_BASE64(ch)) { /* consume a base-64 character */
4608
0
                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4609
0
                base64bits += 6;
4610
0
                s++;
4611
0
                if (base64bits >= 16) {
4612
                    /* we have enough bits for a UTF-16 value */
4613
0
                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
4614
0
                    base64bits -= 16;
4615
0
                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4616
0
                    assert(outCh <= 0xffff);
4617
0
                    if (surrogate) {
4618
                        /* expecting a second surrogate */
4619
0
                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4620
0
                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
4621
0
                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
4622
0
                                goto onError;
4623
0
                            surrogate = 0;
4624
0
                            continue;
4625
0
                        }
4626
0
                        else {
4627
0
                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4628
0
                                goto onError;
4629
0
                            surrogate = 0;
4630
0
                        }
4631
0
                    }
4632
0
                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
4633
                        /* first surrogate */
4634
0
                        surrogate = outCh;
4635
0
                    }
4636
0
                    else {
4637
0
                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
4638
0
                            goto onError;
4639
0
                    }
4640
0
                }
4641
0
            }
4642
0
            else { /* now leaving a base-64 section */
4643
0
                inShift = 0;
4644
0
                if (base64bits > 0) { /* left-over bits */
4645
0
                    if (base64bits >= 6) {
4646
                        /* We've seen at least one base-64 character */
4647
0
                        s++;
4648
0
                        errmsg = "partial character in shift sequence";
4649
0
                        goto utf7Error;
4650
0
                    }
4651
0
                    else {
4652
                        /* Some bits remain; they should be zero */
4653
0
                        if (base64buffer != 0) {
4654
0
                            s++;
4655
0
                            errmsg = "non-zero padding bits in shift sequence";
4656
0
                            goto utf7Error;
4657
0
                        }
4658
0
                    }
4659
0
                }
4660
0
                if (surrogate && DECODE_DIRECT(ch)) {
4661
0
                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4662
0
                        goto onError;
4663
0
                }
4664
0
                surrogate = 0;
4665
0
                if (ch == '-') {
4666
                    /* '-' is absorbed; other terminating
4667
                       characters are preserved */
4668
0
                    s++;
4669
0
                }
4670
0
            }
4671
0
        }
4672
0
        else if ( ch == '+' ) {
4673
0
            startinpos = s-starts;
4674
0
            s++; /* consume '+' */
4675
0
            if (s < e && *s == '-') { /* '+-' encodes '+' */
4676
0
                s++;
4677
0
                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
4678
0
                    goto onError;
4679
0
            }
4680
0
            else if (s < e && !IS_BASE64(*s)) {
4681
0
                s++;
4682
0
                errmsg = "ill-formed sequence";
4683
0
                goto utf7Error;
4684
0
            }
4685
0
            else { /* begin base64-encoded section */
4686
0
                inShift = 1;
4687
0
                surrogate = 0;
4688
0
                shiftOutStart = writer.pos;
4689
0
                base64bits = 0;
4690
0
                base64buffer = 0;
4691
0
            }
4692
0
        }
4693
0
        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
4694
0
            s++;
4695
0
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
4696
0
                goto onError;
4697
0
        }
4698
0
        else {
4699
0
            startinpos = s-starts;
4700
0
            s++;
4701
0
            errmsg = "unexpected special character";
4702
0
            goto utf7Error;
4703
0
        }
4704
0
        continue;
4705
0
utf7Error:
4706
0
        endinpos = s-starts;
4707
0
        if (unicode_decode_call_errorhandler_writer(
4708
0
                errors, &errorHandler,
4709
0
                "utf7", errmsg,
4710
0
                &starts, &e, &startinpos, &endinpos, &exc, &s,
4711
0
                &writer))
4712
0
            goto onError;
4713
0
    }
4714
4715
    /* end of string */
4716
4717
0
    if (inShift && !consumed) { /* in shift sequence, no more to follow */
4718
        /* if we're in an inconsistent state, that's an error */
4719
0
        inShift = 0;
4720
0
        if (surrogate ||
4721
0
                (base64bits >= 6) ||
4722
0
                (base64bits > 0 && base64buffer != 0)) {
4723
0
            endinpos = size;
4724
0
            if (unicode_decode_call_errorhandler_writer(
4725
0
                    errors, &errorHandler,
4726
0
                    "utf7", "unterminated shift sequence",
4727
0
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
4728
0
                    &writer))
4729
0
                goto onError;
4730
0
            if (s < e)
4731
0
                goto restart;
4732
0
        }
4733
0
    }
4734
4735
    /* return state */
4736
0
    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
0
    Py_XDECREF(errorHandler);
4755
0
    Py_XDECREF(exc);
4756
0
    return _PyUnicodeWriter_Finish(&writer);
4757
4758
0
  onError:
4759
0
    Py_XDECREF(errorHandler);
4760
0
    Py_XDECREF(exc);
4761
0
    _PyUnicodeWriter_Dealloc(&writer);
4762
0
    return NULL;
4763
0
}
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
390k
{
4869
390k
    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4870
390k
}
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
65.5M
# define ASCII_CHAR_MASK 0x8080808080808080ULL
4892
// used to count codepoints in UTF-8 string.
4893
31.9M
# define VECTOR_0101     0x0101010101010101ULL
4894
255k
# 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
392k
{
4908
392k
    return __builtin_ctzll((unsigned long long)v);
4909
392k
}
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
2.17M
{
4932
2.17M
    union {
4933
2.17M
        size_t s;
4934
2.17M
        unsigned char b[SIZEOF_SIZE_T];
4935
2.17M
    } u;
4936
2.17M
    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
2.17M
    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
758k
    case 7:
4947
758k
        u.b[6] = p[6];
4948
758k
        _Py_FALLTHROUGH;
4949
792k
    case 6:
4950
792k
        u.b[5] = p[5];
4951
792k
        _Py_FALLTHROUGH;
4952
1.38M
    case 5:
4953
1.38M
        u.b[4] = p[4];
4954
1.38M
        _Py_FALLTHROUGH;
4955
1.38M
#endif
4956
1.51M
    case 4:
4957
1.51M
        u.b[3] = p[3];
4958
1.51M
        _Py_FALLTHROUGH;
4959
1.55M
    case 3:
4960
1.55M
        u.b[2] = p[2];
4961
1.55M
        _Py_FALLTHROUGH;
4962
1.87M
    case 2:
4963
1.87M
        u.b[1] = p[1];
4964
1.87M
        _Py_FALLTHROUGH;
4965
1.92M
    case 1:
4966
1.92M
        u.b[0] = p[0];
4967
1.92M
        break;
4968
248k
    case 0:
4969
248k
        break;
4970
2.17M
    }
4971
2.17M
    return u.s;
4972
2.17M
}
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
2.17M
{
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
2.17M
    const unsigned char *p = start;
4991
4992
2.17M
    if (end - start >= SIZEOF_SIZE_T) {
4993
        // Avoid unaligned read.
4994
1.12M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
4995
1.12M
        size_t u;
4996
1.12M
        memcpy(&u, p, sizeof(size_t));
4997
1.12M
        u &= ASCII_CHAR_MASK;
4998
1.12M
        if (u) {
4999
3.52k
            return (ctz(u) - 7) / 8;
5000
3.52k
        }
5001
1.12M
        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
1.12M
        const unsigned char *e = end - SIZEOF_SIZE_T;
5013
60.2M
        while (p <= e) {
5014
59.1M
            size_t u = (*(const size_t *)p) & ASCII_CHAR_MASK;
5015
59.1M
            if (u) {
5016
2.62k
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5017
2.62k
                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
2.62k
            }
5024
59.1M
            p += SIZEOF_SIZE_T;
5025
59.1M
        }
5026
1.12M
    }
5027
2.17M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5028
2.17M
    assert((end - p) < SIZEOF_SIZE_T);
5029
    // we can not use *(const size_t*)p to avoid buffer overrun.
5030
2.17M
    size_t u = load_unaligned(p, end - p) & ASCII_CHAR_MASK;
5031
2.17M
    if (u) {
5032
386k
        return p - start + (ctz(u) - 7) / 8;
5033
386k
    }
5034
1.78M
    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
2.17M
}
5045
5046
static inline int
5047
scalar_utf8_start_char(unsigned int ch)
5048
952k
{
5049
    // 0xxxxxxx or 11xxxxxx are first byte.
5050
952k
    return (~ch >> 7 | ch >> 6) & 1;
5051
952k
}
5052
5053
static inline size_t
5054
vector_utf8_start_chars(size_t v)
5055
31.9M
{
5056
31.9M
    return ((~v >> 7) | (v >> 6)) & VECTOR_0101;
5057
31.9M
}
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
387k
{
5064
387k
    Py_ssize_t len = 0;
5065
5066
387k
    if (end - s >= SIZEOF_SIZE_T) {
5067
11.7k
        while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
5068
8.54k
            len += scalar_utf8_start_char(*s++);
5069
8.54k
        }
5070
5071
130k
        while (s + SIZEOF_SIZE_T <= end) {
5072
127k
            const unsigned char *e = end;
5073
127k
            if (e - s > SIZEOF_SIZE_T * 255) {
5074
124k
                e = s + SIZEOF_SIZE_T * 255;
5075
124k
            }
5076
127k
            Py_ssize_t vstart = 0;
5077
32.0M
            while (s + SIZEOF_SIZE_T <= e) {
5078
31.9M
                size_t v = *(size_t*)s;
5079
31.9M
                size_t vs = vector_utf8_start_chars(v);
5080
31.9M
                vstart += vs;
5081
31.9M
                s += SIZEOF_SIZE_T;
5082
31.9M
            }
5083
127k
            vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF);
5084
127k
            vstart += vstart >> 16;
5085
127k
#if SIZEOF_SIZE_T == 8
5086
127k
            vstart += vstart >> 32;
5087
127k
#endif
5088
127k
            len += vstart & 0x7ff;
5089
127k
        }
5090
3.20k
    }
5091
1.33M
    while (s < end) {
5092
943k
        len += scalar_utf8_start_char(*s++);
5093
943k
    }
5094
387k
    return len;
5095
387k
}
5096
5097
static Py_ssize_t
5098
ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
5099
11.0k
{
5100
11.0k
#if SIZEOF_SIZE_T <= SIZEOF_VOID_P
5101
11.0k
    if (_Py_IS_ALIGNED(start, ALIGNOF_SIZE_T)
5102
6.00k
        && _Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T))
5103
3.70k
    {
5104
        /* Fast path, see in STRINGLIB(utf8_decode) for
5105
           an explanation. */
5106
3.70k
        const char *p = start;
5107
3.70k
        Py_UCS1 *q = dest;
5108
3.14M
        while (p + SIZEOF_SIZE_T <= end) {
5109
3.14M
            size_t value = *(const size_t *) p;
5110
3.14M
            if (value & ASCII_CHAR_MASK)
5111
131
                break;
5112
3.13M
            *((size_t *)q) = value;
5113
3.13M
            p += SIZEOF_SIZE_T;
5114
3.13M
            q += SIZEOF_SIZE_T;
5115
3.13M
        }
5116
14.8k
        while (p < end) {
5117
11.3k
            if ((unsigned char)*p & 0x80)
5118
181
                break;
5119
11.1k
            *q++ = *p++;
5120
11.1k
        }
5121
3.70k
        return p - start;
5122
3.70k
    }
5123
7.35k
#endif
5124
7.35k
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)start,
5125
7.35k
                                         (const unsigned char*)end);
5126
7.35k
    memcpy(dest, start, pos);
5127
7.35k
    return pos;
5128
11.0k
}
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
392k
{
5137
392k
    Py_ssize_t startinpos, endinpos;
5138
392k
    const char *errmsg = "";
5139
392k
    PyObject *error_handler_obj = NULL;
5140
392k
    PyObject *exc = NULL;
5141
5142
422k
    while (s < end) {
5143
419k
        Py_UCS4 ch;
5144
419k
        int kind = writer->kind;
5145
5146
419k
        if (kind == PyUnicode_1BYTE_KIND) {
5147
309k
            if (PyUnicode_IS_ASCII(writer->buffer))
5148
5.23k
                ch = asciilib_utf8_decode(&s, end, writer->data, &writer->pos);
5149
304k
            else
5150
304k
                ch = ucs1lib_utf8_decode(&s, end, writer->data, &writer->pos);
5151
309k
        } else if (kind == PyUnicode_2BYTE_KIND) {
5152
14.5k
            ch = ucs2lib_utf8_decode(&s, end, writer->data, &writer->pos);
5153
95.5k
        } else {
5154
95.5k
            assert(kind == PyUnicode_4BYTE_KIND);
5155
95.5k
            ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos);
5156
95.5k
        }
5157
5158
419k
        switch (ch) {
5159
388k
        case 0:
5160
388k
            if (s == end || consumed)
5161
387k
                goto End;
5162
1.20k
            errmsg = "unexpected end of data";
5163
1.20k
            startinpos = s - starts;
5164
1.20k
            endinpos = end - starts;
5165
1.20k
            break;
5166
9.30k
        case 1:
5167
9.30k
            errmsg = "invalid start byte";
5168
9.30k
            startinpos = s - starts;
5169
9.30k
            endinpos = startinpos + 1;
5170
9.30k
            break;
5171
12.4k
        case 2:
5172
12.4k
            if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5173
15
                && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
5174
7
            {
5175
                /* Truncated surrogate code in range D800-DFFF */
5176
7
                goto End;
5177
7
            }
5178
12.4k
            _Py_FALLTHROUGH;
5179
14.8k
        case 3:
5180
15.4k
        case 4:
5181
15.4k
            errmsg = "invalid continuation byte";
5182
15.4k
            startinpos = s - starts;
5183
15.4k
            endinpos = startinpos + ch - 1;
5184
15.4k
            break;
5185
6.49k
        default:
5186
            // ch doesn't fit into kind, so change the buffer kind to write
5187
            // the character
5188
6.49k
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
5189
0
                goto onError;
5190
6.49k
            continue;
5191
419k
        }
5192
5193
25.9k
        if (error_handler == _Py_ERROR_UNKNOWN)
5194
508
            error_handler = _Py_GetErrorHandler(errors);
5195
5196
25.9k
        switch (error_handler) {
5197
0
        case _Py_ERROR_IGNORE:
5198
0
            s += (endinpos - startinpos);
5199
0
            break;
5200
5201
20.0k
        case _Py_ERROR_REPLACE:
5202
20.0k
            if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0)
5203
0
                goto onError;
5204
20.0k
            s += (endinpos - startinpos);
5205
20.0k
            break;
5206
5207
0
        case _Py_ERROR_SURROGATEESCAPE:
5208
0
        {
5209
0
            Py_ssize_t i;
5210
5211
0
            if (_PyUnicodeWriter_PrepareKind(writer, PyUnicode_2BYTE_KIND) < 0)
5212
0
                goto onError;
5213
0
            for (i=startinpos; i<endinpos; i++) {
5214
0
                ch = (Py_UCS4)(unsigned char)(starts[i]);
5215
0
                PyUnicode_WRITE(writer->kind, writer->data, writer->pos,
5216
0
                                ch + 0xdc00);
5217
0
                writer->pos++;
5218
0
            }
5219
0
            s += (endinpos - startinpos);
5220
0
            break;
5221
0
        }
5222
5223
5.89k
        default:
5224
5.89k
            if (unicode_decode_call_errorhandler_writer(
5225
5.89k
                    errors, &error_handler_obj,
5226
5.89k
                    "utf-8", errmsg,
5227
5.89k
                    &starts, &end, &startinpos, &endinpos, &exc, &s,
5228
5.89k
                    writer)) {
5229
2.51k
                goto onError;
5230
2.51k
            }
5231
5232
3.37k
            if (_PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) {
5233
0
                goto onError;
5234
0
            }
5235
25.9k
        }
5236
25.9k
    }
5237
5238
390k
End:
5239
390k
    if (consumed)
5240
65
        *consumed = s - starts;
5241
5242
390k
    Py_XDECREF(error_handler_obj);
5243
390k
    Py_XDECREF(exc);
5244
390k
    return 0;
5245
5246
2.51k
onError:
5247
2.51k
    Py_XDECREF(error_handler_obj);
5248
2.51k
    Py_XDECREF(exc);
5249
2.51k
    return -1;
5250
392k
}
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
2.17M
{
5258
2.17M
    if (size == 0) {
5259
1.56k
        if (consumed) {
5260
0
            *consumed = 0;
5261
0
        }
5262
1.56k
        _Py_RETURN_UNICODE_EMPTY();
5263
1.56k
    }
5264
5265
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5266
2.17M
    if (size == 1 && (unsigned char)s[0] < 128) {
5267
5.61k
        if (consumed) {
5268
0
            *consumed = 1;
5269
0
        }
5270
5.61k
        return get_latin1_char((unsigned char)s[0]);
5271
5.61k
    }
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
2.16M
    if (PY_SSIZE_T_MAX - sizeof(PyCompactUnicodeObject) < (size_t)size) {
5276
0
        PyErr_NoMemory();
5277
0
        return NULL;
5278
0
    }
5279
5280
2.16M
    const char *starts = s;
5281
2.16M
    const char *end = s + size;
5282
5283
2.16M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end);
5284
2.16M
    if (pos == size) {  // fast path: ASCII string.
5285
1.77M
        PyObject *u = PyUnicode_New(size, 127);
5286
1.77M
        if (u == NULL) {
5287
0
            return NULL;
5288
0
        }
5289
1.77M
        memcpy(PyUnicode_1BYTE_DATA(u), s, size);
5290
1.77M
        if (consumed) {
5291
11
            *consumed = size;
5292
11
        }
5293
1.77M
        return u;
5294
1.77M
    }
5295
5296
391k
    int maxchr = 127;
5297
391k
    Py_ssize_t maxsize = size;
5298
5299
391k
    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
391k
    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
387k
        maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end);
5312
387k
        if (ch < 0xc4) { // latin1
5313
303k
            maxchr = 0xff;
5314
303k
        }
5315
83.8k
        else if (ch < 0xf0) { // ucs2
5316
2.17k
            maxchr = 0xffff;
5317
2.17k
        }
5318
81.6k
        else { // ucs4
5319
81.6k
            maxchr = 0x10ffff;
5320
81.6k
        }
5321
387k
    }
5322
391k
    PyObject *u = PyUnicode_New(maxsize, maxchr);
5323
391k
    if (!u) {
5324
0
        return NULL;
5325
0
    }
5326
5327
    // Use _PyUnicodeWriter after fast path is failed.
5328
391k
    _PyUnicodeWriter writer;
5329
391k
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
5330
391k
    if (maxchr <= 255) {
5331
307k
        memcpy(PyUnicode_1BYTE_DATA(u), s, pos);
5332
307k
        s += pos;
5333
307k
        writer.pos = pos;
5334
307k
    }
5335
5336
391k
    if (unicode_decode_utf8_impl(&writer, starts, s, end,
5337
391k
                                 error_handler, errors,
5338
391k
                                 consumed) < 0) {
5339
2.51k
        _PyUnicodeWriter_Dealloc(&writer);
5340
2.51k
        return NULL;
5341
2.51k
    }
5342
388k
    return _PyUnicodeWriter_Finish(&writer);
5343
391k
}
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
5.17k
{
5353
5.17k
    if (size == 0) {
5354
15
        if (consumed) {
5355
0
            *consumed = 0;
5356
0
        }
5357
15
        return 0;
5358
15
    }
5359
5360
    // fast path: try ASCII string.
5361
5.15k
    if (_PyUnicodeWriter_Prepare(writer, size, 127) < 0) {
5362
0
        return -1;
5363
0
    }
5364
5365
5.15k
    const char *starts = s;
5366
5.15k
    const char *end = s + size;
5367
5.15k
    Py_ssize_t decoded = 0;
5368
5.15k
    Py_UCS1 *dest = (Py_UCS1*)writer->data + writer->pos * writer->kind;
5369
5.15k
    if (writer->kind == PyUnicode_1BYTE_KIND) {
5370
5.15k
        decoded = ascii_decode(s, end, dest);
5371
5.15k
        writer->pos += decoded;
5372
5373
5.15k
        if (decoded == size) {
5374
3.53k
            if (consumed) {
5375
1
                *consumed = size;
5376
1
            }
5377
3.53k
            return 0;
5378
3.53k
        }
5379
1.62k
        s += decoded;
5380
1.62k
    }
5381
5382
1.62k
    return unicode_decode_utf8_impl(writer, starts, s, end,
5383
1.62k
                                    error_handler, errors, consumed);
5384
5.15k
}
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
2.17M
{
5393
2.17M
    return unicode_decode_utf8(s, size,
5394
2.17M
                               errors ? _Py_ERROR_UNKNOWN : _Py_ERROR_STRICT,
5395
2.17M
                               errors, consumed);
5396
2.17M
}
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
140
{
5415
140
    const char *orig_s = s;
5416
140
    const char *e;
5417
140
    wchar_t *unicode;
5418
140
    Py_ssize_t outpos;
5419
5420
140
    int surrogateescape = 0;
5421
140
    int surrogatepass = 0;
5422
140
    switch (errors)
5423
140
    {
5424
0
    case _Py_ERROR_STRICT:
5425
0
        break;
5426
140
    case _Py_ERROR_SURROGATEESCAPE:
5427
140
        surrogateescape = 1;
5428
140
        break;
5429
0
    case _Py_ERROR_SURROGATEPASS:
5430
0
        surrogatepass = 1;
5431
0
        break;
5432
0
    default:
5433
0
        return -3;
5434
140
    }
5435
5436
    /* Note: size will always be longer than the resulting Unicode
5437
       character count */
5438
140
    if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1 < size) {
5439
0
        return -1;
5440
0
    }
5441
5442
140
    unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
5443
140
    if (!unicode) {
5444
0
        return -1;
5445
0
    }
5446
5447
    /* Unpack UTF-8 encoded data */
5448
140
    e = s + size;
5449
140
    outpos = 0;
5450
140
    while (s < e) {
5451
140
        Py_UCS4 ch;
5452
140
#if SIZEOF_WCHAR_T == 4
5453
140
        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
140
        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
140
        else {
5468
140
            if (!ch && s == e) {
5469
140
                break;
5470
140
            }
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
140
    }
5511
140
    unicode[outpos] = L'\0';
5512
140
    if (wlen) {
5513
140
        *wlen = outpos;
5514
140
    }
5515
140
    *wstr = unicode;
5516
140
    return 0;
5517
140
}
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
380
{
5554
380
    const Py_ssize_t max_char_size = 4;
5555
380
    Py_ssize_t len = wcslen(text);
5556
5557
380
    assert(len >= 0);
5558
5559
380
    int surrogateescape = 0;
5560
380
    int surrogatepass = 0;
5561
380
    switch (errors)
5562
380
    {
5563
80
    case _Py_ERROR_STRICT:
5564
80
        break;
5565
300
    case _Py_ERROR_SURROGATEESCAPE:
5566
300
        surrogateescape = 1;
5567
300
        break;
5568
0
    case _Py_ERROR_SURROGATEPASS:
5569
0
        surrogatepass = 1;
5570
0
        break;
5571
0
    default:
5572
0
        return -3;
5573
380
    }
5574
5575
380
    if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5576
0
        return -1;
5577
0
    }
5578
380
    char *bytes;
5579
380
    if (raw_malloc) {
5580
380
        bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5581
380
    }
5582
0
    else {
5583
0
        bytes = PyMem_Malloc((len + 1) * max_char_size);
5584
0
    }
5585
380
    if (bytes == NULL) {
5586
0
        return -1;
5587
0
    }
5588
5589
380
    char *p = bytes;
5590
380
    Py_ssize_t i;
5591
17.1k
    for (i = 0; i < len; ) {
5592
16.7k
        Py_ssize_t ch_pos = i;
5593
16.7k
        Py_UCS4 ch = text[i];
5594
16.7k
        i++;
5595
16.7k
        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
16.7k
        if (ch < 0x80) {
5605
            /* Encode ASCII */
5606
16.7k
            *p++ = (char) ch;
5607
5608
16.7k
        }
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
16.7k
    }
5647
380
    *p++ = '\0';
5648
5649
380
    size_t final_size = (p - bytes);
5650
380
    char *bytes2;
5651
380
    if (raw_malloc) {
5652
380
        bytes2 = PyMem_RawRealloc(bytes, final_size);
5653
380
    }
5654
0
    else {
5655
0
        bytes2 = PyMem_Realloc(bytes, final_size);
5656
0
    }
5657
380
    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
380
    *str = bytes2;
5670
380
    return 0;
5671
380
}
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
1.08k
{
5685
1.08k
    if (!PyUnicode_Check(unicode)) {
5686
0
        PyErr_BadArgument();
5687
0
        return NULL;
5688
0
    }
5689
5690
1.08k
    if (PyUnicode_UTF8(unicode))
5691
1.08k
        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5692
1.08k
                                         PyUnicode_UTF8_LENGTH(unicode));
5693
5694
2
    int kind = PyUnicode_KIND(unicode);
5695
2
    const void *data = PyUnicode_DATA(unicode);
5696
2
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5697
5698
2
    PyBytesWriter *writer;
5699
2
    char *end;
5700
5701
2
    switch (kind) {
5702
0
    default:
5703
0
        Py_UNREACHABLE();
5704
1
    case PyUnicode_1BYTE_KIND:
5705
        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5706
1
        assert(!PyUnicode_IS_ASCII(unicode));
5707
1
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5708
1
                                      error_handler, errors, &end);
5709
1
        break;
5710
1
    case PyUnicode_2BYTE_KIND:
5711
1
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5712
1
                                      error_handler, errors, &end);
5713
1
        break;
5714
0
    case PyUnicode_4BYTE_KIND:
5715
0
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5716
0
                                      error_handler, errors, &end);
5717
0
        break;
5718
2
    }
5719
5720
2
    if (writer == NULL) {
5721
0
        PyBytesWriter_Discard(writer);
5722
0
        return NULL;
5723
0
    }
5724
2
    return PyBytesWriter_FinishWithPointer(writer, end);
5725
2
}
5726
5727
static int
5728
unicode_fill_utf8(PyObject *unicode)
5729
56
{
5730
56
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(unicode);
5731
    /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5732
56
    assert(!PyUnicode_IS_ASCII(unicode));
5733
5734
56
    int kind = PyUnicode_KIND(unicode);
5735
56
    const void *data = PyUnicode_DATA(unicode);
5736
56
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5737
5738
56
    PyBytesWriter *writer;
5739
56
    char *end;
5740
5741
56
    switch (kind) {
5742
0
    default:
5743
0
        Py_UNREACHABLE();
5744
1
    case PyUnicode_1BYTE_KIND:
5745
1
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5746
1
                                      _Py_ERROR_STRICT, NULL, &end);
5747
1
        break;
5748
23
    case PyUnicode_2BYTE_KIND:
5749
23
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5750
23
                                      _Py_ERROR_STRICT, NULL, &end);
5751
23
        break;
5752
32
    case PyUnicode_4BYTE_KIND:
5753
32
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5754
32
                                      _Py_ERROR_STRICT, NULL, &end);
5755
32
        break;
5756
56
    }
5757
56
    if (writer == NULL) {
5758
0
        return -1;
5759
0
    }
5760
5761
56
    const char *start = PyBytesWriter_GetData(writer);
5762
56
    Py_ssize_t len = end - start;
5763
5764
56
    char *cache = PyMem_Malloc(len + 1);
5765
56
    if (cache == NULL) {
5766
0
        PyBytesWriter_Discard(writer);
5767
0
        PyErr_NoMemory();
5768
0
        return -1;
5769
0
    }
5770
56
    memcpy(cache, start, len);
5771
56
    cache[len] = '\0';
5772
56
    PyUnicode_SET_UTF8_LENGTH(unicode, len);
5773
56
    PyUnicode_SET_UTF8(unicode, cache);
5774
56
    PyBytesWriter_Discard(writer);
5775
56
    return 0;
5776
56
}
5777
5778
PyObject *
5779
_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5780
62
{
5781
62
    return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5782
62
}
5783
5784
5785
PyObject *
5786
PyUnicode_AsUTF8String(PyObject *unicode)
5787
2
{
5788
2
    return _PyUnicode_AsUTF8String(unicode, NULL);
5789
2
}
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
13
{
5799
13
    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5800
13
}
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
338
{
5809
338
    const char *starts = s;
5810
338
    Py_ssize_t startinpos;
5811
338
    Py_ssize_t endinpos;
5812
338
    _PyUnicodeWriter writer;
5813
338
    const unsigned char *q, *e;
5814
338
    int le, bo = 0;       /* assume native ordering by default */
5815
338
    const char *encoding;
5816
338
    const char *errmsg = "";
5817
338
    PyObject *errorHandler = NULL;
5818
338
    PyObject *exc = NULL;
5819
5820
338
    q = (const unsigned char *)s;
5821
338
    e = q + size;
5822
5823
338
    if (byteorder)
5824
325
        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
338
    if (bo == 0 && size >= 4) {
5831
13
        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5832
13
        if (bom == 0x0000FEFF) {
5833
1
            bo = -1;
5834
1
            q += 4;
5835
1
        }
5836
12
        else if (bom == 0xFFFE0000) {
5837
12
            bo = 1;
5838
12
            q += 4;
5839
12
        }
5840
13
        if (byteorder)
5841
0
            *byteorder = bo;
5842
13
    }
5843
5844
338
    if (q == e) {
5845
2
        if (consumed)
5846
0
            *consumed = size;
5847
2
        _Py_RETURN_UNICODE_EMPTY();
5848
2
    }
5849
5850
#ifdef WORDS_BIGENDIAN
5851
    le = bo < 0;
5852
#else
5853
336
    le = bo <= 0;
5854
336
#endif
5855
336
    encoding = le ? "utf-32-le" : "utf-32-be";
5856
5857
336
    _PyUnicodeWriter_Init(&writer);
5858
336
    writer.min_length = (e - q + 3) / 4;
5859
336
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
5860
0
        goto onError;
5861
5862
1.89k
    while (1) {
5863
1.89k
        Py_UCS4 ch = 0;
5864
1.89k
        Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
5865
5866
1.89k
        if (e - q >= 4) {
5867
1.79k
            int kind = writer.kind;
5868
1.79k
            void *data = writer.data;
5869
1.79k
            const unsigned char *last = e - 4;
5870
1.79k
            Py_ssize_t pos = writer.pos;
5871
1.79k
            if (le) {
5872
109k
                do {
5873
109k
                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5874
109k
                    if (ch > maxch)
5875
239
                        break;
5876
108k
                    if (kind != PyUnicode_1BYTE_KIND &&
5877
93.6k
                        Py_UNICODE_IS_SURROGATE(ch))
5878
598
                        break;
5879
108k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5880
108k
                    q += 4;
5881
108k
                } while (q <= last);
5882
887
            }
5883
904
            else {
5884
296k
                do {
5885
296k
                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5886
296k
                    if (ch > maxch)
5887
250
                        break;
5888
296k
                    if (kind != PyUnicode_1BYTE_KIND &&
5889
65.8k
                        Py_UNICODE_IS_SURROGATE(ch))
5890
599
                        break;
5891
295k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5892
295k
                    q += 4;
5893
295k
                } while (q <= last);
5894
904
            }
5895
1.79k
            writer.pos = pos;
5896
1.79k
        }
5897
5898
1.89k
        if (Py_UNICODE_IS_SURROGATE(ch)) {
5899
1.24k
            errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
5900
1.24k
            startinpos = ((const char *)q) - starts;
5901
1.24k
            endinpos = startinpos + 4;
5902
1.24k
        }
5903
651
        else if (ch <= maxch) {
5904
207
            if (q == e || consumed)
5905
184
                break;
5906
            /* remaining bytes at the end? (size should be divisible by 4) */
5907
23
            errmsg = "truncated data";
5908
23
            startinpos = ((const char *)q) - starts;
5909
23
            endinpos = ((const char *)e) - starts;
5910
23
        }
5911
444
        else {
5912
444
            if (ch < 0x110000) {
5913
315
                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
5914
0
                    goto onError;
5915
315
                q += 4;
5916
315
                continue;
5917
315
            }
5918
129
            errmsg = "code point not in range(0x110000)";
5919
129
            startinpos = ((const char *)q) - starts;
5920
129
            endinpos = startinpos + 4;
5921
129
        }
5922
5923
        /* The remaining input chars are ignored if the callback
5924
           chooses to skip the input */
5925
1.39k
        if (unicode_decode_call_errorhandler_writer(
5926
1.39k
                errors, &errorHandler,
5927
1.39k
                encoding, errmsg,
5928
1.39k
                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5929
1.39k
                &writer))
5930
152
            goto onError;
5931
1.39k
    }
5932
5933
184
    if (consumed)
5934
0
        *consumed = (const char *)q-starts;
5935
5936
184
    Py_XDECREF(errorHandler);
5937
184
    Py_XDECREF(exc);
5938
184
    return _PyUnicodeWriter_Finish(&writer);
5939
5940
152
  onError:
5941
152
    _PyUnicodeWriter_Dealloc(&writer);
5942
152
    Py_XDECREF(errorHandler);
5943
152
    Py_XDECREF(exc);
5944
152
    return NULL;
5945
336
}
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
45
{
6115
45
    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
6116
45
}
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
552
{
6125
552
    const char *starts = s;
6126
552
    Py_ssize_t startinpos;
6127
552
    Py_ssize_t endinpos;
6128
552
    _PyUnicodeWriter writer;
6129
552
    const unsigned char *q, *e;
6130
552
    int bo = 0;       /* assume native ordering by default */
6131
552
    int native_ordering;
6132
552
    const char *errmsg = "";
6133
552
    PyObject *errorHandler = NULL;
6134
552
    PyObject *exc = NULL;
6135
552
    const char *encoding;
6136
6137
552
    q = (const unsigned char *)s;
6138
552
    e = q + size;
6139
6140
552
    if (byteorder)
6141
507
        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
552
    if (bo == 0 && size >= 2) {
6148
45
        const Py_UCS4 bom = (q[1] << 8) | q[0];
6149
45
        if (bom == 0xFEFF) {
6150
24
            q += 2;
6151
24
            bo = -1;
6152
24
        }
6153
21
        else if (bom == 0xFFFE) {
6154
21
            q += 2;
6155
21
            bo = 1;
6156
21
        }
6157
45
        if (byteorder)
6158
0
            *byteorder = bo;
6159
45
    }
6160
6161
552
    if (q == e) {
6162
2
        if (consumed)
6163
0
            *consumed = size;
6164
2
        _Py_RETURN_UNICODE_EMPTY();
6165
2
    }
6166
6167
550
#if PY_LITTLE_ENDIAN
6168
550
    native_ordering = bo <= 0;
6169
550
    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
550
    _PyUnicodeWriter_Init(&writer);
6179
550
    writer.min_length = (e - q + 1) / 2;
6180
550
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
6181
0
        goto onError;
6182
6183
47.0k
    while (1) {
6184
47.0k
        Py_UCS4 ch = 0;
6185
47.0k
        if (e - q >= 2) {
6186
46.7k
            int kind = writer.kind;
6187
46.7k
            if (kind == PyUnicode_1BYTE_KIND) {
6188
741
                if (PyUnicode_IS_ASCII(writer.buffer))
6189
548
                    ch = asciilib_utf16_decode(&q, e,
6190
548
                            (Py_UCS1*)writer.data, &writer.pos,
6191
548
                            native_ordering);
6192
193
                else
6193
193
                    ch = ucs1lib_utf16_decode(&q, e,
6194
193
                            (Py_UCS1*)writer.data, &writer.pos,
6195
193
                            native_ordering);
6196
46.0k
            } else if (kind == PyUnicode_2BYTE_KIND) {
6197
22.5k
                ch = ucs2lib_utf16_decode(&q, e,
6198
22.5k
                        (Py_UCS2*)writer.data, &writer.pos,
6199
22.5k
                        native_ordering);
6200
23.4k
            } else {
6201
23.4k
                assert(kind == PyUnicode_4BYTE_KIND);
6202
23.4k
                ch = ucs4lib_utf16_decode(&q, e,
6203
23.4k
                        (Py_UCS4*)writer.data, &writer.pos,
6204
23.4k
                        native_ordering);
6205
23.4k
            }
6206
46.7k
        }
6207
6208
47.0k
        switch (ch)
6209
47.0k
        {
6210
550
        case 0:
6211
            /* remaining byte at the end? (size should be even) */
6212
550
            if (q == e || consumed)
6213
328
                goto End;
6214
222
            errmsg = "truncated data";
6215
222
            startinpos = ((const char *)q) - starts;
6216
222
            endinpos = ((const char *)e) - starts;
6217
222
            break;
6218
            /* The remaining input chars are ignored if the callback
6219
               chooses to skip the input */
6220
139
        case 1:
6221
139
            q -= 2;
6222
139
            if (consumed)
6223
0
                goto End;
6224
139
            errmsg = "unexpected end of data";
6225
139
            startinpos = ((const char *)q) - starts;
6226
139
            endinpos = ((const char *)e) - starts;
6227
139
            break;
6228
15.9k
        case 2:
6229
15.9k
            errmsg = "illegal encoding";
6230
15.9k
            startinpos = ((const char *)q) - 2 - starts;
6231
15.9k
            endinpos = startinpos + 2;
6232
15.9k
            break;
6233
29.8k
        case 3:
6234
29.8k
            errmsg = "illegal UTF-16 surrogate";
6235
29.8k
            startinpos = ((const char *)q) - 4 - starts;
6236
29.8k
            endinpos = startinpos + 2;
6237
29.8k
            break;
6238
542
        default:
6239
542
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
6240
0
                goto onError;
6241
542
            continue;
6242
47.0k
        }
6243
6244
46.1k
        if (unicode_decode_call_errorhandler_writer(
6245
46.1k
                errors,
6246
46.1k
                &errorHandler,
6247
46.1k
                encoding, errmsg,
6248
46.1k
                &starts,
6249
46.1k
                (const char **)&e,
6250
46.1k
                &startinpos,
6251
46.1k
                &endinpos,
6252
46.1k
                &exc,
6253
46.1k
                (const char **)&q,
6254
46.1k
                &writer))
6255
222
            goto onError;
6256
46.1k
    }
6257
6258
328
End:
6259
328
    if (consumed)
6260
0
        *consumed = (const char *)q-starts;
6261
6262
328
    Py_XDECREF(errorHandler);
6263
328
    Py_XDECREF(exc);
6264
328
    return _PyUnicodeWriter_Finish(&writer);
6265
6266
222
  onError:
6267
222
    _PyUnicodeWriter_Dealloc(&writer);
6268
222
    Py_XDECREF(errorHandler);
6269
222
    Py_XDECREF(exc);
6270
222
    return NULL;
6271
550
}
6272
6273
PyObject *
6274
_PyUnicode_EncodeUTF16(PyObject *str,
6275
                       const char *errors,
6276
                       int byteorder)
6277
0
{
6278
0
    if (!PyUnicode_Check(str)) {
6279
0
        PyErr_BadArgument();
6280
0
        return NULL;
6281
0
    }
6282
0
    int kind = PyUnicode_KIND(str);
6283
0
    const void *data = PyUnicode_DATA(str);
6284
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
6285
6286
0
    Py_ssize_t pairs = 0;
6287
0
    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
0
    if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
6297
0
        return PyErr_NoMemory();
6298
0
    }
6299
0
    Py_ssize_t nsize = len + pairs + (byteorder == 0);
6300
6301
#if PY_BIG_ENDIAN
6302
    int native_ordering = byteorder >= 0;
6303
#else
6304
0
    int native_ordering = byteorder <= 0;
6305
0
#endif
6306
6307
0
    if (kind == PyUnicode_1BYTE_KIND) {
6308
        // gh-139156: Don't use PyBytesWriter API here since it has an overhead
6309
        // on short strings
6310
0
        PyObject *v = PyBytes_FromStringAndSize(NULL, nsize * 2);
6311
0
        if (v == NULL) {
6312
0
            return NULL;
6313
0
        }
6314
6315
        /* output buffer is 2-bytes aligned */
6316
0
        assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
6317
0
        unsigned short *out = (unsigned short *)PyBytes_AS_STRING(v);
6318
0
        if (byteorder == 0) {
6319
0
            *out++ = 0xFEFF;
6320
0
        }
6321
0
        if (len > 0) {
6322
0
            ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
6323
0
        }
6324
0
        return v;
6325
0
    }
6326
6327
0
    PyBytesWriter *writer = PyBytesWriter_Create(nsize * 2);
6328
0
    if (writer == NULL) {
6329
0
        return NULL;
6330
0
    }
6331
6332
    /* output buffer is 2-bytes aligned */
6333
0
    assert(_Py_IS_ALIGNED(PyBytesWriter_GetData(writer), 2));
6334
0
    unsigned short *out = PyBytesWriter_GetData(writer);
6335
0
    if (byteorder == 0) {
6336
0
        *out++ = 0xFEFF;
6337
0
    }
6338
0
    if (len == 0) {
6339
0
        return PyBytesWriter_Finish(writer);
6340
0
    }
6341
6342
0
    const char *encoding;
6343
0
    if (byteorder < 0) {
6344
0
        encoding = "utf-16-le";
6345
0
    }
6346
0
    else if (byteorder > 0) {
6347
0
        encoding = "utf-16-be";
6348
0
    }
6349
0
    else {
6350
0
        encoding = "utf-16";
6351
0
    }
6352
6353
0
    PyObject *errorHandler = NULL;
6354
0
    PyObject *exc = NULL;
6355
0
    PyObject *rep = NULL;
6356
6357
0
    for (Py_ssize_t pos = 0; pos < len; ) {
6358
0
        if (kind == PyUnicode_2BYTE_KIND) {
6359
0
            pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
6360
0
                                        &out, native_ordering);
6361
0
        }
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
0
        if (pos == len)
6368
0
            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
0
    Py_XDECREF(errorHandler);
6424
0
    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
0
    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
0
}
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
5
{
6448
5
    PyInterpreterState *interp = _PyInterpreterState_GET();
6449
5
    _PyUnicode_Name_CAPI *ucnhash_capi;
6450
6451
5
    ucnhash_capi = _Py_atomic_load_ptr(&interp->unicode.ucnhash_capi);
6452
5
    if (ucnhash_capi == NULL) {
6453
1
        ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6454
1
                PyUnicodeData_CAPSULE_NAME, 1);
6455
6456
        // It's fine if we overwrite the value here. It's always the same value.
6457
1
        _Py_atomic_store_ptr(&interp->unicode.ucnhash_capi, ucnhash_capi);
6458
1
    }
6459
5
    return ucnhash_capi;
6460
5
}
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
38
{
6472
38
    const char *starts = s;
6473
38
    const char *initial_starts = starts;
6474
38
    _PyUnicodeWriter writer;
6475
38
    const char *end;
6476
38
    PyObject *errorHandler = NULL;
6477
38
    PyObject *exc = NULL;
6478
38
    _PyUnicode_Name_CAPI *ucnhash_capi;
6479
6480
    // so we can remember if we've seen an invalid escape char or not
6481
38
    *first_invalid_escape_char = -1;
6482
38
    *first_invalid_escape_ptr = NULL;
6483
6484
38
    if (size == 0) {
6485
0
        if (consumed) {
6486
0
            *consumed = 0;
6487
0
        }
6488
0
        _Py_RETURN_UNICODE_EMPTY();
6489
0
    }
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
38
    _PyUnicodeWriter_Init(&writer);
6496
38
    writer.min_length = size;
6497
38
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6498
0
        goto onError;
6499
0
    }
6500
6501
38
    end = s + size;
6502
26.6M
    while (s < end) {
6503
26.6M
        unsigned char c = (unsigned char) *s++;
6504
26.6M
        Py_UCS4 ch;
6505
26.6M
        int count;
6506
26.6M
        const char *message;
6507
6508
26.6M
#define WRITE_ASCII_CHAR(ch)                                                  \
6509
26.6M
            do {                                                              \
6510
7.11M
                assert(ch <= 127);                                            \
6511
7.11M
                assert(writer.pos < writer.size);                             \
6512
7.11M
                PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch);  \
6513
7.11M
            } while(0)
6514
6515
26.6M
#define WRITE_CHAR(ch)                                                        \
6516
26.6M
            do {                                                              \
6517
20.5M
                if (ch <= writer.maxchar) {                                   \
6518
20.5M
                    assert(writer.pos < writer.size);                         \
6519
20.5M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6520
20.5M
                }                                                             \
6521
20.5M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6522
0
                    goto onError;                                             \
6523
0
                }                                                             \
6524
20.5M
            } while(0)
6525
6526
        /* Non-escape characters are interpreted as Unicode ordinals */
6527
26.6M
        if (c != '\\') {
6528
18.9M
            WRITE_CHAR(c);
6529
18.9M
            continue;
6530
18.9M
        }
6531
6532
7.69M
        Py_ssize_t startinpos = s - starts - 1;
6533
        /* \ - Escapes */
6534
7.69M
        if (s >= end) {
6535
0
            message = "\\ at end of string";
6536
0
            goto incomplete;
6537
0
        }
6538
7.69M
        c = (unsigned char) *s++;
6539
6540
7.69M
        assert(writer.pos < writer.size);
6541
7.69M
        switch (c) {
6542
6543
            /* \x escapes */
6544
0
        case '\n': continue;
6545
666k
        case '\\': WRITE_ASCII_CHAR('\\'); continue;
6546
666k
        case '\'': WRITE_ASCII_CHAR('\''); continue;
6547
775k
        case '\"': WRITE_ASCII_CHAR('\"'); continue;
6548
775k
        case 'b': WRITE_ASCII_CHAR('\b'); continue;
6549
        /* FF */
6550
1.11M
        case 'f': WRITE_ASCII_CHAR('\014'); continue;
6551
1.11M
        case 't': WRITE_ASCII_CHAR('\t'); continue;
6552
1.86M
        case 'n': WRITE_ASCII_CHAR('\n'); continue;
6553
1.86M
        case 'r': WRITE_ASCII_CHAR('\r'); continue;
6554
        /* VT */
6555
1.05M
        case 'v': WRITE_ASCII_CHAR('\013'); continue;
6556
        /* BEL, not classic C */
6557
84.2k
        case 'a': WRITE_ASCII_CHAR('\007'); continue;
6558
6559
            /* \OOO (octal) escapes */
6560
168k
        case '0': case '1': case '2': case '3':
6561
194k
        case '4': case '5': case '6': case '7':
6562
194k
            ch = c - '0';
6563
194k
            if (s < end && '0' <= *s && *s <= '7') {
6564
1.10k
                ch = (ch<<3) + *s++ - '0';
6565
1.10k
                if (s < end && '0' <= *s && *s <= '7') {
6566
117
                    ch = (ch<<3) + *s++ - '0';
6567
117
                }
6568
1.10k
            }
6569
194k
            if (ch > 0377) {
6570
3
                if (*first_invalid_escape_char == -1) {
6571
0
                    *first_invalid_escape_char = ch;
6572
0
                    if (starts == initial_starts) {
6573
                        /* Back up 3 chars, since we've already incremented s. */
6574
0
                        *first_invalid_escape_ptr = s - 3;
6575
0
                    }
6576
0
                }
6577
3
            }
6578
194k
            WRITE_CHAR(ch);
6579
194k
            continue;
6580
6581
            /* hex escapes */
6582
            /* \xXX */
6583
194k
        case 'x':
6584
0
            count = 2;
6585
0
            message = "truncated \\xXX escape";
6586
0
            goto hexescape;
6587
6588
            /* \uXXXX */
6589
0
        case 'u':
6590
0
            count = 4;
6591
0
            message = "truncated \\uXXXX escape";
6592
0
            goto hexescape;
6593
6594
            /* \UXXXXXXXX */
6595
381k
        case 'U':
6596
381k
            count = 8;
6597
381k
            message = "truncated \\UXXXXXXXX escape";
6598
381k
        hexescape:
6599
3.43M
            for (ch = 0; count; ++s, --count) {
6600
3.05M
                if (s >= end) {
6601
0
                    goto incomplete;
6602
0
                }
6603
3.05M
                c = (unsigned char)*s;
6604
3.05M
                ch <<= 4;
6605
3.05M
                if (c >= '0' && c <= '9') {
6606
2.43M
                    ch += c - '0';
6607
2.43M
                }
6608
616k
                else if (c >= 'a' && c <= 'f') {
6609
616k
                    ch += c - ('a' - 10);
6610
616k
                }
6611
0
                else if (c >= 'A' && c <= 'F') {
6612
0
                    ch += c - ('A' - 10);
6613
0
                }
6614
0
                else {
6615
0
                    goto error;
6616
0
                }
6617
3.05M
            }
6618
6619
            /* when we get here, ch is a 32-bit unicode character */
6620
381k
            if (ch > MAX_UNICODE) {
6621
0
                message = "illegal Unicode character";
6622
0
                goto error;
6623
0
            }
6624
6625
381k
            WRITE_CHAR(ch);
6626
381k
            continue;
6627
6628
            /* \N{name} */
6629
381k
        case 'N':
6630
5
            ucnhash_capi = _PyUnicode_GetNameCAPI();
6631
5
            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
5
            message = "malformed \\N character escape";
6640
5
            if (s >= end) {
6641
0
                goto incomplete;
6642
0
            }
6643
5
            if (*s == '{') {
6644
5
                const char *start = ++s;
6645
5
                size_t namelen;
6646
                /* look for the closing brace */
6647
5.23M
                while (s < end && *s != '}')
6648
5.23M
                    s++;
6649
5
                if (s >= end) {
6650
0
                    goto incomplete;
6651
0
                }
6652
5
                namelen = s - start;
6653
5
                if (namelen) {
6654
                    /* found a name.  look it up in the unicode database */
6655
5
                    s++;
6656
5
                    ch = 0xffffffff; /* in case 'getcode' messes up */
6657
5
                    if (namelen <= INT_MAX &&
6658
5
                        ucnhash_capi->getcode(start, (int)namelen,
6659
5
                                              &ch, 0)) {
6660
0
                        assert(ch <= MAX_UNICODE);
6661
0
                        WRITE_CHAR(ch);
6662
0
                        continue;
6663
0
                    }
6664
5
                    message = "unknown Unicode character name";
6665
5
                }
6666
5
            }
6667
5
            goto error;
6668
6669
985k
        default:
6670
985k
            if (*first_invalid_escape_char == -1) {
6671
33
                *first_invalid_escape_char = c;
6672
33
                if (starts == initial_starts) {
6673
                    /* Back up one char, since we've already incremented s. */
6674
33
                    *first_invalid_escape_ptr = s - 1;
6675
33
                }
6676
33
            }
6677
985k
            WRITE_ASCII_CHAR('\\');
6678
985k
            WRITE_CHAR(c);
6679
985k
            continue;
6680
7.69M
        }
6681
6682
0
      incomplete:
6683
0
        if (consumed) {
6684
0
            *consumed = startinpos;
6685
0
            break;
6686
0
        }
6687
5
      error:;
6688
5
        Py_ssize_t endinpos = s-starts;
6689
5
        writer.min_length = end - s + writer.pos;
6690
5
        if (unicode_decode_call_errorhandler_writer(
6691
5
                errors, &errorHandler,
6692
5
                "unicodeescape", message,
6693
5
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6694
5
                &writer)) {
6695
5
            goto onError;
6696
5
        }
6697
5
        assert(end - s <= writer.size - writer.pos);
6698
6699
0
#undef WRITE_ASCII_CHAR
6700
0
#undef WRITE_CHAR
6701
0
    }
6702
6703
33
    Py_XDECREF(errorHandler);
6704
33
    Py_XDECREF(exc);
6705
33
    return _PyUnicodeWriter_Finish(&writer);
6706
6707
5
  onError:
6708
5
    _PyUnicodeWriter_Dealloc(&writer);
6709
5
    Py_XDECREF(errorHandler);
6710
5
    Py_XDECREF(exc);
6711
5
    return NULL;
6712
38
}
6713
6714
PyObject *
6715
_PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
6716
                              Py_ssize_t size,
6717
                              const char *errors,
6718
                              Py_ssize_t *consumed)
6719
0
{
6720
0
    int first_invalid_escape_char;
6721
0
    const char *first_invalid_escape_ptr;
6722
0
    PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal2(s, size, errors,
6723
0
                                                      consumed,
6724
0
                                                      &first_invalid_escape_char,
6725
0
                                                      &first_invalid_escape_ptr);
6726
0
    if (result == NULL)
6727
0
        return NULL;
6728
0
    if (first_invalid_escape_char != -1) {
6729
0
        if (first_invalid_escape_char > 0xff) {
6730
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6731
0
                                 "\"\\%o\" is an invalid octal escape sequence. "
6732
0
                                 "Such sequences will not work in the future. ",
6733
0
                                 first_invalid_escape_char) < 0)
6734
0
            {
6735
0
                Py_DECREF(result);
6736
0
                return NULL;
6737
0
            }
6738
0
        }
6739
0
        else {
6740
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6741
0
                                 "\"\\%c\" is an invalid escape sequence. "
6742
0
                                 "Such sequences will not work in the future. ",
6743
0
                                 first_invalid_escape_char) < 0)
6744
0
            {
6745
0
                Py_DECREF(result);
6746
0
                return NULL;
6747
0
            }
6748
0
        }
6749
0
    }
6750
0
    return result;
6751
0
}
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
0
{
6766
0
    if (!PyUnicode_Check(unicode)) {
6767
0
        PyErr_BadArgument();
6768
0
        return NULL;
6769
0
    }
6770
6771
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
6772
0
    if (len == 0) {
6773
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
6774
0
    }
6775
0
    int kind = PyUnicode_KIND(unicode);
6776
0
    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
0
    Py_ssize_t expandsize = kind * 2 + 2;
6785
0
    if (len > PY_SSIZE_T_MAX / expandsize) {
6786
0
        return PyErr_NoMemory();
6787
0
    }
6788
6789
0
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
6790
0
    if (writer == NULL) {
6791
0
        return NULL;
6792
0
    }
6793
0
    char *p = PyBytesWriter_GetData(writer);
6794
6795
0
    for (Py_ssize_t i = 0; i < len; i++) {
6796
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6797
6798
        /* U+0000-U+00ff range */
6799
0
        if (ch < 0x100) {
6800
0
            if (ch >= ' ' && ch < 127) {
6801
0
                if (ch != '\\') {
6802
                    /* Copy printable US ASCII as-is */
6803
0
                    *p++ = (char) ch;
6804
0
                }
6805
                /* Escape backslashes */
6806
0
                else {
6807
0
                    *p++ = '\\';
6808
0
                    *p++ = '\\';
6809
0
                }
6810
0
            }
6811
6812
            /* Map special whitespace to '\t', \n', '\r' */
6813
0
            else if (ch == '\t') {
6814
0
                *p++ = '\\';
6815
0
                *p++ = 't';
6816
0
            }
6817
0
            else if (ch == '\n') {
6818
0
                *p++ = '\\';
6819
0
                *p++ = 'n';
6820
0
            }
6821
0
            else if (ch == '\r') {
6822
0
                *p++ = '\\';
6823
0
                *p++ = 'r';
6824
0
            }
6825
6826
            /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6827
0
            else {
6828
0
                *p++ = '\\';
6829
0
                *p++ = 'x';
6830
0
                *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6831
0
                *p++ = Py_hexdigits[ch & 0x000F];
6832
0
            }
6833
0
        }
6834
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
6835
0
        else if (ch < 0x10000) {
6836
0
            *p++ = '\\';
6837
0
            *p++ = 'u';
6838
0
            *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6839
0
            *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6840
0
            *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6841
0
            *p++ = Py_hexdigits[ch & 0x000F];
6842
0
        }
6843
        /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6844
0
        else {
6845
6846
            /* Make sure that the first two digits are zero */
6847
0
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6848
0
            *p++ = '\\';
6849
0
            *p++ = 'U';
6850
0
            *p++ = '0';
6851
0
            *p++ = '0';
6852
0
            *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6853
0
            *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6854
0
            *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6855
0
            *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6856
0
            *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6857
0
            *p++ = Py_hexdigits[ch & 0x0000000F];
6858
0
        }
6859
0
    }
6860
6861
0
    return PyBytesWriter_FinishWithPointer(writer, p);
6862
0
}
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
0
{
6872
0
    const char *starts = s;
6873
0
    _PyUnicodeWriter writer;
6874
0
    const char *end;
6875
0
    PyObject *errorHandler = NULL;
6876
0
    PyObject *exc = NULL;
6877
6878
0
    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
0
    _PyUnicodeWriter_Init(&writer);
6890
0
    writer.min_length = size;
6891
0
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6892
0
        goto onError;
6893
0
    }
6894
6895
0
    end = s + size;
6896
0
    while (s < end) {
6897
0
        unsigned char c = (unsigned char) *s++;
6898
0
        Py_UCS4 ch;
6899
0
        int count;
6900
0
        const char *message;
6901
6902
0
#define WRITE_CHAR(ch)                                                        \
6903
0
            do {                                                              \
6904
0
                if (ch <= writer.maxchar) {                                   \
6905
0
                    assert(writer.pos < writer.size);                         \
6906
0
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6907
0
                }                                                             \
6908
0
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6909
0
                    goto onError;                                             \
6910
0
                }                                                             \
6911
0
            } while(0)
6912
6913
        /* Non-escape characters are interpreted as Unicode ordinals */
6914
0
        if (c != '\\' || (s >= end && !consumed)) {
6915
0
            WRITE_CHAR(c);
6916
0
            continue;
6917
0
        }
6918
6919
0
        Py_ssize_t startinpos = s - starts - 1;
6920
        /* \ - Escapes */
6921
0
        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
0
        c = (unsigned char) *s++;
6930
0
        if (c == 'u') {
6931
0
            count = 4;
6932
0
            message = "truncated \\uXXXX escape";
6933
0
        }
6934
0
        else if (c == 'U') {
6935
0
            count = 8;
6936
0
            message = "truncated \\UXXXXXXXX escape";
6937
0
        }
6938
0
        else {
6939
0
            assert(writer.pos < writer.size);
6940
0
            PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6941
0
            WRITE_CHAR(c);
6942
0
            continue;
6943
0
        }
6944
6945
        /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6946
0
        for (ch = 0; count; ++s, --count) {
6947
0
            if (s >= end) {
6948
0
                goto incomplete;
6949
0
            }
6950
0
            c = (unsigned char)*s;
6951
0
            ch <<= 4;
6952
0
            if (c >= '0' && c <= '9') {
6953
0
                ch += c - '0';
6954
0
            }
6955
0
            else if (c >= 'a' && c <= 'f') {
6956
0
                ch += c - ('a' - 10);
6957
0
            }
6958
0
            else if (c >= 'A' && c <= 'F') {
6959
0
                ch += c - ('A' - 10);
6960
0
            }
6961
0
            else {
6962
0
                goto error;
6963
0
            }
6964
0
        }
6965
0
        if (ch > MAX_UNICODE) {
6966
0
            message = "\\Uxxxxxxxx out of range";
6967
0
            goto error;
6968
0
        }
6969
0
        WRITE_CHAR(ch);
6970
0
        continue;
6971
6972
0
      incomplete:
6973
0
        if (consumed) {
6974
0
            *consumed = startinpos;
6975
0
            break;
6976
0
        }
6977
0
      error:;
6978
0
        Py_ssize_t endinpos = s-starts;
6979
0
        writer.min_length = end - s + writer.pos;
6980
0
        if (unicode_decode_call_errorhandler_writer(
6981
0
                errors, &errorHandler,
6982
0
                "rawunicodeescape", message,
6983
0
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6984
0
                &writer)) {
6985
0
            goto onError;
6986
0
        }
6987
0
        assert(end - s <= writer.size - writer.pos);
6988
6989
0
#undef WRITE_CHAR
6990
0
    }
6991
0
    Py_XDECREF(errorHandler);
6992
0
    Py_XDECREF(exc);
6993
0
    return _PyUnicodeWriter_Finish(&writer);
6994
6995
0
  onError:
6996
0
    _PyUnicodeWriter_Dealloc(&writer);
6997
0
    Py_XDECREF(errorHandler);
6998
0
    Py_XDECREF(exc);
6999
0
    return NULL;
7000
0
}
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
0
{
7014
0
    if (!PyUnicode_Check(unicode)) {
7015
0
        PyErr_BadArgument();
7016
0
        return NULL;
7017
0
    }
7018
0
    int kind = PyUnicode_KIND(unicode);
7019
0
    const void *data = PyUnicode_DATA(unicode);
7020
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
7021
0
    if (len == 0) {
7022
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7023
0
    }
7024
0
    if (kind == PyUnicode_1BYTE_KIND) {
7025
0
        return PyBytes_FromStringAndSize(data, len);
7026
0
    }
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
0
    Py_ssize_t expandsize = kind * 2 + 2;
7031
0
    if (len > PY_SSIZE_T_MAX / expandsize) {
7032
0
        return PyErr_NoMemory();
7033
0
    }
7034
7035
0
    PyBytesWriter *writer = PyBytesWriter_Create(expandsize * len);
7036
0
    if (writer == NULL) {
7037
0
        return NULL;
7038
0
    }
7039
0
    char *p = PyBytesWriter_GetData(writer);
7040
7041
0
    for (Py_ssize_t pos = 0; pos < len; pos++) {
7042
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7043
7044
        /* U+0000-U+00ff range: Copy 8-bit characters as-is */
7045
0
        if (ch < 0x100) {
7046
0
            *p++ = (char) ch;
7047
0
        }
7048
        /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
7049
0
        else if (ch < 0x10000) {
7050
0
            *p++ = '\\';
7051
0
            *p++ = 'u';
7052
0
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7053
0
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7054
0
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7055
0
            *p++ = Py_hexdigits[ch & 15];
7056
0
        }
7057
        /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
7058
0
        else {
7059
0
            assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
7060
0
            *p++ = '\\';
7061
0
            *p++ = 'U';
7062
0
            *p++ = '0';
7063
0
            *p++ = '0';
7064
0
            *p++ = Py_hexdigits[(ch >> 20) & 0xf];
7065
0
            *p++ = Py_hexdigits[(ch >> 16) & 0xf];
7066
0
            *p++ = Py_hexdigits[(ch >> 12) & 0xf];
7067
0
            *p++ = Py_hexdigits[(ch >> 8) & 0xf];
7068
0
            *p++ = Py_hexdigits[(ch >> 4) & 0xf];
7069
0
            *p++ = Py_hexdigits[ch & 15];
7070
0
        }
7071
0
    }
7072
7073
0
    return PyBytesWriter_FinishWithPointer(writer, p);
7074
0
}
7075
7076
/* --- Latin-1 Codec ------------------------------------------------------ */
7077
7078
PyObject *
7079
PyUnicode_DecodeLatin1(const char *s,
7080
                       Py_ssize_t size,
7081
                       const char *errors)
7082
4.59k
{
7083
    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
7084
4.59k
    return _PyUnicode_FromUCS1((const unsigned char*)s, size);
7085
4.59k
}
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
0
{
7095
0
    if (*exceptionObject == NULL) {
7096
0
        *exceptionObject = PyObject_CallFunction(
7097
0
            PyExc_UnicodeEncodeError, "sOnns",
7098
0
            encoding, unicode, startpos, endpos, reason);
7099
0
    }
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
0
}
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
0
{
7121
0
    make_encode_exception(exceptionObject,
7122
0
                          encoding, unicode, startpos, endpos, reason);
7123
0
    if (*exceptionObject != NULL)
7124
0
        PyCodec_StrictErrors(*exceptionObject);
7125
0
}
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
0
{
7139
0
    static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
7140
0
    Py_ssize_t len;
7141
0
    PyObject *restuple;
7142
0
    PyObject *resunicode;
7143
7144
0
    if (*errorHandler == NULL) {
7145
0
        *errorHandler = PyCodec_LookupError(errors);
7146
0
        if (*errorHandler == NULL)
7147
0
            return NULL;
7148
0
    }
7149
7150
0
    len = PyUnicode_GET_LENGTH(unicode);
7151
7152
0
    make_encode_exception(exceptionObject,
7153
0
                          encoding, unicode, startpos, endpos, reason);
7154
0
    if (*exceptionObject == NULL)
7155
0
        return NULL;
7156
7157
0
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
7158
0
    if (restuple == NULL)
7159
0
        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
281
{
7192
    /* input state */
7193
281
    Py_ssize_t pos=0, size;
7194
281
    int kind;
7195
281
    const void *data;
7196
281
    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
7197
281
    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
7198
281
    PyObject *error_handler_obj = NULL;
7199
281
    PyObject *exc = NULL;
7200
281
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7201
281
    PyObject *rep = NULL;
7202
7203
281
    size = PyUnicode_GET_LENGTH(unicode);
7204
281
    kind = PyUnicode_KIND(unicode);
7205
281
    data = PyUnicode_DATA(unicode);
7206
    /* allocate enough for a simple encoding without
7207
       replacements, if we need more, we'll resize */
7208
281
    if (size == 0)
7209
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7210
7211
    /* output object */
7212
281
    PyBytesWriter *writer = PyBytesWriter_Create(size);
7213
281
    if (writer == NULL) {
7214
0
        return NULL;
7215
0
    }
7216
    /* pointer into the output */
7217
281
    char *str = PyBytesWriter_GetData(writer);
7218
7219
3.61M
    while (pos < size) {
7220
3.61M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7221
7222
        /* can we encode this? */
7223
3.61M
        if (ch < limit) {
7224
            /* no overflow check, because we know that the space is enough */
7225
3.59M
            *str++ = (char)ch;
7226
3.59M
            ++pos;
7227
3.59M
        }
7228
15.7k
        else {
7229
15.7k
            Py_ssize_t newpos, i;
7230
            /* startpos for collecting unencodable chars */
7231
15.7k
            Py_ssize_t collstart = pos;
7232
15.7k
            Py_ssize_t collend = collstart + 1;
7233
            /* find all unecodable characters */
7234
7235
140k
            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
7236
124k
                ++collend;
7237
7238
            /* Only overallocate the buffer if it's not the last write */
7239
15.7k
            writer->overallocate = (collend < size);
7240
7241
            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
7242
15.7k
            if (error_handler == _Py_ERROR_UNKNOWN)
7243
281
                error_handler = _Py_GetErrorHandler(errors);
7244
7245
15.7k
            switch (error_handler) {
7246
0
            case _Py_ERROR_STRICT:
7247
0
                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
7248
0
                goto onError;
7249
7250
0
            case _Py_ERROR_REPLACE:
7251
0
                memset(str, '?', collend - collstart);
7252
0
                str += (collend - collstart);
7253
0
                _Py_FALLTHROUGH;
7254
0
            case _Py_ERROR_IGNORE:
7255
0
                pos = collend;
7256
0
                break;
7257
7258
15.7k
            case _Py_ERROR_BACKSLASHREPLACE:
7259
                /* subtract preallocated bytes */
7260
15.7k
                writer->size -= (collend - collstart);
7261
15.7k
                str = backslashreplace(writer, str,
7262
15.7k
                                       unicode, collstart, collend);
7263
15.7k
                if (str == NULL)
7264
0
                    goto onError;
7265
15.7k
                pos = collend;
7266
15.7k
                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
0
            case _Py_ERROR_SURROGATEESCAPE:
7279
0
                for (i = collstart; i < collend; ++i) {
7280
0
                    ch = PyUnicode_READ(kind, data, i);
7281
0
                    if (ch < 0xdc80 || 0xdcff < ch) {
7282
                        /* Not a UTF-8b surrogate */
7283
0
                        break;
7284
0
                    }
7285
0
                    *str++ = (char)(ch - 0xdc00);
7286
0
                    ++pos;
7287
0
                }
7288
0
                if (i >= collend)
7289
0
                    break;
7290
0
                collstart = pos;
7291
0
                assert(collstart != collend);
7292
0
                _Py_FALLTHROUGH;
7293
7294
0
            default:
7295
0
                rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
7296
0
                                                       encoding, reason, unicode, &exc,
7297
0
                                                       collstart, collend, &newpos);
7298
0
                if (rep == NULL)
7299
0
                    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
15.7k
            }
7351
7352
            /* If overallocation was disabled, ensure that it was the last
7353
               write. Otherwise, we missed an optimization */
7354
15.7k
            assert(writer->overallocate || pos == size);
7355
15.7k
        }
7356
3.61M
    }
7357
7358
281
    Py_XDECREF(error_handler_obj);
7359
281
    Py_XDECREF(exc);
7360
281
    return PyBytesWriter_FinishWithPointer(writer, str);
7361
7362
0
  onError:
7363
0
    Py_XDECREF(rep);
7364
0
    PyBytesWriter_Discard(writer);
7365
0
    Py_XDECREF(error_handler_obj);
7366
0
    Py_XDECREF(exc);
7367
0
    return NULL;
7368
281
}
7369
7370
PyObject *
7371
_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
7372
0
{
7373
0
    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
0
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7380
0
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7381
0
                                         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
0
}
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
5.96k
{
7400
5.96k
    const char *starts = s;
7401
5.96k
    const char *e = s + size;
7402
5.96k
    PyObject *error_handler_obj = NULL;
7403
5.96k
    PyObject *exc = NULL;
7404
5.96k
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7405
7406
5.96k
    if (size == 0)
7407
10
        _Py_RETURN_UNICODE_EMPTY();
7408
7409
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
7410
5.95k
    if (size == 1 && (unsigned char)s[0] < 128) {
7411
61
        return get_latin1_char((unsigned char)s[0]);
7412
61
    }
7413
7414
    // Shortcut for simple case
7415
5.89k
    PyObject *u = PyUnicode_New(size, 127);
7416
5.89k
    if (u == NULL) {
7417
0
        return NULL;
7418
0
    }
7419
5.89k
    Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
7420
5.89k
    if (outpos == size) {
7421
5.71k
        return u;
7422
5.71k
    }
7423
7424
181
    _PyUnicodeWriter writer;
7425
181
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
7426
181
    writer.pos = outpos;
7427
7428
181
    s += outpos;
7429
181
    int kind = writer.kind;
7430
181
    void *data = writer.data;
7431
181
    Py_ssize_t startinpos, endinpos;
7432
7433
7.42M
    while (s < e) {
7434
7.42M
        unsigned char c = (unsigned char)*s;
7435
7.42M
        if (c < 128) {
7436
7.13M
            PyUnicode_WRITE(kind, data, writer.pos, c);
7437
7.13M
            writer.pos++;
7438
7.13M
            ++s;
7439
7.13M
            continue;
7440
7.13M
        }
7441
7442
        /* byte outsize range 0x00..0x7f: call the error handler */
7443
7444
288k
        if (error_handler == _Py_ERROR_UNKNOWN)
7445
181
            error_handler = _Py_GetErrorHandler(errors);
7446
7447
288k
        switch (error_handler)
7448
288k
        {
7449
0
        case _Py_ERROR_REPLACE:
7450
288k
        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
288k
            if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7454
0
                goto onError;
7455
288k
            kind = writer.kind;
7456
288k
            data = writer.data;
7457
7458
288k
            if (error_handler == _Py_ERROR_REPLACE)
7459
0
                PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7460
288k
            else
7461
288k
                PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7462
288k
            writer.pos++;
7463
288k
            ++s;
7464
288k
            break;
7465
7466
0
        case _Py_ERROR_IGNORE:
7467
0
            ++s;
7468
0
            break;
7469
7470
0
        default:
7471
0
            startinpos = s-starts;
7472
0
            endinpos = startinpos + 1;
7473
0
            if (unicode_decode_call_errorhandler_writer(
7474
0
                    errors, &error_handler_obj,
7475
0
                    "ascii", "ordinal not in range(128)",
7476
0
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
7477
0
                    &writer))
7478
0
                goto onError;
7479
0
            kind = writer.kind;
7480
0
            data = writer.data;
7481
288k
        }
7482
288k
    }
7483
181
    Py_XDECREF(error_handler_obj);
7484
181
    Py_XDECREF(exc);
7485
181
    return _PyUnicodeWriter_Finish(&writer);
7486
7487
0
  onError:
7488
0
    _PyUnicodeWriter_Dealloc(&writer);
7489
0
    Py_XDECREF(error_handler_obj);
7490
0
    Py_XDECREF(exc);
7491
0
    return NULL;
7492
181
}
7493
7494
PyObject *
7495
_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
7496
2.49k
{
7497
2.49k
    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
2.49k
    if (PyUnicode_IS_ASCII(unicode))
7504
2.21k
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7505
2.21k
                                         PyUnicode_GET_LENGTH(unicode));
7506
281
    return unicode_encode_ucs1(unicode, errors, 128);
7507
2.49k
}
7508
7509
PyObject *
7510
PyUnicode_AsASCIIString(PyObject *unicode)
7511
0
{
7512
0
    return _PyUnicode_AsASCIIString(unicode, NULL);
7513
0
}
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
0
#  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
0
{
8230
0
    iconv_t cd = iconv_open(tocode, fromcode);
8231
0
    if (cd == (iconv_t)-1) {
8232
0
        if (errno == EINVAL) {
8233
0
            PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding);
8234
0
        }
8235
0
        else {
8236
0
            PyErr_SetFromErrno(PyExc_OSError);
8237
0
        }
8238
0
    }
8239
0
    return cd;
8240
0
}
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
0
{
8254
0
    if (size < 0) {
8255
0
        PyErr_BadInternalCall();
8256
0
        return NULL;
8257
0
    }
8258
8259
0
    iconv_t cd = iconv_open_or_set_error(ICONV_PIVOT, encoding, encoding);
8260
0
    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
0
    Py_UCS4 chunk[1024];
8266
0
    const char *starts = s;
8267
0
    const char *in = s;
8268
0
    const char *inend = s + size;
8269
0
    _PyUnicodeWriter writer;
8270
0
    PyObject *errorHandler = NULL;
8271
0
    PyObject *exc = NULL;
8272
8273
0
    _PyUnicodeWriter_Init(&writer);
8274
0
    writer.min_length = size;
8275
8276
0
    while (in < inend) {
8277
0
        char *inptr = (char *)in;
8278
0
        size_t inleft = (size_t)(inend - in);
8279
0
        char *outptr = (char *)chunk;
8280
0
        size_t outleft = sizeof(chunk);
8281
8282
0
        size_t ret = iconv(cd, &inptr, &inleft, &outptr, &outleft);
8283
0
        int err = errno;
8284
0
        in = inptr;
8285
8286
        /* Append whatever code points this call produced. */
8287
0
        Py_ssize_t nch = (Py_UCS4 *)outptr - chunk;
8288
0
        if (nch > 0 && PyUnicodeWriter_WriteUCS4((PyUnicodeWriter *)&writer,
8289
0
                                                 chunk, nch) < 0) {
8290
0
            goto error;
8291
0
        }
8292
8293
0
        if (ret != (size_t)-1) {
8294
0
            assert(in == inend);
8295
0
            break;
8296
0
        }
8297
8298
0
        if (err == E2BIG) {
8299
            /* The scratch buffer filled up; drain it and continue. */
8300
0
            continue;
8301
0
        }
8302
8303
0
        const char *reason;
8304
0
        if (err == EINVAL) {
8305
            /* Incomplete multibyte sequence at the end of the input. */
8306
0
            if (consumed != NULL) {
8307
                /* Stateful decoding: stop and report the consumed bytes. */
8308
0
                break;
8309
0
            }
8310
0
            reason = "incomplete multibyte sequence";
8311
0
        }
8312
0
        else if (err == EILSEQ) {
8313
0
            reason = "invalid multibyte sequence";
8314
0
        }
8315
0
        else {
8316
0
            errno = err;
8317
0
            PyErr_SetFromErrno(PyExc_OSError);
8318
0
            goto error;
8319
0
        }
8320
8321
0
        Py_ssize_t startinpos = in - starts;
8322
0
        Py_ssize_t endinpos = startinpos + 1;
8323
0
        if (unicode_decode_call_errorhandler_writer(
8324
0
                errors, &errorHandler, encoding, reason,
8325
0
                &starts, &inend, &startinpos, &endinpos, &exc, &in,
8326
0
                &writer)) {
8327
0
            goto error;
8328
0
        }
8329
        /* The error handler may have skipped bytes; reset the conversion
8330
           descriptor to the initial shift state before continuing. */
8331
0
        iconv(cd, NULL, NULL, NULL, NULL);
8332
0
    }
8333
8334
0
    if (consumed != NULL) {
8335
0
        *consumed = in - starts;
8336
0
    }
8337
0
    iconv_close(cd);
8338
0
    Py_XDECREF(errorHandler);
8339
0
    Py_XDECREF(exc);
8340
0
    return _PyUnicodeWriter_Finish(&writer);
8341
8342
0
error:
8343
0
    iconv_close(cd);
8344
0
    _PyUnicodeWriter_Dealloc(&writer);
8345
0
    Py_XDECREF(errorHandler);
8346
0
    Py_XDECREF(exc);
8347
0
    return NULL;
8348
0
}
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
0
{
8381
0
    if (!PyUnicode_Check(unicode)) {
8382
0
        PyErr_BadArgument();
8383
0
        return NULL;
8384
0
    }
8385
8386
0
    Py_ssize_t ulen = PyUnicode_GET_LENGTH(unicode);
8387
0
    const char *source;         /* iconv source encoding for this kind */
8388
0
    const char *data;           /* the units to encode */
8389
0
    Py_ssize_t unit;            /* bytes per code point in *data */
8390
0
    Py_UCS4 *widened = NULL;    /* owned UTF-32 copy of a 2-byte string */
8391
0
    int kind = PyUnicode_KIND(unicode);
8392
0
    if (kind == PyUnicode_1BYTE_KIND) {
8393
0
        source = "ISO-8859-1";
8394
0
        data = (const char *)PyUnicode_1BYTE_DATA(unicode);
8395
0
        unit = 1;
8396
0
    }
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
0
    iconv_t cd = iconv_open_or_set_error(encoding, source, encoding);
8421
0
    if (cd == (iconv_t)-1) {
8422
0
        PyMem_Free(widened);
8423
0
        return NULL;
8424
0
    }
8425
8426
0
    PyBytesWriter *writer = NULL;
8427
0
    PyObject *errorHandler = NULL;
8428
0
    PyObject *exc = NULL;
8429
0
    PyObject *result = NULL;
8430
0
    const char *ustart = data;
8431
0
    const char *up = data;
8432
0
    const char *uend = data + (size_t)ulen * unit;
8433
0
    int flushing = 0;
8434
0
    int careful = 0;            /* feed one code point per iconv() call */
8435
8436
    /* A generous initial estimate for the output size. */
8437
0
    writer = PyBytesWriter_Create(ulen + (ulen >> 1) + 16);
8438
0
    if (writer == NULL) {
8439
0
        goto done;
8440
0
    }
8441
0
    char *out = PyBytesWriter_GetData(writer);
8442
0
    char *outend = out + PyBytesWriter_GetSize(writer);
8443
8444
0
    for (;;) {
8445
0
        char *inptr = (char *)up;
8446
0
        size_t inleft = (size_t)(uend - up);
8447
        /* One code point at a time, to pin a substitution to its position. */
8448
0
        if (careful && inleft > (size_t)unit) {
8449
0
            inleft = (size_t)unit;
8450
0
        }
8451
0
        char *out_before = out;
8452
0
        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
0
        size_t ret = iconv(cd, flushing ? NULL : &inptr, &inleft, &out, &outleft);
8456
0
        if (!flushing) {
8457
0
            up = inptr;
8458
0
        }
8459
8460
0
        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
0
            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
0
            else if (flushing) {
8479
0
                break;
8480
0
            }
8481
0
            else if (careful && up < uend) {
8482
0
                continue;
8483
0
            }
8484
0
            else {
8485
                /* All input consumed; switch to flushing the shift state. */
8486
0
                flushing = 1;
8487
0
                continue;
8488
0
            }
8489
0
        }
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
0
    if (PyBytesWriter_Resize(writer, out - (char *)PyBytesWriter_GetData(writer)) < 0) {
8555
0
        goto done;
8556
0
    }
8557
0
    result = PyBytesWriter_Finish(writer);
8558
0
    writer = NULL;
8559
8560
0
done:
8561
0
    if (writer != NULL) {
8562
0
        PyBytesWriter_Discard(writer);
8563
0
    }
8564
0
    iconv_close(cd);
8565
0
    PyMem_Free(widened);
8566
0
    Py_XDECREF(errorHandler);
8567
0
    Py_XDECREF(exc);
8568
0
    return result;
8569
0
}
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
0
{
8582
0
    const char *starts = s;
8583
0
    const char *e;
8584
0
    Py_ssize_t startinpos, endinpos;
8585
0
    PyObject *errorHandler = NULL, *exc = NULL;
8586
0
    Py_ssize_t maplen;
8587
0
    int mapkind;
8588
0
    const void *mapdata;
8589
0
    Py_UCS4 x;
8590
0
    unsigned char ch;
8591
8592
0
    maplen = PyUnicode_GET_LENGTH(mapping);
8593
0
    mapdata = PyUnicode_DATA(mapping);
8594
0
    mapkind = PyUnicode_KIND(mapping);
8595
8596
0
    e = s + size;
8597
8598
0
    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
0
        const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
8603
0
        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8604
0
        Py_UCS4 maxchar = writer->maxchar;
8605
8606
0
        assert (writer->kind == PyUnicode_1BYTE_KIND);
8607
0
        while (s < e) {
8608
0
            ch = *s;
8609
0
            x = mapdata_ucs1[ch];
8610
0
            if (x > maxchar) {
8611
0
                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8612
0
                    goto onError;
8613
0
                maxchar = writer->maxchar;
8614
0
                outdata = (Py_UCS1 *)writer->data;
8615
0
            }
8616
0
            outdata[writer->pos] = x;
8617
0
            writer->pos++;
8618
0
            ++s;
8619
0
        }
8620
0
        return 0;
8621
0
    }
8622
8623
0
    while (s < e) {
8624
0
        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8625
0
            int outkind = writer->kind;
8626
0
            const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
8627
0
            if (outkind == PyUnicode_1BYTE_KIND) {
8628
0
                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8629
0
                Py_UCS4 maxchar = writer->maxchar;
8630
0
                while (s < e) {
8631
0
                    ch = *s;
8632
0
                    x = mapdata_ucs2[ch];
8633
0
                    if (x > maxchar)
8634
0
                        goto Error;
8635
0
                    outdata[writer->pos] = x;
8636
0
                    writer->pos++;
8637
0
                    ++s;
8638
0
                }
8639
0
                break;
8640
0
            }
8641
0
            else if (outkind == PyUnicode_2BYTE_KIND) {
8642
0
                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8643
0
                while (s < e) {
8644
0
                    ch = *s;
8645
0
                    x = mapdata_ucs2[ch];
8646
0
                    if (x == 0xFFFE)
8647
0
                        goto Error;
8648
0
                    outdata[writer->pos] = x;
8649
0
                    writer->pos++;
8650
0
                    ++s;
8651
0
                }
8652
0
                break;
8653
0
            }
8654
0
        }
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
0
Error:
8662
0
        if (x == 0xfffe)
8663
0
        {
8664
            /* undefined mapping */
8665
0
            startinpos = s-starts;
8666
0
            endinpos = startinpos+1;
8667
0
            if (unicode_decode_call_errorhandler_writer(
8668
0
                    errors, &errorHandler,
8669
0
                    "charmap", "character maps to <undefined>",
8670
0
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
8671
0
                    writer)) {
8672
0
                goto onError;
8673
0
            }
8674
0
            continue;
8675
0
        }
8676
8677
0
        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8678
0
            goto onError;
8679
0
        ++s;
8680
0
    }
8681
0
    Py_XDECREF(errorHandler);
8682
0
    Py_XDECREF(exc);
8683
0
    return 0;
8684
8685
0
onError:
8686
0
    Py_XDECREF(errorHandler);
8687
0
    Py_XDECREF(exc);
8688
0
    return -1;
8689
0
}
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
0
{
8801
0
    _PyUnicodeWriter writer;
8802
8803
    /* Default to Latin-1 */
8804
0
    if (mapping == NULL)
8805
0
        return PyUnicode_DecodeLatin1(s, size, errors);
8806
8807
0
    if (size == 0)
8808
0
        _Py_RETURN_UNICODE_EMPTY();
8809
0
    _PyUnicodeWriter_Init(&writer);
8810
0
    writer.min_length = size;
8811
0
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
8812
0
        goto onError;
8813
8814
0
    if (PyUnicode_CheckExact(mapping)) {
8815
0
        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8816
0
            goto onError;
8817
0
    }
8818
0
    else {
8819
0
        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8820
0
            goto onError;
8821
0
    }
8822
0
    return _PyUnicodeWriter_Finish(&writer);
8823
8824
0
  onError:
8825
0
    _PyUnicodeWriter_Dealloc(&writer);
8826
0
    return NULL;
8827
0
}
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
0
{
8874
0
    PyObject *result;
8875
0
    struct encoding_map *mresult;
8876
0
    int i;
8877
0
    int need_dict = 0;
8878
0
    unsigned char level1[32];
8879
0
    unsigned char level2[512];
8880
0
    unsigned char *mlevel1, *mlevel2, *mlevel3;
8881
0
    int count2 = 0, count3 = 0;
8882
0
    int kind;
8883
0
    const void *data;
8884
0
    int length;
8885
0
    Py_UCS4 ch;
8886
8887
0
    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
8888
0
        PyErr_BadArgument();
8889
0
        return NULL;
8890
0
    }
8891
0
    kind = PyUnicode_KIND(string);
8892
0
    data = PyUnicode_DATA(string);
8893
0
    length = (int)Py_MIN(PyUnicode_GET_LENGTH(string), 256);
8894
0
    memset(level1, 0xFF, sizeof level1);
8895
0
    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
0
    if (PyUnicode_READ(kind, data, 0) != 0)
8901
0
        need_dict = 1;
8902
0
    for (i = 1; i < length; i++) {
8903
0
        int l1, l2;
8904
0
        ch = PyUnicode_READ(kind, data, i);
8905
0
        if (ch == 0 || ch > 0xFFFF) {
8906
0
            need_dict = 1;
8907
0
            break;
8908
0
        }
8909
0
        if (ch == 0xFFFE)
8910
            /* unmapped character */
8911
0
            continue;
8912
0
        l1 = ch >> 11;
8913
0
        l2 = ch >> 7;
8914
0
        if (level1[l1] == 0xFF)
8915
0
            level1[l1] = count2++;
8916
0
        if (level2[l2] == 0xFF)
8917
0
            level2[l2] = count3++;
8918
0
    }
8919
8920
0
    if (count2 >= 0xFF || count3 >= 0xFF)
8921
0
        need_dict = 1;
8922
8923
0
    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
0
    result = PyObject_Malloc(sizeof(struct encoding_map) +
8953
0
                             16*count2 + 128*count3 - 1);
8954
0
    if (!result) {
8955
0
        return PyErr_NoMemory();
8956
0
    }
8957
8958
0
    _PyObject_Init(result, &EncodingMapType);
8959
0
    mresult = (struct encoding_map*)result;
8960
0
    mresult->count2 = count2;
8961
0
    mresult->count3 = count3;
8962
0
    mlevel1 = mresult->level1;
8963
0
    mlevel2 = mresult->level23;
8964
0
    mlevel3 = mresult->level23 + 16*count2;
8965
0
    memcpy(mlevel1, level1, 32);
8966
0
    memset(mlevel2, 0xFF, 16*count2);
8967
0
    memset(mlevel3, 0, 128*count3);
8968
0
    count3 = 0;
8969
0
    for (i = 1; i < length; i++) {
8970
0
        int o1, o2, o3, i2, i3;
8971
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8972
0
        if (ch == 0xFFFE)
8973
            /* unmapped character */
8974
0
            continue;
8975
0
        o1 = ch>>11;
8976
0
        o2 = (ch>>7) & 0xF;
8977
0
        i2 = 16*mlevel1[o1] + o2;
8978
0
        if (mlevel2[i2] == 0xFF)
8979
0
            mlevel2[i2] = count3++;
8980
0
        o3 = ch & 0x7F;
8981
0
        i3 = 128*mlevel2[i2] + o3;
8982
0
        mlevel3[i3] = i;
8983
0
    }
8984
0
    return result;
8985
0
}
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
188
{
9501
188
    PyObject *w = PyLong_FromLong((long)c);
9502
188
    PyObject *x;
9503
9504
188
    if (w == NULL)
9505
0
        return -1;
9506
188
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9507
188
    Py_DECREF(w);
9508
188
    if (rc == 0) {
9509
        /* No mapping found means: use 1:1 mapping. */
9510
84
        *result = NULL;
9511
84
        return 0;
9512
84
    }
9513
104
    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
104
    else if (x == Py_None) {
9523
0
        *result = x;
9524
0
        return 0;
9525
0
    }
9526
104
    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
104
    else if (PyUnicode_Check(x)) {
9540
104
        *result = x;
9541
104
        return 0;
9542
104
    }
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
104
}
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
72
{
9559
72
    PyObject *item;
9560
72
    Py_UCS4 replace;
9561
9562
72
    if (charmaptranslate_lookup(ch, mapping, &item, &replace))
9563
0
        return -1;
9564
9565
72
    if (item == NULL) {
9566
        /* not found => default to 1:1 mapping */
9567
16
        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
9568
0
            return -1;
9569
0
        }
9570
16
        return 1;
9571
16
    }
9572
9573
56
    if (item == Py_None) {
9574
0
        Py_DECREF(item);
9575
0
        return 0;
9576
0
    }
9577
9578
56
    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
56
    if (!PyUnicode_Check(item)) {
9588
0
        Py_DECREF(item);
9589
0
        return -1;
9590
0
    }
9591
9592
56
    if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
9593
0
        Py_DECREF(item);
9594
0
        return -1;
9595
0
    }
9596
9597
56
    Py_DECREF(item);
9598
56
    return 1;
9599
56
}
9600
9601
static int
9602
unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
9603
                              Py_UCS1 *translate)
9604
116
{
9605
116
    PyObject *item = NULL;
9606
116
    Py_UCS4 replace;
9607
116
    int ret = 0;
9608
9609
116
    if (charmaptranslate_lookup(ch, mapping, &item, &replace)) {
9610
0
        return -1;
9611
0
    }
9612
9613
116
    if (item == Py_None) {
9614
        /* deletion */
9615
0
        translate[ch] = 0xfe;
9616
0
    }
9617
116
    else if (item == NULL) {
9618
        /* not found => default to 1:1 mapping */
9619
68
        translate[ch] = ch;
9620
68
        return 1;
9621
68
    }
9622
48
    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
48
    else if (PyUnicode_Check(item)) {
9631
48
        if (PyUnicode_GET_LENGTH(item) != 1)
9632
48
            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
48
  exit:
9646
48
    Py_DECREF(item);
9647
48
    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
96
{
9658
96
    Py_UCS1 ascii_table[128], ch, ch2;
9659
96
    Py_ssize_t len;
9660
96
    const Py_UCS1 *in, *end;
9661
96
    Py_UCS1 *out;
9662
96
    int res = 0;
9663
9664
96
    len = PyUnicode_GET_LENGTH(input);
9665
9666
96
    memset(ascii_table, 0xff, 128);
9667
9668
96
    in = PyUnicode_1BYTE_DATA(input);
9669
96
    end = in + len;
9670
9671
96
    assert(PyUnicode_IS_ASCII(writer->buffer));
9672
96
    assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9673
96
    out = PyUnicode_1BYTE_DATA(writer->buffer);
9674
9675
178
    for (; in < end; in++) {
9676
130
        ch = *in;
9677
130
        ch2 = ascii_table[ch];
9678
130
        if (ch2 == 0xff) {
9679
116
            int translate = unicode_fast_translate_lookup(mapping, ch,
9680
116
                                                          ascii_table);
9681
116
            if (translate < 0)
9682
0
                return -1;
9683
116
            if (translate == 0)
9684
48
                goto exit;
9685
68
            ch2 = ascii_table[ch];
9686
68
        }
9687
82
        if (ch2 == 0xfe) {
9688
0
            if (ignore)
9689
0
                continue;
9690
0
            goto exit;
9691
0
        }
9692
82
        assert(ch2 < 128);
9693
82
        *out = ch2;
9694
82
        out++;
9695
82
    }
9696
48
    res = 1;
9697
9698
96
exit:
9699
96
    writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
9700
96
    *input_pos = in - PyUnicode_1BYTE_DATA(input);
9701
96
    return res;
9702
48
}
9703
9704
static PyObject *
9705
_PyUnicode_TranslateCharmap(PyObject *input,
9706
                            PyObject *mapping,
9707
                            const char *errors)
9708
96
{
9709
    /* input object */
9710
96
    const void *data;
9711
96
    Py_ssize_t size, i;
9712
96
    int kind;
9713
    /* output buffer */
9714
96
    _PyUnicodeWriter writer;
9715
    /* error handler */
9716
96
    const char *reason = "character maps to <undefined>";
9717
96
    PyObject *errorHandler = NULL;
9718
96
    PyObject *exc = NULL;
9719
96
    int ignore;
9720
96
    int res;
9721
9722
96
    if (mapping == NULL) {
9723
0
        PyErr_BadArgument();
9724
0
        return NULL;
9725
0
    }
9726
9727
96
    data = PyUnicode_DATA(input);
9728
96
    kind = PyUnicode_KIND(input);
9729
96
    size = PyUnicode_GET_LENGTH(input);
9730
9731
96
    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
96
    _PyUnicodeWriter_Init(&writer);
9737
96
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
9738
0
        goto onError;
9739
9740
96
    ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9741
9742
96
    if (PyUnicode_IS_ASCII(input)) {
9743
96
        res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9744
96
        if (res < 0) {
9745
0
            _PyUnicodeWriter_Dealloc(&writer);
9746
0
            return NULL;
9747
0
        }
9748
96
        if (res == 1)
9749
48
            return _PyUnicodeWriter_Finish(&writer);
9750
96
    }
9751
0
    else {
9752
0
        i = 0;
9753
0
    }
9754
9755
120
    while (i<size) {
9756
        /* try to encode it */
9757
72
        int translate;
9758
72
        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9759
72
        Py_ssize_t newpos;
9760
        /* startpos for collecting untranslatable chars */
9761
72
        Py_ssize_t collstart;
9762
72
        Py_ssize_t collend;
9763
72
        Py_UCS4 ch;
9764
9765
72
        ch = PyUnicode_READ(kind, data, i);
9766
72
        translate = charmaptranslate_output(ch, mapping, &writer);
9767
72
        if (translate < 0)
9768
0
            goto onError;
9769
9770
72
        if (translate != 0) {
9771
            /* it worked => adjust input pointer */
9772
72
            ++i;
9773
72
            continue;
9774
72
        }
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
48
    Py_XDECREF(exc);
9811
48
    Py_XDECREF(errorHandler);
9812
48
    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
48
}
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
217k
{
9834
217k
    if (!PyUnicode_Check(unicode)) {
9835
0
        PyErr_BadInternalCall();
9836
0
        return NULL;
9837
0
    }
9838
217k
    if (PyUnicode_IS_ASCII(unicode)) {
9839
        /* If the string is already ASCII, just return the same string */
9840
215k
        return Py_NewRef(unicode);
9841
215k
    }
9842
9843
1.62k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9844
1.62k
    PyObject *result = PyUnicode_New(len, 127);
9845
1.62k
    if (result == NULL) {
9846
0
        return NULL;
9847
0
    }
9848
9849
1.62k
    Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9850
1.62k
    int kind = PyUnicode_KIND(unicode);
9851
1.62k
    const void *data = PyUnicode_DATA(unicode);
9852
1.62k
    Py_ssize_t i;
9853
1.38M
    for (i = 0; i < len; ++i) {
9854
1.37M
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9855
1.37M
        if (ch < 127) {
9856
1.37M
            out[i] = ch;
9857
1.37M
        }
9858
7.48k
        else if (Py_UNICODE_ISSPACE(ch)) {
9859
5.46k
            out[i] = ' ';
9860
5.46k
        }
9861
2.01k
        else {
9862
2.01k
            int decimal = Py_UNICODE_TODECIMAL(ch);
9863
2.01k
            if (decimal < 0) {
9864
1.34k
                out[i] = '?';
9865
1.34k
                out[i+1] = '\0';
9866
1.34k
                _PyUnicode_LENGTH(result) = i + 1;
9867
0
                break;
9868
1.34k
            }
9869
668
            out[i] = '0' + decimal;
9870
668
        }
9871
1.37M
    }
9872
9873
1.62k
    assert(_PyUnicode_CheckConsistency(result, 1));
9874
1.62k
    return result;
9875
1.62k
}
9876
9877
/* --- Helpers ------------------------------------------------------------ */
9878
9879
/* helper macro to fixup start/end slice values */
9880
#define ADJUST_INDICES(start, end, len) \
9881
2.67M
    do {                                \
9882
2.67M
        if (end > len) {                \
9883
238k
            end = len;                  \
9884
238k
        }                               \
9885
2.67M
        else if (end < 0) {             \
9886
0
            end += len;                 \
9887
0
            if (end < 0) {              \
9888
0
                end = 0;                \
9889
0
            }                           \
9890
0
        }                               \
9891
2.67M
        if (start < 0) {                \
9892
0
            start += len;               \
9893
0
            if (start < 0) {            \
9894
0
                start = 0;              \
9895
0
            }                           \
9896
0
        }                               \
9897
2.67M
    } 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
6.51k
{
9905
6.51k
    int kind1, kind2;
9906
6.51k
    const void *buf1, *buf2;
9907
6.51k
    Py_ssize_t len1, len2, result;
9908
9909
6.51k
    kind1 = PyUnicode_KIND(s1);
9910
6.51k
    kind2 = PyUnicode_KIND(s2);
9911
6.51k
    if (kind1 < kind2)
9912
0
        return -1;
9913
9914
6.51k
    len1 = PyUnicode_GET_LENGTH(s1);
9915
6.51k
    len2 = PyUnicode_GET_LENGTH(s2);
9916
6.51k
    ADJUST_INDICES(start, end, len1);
9917
6.51k
    if (end - start < len2)
9918
1.22k
        return -1;
9919
9920
5.29k
    buf1 = PyUnicode_DATA(s1);
9921
5.29k
    buf2 = PyUnicode_DATA(s2);
9922
5.29k
    if (len2 == 1) {
9923
5.29k
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9924
5.29k
        result = findchar((const char *)buf1 + kind1*start,
9925
5.29k
                          kind1, end - start, ch, direction);
9926
5.29k
        if (result == -1)
9927
4.39k
            return -1;
9928
894
        else
9929
894
            return start + result;
9930
5.29k
    }
9931
9932
0
    if (kind2 != kind1) {
9933
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
9934
0
        if (!buf2)
9935
0
            return -2;
9936
0
    }
9937
9938
0
    if (direction > 0) {
9939
0
        switch (kind1) {
9940
0
        case PyUnicode_1BYTE_KIND:
9941
0
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9942
0
                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9943
0
            else
9944
0
                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9945
0
            break;
9946
0
        case PyUnicode_2BYTE_KIND:
9947
0
            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9948
0
            break;
9949
0
        case PyUnicode_4BYTE_KIND:
9950
0
            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9951
0
            break;
9952
0
        default:
9953
0
            Py_UNREACHABLE();
9954
0
        }
9955
0
    }
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
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
9976
0
    if (kind2 != kind1)
9977
0
        PyMem_Free((void *)buf2);
9978
9979
0
    return result;
9980
0
}
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
2.42M
{
10013
2.42M
    int kind;
10014
2.42M
    Py_ssize_t len, result;
10015
2.42M
    len = PyUnicode_GET_LENGTH(str);
10016
2.42M
    ADJUST_INDICES(start, end, len);
10017
2.42M
    if (end - start < 1)
10018
0
        return -1;
10019
2.42M
    kind = PyUnicode_KIND(str);
10020
2.42M
    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
10021
2.42M
                      kind, end-start, ch, direction);
10022
2.42M
    if (result == -1)
10023
2.06M
        return -1;
10024
360k
    else
10025
360k
        return start + result;
10026
2.42M
}
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
238k
{
10035
238k
    int kind_self;
10036
238k
    int kind_sub;
10037
238k
    const void *data_self;
10038
238k
    const void *data_sub;
10039
238k
    Py_ssize_t offset;
10040
238k
    Py_ssize_t i;
10041
238k
    Py_ssize_t end_sub;
10042
10043
238k
    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
10044
238k
    end -= PyUnicode_GET_LENGTH(substring);
10045
238k
    if (end < start)
10046
78.9k
        return 0;
10047
10048
159k
    if (PyUnicode_GET_LENGTH(substring) == 0)
10049
0
        return 1;
10050
10051
159k
    kind_self = PyUnicode_KIND(self);
10052
159k
    data_self = PyUnicode_DATA(self);
10053
159k
    kind_sub = PyUnicode_KIND(substring);
10054
159k
    data_sub = PyUnicode_DATA(substring);
10055
159k
    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
10056
10057
159k
    if (direction > 0)
10058
78.9k
        offset = end;
10059
80.3k
    else
10060
80.3k
        offset = start;
10061
10062
159k
    if (PyUnicode_READ(kind_self, data_self, offset) ==
10063
159k
        PyUnicode_READ(kind_sub, data_sub, 0) &&
10064
157k
        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
10065
157k
        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
10066
        /* If both are of the same kind, memcmp is sufficient */
10067
157k
        if (kind_self == kind_sub) {
10068
157k
            return ! memcmp((char *)data_self +
10069
157k
                                (offset * PyUnicode_KIND(substring)),
10070
0
                            data_sub,
10071
157k
                            PyUnicode_GET_LENGTH(substring) *
10072
157k
                                PyUnicode_KIND(substring));
10073
157k
        }
10074
        /* otherwise we have to compare each character by first accessing it */
10075
0
        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
0
            for (i = 1; i < end_sub; ++i) {
10080
0
                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
10081
0
                    PyUnicode_READ(kind_sub, data_sub, i))
10082
0
                    return 0;
10083
0
            }
10084
0
            return 1;
10085
0
        }
10086
157k
    }
10087
10088
1.58k
    return 0;
10089
159k
}
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
0
{
10098
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10099
0
        return -1;
10100
10101
0
    return tailmatch(str, substr, start, end, direction);
10102
0
}
10103
10104
static PyObject *
10105
ascii_upper_or_lower(PyObject *self, int lower)
10106
162
{
10107
162
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
10108
162
    const char *data = PyUnicode_DATA(self);
10109
162
    char *resdata;
10110
162
    PyObject *res;
10111
10112
162
    res = PyUnicode_New(len, 127);
10113
162
    if (res == NULL)
10114
0
        return NULL;
10115
162
    resdata = PyUnicode_DATA(res);
10116
162
    if (lower)
10117
60
        _Py_bytes_lower(resdata, data, len);
10118
102
    else
10119
102
        _Py_bytes_upper(resdata, data, len);
10120
162
    return res;
10121
162
}
10122
10123
static Py_UCS4
10124
handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
10125
0
{
10126
0
    Py_ssize_t j;
10127
0
    int final_sigma;
10128
0
    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
0
    for (j = i - 1; j >= 0; j--) {
10136
0
        c = PyUnicode_READ(kind, data, j);
10137
0
        if (!_PyUnicode_IsCaseIgnorable(c))
10138
0
            break;
10139
0
    }
10140
0
    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
10141
0
    if (final_sigma) {
10142
0
        for (j = i + 1; j < length; j++) {
10143
0
            c = PyUnicode_READ(kind, data, j);
10144
0
            if (!_PyUnicode_IsCaseIgnorable(c))
10145
0
                break;
10146
0
        }
10147
0
        final_sigma = j == length || !_PyUnicode_IsCased(c);
10148
0
    }
10149
0
    return (final_sigma) ? 0x3C2 : 0x3C3;
10150
0
}
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
0
{
10156
    /* Obscure special case. */
10157
0
    if (c == 0x3A3) {
10158
0
        mapped[0] = handle_capital_sigma(kind, data, length, i);
10159
0
        return 1;
10160
0
    }
10161
0
    return _PyUnicode_ToLowerFull(c, mapped);
10162
0
}
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
0
{
10217
0
    Py_ssize_t i, k = 0;
10218
10219
0
    for (i = 0; i < length; i++) {
10220
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10221
0
        int n_res, j;
10222
0
        if (lower)
10223
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10224
0
        else
10225
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10226
0
        for (j = 0; j < n_res; j++) {
10227
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10228
0
            res[k++] = mapped[j];
10229
0
        }
10230
0
    }
10231
0
    return k;
10232
0
}
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
0
{
10243
0
    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
10244
0
}
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
0
{
10294
0
    PyObject *res = NULL;
10295
0
    Py_ssize_t length, newlength = 0;
10296
0
    int kind, outkind;
10297
0
    const void *data;
10298
0
    void *outdata;
10299
0
    Py_UCS4 maxchar = 0, *tmp, *tmpend;
10300
10301
0
    kind = PyUnicode_KIND(self);
10302
0
    data = PyUnicode_DATA(self);
10303
0
    length = PyUnicode_GET_LENGTH(self);
10304
0
    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
0
    tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
10309
0
    if (tmp == NULL)
10310
0
        return PyErr_NoMemory();
10311
0
    newlength = perform(kind, data, length, tmp, &maxchar);
10312
0
    res = PyUnicode_New(newlength, maxchar);
10313
0
    if (res == NULL)
10314
0
        goto leave;
10315
0
    tmpend = tmp + newlength;
10316
0
    outdata = PyUnicode_DATA(res);
10317
0
    outkind = PyUnicode_KIND(res);
10318
0
    switch (outkind) {
10319
0
    case PyUnicode_1BYTE_KIND:
10320
0
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10321
0
        break;
10322
0
    case PyUnicode_2BYTE_KIND:
10323
0
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10324
0
        break;
10325
0
    case PyUnicode_4BYTE_KIND:
10326
0
        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10327
0
        break;
10328
0
    default:
10329
0
        Py_UNREACHABLE();
10330
0
    }
10331
0
  leave:
10332
0
    PyMem_Free(tmp);
10333
0
    return res;
10334
0
}
10335
10336
PyObject *
10337
PyUnicode_Join(PyObject *separator, PyObject *seq)
10338
2.15k
{
10339
2.15k
    PyObject *res;
10340
2.15k
    PyObject *fseq;
10341
2.15k
    Py_ssize_t seqlen;
10342
2.15k
    PyObject **items;
10343
10344
2.15k
    fseq = PySequence_Fast(seq, "can only join an iterable");
10345
2.15k
    if (fseq == NULL) {
10346
0
        return NULL;
10347
0
    }
10348
10349
2.15k
    Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(seq);
10350
10351
2.15k
    items = PySequence_Fast_ITEMS(fseq);
10352
2.15k
    seqlen = PySequence_Fast_GET_SIZE(fseq);
10353
2.15k
    res = _PyUnicode_JoinArray(separator, items, seqlen);
10354
10355
2.15k
    Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
10356
10357
2.15k
    Py_DECREF(fseq);
10358
2.15k
    return res;
10359
2.15k
}
10360
10361
PyObject *
10362
_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
10363
359k
{
10364
359k
    PyObject *res = NULL; /* the result */
10365
359k
    PyObject *sep = NULL;
10366
359k
    Py_ssize_t seplen;
10367
359k
    PyObject *item;
10368
359k
    Py_ssize_t sz, i, res_offset;
10369
359k
    Py_UCS4 maxchar;
10370
359k
    Py_UCS4 item_maxchar;
10371
359k
    int use_memcpy;
10372
359k
    unsigned char *res_data = NULL, *sep_data = NULL;
10373
359k
    PyObject *last_obj;
10374
359k
    int kind = 0;
10375
10376
    /* If empty sequence, return u"". */
10377
359k
    if (seqlen == 0) {
10378
0
        _Py_RETURN_UNICODE_EMPTY();
10379
0
    }
10380
10381
    /* If singleton sequence with an exact Unicode, return that. */
10382
359k
    last_obj = NULL;
10383
359k
    if (seqlen == 1) {
10384
179
        if (PyUnicode_CheckExact(items[0])) {
10385
179
            res = items[0];
10386
179
            return Py_NewRef(res);
10387
179
        }
10388
0
        seplen = 0;
10389
0
        maxchar = 0;
10390
0
    }
10391
359k
    else {
10392
        /* Set up sep and seplen */
10393
359k
        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
359k
        else {
10402
359k
            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
359k
            sep = separator;
10410
359k
            seplen = PyUnicode_GET_LENGTH(separator);
10411
359k
            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
359k
            Py_INCREF(sep);
10415
359k
        }
10416
359k
        last_obj = sep;
10417
359k
    }
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
359k
    sz = 0;
10425
#ifdef Py_DEBUG
10426
    use_memcpy = 0;
10427
#else
10428
359k
    use_memcpy = 1;
10429
359k
#endif
10430
3.21M
    for (i = 0; i < seqlen; i++) {
10431
2.85M
        size_t add_sz;
10432
2.85M
        item = items[i];
10433
2.85M
        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
2.85M
        add_sz = PyUnicode_GET_LENGTH(item);
10441
2.85M
        item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
10442
2.85M
        maxchar = Py_MAX(maxchar, item_maxchar);
10443
2.85M
        if (i != 0) {
10444
2.49M
            add_sz += seplen;
10445
2.49M
        }
10446
2.85M
        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
2.85M
        sz += add_sz;
10452
2.85M
        if (use_memcpy && last_obj != NULL) {
10453
5.70M
            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10454
19
                use_memcpy = 0;
10455
2.85M
        }
10456
0
        last_obj = item;
10457
2.85M
    }
10458
10459
359k
    res = PyUnicode_New(sz, maxchar);
10460
359k
    if (res == NULL)
10461
0
        goto onError;
10462
10463
    /* Catenate everything. */
10464
#ifdef Py_DEBUG
10465
    use_memcpy = 0;
10466
#else
10467
359k
    if (use_memcpy) {
10468
359k
        res_data = PyUnicode_1BYTE_DATA(res);
10469
359k
        kind = PyUnicode_KIND(res);
10470
359k
        if (seplen != 0)
10471
1.71k
            sep_data = PyUnicode_1BYTE_DATA(sep);
10472
359k
    }
10473
359k
#endif
10474
359k
    if (use_memcpy) {
10475
3.21M
        for (i = 0; i < seqlen; ++i) {
10476
2.85M
            Py_ssize_t itemlen;
10477
2.85M
            item = items[i];
10478
10479
            /* Copy item, and maybe the separator. */
10480
2.85M
            if (i && seplen != 0) {
10481
2.04k
                memcpy(res_data,
10482
2.04k
                          sep_data,
10483
2.04k
                          kind * seplen);
10484
2.04k
                res_data += kind * seplen;
10485
2.04k
            }
10486
10487
2.85M
            itemlen = PyUnicode_GET_LENGTH(item);
10488
2.85M
            if (itemlen != 0) {
10489
2.85M
                memcpy(res_data,
10490
2.85M
                          PyUnicode_DATA(item),
10491
2.85M
                          kind * itemlen);
10492
2.85M
                res_data += kind * itemlen;
10493
2.85M
            }
10494
2.85M
        }
10495
359k
        assert(res_data == PyUnicode_1BYTE_DATA(res)
10496
359k
                           + kind * PyUnicode_GET_LENGTH(res));
10497
359k
    }
10498
19
    else {
10499
57
        for (i = 0, res_offset = 0; i < seqlen; ++i) {
10500
38
            Py_ssize_t itemlen;
10501
38
            item = items[i];
10502
10503
            /* Copy item, and maybe the separator. */
10504
38
            if (i && seplen != 0) {
10505
0
                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10506
0
                res_offset += seplen;
10507
0
            }
10508
10509
38
            itemlen = PyUnicode_GET_LENGTH(item);
10510
38
            if (itemlen != 0) {
10511
38
                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
10512
38
                res_offset += itemlen;
10513
38
            }
10514
38
        }
10515
19
        assert(res_offset == PyUnicode_GET_LENGTH(res));
10516
19
    }
10517
10518
359k
    Py_XDECREF(sep);
10519
359k
    assert(_PyUnicode_CheckConsistency(res, 1));
10520
359k
    return res;
10521
10522
0
  onError:
10523
0
    Py_XDECREF(sep);
10524
0
    Py_XDECREF(res);
10525
0
    return NULL;
10526
359k
}
10527
10528
void
10529
_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10530
                    Py_UCS4 fill_char)
10531
9
{
10532
9
    const int kind = PyUnicode_KIND(unicode);
10533
9
    void *data = PyUnicode_DATA(unicode);
10534
9
    assert(_PyUnicode_IsModifiable(unicode));
10535
9
    assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10536
9
    assert(start >= 0);
10537
9
    assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10538
9
    _PyUnicode_Fill(kind, data, fill_char, start, length);
10539
9
}
10540
10541
Py_ssize_t
10542
PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10543
               Py_UCS4 fill_char)
10544
9
{
10545
9
    Py_ssize_t maxlen;
10546
10547
9
    if (!PyUnicode_Check(unicode)) {
10548
0
        PyErr_BadInternalCall();
10549
0
        return -1;
10550
0
    }
10551
9
    if (unicode_check_modifiable(unicode))
10552
0
        return -1;
10553
10554
9
    if (start < 0) {
10555
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
10556
0
        return -1;
10557
0
    }
10558
9
    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
9
    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10566
9
    length = Py_MIN(maxlen, length);
10567
9
    if (length <= 0)
10568
0
        return 0;
10569
10570
9
    _PyUnicode_FastFill(unicode, start, length, fill_char);
10571
9
    return length;
10572
9
}
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
0
{
10619
0
    PyObject *list;
10620
10621
0
    if (ensure_unicode(string) < 0)
10622
0
        return NULL;
10623
10624
0
    switch (PyUnicode_KIND(string)) {
10625
0
    case PyUnicode_1BYTE_KIND:
10626
0
        if (PyUnicode_IS_ASCII(string))
10627
0
            list = asciilib_splitlines(
10628
0
                string, PyUnicode_1BYTE_DATA(string),
10629
0
                PyUnicode_GET_LENGTH(string), keepends);
10630
0
        else
10631
0
            list = ucs1lib_splitlines(
10632
0
                string, PyUnicode_1BYTE_DATA(string),
10633
0
                PyUnicode_GET_LENGTH(string), keepends);
10634
0
        break;
10635
0
    case PyUnicode_2BYTE_KIND:
10636
0
        list = ucs2lib_splitlines(
10637
0
            string, PyUnicode_2BYTE_DATA(string),
10638
0
            PyUnicode_GET_LENGTH(string), keepends);
10639
0
        break;
10640
0
    case PyUnicode_4BYTE_KIND:
10641
0
        list = ucs4lib_splitlines(
10642
0
            string, PyUnicode_4BYTE_DATA(string),
10643
0
            PyUnicode_GET_LENGTH(string), keepends);
10644
0
        break;
10645
0
    default:
10646
0
        Py_UNREACHABLE();
10647
0
    }
10648
0
    return list;
10649
0
}
10650
10651
static PyObject *
10652
split(PyObject *self,
10653
      PyObject *substring,
10654
      Py_ssize_t maxcount)
10655
1.78k
{
10656
1.78k
    int kind1, kind2;
10657
1.78k
    const void *buf1, *buf2;
10658
1.78k
    Py_ssize_t len1, len2;
10659
1.78k
    PyObject* out;
10660
1.78k
    len1 = PyUnicode_GET_LENGTH(self);
10661
1.78k
    kind1 = PyUnicode_KIND(self);
10662
10663
1.78k
    if (substring == NULL) {
10664
5
        if (maxcount < 0) {
10665
5
            maxcount = (len1 - 1) / 2 + 1;
10666
5
        }
10667
5
        switch (kind1) {
10668
5
        case PyUnicode_1BYTE_KIND:
10669
5
            if (PyUnicode_IS_ASCII(self))
10670
5
                return asciilib_split_whitespace(
10671
5
                    self,  PyUnicode_1BYTE_DATA(self),
10672
5
                    len1, maxcount
10673
5
                    );
10674
0
            else
10675
0
                return ucs1lib_split_whitespace(
10676
0
                    self,  PyUnicode_1BYTE_DATA(self),
10677
0
                    len1, maxcount
10678
0
                    );
10679
0
        case PyUnicode_2BYTE_KIND:
10680
0
            return ucs2lib_split_whitespace(
10681
0
                self,  PyUnicode_2BYTE_DATA(self),
10682
0
                len1, maxcount
10683
0
                );
10684
0
        case PyUnicode_4BYTE_KIND:
10685
0
            return ucs4lib_split_whitespace(
10686
0
                self,  PyUnicode_4BYTE_DATA(self),
10687
0
                len1, maxcount
10688
0
                );
10689
0
        default:
10690
0
            Py_UNREACHABLE();
10691
5
        }
10692
5
    }
10693
10694
1.78k
    kind2 = PyUnicode_KIND(substring);
10695
1.78k
    len2 = PyUnicode_GET_LENGTH(substring);
10696
1.78k
    if (maxcount < 0) {
10697
        // if len2 == 0, it will raise ValueError.
10698
1.78k
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10699
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10700
1.78k
        maxcount = maxcount < 0 ? len1 : maxcount;
10701
1.78k
    }
10702
1.78k
    if (kind1 < kind2 || len1 < len2) {
10703
1
        out = PyList_New(1);
10704
1
        if (out == NULL)
10705
0
            return NULL;
10706
1
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10707
1
        return out;
10708
1
    }
10709
1.77k
    buf1 = PyUnicode_DATA(self);
10710
1.77k
    buf2 = PyUnicode_DATA(substring);
10711
1.77k
    if (kind2 != kind1) {
10712
1.03k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10713
1.03k
        if (!buf2)
10714
0
            return NULL;
10715
1.03k
    }
10716
10717
1.77k
    switch (kind1) {
10718
741
    case PyUnicode_1BYTE_KIND:
10719
741
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10720
472
            out = asciilib_split(
10721
472
                self,  buf1, len1, buf2, len2, maxcount);
10722
269
        else
10723
269
            out = ucs1lib_split(
10724
269
                self,  buf1, len1, buf2, len2, maxcount);
10725
741
        break;
10726
525
    case PyUnicode_2BYTE_KIND:
10727
525
        out = ucs2lib_split(
10728
525
            self,  buf1, len1, buf2, len2, maxcount);
10729
525
        break;
10730
513
    case PyUnicode_4BYTE_KIND:
10731
513
        out = ucs4lib_split(
10732
513
            self,  buf1, len1, buf2, len2, maxcount);
10733
513
        break;
10734
0
    default:
10735
0
        out = NULL;
10736
1.77k
    }
10737
1.77k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10738
1.77k
    if (kind2 != kind1)
10739
1.03k
        PyMem_Free((void *)buf2);
10740
1.77k
    return out;
10741
1.77k
}
10742
10743
static PyObject *
10744
rsplit(PyObject *self,
10745
       PyObject *substring,
10746
       Py_ssize_t maxcount)
10747
0
{
10748
0
    int kind1, kind2;
10749
0
    const void *buf1, *buf2;
10750
0
    Py_ssize_t len1, len2;
10751
0
    PyObject* out;
10752
10753
0
    len1 = PyUnicode_GET_LENGTH(self);
10754
0
    kind1 = PyUnicode_KIND(self);
10755
10756
0
    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
0
    kind2 = PyUnicode_KIND(substring);
10787
0
    len2 = PyUnicode_GET_LENGTH(substring);
10788
0
    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
0
    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
0
    buf1 = PyUnicode_DATA(self);
10802
0
    buf2 = PyUnicode_DATA(substring);
10803
0
    if (kind2 != kind1) {
10804
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10805
0
        if (!buf2)
10806
0
            return NULL;
10807
0
    }
10808
10809
0
    switch (kind1) {
10810
0
    case PyUnicode_1BYTE_KIND:
10811
0
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10812
0
            out = asciilib_rsplit(
10813
0
                self,  buf1, len1, buf2, len2, maxcount);
10814
0
        else
10815
0
            out = ucs1lib_rsplit(
10816
0
                self,  buf1, len1, buf2, len2, maxcount);
10817
0
        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
0
    }
10829
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10830
0
    if (kind2 != kind1)
10831
0
        PyMem_Free((void *)buf2);
10832
0
    return out;
10833
0
}
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
5.90k
{
10839
5.90k
    switch (kind) {
10840
5.90k
    case PyUnicode_1BYTE_KIND:
10841
5.90k
        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10842
5.90k
            return asciilib_find(buf1, len1, buf2, len2, offset);
10843
0
        else
10844
0
            return ucs1lib_find(buf1, len1, buf2, len2, offset);
10845
0
    case PyUnicode_2BYTE_KIND:
10846
0
        return ucs2lib_find(buf1, len1, buf2, len2, offset);
10847
0
    case PyUnicode_4BYTE_KIND:
10848
0
        return ucs4lib_find(buf1, len1, buf2, len2, offset);
10849
5.90k
    }
10850
5.90k
    Py_UNREACHABLE();
10851
5.90k
}
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
19.4k
{
10857
19.4k
    switch (kind) {
10858
19.4k
    case PyUnicode_1BYTE_KIND:
10859
19.4k
        return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10860
0
    case PyUnicode_2BYTE_KIND:
10861
0
        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10862
0
    case PyUnicode_4BYTE_KIND:
10863
0
        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10864
19.4k
    }
10865
19.4k
    Py_UNREACHABLE();
10866
19.4k
}
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
80
{
10872
80
    int kind = PyUnicode_KIND(u);
10873
80
    void *data = PyUnicode_DATA(u);
10874
80
    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10875
80
    if (kind == PyUnicode_1BYTE_KIND) {
10876
80
        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10877
80
                                      (Py_UCS1 *)data + len,
10878
80
                                      u1, u2, maxcount);
10879
80
    }
10880
0
    else if (kind == PyUnicode_2BYTE_KIND) {
10881
0
        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10882
0
                                      (Py_UCS2 *)data + len,
10883
0
                                      u1, u2, maxcount);
10884
0
    }
10885
0
    else {
10886
0
        assert(kind == PyUnicode_4BYTE_KIND);
10887
0
        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10888
0
                                      (Py_UCS4 *)data + len,
10889
0
                                      u1, u2, maxcount);
10890
0
    }
10891
80
}
10892
10893
static PyObject *
10894
replace(PyObject *self, PyObject *str1,
10895
        PyObject *str2, Py_ssize_t maxcount)
10896
19.8k
{
10897
19.8k
    PyObject *u;
10898
19.8k
    const char *sbuf = PyUnicode_DATA(self);
10899
19.8k
    const void *buf1 = PyUnicode_DATA(str1);
10900
19.8k
    const void *buf2 = PyUnicode_DATA(str2);
10901
19.8k
    int srelease = 0, release1 = 0, release2 = 0;
10902
19.8k
    int skind = PyUnicode_KIND(self);
10903
19.8k
    int kind1 = PyUnicode_KIND(str1);
10904
19.8k
    int kind2 = PyUnicode_KIND(str2);
10905
19.8k
    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10906
19.8k
    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10907
19.8k
    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
10908
19.8k
    int mayshrink;
10909
19.8k
    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
10910
10911
19.8k
    if (slen < len1)
10912
0
        goto nothing;
10913
10914
19.8k
    if (maxcount < 0)
10915
19.8k
        maxcount = PY_SSIZE_T_MAX;
10916
0
    else if (maxcount == 0)
10917
0
        goto nothing;
10918
10919
19.8k
    if (str1 == str2)
10920
0
        goto nothing;
10921
10922
19.8k
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10923
19.8k
    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10924
19.8k
    if (maxchar < maxchar_str1)
10925
        /* substring too wide to be present */
10926
0
        goto nothing;
10927
19.8k
    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10928
    /* Replacing str1 with str2 may cause a maxchar reduction in the
10929
       result string. */
10930
19.8k
    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
10931
19.8k
    maxchar = Py_MAX(maxchar, maxchar_str2);
10932
10933
19.8k
    if (len1 == len2) {
10934
        /* same length */
10935
335
        if (len1 == 0)
10936
0
            goto nothing;
10937
335
        if (len1 == 1) {
10938
            /* replace characters */
10939
335
            Py_UCS4 u1, u2;
10940
335
            Py_ssize_t pos;
10941
10942
335
            u1 = PyUnicode_READ(kind1, buf1, 0);
10943
335
            pos = findchar(sbuf, skind, slen, u1, 1);
10944
335
            if (pos < 0)
10945
255
                goto nothing;
10946
80
            u2 = PyUnicode_READ(kind2, buf2, 0);
10947
80
            u = PyUnicode_New(slen, maxchar);
10948
80
            if (!u)
10949
0
                goto error;
10950
10951
80
            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10952
80
            replace_1char_inplace(u, pos, u1, u2, maxcount);
10953
80
        }
10954
0
        else {
10955
0
            int rkind = skind;
10956
0
            char *res;
10957
0
            Py_ssize_t i;
10958
10959
0
            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
0
            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
10966
0
            if (i < 0)
10967
0
                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
335
    }
11016
19.4k
    else {
11017
19.4k
        Py_ssize_t n, i, j, ires;
11018
19.4k
        Py_ssize_t new_size;
11019
19.4k
        int rkind = skind;
11020
19.4k
        char *res;
11021
11022
19.4k
        if (kind1 < rkind) {
11023
            /* widen substring */
11024
0
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11025
0
            if (!buf1) goto error;
11026
0
            release1 = 1;
11027
0
        }
11028
19.4k
        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
11029
19.4k
        if (n == 0)
11030
19.3k
            goto nothing;
11031
148
        if (kind2 < rkind) {
11032
            /* widen replacement */
11033
0
            buf2 = unicode_askind(kind2, buf2, len2, rkind);
11034
0
            if (!buf2) goto error;
11035
0
            release2 = 1;
11036
0
        }
11037
148
        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
148
        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
148
        new_size = slen + n * (len2 - len1);
11061
148
        if (new_size == 0) {
11062
0
            u = _PyUnicode_GetEmpty();
11063
0
            goto done;
11064
0
        }
11065
148
        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
148
        u = PyUnicode_New(new_size, maxchar);
11071
148
        if (!u)
11072
0
            goto error;
11073
148
        assert(PyUnicode_KIND(u) == rkind);
11074
148
        res = PyUnicode_DATA(u);
11075
148
        ires = i = 0;
11076
148
        if (len1 > 0) {
11077
6.05k
            while (n-- > 0) {
11078
                /* look for next match */
11079
5.90k
                j = anylib_find(rkind, self,
11080
5.90k
                                sbuf + rkind * i, slen-i,
11081
5.90k
                                str1, buf1, len1, i);
11082
5.90k
                if (j == -1)
11083
0
                    break;
11084
5.90k
                else if (j > i) {
11085
                    /* copy unchanged part [i:j] */
11086
5.90k
                    memcpy(res + rkind * ires,
11087
5.90k
                           sbuf + rkind * i,
11088
5.90k
                           rkind * (j-i));
11089
5.90k
                    ires += j - i;
11090
5.90k
                }
11091
                /* copy substitution string */
11092
5.90k
                if (len2 > 0) {
11093
0
                    memcpy(res + rkind * ires,
11094
0
                           buf2,
11095
0
                           rkind * len2);
11096
0
                    ires += len2;
11097
0
                }
11098
5.90k
                i = j + len1;
11099
5.90k
            }
11100
148
            if (i < slen)
11101
                /* copy tail [i:] */
11102
148
                memcpy(res + rkind * ires,
11103
148
                       sbuf + rkind * i,
11104
148
                       rkind * (slen-i));
11105
148
        }
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
148
    }
11126
11127
228
    if (mayshrink) {
11128
0
        unicode_adjust_maxchar(&u);
11129
0
        if (u == NULL)
11130
0
            goto error;
11131
0
    }
11132
11133
228
  done:
11134
228
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11135
228
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11136
228
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11137
228
    if (srelease)
11138
0
        PyMem_Free((void *)sbuf);
11139
228
    if (release1)
11140
0
        PyMem_Free((void *)buf1);
11141
228
    if (release2)
11142
0
        PyMem_Free((void *)buf2);
11143
228
    assert(_PyUnicode_CheckConsistency(u, 1));
11144
228
    return u;
11145
11146
19.6k
  nothing:
11147
    /* nothing to replace; return original string (when possible) */
11148
19.6k
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11149
19.6k
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11150
19.6k
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11151
19.6k
    if (srelease)
11152
0
        PyMem_Free((void *)sbuf);
11153
19.6k
    if (release1)
11154
0
        PyMem_Free((void *)buf1);
11155
19.6k
    if (release2)
11156
0
        PyMem_Free((void *)buf2);
11157
19.6k
    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
0
}
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
414k
{
11279
414k
#define COMPARE(TYPE1, TYPE2) \
11280
414k
    do { \
11281
0
        TYPE1* p1 = (TYPE1 *)data1; \
11282
0
        TYPE2* p2 = (TYPE2 *)data2; \
11283
0
        TYPE1* end = p1 + len; \
11284
0
        Py_UCS4 c1, c2; \
11285
0
        for (; p1 != end; p1++, p2++) { \
11286
0
            c1 = *p1; \
11287
0
            c2 = *p2; \
11288
0
            if (c1 != c2) \
11289
0
                return (c1 < c2) ? -1 : 1; \
11290
0
        } \
11291
0
    } \
11292
0
    while (0)
11293
11294
414k
    int kind1, kind2;
11295
414k
    const void *data1, *data2;
11296
414k
    Py_ssize_t len1, len2, len;
11297
11298
414k
    kind1 = PyUnicode_KIND(str1);
11299
414k
    kind2 = PyUnicode_KIND(str2);
11300
414k
    data1 = PyUnicode_DATA(str1);
11301
414k
    data2 = PyUnicode_DATA(str2);
11302
414k
    len1 = PyUnicode_GET_LENGTH(str1);
11303
414k
    len2 = PyUnicode_GET_LENGTH(str2);
11304
414k
    len = Py_MIN(len1, len2);
11305
11306
414k
    switch(kind1) {
11307
414k
    case PyUnicode_1BYTE_KIND:
11308
414k
    {
11309
414k
        switch(kind2) {
11310
414k
        case PyUnicode_1BYTE_KIND:
11311
414k
        {
11312
414k
            int cmp = memcmp(data1, data2, len);
11313
            /* normalize result of memcmp() into the range [-1; 1] */
11314
414k
            if (cmp < 0)
11315
388k
                return -1;
11316
26.1k
            if (cmp > 0)
11317
25.2k
                return 1;
11318
885
            break;
11319
26.1k
        }
11320
885
        case PyUnicode_2BYTE_KIND:
11321
0
            COMPARE(Py_UCS1, Py_UCS2);
11322
0
            break;
11323
0
        case PyUnicode_4BYTE_KIND:
11324
0
            COMPARE(Py_UCS1, Py_UCS4);
11325
0
            break;
11326
0
        default:
11327
0
            Py_UNREACHABLE();
11328
414k
        }
11329
885
        break;
11330
414k
    }
11331
885
    case PyUnicode_2BYTE_KIND:
11332
0
    {
11333
0
        switch(kind2) {
11334
0
        case PyUnicode_1BYTE_KIND:
11335
0
            COMPARE(Py_UCS2, Py_UCS1);
11336
0
            break;
11337
0
        case PyUnicode_2BYTE_KIND:
11338
0
        {
11339
0
            COMPARE(Py_UCS2, Py_UCS2);
11340
0
            break;
11341
0
        }
11342
0
        case PyUnicode_4BYTE_KIND:
11343
0
            COMPARE(Py_UCS2, Py_UCS4);
11344
0
            break;
11345
0
        default:
11346
0
            Py_UNREACHABLE();
11347
0
        }
11348
0
        break;
11349
0
    }
11350
0
    case PyUnicode_4BYTE_KIND:
11351
0
    {
11352
0
        switch(kind2) {
11353
0
        case PyUnicode_1BYTE_KIND:
11354
0
            COMPARE(Py_UCS4, Py_UCS1);
11355
0
            break;
11356
0
        case PyUnicode_2BYTE_KIND:
11357
0
            COMPARE(Py_UCS4, Py_UCS2);
11358
0
            break;
11359
0
        case PyUnicode_4BYTE_KIND:
11360
0
        {
11361
0
#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11362
0
            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11363
            /* normalize result of wmemcmp() into the range [-1; 1] */
11364
0
            if (cmp < 0)
11365
0
                return -1;
11366
0
            if (cmp > 0)
11367
0
                return 1;
11368
#else
11369
            COMPARE(Py_UCS4, Py_UCS4);
11370
#endif
11371
0
            break;
11372
0
        }
11373
0
        default:
11374
0
            Py_UNREACHABLE();
11375
0
        }
11376
0
        break;
11377
0
    }
11378
0
    default:
11379
0
        Py_UNREACHABLE();
11380
414k
    }
11381
11382
885
    if (len1 == len2)
11383
109
        return 0;
11384
776
    if (len1 < len2)
11385
58
        return -1;
11386
718
    else
11387
718
        return 1;
11388
11389
776
#undef COMPARE
11390
776
}
11391
11392
11393
int
11394
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
11395
66.7M
{
11396
66.7M
    assert(PyUnicode_Check(str1));
11397
66.7M
    assert(PyUnicode_Check(str2));
11398
66.7M
    if (str1 == str2) {
11399
10.4M
        return 1;
11400
10.4M
    }
11401
56.3M
    return unicode_eq(str1, str2);
11402
66.7M
}
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
362k
{
11426
362k
    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11427
        /* a string is equal to itself */
11428
362k
        if (left == right)
11429
0
            return 0;
11430
11431
362k
        return unicode_compare(left, right);
11432
362k
    }
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
362k
}
11439
11440
int
11441
PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11442
10.7k
{
11443
10.7k
    Py_ssize_t i;
11444
10.7k
    int kind;
11445
10.7k
    Py_UCS4 chr;
11446
11447
10.7k
    assert(_PyUnicode_CHECK(uni));
11448
10.7k
    kind = PyUnicode_KIND(uni);
11449
10.7k
    if (kind == PyUnicode_1BYTE_KIND) {
11450
10.7k
        const void *data = PyUnicode_1BYTE_DATA(uni);
11451
10.7k
        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
11452
10.7k
        size_t len, len2 = strlen(str);
11453
10.7k
        int cmp;
11454
11455
10.7k
        len = Py_MIN(len1, len2);
11456
10.7k
        cmp = memcmp(data, str, len);
11457
10.7k
        if (cmp != 0) {
11458
10.6k
            if (cmp < 0)
11459
762
                return -1;
11460
9.84k
            else
11461
9.84k
                return 1;
11462
10.6k
        }
11463
138
        if (len1 > len2)
11464
0
            return 1; /* uni is longer */
11465
138
        if (len1 < len2)
11466
0
            return -1; /* str is longer */
11467
138
        return 0;
11468
138
    }
11469
0
    else {
11470
0
        const void *data = PyUnicode_DATA(uni);
11471
        /* Compare Unicode string and source character set string */
11472
0
        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
11473
0
            if (chr != (unsigned char)str[i])
11474
0
                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
0
        if (PyUnicode_GET_LENGTH(uni) != i || chr)
11478
0
            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.7k
}
11484
11485
int
11486
PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
11487
0
{
11488
0
    return PyUnicode_EqualToUTF8AndSize(unicode, str, strlen(str));
11489
0
}
11490
11491
int
11492
PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t size)
11493
0
{
11494
0
    assert(_PyUnicode_CHECK(unicode));
11495
0
    assert(str);
11496
11497
0
    if (PyUnicode_IS_ASCII(unicode)) {
11498
0
        Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11499
0
        return size == len &&
11500
0
            memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11501
0
    }
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
2.55M
{
11564
2.55M
    size_t len;
11565
2.55M
    assert(_PyUnicode_CHECK(unicode));
11566
2.55M
    assert(str);
11567
2.55M
#ifndef NDEBUG
11568
16.1M
    for (const char *p = str; *p; p++) {
11569
13.5M
        assert((unsigned char)*p < 128);
11570
13.5M
    }
11571
2.55M
#endif
11572
2.55M
    if (!PyUnicode_IS_ASCII(unicode))
11573
120
        return 0;
11574
2.55M
    len = (size_t)PyUnicode_GET_LENGTH(unicode);
11575
2.55M
    return strlen(str) == len &&
11576
366k
           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11577
2.55M
}
11578
11579
PyObject *
11580
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
11581
815k
{
11582
815k
    int result;
11583
11584
815k
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11585
5.90k
        Py_RETURN_NOTIMPLEMENTED;
11586
11587
809k
    if (left == right) {
11588
484
        switch (op) {
11589
445
        case Py_EQ:
11590
445
        case Py_LE:
11591
445
        case Py_GE:
11592
            /* a string is equal to itself */
11593
445
            Py_RETURN_TRUE;
11594
39
        case Py_NE:
11595
39
        case Py_LT:
11596
39
        case Py_GT:
11597
39
            Py_RETURN_FALSE;
11598
0
        default:
11599
0
            PyErr_BadArgument();
11600
0
            return NULL;
11601
484
        }
11602
484
    }
11603
809k
    else if (op == Py_EQ || op == Py_NE) {
11604
756k
        result = unicode_eq(left, right);
11605
756k
        result ^= (op == Py_NE);
11606
756k
        return PyBool_FromLong(result);
11607
756k
    }
11608
52.2k
    else {
11609
52.2k
        result = unicode_compare(left, right);
11610
52.2k
        Py_RETURN_RICHCOMPARE(result, 0, op);
11611
52.2k
    }
11612
809k
}
11613
11614
int
11615
PyUnicode_Contains(PyObject *str, PyObject *substr)
11616
114M
{
11617
114M
    int kind1, kind2;
11618
114M
    const void *buf1, *buf2;
11619
114M
    Py_ssize_t len1, len2;
11620
114M
    int result;
11621
11622
114M
    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
114M
    if (ensure_unicode(str) < 0)
11629
0
        return -1;
11630
11631
114M
    kind1 = PyUnicode_KIND(str);
11632
114M
    kind2 = PyUnicode_KIND(substr);
11633
114M
    if (kind1 < kind2)
11634
0
        return 0;
11635
114M
    len1 = PyUnicode_GET_LENGTH(str);
11636
114M
    len2 = PyUnicode_GET_LENGTH(substr);
11637
114M
    if (len1 < len2)
11638
40
        return 0;
11639
114M
    buf1 = PyUnicode_DATA(str);
11640
114M
    buf2 = PyUnicode_DATA(substr);
11641
114M
    if (len2 == 1) {
11642
24.3M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11643
24.3M
        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11644
24.3M
        return result;
11645
24.3M
    }
11646
90.1M
    if (kind2 != kind1) {
11647
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11648
0
        if (!buf2)
11649
0
            return -1;
11650
0
    }
11651
11652
90.1M
    switch (kind1) {
11653
90.1M
    case PyUnicode_1BYTE_KIND:
11654
90.1M
        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11655
90.1M
        break;
11656
0
    case PyUnicode_2BYTE_KIND:
11657
0
        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11658
0
        break;
11659
0
    case PyUnicode_4BYTE_KIND:
11660
0
        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11661
0
        break;
11662
0
    default:
11663
0
        Py_UNREACHABLE();
11664
90.1M
    }
11665
11666
90.1M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
11667
90.1M
    if (kind2 != kind1)
11668
0
        PyMem_Free((void *)buf2);
11669
11670
90.1M
    return result;
11671
90.1M
}
11672
11673
/* Concat to string or Unicode object giving a new Unicode object. */
11674
11675
PyObject *
11676
PyUnicode_Concat(PyObject *left, PyObject *right)
11677
512k
{
11678
512k
    PyObject *result;
11679
512k
    Py_UCS4 maxchar, maxchar2;
11680
512k
    Py_ssize_t left_len, right_len, new_len;
11681
11682
512k
    if (ensure_unicode(left) < 0)
11683
0
        return NULL;
11684
11685
512k
    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
512k
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11694
512k
    if (left == empty) {
11695
26
        return PyUnicode_FromObject(right);
11696
26
    }
11697
512k
    if (right == empty) {
11698
3
        return PyUnicode_FromObject(left);
11699
3
    }
11700
11701
512k
    left_len = PyUnicode_GET_LENGTH(left);
11702
512k
    right_len = PyUnicode_GET_LENGTH(right);
11703
512k
    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
512k
    new_len = left_len + right_len;
11709
11710
512k
    maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11711
512k
    maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11712
512k
    maxchar = Py_MAX(maxchar, maxchar2);
11713
11714
    /* Concat the two Unicode strings */
11715
512k
    result = PyUnicode_New(new_len, maxchar);
11716
512k
    if (result == NULL)
11717
0
        return NULL;
11718
512k
    _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11719
512k
    _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11720
512k
    assert(_PyUnicode_CheckConsistency(result, 1));
11721
512k
    return result;
11722
512k
}
11723
11724
void
11725
PyUnicode_Append(PyObject **p_left, PyObject *right)
11726
5.90M
{
11727
5.90M
    PyObject *left, *res;
11728
5.90M
    Py_UCS4 maxchar, maxchar2;
11729
5.90M
    Py_ssize_t left_len, right_len, new_len;
11730
11731
5.90M
    if (p_left == NULL) {
11732
0
        if (!PyErr_Occurred())
11733
0
            PyErr_BadInternalCall();
11734
0
        return;
11735
0
    }
11736
5.90M
    left = *p_left;
11737
5.90M
    if (right == NULL || left == NULL
11738
5.90M
        || !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
5.90M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11746
5.90M
    if (left == empty) {
11747
72.8k
        Py_DECREF(left);
11748
72.8k
        *p_left = Py_NewRef(right);
11749
72.8k
        return;
11750
72.8k
    }
11751
5.82M
    if (right == empty) {
11752
2.28k
        return;
11753
2.28k
    }
11754
11755
5.82M
    left_len = PyUnicode_GET_LENGTH(left);
11756
5.82M
    right_len = PyUnicode_GET_LENGTH(right);
11757
5.82M
    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.82M
    new_len = left_len + right_len;
11763
11764
5.82M
    if (_PyUnicode_IsModifiable(left)
11765
5.82M
        && PyUnicode_CheckExact(right)
11766
10.7M
        && 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
5.39M
        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11772
5.39M
    {
11773
        /* append inplace */
11774
5.39M
        if (unicode_resize(p_left, new_len) != 0)
11775
0
            goto error;
11776
11777
        /* copy 'right' into the newly allocated area of 'left' */
11778
5.39M
        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
11779
5.39M
    }
11780
430k
    else {
11781
430k
        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11782
430k
        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11783
430k
        maxchar = Py_MAX(maxchar, maxchar2);
11784
11785
        /* Concat the two Unicode strings */
11786
430k
        res = PyUnicode_New(new_len, maxchar);
11787
430k
        if (res == NULL)
11788
0
            goto error;
11789
430k
        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11790
430k
        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
11791
430k
        Py_DECREF(left);
11792
430k
        *p_left = res;
11793
430k
    }
11794
5.82M
    assert(_PyUnicode_CheckConsistency(*p_left, 1));
11795
5.82M
    return;
11796
11797
5.82M
error:
11798
0
    Py_CLEAR(*p_left);
11799
0
}
11800
11801
void
11802
PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11803
0
{
11804
0
    PyUnicode_Append(pleft, right);
11805
0
    Py_XDECREF(right);
11806
0
}
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
6.32k
{
11830
6.32k
    assert(PyUnicode_Check(str));
11831
6.32k
    assert(PyUnicode_Check(substr));
11832
11833
6.32k
    Py_ssize_t result;
11834
6.32k
    int kind1, kind2;
11835
6.32k
    const void *buf1 = NULL, *buf2 = NULL;
11836
6.32k
    Py_ssize_t len1, len2;
11837
11838
6.32k
    kind1 = PyUnicode_KIND(str);
11839
6.32k
    kind2 = PyUnicode_KIND(substr);
11840
6.32k
    if (kind1 < kind2)
11841
0
        return 0;
11842
11843
6.32k
    len1 = PyUnicode_GET_LENGTH(str);
11844
6.32k
    len2 = PyUnicode_GET_LENGTH(substr);
11845
6.32k
    ADJUST_INDICES(start, end, len1);
11846
6.32k
    if (end - start < len2)
11847
1.22k
        return 0;
11848
11849
5.10k
    buf1 = PyUnicode_DATA(str);
11850
5.10k
    buf2 = PyUnicode_DATA(substr);
11851
5.10k
    if (kind2 != kind1) {
11852
2.26k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11853
2.26k
        if (!buf2)
11854
0
            goto onError;
11855
2.26k
    }
11856
11857
    // We don't reuse `anylib_count` here because of the explicit casts.
11858
5.10k
    switch (kind1) {
11859
2.83k
    case PyUnicode_1BYTE_KIND:
11860
2.83k
        result = ucs1lib_count(
11861
2.83k
            ((const Py_UCS1*)buf1) + start, end - start,
11862
2.83k
            buf2, len2, PY_SSIZE_T_MAX
11863
2.83k
            );
11864
2.83k
        break;
11865
915
    case PyUnicode_2BYTE_KIND:
11866
915
        result = ucs2lib_count(
11867
915
            ((const Py_UCS2*)buf1) + start, end - start,
11868
915
            buf2, len2, PY_SSIZE_T_MAX
11869
915
            );
11870
915
        break;
11871
1.35k
    case PyUnicode_4BYTE_KIND:
11872
1.35k
        result = ucs4lib_count(
11873
1.35k
            ((const Py_UCS4*)buf1) + start, end - start,
11874
1.35k
            buf2, len2, PY_SSIZE_T_MAX
11875
1.35k
            );
11876
1.35k
        break;
11877
0
    default:
11878
0
        Py_UNREACHABLE();
11879
5.10k
    }
11880
11881
5.10k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11882
5.10k
    if (kind2 != kind1)
11883
2.26k
        PyMem_Free((void *)buf2);
11884
11885
5.10k
    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
0
}
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
2.00k
{
11912
2.00k
    return PyUnicode_AsEncodedString(self, encoding, errors);
11913
2.00k
}
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
0
{
11929
0
    Py_ssize_t i, j, line_pos, src_len, incr;
11930
0
    Py_UCS4 ch;
11931
0
    PyObject *u;
11932
0
    const void *src_data;
11933
0
    void *dest_data;
11934
0
    int kind;
11935
0
    int found;
11936
11937
    /* First pass: determine size of output string */
11938
0
    src_len = PyUnicode_GET_LENGTH(self);
11939
0
    i = j = line_pos = 0;
11940
0
    kind = PyUnicode_KIND(self);
11941
0
    src_data = PyUnicode_DATA(self);
11942
0
    found = 0;
11943
0
    for (; i < src_len; i++) {
11944
0
        ch = PyUnicode_READ(kind, src_data, i);
11945
0
        if (ch == '\t') {
11946
0
            found = 1;
11947
0
            if (tabsize > 0) {
11948
0
                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
11949
0
                if (j > PY_SSIZE_T_MAX - incr)
11950
0
                    goto overflow;
11951
0
                line_pos += incr;
11952
0
                j += incr;
11953
0
            }
11954
0
        }
11955
0
        else {
11956
0
            if (j > PY_SSIZE_T_MAX - 1)
11957
0
                goto overflow;
11958
0
            line_pos++;
11959
0
            j++;
11960
0
            if (ch == '\n' || ch == '\r')
11961
0
                line_pos = 0;
11962
0
        }
11963
0
    }
11964
0
    if (!found)
11965
0
        return unicode_result_unchanged(self);
11966
11967
    /* Second pass: create output string and fill it */
11968
0
    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
11969
0
    if (!u)
11970
0
        return NULL;
11971
0
    dest_data = PyUnicode_DATA(u);
11972
11973
0
    i = j = line_pos = 0;
11974
11975
0
    for (; i < src_len; i++) {
11976
0
        ch = PyUnicode_READ(kind, src_data, i);
11977
0
        if (ch == '\t') {
11978
0
            if (tabsize > 0) {
11979
0
                incr = tabsize - (line_pos % tabsize);
11980
0
                line_pos += incr;
11981
0
                _PyUnicode_Fill(kind, dest_data, ' ', j, incr);
11982
0
                j += incr;
11983
0
            }
11984
0
        }
11985
0
        else {
11986
0
            line_pos++;
11987
0
            PyUnicode_WRITE(kind, dest_data, j, ch);
11988
0
            j++;
11989
0
            if (ch == '\n' || ch == '\r')
11990
0
                line_pos = 0;
11991
0
        }
11992
0
    }
11993
0
    assert (j == PyUnicode_GET_LENGTH(u));
11994
0
    return unicode_result(u);
11995
11996
0
  overflow:
11997
0
    PyErr_SetString(PyExc_OverflowError, "new string is too long");
11998
0
    return NULL;
11999
0
}
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
20
{
12016
20
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12017
20
    if (result < 0) {
12018
0
        return -1;
12019
0
    }
12020
20
    return result;
12021
20
}
12022
12023
static PyObject *
12024
unicode_getitem(PyObject *self, Py_ssize_t index)
12025
3.14M
{
12026
3.14M
    const void *data;
12027
3.14M
    int kind;
12028
3.14M
    Py_UCS4 ch;
12029
12030
3.14M
    if (!PyUnicode_Check(self)) {
12031
0
        PyErr_BadArgument();
12032
0
        return NULL;
12033
0
    }
12034
3.14M
    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
12035
4.88k
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12036
4.88k
        return NULL;
12037
4.88k
    }
12038
3.13M
    kind = PyUnicode_KIND(self);
12039
3.13M
    data = PyUnicode_DATA(self);
12040
3.13M
    ch = PyUnicode_READ(kind, data, index);
12041
3.13M
    return unicode_char(ch);
12042
3.13M
}
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
9.23M
{
12049
9.23M
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
12050
12051
#ifdef Py_DEBUG
12052
    assert(_Py_HashSecret_Initialized);
12053
#endif
12054
9.23M
    Py_hash_t hash = PyUnicode_HASH(self);
12055
9.23M
    if (hash != -1) {
12056
6.16M
        return hash;
12057
6.16M
    }
12058
3.06M
    x = Py_HashBuffer(PyUnicode_DATA(self),
12059
3.06M
                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
12060
12061
0
    PyUnicode_SET_HASH(self, x);
12062
3.06M
    return x;
12063
3.06M
}
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.39k
{
12104
5.39k
    return PyBool_FromLong(PyUnicode_IS_ASCII(self));
12105
5.39k
}
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
0
{
12163
0
    Py_ssize_t i, length;
12164
0
    int kind;
12165
0
    const void *data;
12166
0
    int cased;
12167
12168
0
    length = PyUnicode_GET_LENGTH(self);
12169
0
    kind = PyUnicode_KIND(self);
12170
0
    data = PyUnicode_DATA(self);
12171
12172
    /* Shortcut for single character strings */
12173
0
    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
0
    if (length == 0)
12179
0
        Py_RETURN_FALSE;
12180
12181
0
    cased = 0;
12182
0
    for (i = 0; i < length; i++) {
12183
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12184
12185
0
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
12186
0
            Py_RETURN_FALSE;
12187
0
        else if (!cased && Py_UNICODE_ISUPPER(ch))
12188
0
            cased = 1;
12189
0
    }
12190
0
    return PyBool_FromLong(cased);
12191
0
}
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
0
{
12262
0
    Py_ssize_t i, length;
12263
0
    int kind;
12264
0
    const void *data;
12265
12266
0
    length = PyUnicode_GET_LENGTH(self);
12267
0
    kind = PyUnicode_KIND(self);
12268
0
    data = PyUnicode_DATA(self);
12269
12270
    /* Shortcut for single character strings */
12271
0
    if (length == 1)
12272
0
        return PyBool_FromLong(
12273
0
            Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
12274
12275
    /* Special case for empty strings */
12276
0
    if (length == 0)
12277
0
        Py_RETURN_FALSE;
12278
12279
0
    for (i = 0; i < length; i++) {
12280
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12281
0
        if (!Py_UNICODE_ISSPACE(ch))
12282
0
            Py_RETURN_FALSE;
12283
0
    }
12284
0
    Py_RETURN_TRUE;
12285
0
}
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
14
{
12300
14
    Py_ssize_t i, length;
12301
14
    int kind;
12302
14
    const void *data;
12303
12304
14
    length = PyUnicode_GET_LENGTH(self);
12305
14
    kind = PyUnicode_KIND(self);
12306
14
    data = PyUnicode_DATA(self);
12307
12308
    /* Shortcut for single character strings */
12309
14
    if (length == 1)
12310
8
        return PyBool_FromLong(
12311
8
            Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
12312
12313
    /* Special case for empty strings */
12314
6
    if (length == 0)
12315
0
        Py_RETURN_FALSE;
12316
12317
6
    for (i = 0; i < length; i++) {
12318
6
        if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
12319
6
            Py_RETURN_FALSE;
12320
6
    }
12321
6
    Py_RETURN_TRUE;
12322
6
}
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
4.88k
{
12377
4.88k
    Py_ssize_t i, length;
12378
4.88k
    int kind;
12379
4.88k
    const void *data;
12380
12381
4.88k
    length = PyUnicode_GET_LENGTH(self);
12382
4.88k
    kind = PyUnicode_KIND(self);
12383
4.88k
    data = PyUnicode_DATA(self);
12384
12385
    /* Shortcut for single character strings */
12386
4.88k
    if (length == 1)
12387
3.67k
        return PyBool_FromLong(
12388
3.67k
            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
12389
12390
    /* Special case for empty strings */
12391
1.21k
    if (length == 0)
12392
0
        Py_RETURN_FALSE;
12393
12394
842k
    for (i = 0; i < length; i++) {
12395
842k
        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
12396
349
            Py_RETURN_FALSE;
12397
842k
    }
12398
1.21k
    Py_RETURN_TRUE;
12399
1.21k
}
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
0
{
12414
0
    Py_ssize_t i, length;
12415
0
    int kind;
12416
0
    const void *data;
12417
12418
0
    length = PyUnicode_GET_LENGTH(self);
12419
0
    kind = PyUnicode_KIND(self);
12420
0
    data = PyUnicode_DATA(self);
12421
12422
    /* Shortcut for single character strings */
12423
0
    if (length == 1) {
12424
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12425
0
        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12426
0
    }
12427
12428
    /* Special case for empty strings */
12429
0
    if (length == 0)
12430
0
        Py_RETURN_FALSE;
12431
12432
0
    for (i = 0; i < length; i++) {
12433
0
        if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
12434
0
            Py_RETURN_FALSE;
12435
0
    }
12436
0
    Py_RETURN_TRUE;
12437
0
}
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
1.50k
{
12479
1.50k
    Py_ssize_t i;
12480
1.50k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12481
1.50k
    if (len == 0) {
12482
        /* an empty string is not a valid identifier */
12483
0
        return 0;
12484
0
    }
12485
12486
1.50k
    int kind = PyUnicode_KIND(self);
12487
1.50k
    const void *data = PyUnicode_DATA(self);
12488
1.50k
    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
1.50k
    if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12498
85
        return 0;
12499
85
    }
12500
12501
18.2M
    for (i = 1; i < len; i++) {
12502
18.2M
        ch = PyUnicode_READ(kind, data, i);
12503
18.2M
        if (!_PyUnicode_IsXidContinue(ch)) {
12504
13
            return i;
12505
13
        }
12506
18.2M
    }
12507
1.41k
    return i;
12508
1.42k
}
12509
12510
int
12511
PyUnicode_IsIdentifier(PyObject *self)
12512
1.48k
{
12513
1.48k
    Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12514
1.48k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12515
    /* an empty string is not a valid identifier */
12516
1.48k
    return len && i == len;
12517
1.48k
}
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
1.21k
{
12533
1.21k
    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12534
1.21k
}
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
0
{
12549
0
    Py_ssize_t i, length;
12550
0
    int kind;
12551
0
    const void *data;
12552
12553
0
    length = PyUnicode_GET_LENGTH(self);
12554
0
    kind = PyUnicode_KIND(self);
12555
0
    data = PyUnicode_DATA(self);
12556
12557
    /* Shortcut for single character strings */
12558
0
    if (length == 1)
12559
0
        return PyBool_FromLong(
12560
0
            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
2.14k
{
12588
2.14k
    return PyUnicode_Join(self, iterable);
12589
2.14k
}
12590
12591
static Py_ssize_t
12592
unicode_length(PyObject *self)
12593
4.43M
{
12594
4.43M
    return PyUnicode_GET_LENGTH(self);
12595
4.43M
}
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
60
{
12630
60
    if (PyUnicode_IS_ASCII(self))
12631
60
        return ascii_upper_or_lower(self, 1);
12632
0
    return case_operation(self, do_lower);
12633
60
}
12634
12635
285k
#define LEFTSTRIP 0
12636
307k
#define RIGHTSTRIP 1
12637
262k
#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
3.34k
{
12648
3.34k
    const void *data;
12649
3.34k
    int kind;
12650
3.34k
    Py_ssize_t i, j, len;
12651
3.34k
    BLOOM_MASK sepmask;
12652
3.34k
    Py_ssize_t seplen;
12653
12654
3.34k
    kind = PyUnicode_KIND(self);
12655
3.34k
    data = PyUnicode_DATA(self);
12656
3.34k
    len = PyUnicode_GET_LENGTH(self);
12657
3.34k
    seplen = PyUnicode_GET_LENGTH(sepobj);
12658
3.34k
    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12659
3.34k
                              PyUnicode_DATA(sepobj),
12660
3.34k
                              seplen);
12661
12662
0
    i = 0;
12663
3.34k
    if (striptype != RIGHTSTRIP) {
12664
49
        while (i < len) {
12665
46
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12666
46
            if (!BLOOM(sepmask, ch))
12667
43
                break;
12668
3
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12669
0
                break;
12670
3
            i++;
12671
3
        }
12672
46
    }
12673
12674
3.34k
    j = len;
12675
3.34k
    if (striptype != LEFTSTRIP) {
12676
3.29k
        j--;
12677
3.33k
        while (j >= i) {
12678
3.33k
            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12679
3.33k
            if (!BLOOM(sepmask, ch))
12680
2.25k
                break;
12681
1.07k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12682
1.03k
                break;
12683
40
            j--;
12684
40
        }
12685
12686
3.29k
        j++;
12687
3.29k
    }
12688
12689
3.34k
    return PyUnicode_Substring(self, i, j);
12690
3.34k
}
12691
12692
PyObject*
12693
_PyUnicode_BinarySlice(PyObject *container, PyObject *start_o, PyObject *stop_o)
12694
78.1k
{
12695
78.1k
    assert(PyUnicode_CheckExact(container));
12696
78.1k
    Py_ssize_t len = PyUnicode_GET_LENGTH(container);
12697
78.1k
    Py_ssize_t istart, istop;
12698
78.1k
    if (!_PyEval_UnpackIndices(start_o, stop_o, len, &istart, &istop)) {
12699
0
        return NULL;
12700
0
    }
12701
78.1k
    return PyUnicode_Substring(container, istart, istop);
12702
78.1k
}
12703
12704
PyObject*
12705
PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12706
1.26M
{
12707
1.26M
    const unsigned char *data;
12708
1.26M
    int kind;
12709
1.26M
    Py_ssize_t length;
12710
12711
1.26M
    length = PyUnicode_GET_LENGTH(self);
12712
1.26M
    end = Py_MIN(end, length);
12713
12714
1.26M
    if (start == 0 && end == length)
12715
22.7k
        return unicode_result_unchanged(self);
12716
12717
1.24M
    if (start < 0 || end < 0) {
12718
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12719
0
        return NULL;
12720
0
    }
12721
1.24M
    if (start >= length || end < start)
12722
6
        _Py_RETURN_UNICODE_EMPTY();
12723
12724
1.24M
    length = end - start;
12725
1.24M
    if (PyUnicode_IS_ASCII(self)) {
12726
699k
        data = PyUnicode_1BYTE_DATA(self);
12727
699k
        return _PyUnicode_FromASCII((const char*)(data + start), length);
12728
699k
    }
12729
540k
    else {
12730
540k
        kind = PyUnicode_KIND(self);
12731
540k
        data = PyUnicode_1BYTE_DATA(self);
12732
540k
        return PyUnicode_FromKindAndData(kind,
12733
540k
                                         data + kind * start,
12734
540k
                                         length);
12735
540k
    }
12736
1.24M
}
12737
12738
static PyObject *
12739
do_strip(PyObject *self, int striptype)
12740
281k
{
12741
281k
    Py_ssize_t len, i, j;
12742
12743
281k
    len = PyUnicode_GET_LENGTH(self);
12744
12745
281k
    if (PyUnicode_IS_ASCII(self)) {
12746
281k
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12747
12748
281k
        i = 0;
12749
281k
        if (striptype != RIGHTSTRIP) {
12750
2.30M
            while (i < len) {
12751
2.30M
                Py_UCS1 ch = data[i];
12752
2.30M
                if (!_Py_ascii_whitespace[ch])
12753
262k
                    break;
12754
2.04M
                i++;
12755
2.04M
            }
12756
262k
        }
12757
12758
281k
        j = len;
12759
281k
        if (striptype != LEFTSTRIP) {
12760
281k
            j--;
12761
544k
            while (j >= i) {
12762
544k
                Py_UCS1 ch = data[j];
12763
544k
                if (!_Py_ascii_whitespace[ch])
12764
281k
                    break;
12765
262k
                j--;
12766
262k
            }
12767
281k
            j++;
12768
281k
        }
12769
281k
    }
12770
0
    else {
12771
0
        int kind = PyUnicode_KIND(self);
12772
0
        const void *data = PyUnicode_DATA(self);
12773
12774
0
        i = 0;
12775
0
        if (striptype != RIGHTSTRIP) {
12776
0
            while (i < len) {
12777
0
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12778
0
                if (!Py_UNICODE_ISSPACE(ch))
12779
0
                    break;
12780
0
                i++;
12781
0
            }
12782
0
        }
12783
12784
0
        j = len;
12785
0
        if (striptype != LEFTSTRIP) {
12786
0
            j--;
12787
0
            while (j >= i) {
12788
0
                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12789
0
                if (!Py_UNICODE_ISSPACE(ch))
12790
0
                    break;
12791
0
                j--;
12792
0
            }
12793
0
            j++;
12794
0
        }
12795
0
    }
12796
12797
281k
    return PyUnicode_Substring(self, i, j);
12798
281k
}
12799
12800
12801
static PyObject *
12802
do_argstrip(PyObject *self, int striptype, PyObject *sep)
12803
285k
{
12804
285k
    if (sep != Py_None) {
12805
3.34k
        if (PyUnicode_Check(sep))
12806
3.34k
            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
3.34k
    }
12814
12815
281k
    return do_strip(self, striptype);
12816
285k
}
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
262k
{
12835
262k
    return do_argstrip(self, BOTHSTRIP, chars);
12836
262k
}
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
46
{
12854
46
    return do_argstrip(self, LEFTSTRIP, chars);
12855
46
}
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
22.6k
{
12873
22.6k
    return do_argstrip(self, RIGHTSTRIP, chars);
12874
22.6k
}
12875
12876
12877
PyObject *
12878
_PyUnicode_Repeat(PyObject *str, Py_ssize_t len)
12879
40
{
12880
40
    PyObject *u;
12881
40
    Py_ssize_t nchars, n;
12882
12883
40
    if (len < 1)
12884
0
        _Py_RETURN_UNICODE_EMPTY();
12885
12886
    /* no repeat, return original string */
12887
40
    if (len == 1)
12888
0
        return unicode_result_unchanged(str);
12889
12890
40
    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
40
    nchars = len * PyUnicode_GET_LENGTH(str);
12896
12897
40
    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
12898
40
    if (!u)
12899
0
        return NULL;
12900
40
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
12901
12902
40
    if (PyUnicode_GET_LENGTH(str) == 1) {
12903
40
        int kind = PyUnicode_KIND(str);
12904
40
        Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12905
40
        if (kind == PyUnicode_1BYTE_KIND) {
12906
40
            void *to = PyUnicode_DATA(u);
12907
40
            memset(to, (unsigned char)fill_char, len);
12908
40
        }
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
40
    }
12920
0
    else {
12921
0
        Py_ssize_t char_size = PyUnicode_KIND(str);
12922
0
        char *to = (char *) PyUnicode_DATA(u);
12923
0
        _PyBytes_RepeatBuffer(to, nchars * char_size, PyUnicode_DATA(str),
12924
0
            PyUnicode_GET_LENGTH(str) * char_size);
12925
0
    }
12926
12927
40
    assert(_PyUnicode_CheckConsistency(u, 1));
12928
40
    return u;
12929
40
}
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
19.8k
{
12964
19.8k
    return replace(self, old, new, count);
12965
19.8k
}
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
0
{
12984
0
    int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
12985
0
    if (match == -1) {
12986
0
        return NULL;
12987
0
    }
12988
0
    if (match) {
12989
0
        return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
12990
0
                                   PyUnicode_GET_LENGTH(self));
12991
0
    }
12992
0
    return unicode_result_unchanged(self);
12993
0
}
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
5.08k
{
13026
5.08k
    Py_ssize_t isize = PyUnicode_GET_LENGTH(unicode);
13027
5.08k
    const void *idata = PyUnicode_DATA(unicode);
13028
13029
    /* Compute length of output, quote characters, and
13030
       maximum character */
13031
5.08k
    Py_ssize_t osize = 0;
13032
5.08k
    Py_UCS4 maxch = 127;
13033
5.08k
    Py_ssize_t squote = 0;
13034
5.08k
    Py_ssize_t dquote = 0;
13035
5.08k
    int ikind = PyUnicode_KIND(unicode);
13036
27.3M
    for (Py_ssize_t i = 0; i < isize; i++) {
13037
27.3M
        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
13038
27.3M
        Py_ssize_t incr = 1;
13039
27.3M
        switch (ch) {
13040
102k
        case '\'': squote++; break;
13041
93.9k
        case '"':  dquote++; break;
13042
45.1k
        case '\\': case '\t': case '\r': case '\n':
13043
45.1k
            incr = 2;
13044
45.1k
            break;
13045
27.0M
        default:
13046
            /* Fast-path ASCII */
13047
27.0M
            if (ch < ' ' || ch == 0x7f)
13048
1.48M
                incr = 4; /* \xHH */
13049
25.5M
            else if (ch < 0x7f)
13050
24.7M
                ;
13051
788k
            else if (Py_UNICODE_ISPRINTABLE(ch))
13052
146k
                maxch = (ch > maxch) ? ch : maxch;
13053
642k
            else if (ch < 0x100)
13054
631k
                incr = 4; /* \xHH */
13055
11.3k
            else if (ch < 0x10000)
13056
8.77k
                incr = 6; /* \uHHHH */
13057
2.59k
            else
13058
2.59k
                incr = 10; /* \uHHHHHHHH */
13059
27.3M
        }
13060
27.3M
        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
27.3M
        osize += incr;
13066
27.3M
    }
13067
13068
5.08k
    Py_UCS4 quote = '\'';
13069
5.08k
    int changed = (osize != isize);
13070
5.08k
    if (squote) {
13071
352
        changed = 1;
13072
352
        if (dquote)
13073
            /* Both squote and dquote present. Use squote,
13074
               and escape them */
13075
118
            osize += squote;
13076
234
        else
13077
234
            quote = '"';
13078
352
    }
13079
5.08k
    osize += 2;   /* quotes */
13080
13081
5.08k
    PyObject *repr = PyUnicode_New(osize, maxch);
13082
5.08k
    if (repr == NULL)
13083
0
        return NULL;
13084
5.08k
    int okind = PyUnicode_KIND(repr);
13085
5.08k
    void *odata = PyUnicode_DATA(repr);
13086
13087
5.08k
    if (!changed) {
13088
2.70k
        PyUnicode_WRITE(okind, odata, 0, quote);
13089
13090
2.70k
        _PyUnicode_FastCopyCharacters(repr, 1,
13091
2.70k
                                      unicode, 0,
13092
2.70k
                                      isize);
13093
13094
2.70k
        PyUnicode_WRITE(okind, odata, osize-1, quote);
13095
2.70k
    }
13096
2.37k
    else {
13097
2.37k
        switch (okind) {
13098
1.56k
        case PyUnicode_1BYTE_KIND:
13099
1.56k
            ucs1lib_repr(unicode, quote, odata);
13100
1.56k
            break;
13101
466
        case PyUnicode_2BYTE_KIND:
13102
466
            ucs2lib_repr(unicode, quote, odata);
13103
466
            break;
13104
345
        default:
13105
345
            assert(okind == PyUnicode_4BYTE_KIND);
13106
345
            ucs4lib_repr(unicode, quote, odata);
13107
2.37k
        }
13108
2.37k
    }
13109
13110
5.08k
    assert(_PyUnicode_CheckConsistency(repr, 1));
13111
5.08k
    return repr;
13112
5.08k
}
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
6.49k
{
13129
6.49k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13130
6.49k
    if (result < 0) {
13131
5.62k
        return -1;
13132
5.62k
    }
13133
874
    return result;
13134
6.49k
}
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
0
{
13151
0
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13152
0
    if (result == -1) {
13153
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
13154
0
    }
13155
0
    else if (result < 0) {
13156
0
        return -1;
13157
0
    }
13158
0
    return result;
13159
0
}
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
1.78k
{
13221
1.78k
    if (sep == Py_None)
13222
5
        return split(self, NULL, maxsplit);
13223
1.78k
    if (PyUnicode_Check(sep))
13224
1.78k
        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
1.78k
}
13231
13232
PyObject *
13233
PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
13234
0
{
13235
0
    PyObject* out;
13236
0
    int kind1, kind2;
13237
0
    const void *buf1, *buf2;
13238
0
    Py_ssize_t len1, len2;
13239
13240
0
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13241
0
        return NULL;
13242
13243
0
    kind1 = PyUnicode_KIND(str_obj);
13244
0
    kind2 = PyUnicode_KIND(sep_obj);
13245
0
    len1 = PyUnicode_GET_LENGTH(str_obj);
13246
0
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13247
0
    if (kind1 < kind2 || len1 < len2) {
13248
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13249
0
        return PyTuple_Pack(3, str_obj, empty, empty);
13250
0
    }
13251
0
    buf1 = PyUnicode_DATA(str_obj);
13252
0
    buf2 = PyUnicode_DATA(sep_obj);
13253
0
    if (kind2 != kind1) {
13254
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13255
0
        if (!buf2)
13256
0
            return NULL;
13257
0
    }
13258
13259
0
    switch (kind1) {
13260
0
    case PyUnicode_1BYTE_KIND:
13261
0
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13262
0
            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13263
0
        else
13264
0
            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13265
0
        break;
13266
0
    case PyUnicode_2BYTE_KIND:
13267
0
        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13268
0
        break;
13269
0
    case PyUnicode_4BYTE_KIND:
13270
0
        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13271
0
        break;
13272
0
    default:
13273
0
        Py_UNREACHABLE();
13274
0
    }
13275
13276
0
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13277
0
    if (kind2 != kind1)
13278
0
        PyMem_Free((void *)buf2);
13279
13280
0
    return out;
13281
0
}
13282
13283
13284
PyObject *
13285
PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
13286
1.90k
{
13287
1.90k
    PyObject* out;
13288
1.90k
    int kind1, kind2;
13289
1.90k
    const void *buf1, *buf2;
13290
1.90k
    Py_ssize_t len1, len2;
13291
13292
1.90k
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13293
0
        return NULL;
13294
13295
1.90k
    kind1 = PyUnicode_KIND(str_obj);
13296
1.90k
    kind2 = PyUnicode_KIND(sep_obj);
13297
1.90k
    len1 = PyUnicode_GET_LENGTH(str_obj);
13298
1.90k
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13299
1.90k
    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
1.90k
    buf1 = PyUnicode_DATA(str_obj);
13304
1.90k
    buf2 = PyUnicode_DATA(sep_obj);
13305
1.90k
    if (kind2 != kind1) {
13306
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13307
0
        if (!buf2)
13308
0
            return NULL;
13309
0
    }
13310
13311
1.90k
    switch (kind1) {
13312
1.90k
    case PyUnicode_1BYTE_KIND:
13313
1.90k
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13314
1.90k
            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
1.90k
        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
1.90k
    }
13327
13328
1.90k
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13329
1.90k
    if (kind2 != kind1)
13330
0
        PyMem_Free((void *)buf2);
13331
13332
1.90k
    return out;
13333
1.90k
}
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
0
{
13355
0
    return PyUnicode_Partition(self, sep);
13356
0
}
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
1.90k
{
13376
1.90k
    return PyUnicode_RPartition(self, sep);
13377
1.90k
}
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
0
{
13401
0
    if (sep == Py_None)
13402
0
        return rsplit(self, NULL, maxsplit);
13403
0
    if (PyUnicode_Check(sep))
13404
0
        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
0
}
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
0
{
13428
0
    return PyUnicode_Splitlines(self, keepends);
13429
0
}
13430
13431
static
13432
PyObject *unicode_str(PyObject *self)
13433
0
{
13434
0
    return unicode_result_unchanged(self);
13435
0
}
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
0
{
13519
0
    PyObject *new = NULL, *key, *value;
13520
0
    Py_ssize_t i = 0;
13521
0
    int res;
13522
13523
0
    new = PyDict_New();
13524
0
    if (!new)
13525
0
        return NULL;
13526
0
    if (y != NULL) {
13527
0
        int x_kind, y_kind, z_kind;
13528
0
        const void *x_data, *y_data, *z_data;
13529
13530
        /* x must be a string too, of equal length */
13531
0
        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
0
        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
0
        x_kind = PyUnicode_KIND(x);
13543
0
        y_kind = PyUnicode_KIND(y);
13544
0
        x_data = PyUnicode_DATA(x);
13545
0
        y_data = PyUnicode_DATA(y);
13546
0
        for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13547
0
            key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
13548
0
            if (!key)
13549
0
                goto err;
13550
0
            value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
13551
0
            if (!value) {
13552
0
                Py_DECREF(key);
13553
0
                goto err;
13554
0
            }
13555
0
            res = PyDict_SetItem(new, key, value);
13556
0
            Py_DECREF(key);
13557
0
            Py_DECREF(value);
13558
0
            if (res < 0)
13559
0
                goto err;
13560
0
        }
13561
        /* create entries for deleting chars in z */
13562
0
        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
0
    } 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
0
    return new;
13591
0
  err:
13592
0
    Py_DECREF(new);
13593
0
    return NULL;
13594
0
}
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
96
{
13617
96
    return _PyUnicode_TranslateCharmap(self, table, "ignore");
13618
96
}
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
102
{
13630
102
    if (PyUnicode_IS_ASCII(self))
13631
102
        return ascii_upper_or_lower(self, 0);
13632
0
    return case_operation(self, do_upper);
13633
102
}
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
158k
{
13702
158k
    if (PyTuple_Check(subobj)) {
13703
87
        Py_ssize_t i;
13704
609
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13705
522
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13706
522
            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
522
            int result = tailmatch(self, substring, start, end, -1);
13714
522
            if (result < 0) {
13715
0
                return NULL;
13716
0
            }
13717
522
            if (result) {
13718
0
                Py_RETURN_TRUE;
13719
0
            }
13720
522
        }
13721
        /* nothing matched */
13722
87
        Py_RETURN_FALSE;
13723
87
    }
13724
158k
    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
158k
    int result = tailmatch(self, subobj, start, end, -1);
13731
158k
    if (result < 0) {
13732
0
        return NULL;
13733
0
    }
13734
158k
    return PyBool_FromLong(result);
13735
158k
}
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
79.0k
{
13759
79.0k
    if (PyTuple_Check(subobj)) {
13760
0
        Py_ssize_t i;
13761
0
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13762
0
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13763
0
            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
0
            int result = tailmatch(self, substring, start, end, +1);
13771
0
            if (result < 0) {
13772
0
                return NULL;
13773
0
            }
13774
0
            if (result) {
13775
0
                Py_RETURN_TRUE;
13776
0
            }
13777
0
        }
13778
0
        Py_RETURN_FALSE;
13779
0
    }
13780
79.0k
    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
79.0k
    int result = tailmatch(self, subobj, start, end, +1);
13787
79.0k
    if (result < 0) {
13788
0
        return NULL;
13789
0
    }
13790
79.0k
    return PyBool_FromLong(result);
13791
79.0k
}
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
1.35M
{
14097
1.35M
    if (!PyUnicode_Check(v))
14098
0
        Py_RETURN_NOTIMPLEMENTED;
14099
1.35M
    return PyUnicode_Format(v, w);
14100
1.35M
}
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
3.26M
{
14123
3.26M
    if (_PyIndex_Check(item)) {
14124
3.14M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
14125
3.14M
        if (i == -1 && PyErr_Occurred())
14126
0
            return NULL;
14127
3.14M
        if (i < 0)
14128
930
            i += PyUnicode_GET_LENGTH(self);
14129
3.14M
        return unicode_getitem(self, i);
14130
3.14M
    } else if (PySlice_Check(item)) {
14131
118k
        Py_ssize_t start, stop, step, slicelength, i;
14132
118k
        size_t cur;
14133
118k
        PyObject *result;
14134
118k
        const void *src_data;
14135
118k
        void *dest_data;
14136
118k
        int src_kind, dest_kind;
14137
118k
        Py_UCS4 ch, max_char, kind_limit;
14138
14139
118k
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
14140
0
            return NULL;
14141
0
        }
14142
118k
        slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14143
118k
                                            &start, &stop, step);
14144
14145
118k
        if (slicelength <= 0) {
14146
20
            _Py_RETURN_UNICODE_EMPTY();
14147
118k
        } else if (start == 0 && step == 1 &&
14148
440
                   slicelength == PyUnicode_GET_LENGTH(self)) {
14149
0
            return unicode_result_unchanged(self);
14150
118k
        } else if (step == 1) {
14151
118k
            return PyUnicode_Substring(self,
14152
118k
                                       start, start + slicelength);
14153
118k
        }
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
3.26M
}
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
35
{
14215
35
    PyObject *unicode;
14216
35
    if (x == NULL) {
14217
0
        unicode = _PyUnicode_GetEmpty();
14218
0
    }
14219
35
    else if (encoding == NULL && errors == NULL) {
14220
35
        unicode = PyObject_Str(x);
14221
35
    }
14222
0
    else {
14223
0
        unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
14224
0
    }
14225
14226
35
    if (unicode != NULL && type != &PyUnicode_Type) {
14227
35
        Py_SETREF(unicode, unicode_subtype_new(type, unicode));
14228
35
    }
14229
35
    return unicode;
14230
35
}
14231
14232
static const char *
14233
arg_as_utf8(PyObject *obj, const char *name)
14234
4.62k
{
14235
4.62k
    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
4.62k
    return _PyUnicode_AsUTF8NoNUL(obj);
14242
4.62k
}
14243
14244
static PyObject *
14245
unicode_vectorcall(PyObject *type, PyObject *const *args,
14246
                   size_t nargsf, PyObject *kwnames)
14247
4.71k
{
14248
4.71k
    assert(Py_Is(_PyType_CAST(type), &PyUnicode_Type));
14249
14250
4.71k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
14251
4.71k
    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
4.71k
    if (!_PyArg_CheckPositional("str", nargs, 0, 3)) {
14268
0
        return NULL;
14269
0
    }
14270
4.71k
    if (nargs == 0) {
14271
0
        return _PyUnicode_GetEmpty();
14272
0
    }
14273
4.71k
    PyObject *object = args[0];
14274
4.71k
    if (nargs == 1) {
14275
84
        return PyObject_Str(object);
14276
84
    }
14277
4.62k
    const char *encoding = arg_as_utf8(args[1], "encoding");
14278
4.62k
    if (encoding == NULL) {
14279
0
        return NULL;
14280
0
    }
14281
4.62k
    const char *errors = NULL;
14282
4.62k
    if (nargs == 3) {
14283
0
        errors = arg_as_utf8(args[2], "errors");
14284
0
        if (errors == NULL) {
14285
0
            return NULL;
14286
0
        }
14287
0
    }
14288
4.62k
    return PyUnicode_FromEncodedObject(object, encoding, errors);
14289
4.62k
}
14290
14291
static PyObject *
14292
unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
14293
35
{
14294
35
    PyObject *self;
14295
35
    Py_ssize_t length, char_size;
14296
35
    int share_utf8;
14297
35
    int kind;
14298
35
    void *data;
14299
14300
35
    assert(PyType_IsSubtype(type, &PyUnicode_Type));
14301
35
    assert(_PyUnicode_CHECK(unicode));
14302
14303
35
    self = type->tp_alloc(type, 0);
14304
35
    if (self == NULL) {
14305
0
        return NULL;
14306
0
    }
14307
35
    kind = PyUnicode_KIND(unicode);
14308
35
    length = PyUnicode_GET_LENGTH(unicode);
14309
14310
35
    _PyUnicode_LENGTH(self) = length;
14311
#ifdef Py_DEBUG
14312
    _PyUnicode_HASH(self) = -1;
14313
#else
14314
35
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14315
0
#endif
14316
35
    _PyUnicode_STATE(self).interned = 0;
14317
35
    _PyUnicode_STATE(self).kind = kind;
14318
35
    _PyUnicode_STATE(self).compact = 0;
14319
35
    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
14320
35
    _PyUnicode_STATE(self).statically_allocated = 0;
14321
0
    PyUnicode_SET_UTF8_LENGTH(self, 0);
14322
35
    PyUnicode_SET_UTF8(self, NULL);
14323
35
    _PyUnicode_DATA_ANY(self) = NULL;
14324
14325
0
    share_utf8 = 0;
14326
35
    if (kind == PyUnicode_1BYTE_KIND) {
14327
35
        char_size = 1;
14328
35
        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14329
35
            share_utf8 = 1;
14330
35
    }
14331
0
    else if (kind == PyUnicode_2BYTE_KIND) {
14332
0
        char_size = 2;
14333
0
    }
14334
0
    else {
14335
0
        assert(kind == PyUnicode_4BYTE_KIND);
14336
0
        char_size = 4;
14337
0
    }
14338
14339
    /* Ensure we won't overflow the length. */
14340
35
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14341
0
        PyErr_NoMemory();
14342
0
        goto onError;
14343
0
    }
14344
35
    data = PyMem_Malloc((length + 1) * char_size);
14345
35
    if (data == NULL) {
14346
0
        PyErr_NoMemory();
14347
0
        goto onError;
14348
0
    }
14349
14350
70
    _PyUnicode_DATA_ANY(self) = data;
14351
35
    if (share_utf8) {
14352
35
        PyUnicode_SET_UTF8_LENGTH(self, length);
14353
35
        PyUnicode_SET_UTF8(self, data);
14354
35
    }
14355
14356
70
    memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
14357
70
    assert(_PyUnicode_CheckConsistency(self, 1));
14358
#ifdef Py_DEBUG
14359
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14360
#endif
14361
35
    return self;
14362
14363
0
onError:
14364
0
    Py_DECREF(self);
14365
0
    return NULL;
14366
70
}
14367
14368
static _PyObjectIndexPair
14369
unicode_iteritem(PyObject *obj, Py_ssize_t index)
14370
298
{
14371
298
    if (index >= PyUnicode_GET_LENGTH(obj)) {
14372
149
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
14373
149
    }
14374
149
    const void *data = PyUnicode_DATA(obj);
14375
149
    int kind = PyUnicode_KIND(obj);
14376
149
    Py_UCS4 ch = PyUnicode_READ(kind, data, index);
14377
149
    PyObject *result = unicode_char(ch);
14378
149
    index = (result == NULL) ? -1 : index + 1;
14379
149
    return (_PyObjectIndexPair) { .object = result, .index = index };
14380
149
}
14381
14382
void
14383
_PyUnicode_ExactDealloc(PyObject *op)
14384
264k
{
14385
264k
    assert(PyUnicode_CheckExact(op));
14386
264k
    unicode_dealloc(op);
14387
264k
}
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
20
{
14455
20
    static int initialized = 0;
14456
20
    if (initialized) {
14457
0
        return;
14458
0
    }
14459
20
    initialized = 1;
14460
14461
    /* initialize the linebreak bloom filter */
14462
20
    const Py_UCS2 linebreak[] = {
14463
20
        0x000A, /* LINE FEED */
14464
20
        0x000D, /* CARRIAGE RETURN */
14465
20
        0x001C, /* FILE SEPARATOR */
14466
20
        0x001D, /* GROUP SEPARATOR */
14467
20
        0x001E, /* RECORD SEPARATOR */
14468
20
        0x0085, /* NEXT LINE */
14469
20
        0x2028, /* LINE SEPARATOR */
14470
20
        0x2029, /* PARAGRAPH SEPARATOR */
14471
20
    };
14472
20
    bloom_linebreak = make_bloom_mask(
14473
20
        PyUnicode_2BYTE_KIND, linebreak,
14474
20
        Py_ARRAY_LENGTH(linebreak));
14475
20
}
14476
14477
void
14478
_PyUnicode_InitState(PyInterpreterState *interp)
14479
20
{
14480
20
    if (!_Py_IsMainInterpreter(interp)) {
14481
0
        return;
14482
0
    }
14483
20
    _init_global_state();
14484
20
}
14485
14486
14487
PyStatus
14488
_PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
14489
20
{
14490
20
    if (_Py_IsMainInterpreter(interp)) {
14491
20
        PyStatus status = init_global_interned_strings(interp);
14492
20
        if (_PyStatus_EXCEPTION(status)) {
14493
0
            return status;
14494
0
        }
14495
20
    }
14496
20
    assert(INTERNED_STRINGS);
14497
14498
20
    if (init_interned_dict(interp)) {
14499
0
        PyErr_Clear();
14500
0
        return _PyStatus_ERR("failed to create interned dict");
14501
0
    }
14502
14503
20
    return _PyStatus_OK();
14504
20
}
14505
14506
14507
PyStatus
14508
_PyUnicode_InitTypes(PyInterpreterState *interp)
14509
20
{
14510
20
    if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
14511
0
        goto error;
14512
0
    }
14513
20
    if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
14514
0
        goto error;
14515
0
    }
14516
20
    if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
14517
0
        goto error;
14518
0
    }
14519
20
    return _PyStatus_OK();
14520
14521
0
error:
14522
0
    return _PyStatus_ERR("Can't initialize unicode types");
14523
20
}
14524
14525
static /* non-null */ PyObject*
14526
intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
14527
22.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
22.4k
    assert(s != NULL);
14532
22.4k
    assert(_PyUnicode_CHECK(s));
14533
22.4k
    assert(_PyUnicode_STATE(s).statically_allocated);
14534
22.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
22.4k
    PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14546
    /* We should only init each string once */
14547
22.4k
    assert(r == NULL);
14548
    /* but just in case (for the non-debug build), handle this */
14549
22.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
22.4k
    if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < -1) {
14557
0
        Py_FatalError("failed to intern static string");
14558
0
    }
14559
14560
22.4k
    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
14561
0
    return s;
14562
22.4k
}
14563
14564
void
14565
_PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
14566
22.4k
{
14567
    // This should only be called as part of runtime initialization
14568
22.4k
    assert(!Py_IsInitialized());
14569
14570
22.4k
    *p = intern_static(interp, *p);
14571
22.4k
    assert(*p);
14572
22.4k
}
14573
14574
static void
14575
immortalize_interned(PyObject *s)
14576
73.5k
{
14577
73.5k
    assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
14578
73.5k
    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
73.5k
    _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
73.5k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_IMMORTAL);
14592
73.5k
}
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
1.17M
{
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
1.17M
    if (s == NULL || !PyUnicode_Check(s)) {
14618
0
        return s;
14619
0
    }
14620
1.17M
#endif
14621
14622
    /* If it's a subclass, we don't really know what putting
14623
       it in the interned dict might do. */
14624
1.17M
    if (!PyUnicode_CheckExact(s)) {
14625
0
        return s;
14626
0
    }
14627
14628
    /* Is it already interned? */
14629
1.17M
    switch (PyUnicode_CHECK_INTERNED(s)) {
14630
409k
        case SSTATE_NOT_INTERNED:
14631
            // no, go on
14632
409k
            break;
14633
7.74k
        case SSTATE_INTERNED_MORTAL:
14634
7.74k
#ifndef Py_GIL_DISABLED
14635
            // yes but we might need to make it immortal
14636
7.74k
            if (immortalize) {
14637
5
                immortalize_interned(s);
14638
5
            }
14639
7.74k
            return s;
14640
#else
14641
            // not fully interned yet; fall through to the locking path
14642
            break;
14643
#endif
14644
756k
        default:
14645
            // all done
14646
756k
            return s;
14647
1.17M
    }
14648
14649
    /* Statically allocated strings must be already interned. */
14650
1.17M
    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
409k
    if (_Py_IsImmortal(s)) {
14659
0
        immortalize = 1;
14660
0
    }
14661
14662
    /* if it's a short string, get the singleton */
14663
409k
    if (PyUnicode_GET_LENGTH(s) == 1 &&
14664
0
                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
409k
    {
14676
409k
        PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14677
409k
        if (r != NULL) {
14678
62.5k
            assert(_PyUnicode_STATE(r).statically_allocated);
14679
62.5k
            assert(r != s);  // r must be statically_allocated; s is not
14680
62.5k
            Py_DECREF(s);
14681
62.5k
            return Py_NewRef(r);
14682
62.5k
        }
14683
409k
    }
14684
14685
    /* Do a setdefault on the per-interpreter cache. */
14686
346k
    PyObject *interned = get_interned_dict(interp);
14687
346k
    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
346k
    FT_MUTEX_LOCK(INTERN_MUTEX);
14726
346k
    PyObject *t;
14727
346k
    {
14728
346k
        int res = PyDict_SetDefaultRef(interned, s, s, &t);
14729
346k
        if (res < 0) {
14730
0
            PyErr_Clear();
14731
0
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14732
0
            return s;
14733
0
        }
14734
346k
        else if (res == 1) {
14735
            // value was already present (not inserted)
14736
102k
            Py_DECREF(s);
14737
102k
            if (immortalize &&
14738
30.2k
                    PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
14739
3.30k
                immortalize_interned(t);
14740
3.30k
            }
14741
102k
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14742
102k
            return t;
14743
102k
        }
14744
244k
        else {
14745
            // value was newly inserted
14746
244k
            assert (s == t);
14747
244k
            Py_DECREF(t);
14748
244k
        }
14749
346k
    }
14750
14751
    /* NOT_INTERNED -> INTERNED_MORTAL */
14752
14753
346k
    assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
14754
14755
244k
    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
244k
        Py_DECREF(s);
14759
244k
        Py_DECREF(s);
14760
244k
    }
14761
244k
    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
244k
    if (immortalize) {
14771
70.2k
        immortalize_interned(s);
14772
70.2k
    }
14773
14774
244k
    FT_MUTEX_UNLOCK(INTERN_MUTEX);
14775
244k
    return s;
14776
244k
}
14777
14778
void
14779
_PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
14780
324k
{
14781
324k
    *p = intern_common(interp, *p, 1);
14782
324k
    assert(*p);
14783
324k
}
14784
14785
void
14786
_PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
14787
849k
{
14788
849k
    *p = intern_common(interp, *p, 0);
14789
849k
    assert(*p);
14790
849k
}
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
0
{
14803
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14804
0
    _PyUnicode_InternMortal(interp, p);
14805
0
}
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
283k
{
14819
283k
    PyObject *s = PyUnicode_FromString(cp);
14820
283k
    if (s == NULL) {
14821
0
        return NULL;
14822
0
    }
14823
283k
    PyInterpreterState *interp = _PyInterpreterState_GET();
14824
283k
    _PyUnicode_InternMortal(interp, &s);
14825
283k
    return s;
14826
283k
}
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
93
{
14929
93
    unicodeiterobject *it = (unicodeiterobject *)op;
14930
93
    _PyObject_GC_UNTRACK(it);
14931
93
    Py_XDECREF(it->it_seq);
14932
93
    PyObject_GC_Del(it);
14933
93
}
14934
14935
static int
14936
unicodeiter_traverse(PyObject *op, visitproc visit, void *arg)
14937
0
{
14938
0
    unicodeiterobject *it = (unicodeiterobject *)op;
14939
0
    Py_VISIT(it->it_seq);
14940
0
    return 0;
14941
0
}
14942
14943
static PyObject *
14944
unicodeiter_next(PyObject *op)
14945
0
{
14946
0
    unicodeiterobject *it = (unicodeiterobject *)op;
14947
0
    PyObject *seq;
14948
14949
0
    assert(it != NULL);
14950
0
    seq = it->it_seq;
14951
0
    if (seq == NULL)
14952
0
        return NULL;
14953
0
    assert(_PyUnicode_CHECK(seq));
14954
14955
0
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14956
0
        int kind = PyUnicode_KIND(seq);
14957
0
        const void *data = PyUnicode_DATA(seq);
14958
0
        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14959
0
        it->it_index++;
14960
0
        return unicode_char(chr);
14961
0
    }
14962
14963
0
    it->it_seq = NULL;
14964
0
    Py_DECREF(seq);
14965
0
    return NULL;
14966
0
}
14967
14968
static PyObject *
14969
unicode_ascii_iter_next(PyObject *op)
14970
629
{
14971
629
    unicodeiterobject *it = (unicodeiterobject *)op;
14972
629
    assert(it != NULL);
14973
629
    PyObject *seq = it->it_seq;
14974
629
    if (seq == NULL) {
14975
0
        return NULL;
14976
0
    }
14977
629
    assert(_PyUnicode_CHECK(seq));
14978
629
    assert(PyUnicode_IS_COMPACT_ASCII(seq));
14979
629
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14980
556
        const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
14981
556
        Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
14982
556
                                              data, it->it_index);
14983
556
        it->it_index++;
14984
556
        return (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
14985
556
    }
14986
73
    it->it_seq = NULL;
14987
73
    Py_DECREF(seq);
14988
73
    return NULL;
14989
629
}
14990
14991
static PyObject *
14992
unicodeiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
14993
0
{
14994
0
    unicodeiterobject *it = (unicodeiterobject *)op;
14995
0
    Py_ssize_t len = 0;
14996
0
    if (it->it_seq)
14997
0
        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
14998
0
    return PyLong_FromSsize_t(len);
14999
0
}
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
93
{
15102
93
    unicodeiterobject *it;
15103
15104
93
    if (!PyUnicode_Check(seq)) {
15105
0
        PyErr_BadInternalCall();
15106
0
        return NULL;
15107
0
    }
15108
93
    if (PyUnicode_IS_COMPACT_ASCII(seq)) {
15109
93
        it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
15110
93
    }
15111
0
    else {
15112
0
        it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15113
0
    }
15114
93
    if (it == NULL)
15115
0
        return NULL;
15116
93
    it->it_index = 0;
15117
93
    it->it_seq = Py_NewRef(seq);
15118
93
    _PyObject_GC_TRACK(it);
15119
93
    return (PyObject *)it;
15120
93
}
15121
15122
static int
15123
encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
15124
80
{
15125
80
    int res;
15126
80
    res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
15127
80
    if (res == -2) {
15128
0
        PyErr_Format(PyExc_RuntimeError, "cannot encode %s", name);
15129
0
        return -1;
15130
0
    }
15131
80
    if (res < 0) {
15132
0
        PyErr_NoMemory();
15133
0
        return -1;
15134
0
    }
15135
80
    return 0;
15136
80
}
15137
15138
15139
static int
15140
config_get_codec_name(wchar_t **config_encoding)
15141
40
{
15142
40
    char *encoding;
15143
40
    if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15144
0
        return -1;
15145
0
    }
15146
15147
40
    PyObject *name_obj = NULL;
15148
40
    PyObject *codec = _PyCodec_Lookup(encoding);
15149
40
    PyMem_RawFree(encoding);
15150
15151
40
    if (!codec)
15152
0
        goto error;
15153
15154
40
    name_obj = PyObject_GetAttrString(codec, "name");
15155
40
    Py_CLEAR(codec);
15156
40
    if (!name_obj) {
15157
0
        goto error;
15158
0
    }
15159
15160
40
    wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
15161
40
    Py_DECREF(name_obj);
15162
40
    if (wname == NULL) {
15163
0
        goto error;
15164
0
    }
15165
15166
40
    wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
15167
40
    if (raw_wname == NULL) {
15168
0
        PyMem_Free(wname);
15169
0
        PyErr_NoMemory();
15170
0
        goto error;
15171
0
    }
15172
15173
40
    PyMem_RawFree(*config_encoding);
15174
40
    *config_encoding = raw_wname;
15175
15176
40
    PyMem_Free(wname);
15177
40
    return 0;
15178
15179
0
error:
15180
0
    Py_XDECREF(codec);
15181
0
    Py_XDECREF(name_obj);
15182
0
    return -1;
15183
40
}
15184
15185
15186
static PyStatus
15187
init_stdio_encoding(PyInterpreterState *interp)
15188
20
{
15189
    /* Update the stdio encoding to the normalized Python codec name. */
15190
20
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15191
20
    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
20
    return _PyStatus_OK();
15196
20
}
15197
15198
15199
static int
15200
init_fs_codec(PyInterpreterState *interp)
15201
20
{
15202
20
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
15203
15204
20
    _Py_error_handler error_handler;
15205
20
    error_handler = get_error_handler_wide(config->filesystem_errors);
15206
20
    if (error_handler == _Py_ERROR_UNKNOWN) {
15207
0
        PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
15208
0
        return -1;
15209
0
    }
15210
15211
20
    char *encoding, *errors;
15212
20
    if (encode_wstr_utf8(config->filesystem_encoding,
15213
20
                         &encoding,
15214
20
                         "filesystem_encoding") < 0) {
15215
0
        return -1;
15216
0
    }
15217
15218
20
    if (encode_wstr_utf8(config->filesystem_errors,
15219
20
                         &errors,
15220
20
                         "filesystem_errors") < 0) {
15221
0
        PyMem_RawFree(encoding);
15222
0
        return -1;
15223
0
    }
15224
15225
20
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
15226
20
    PyMem_RawFree(fs_codec->encoding);
15227
20
    fs_codec->encoding = encoding;
15228
    /* encoding has been normalized by init_fs_encoding() */
15229
20
    fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
15230
20
    PyMem_RawFree(fs_codec->errors);
15231
20
    fs_codec->errors = errors;
15232
20
    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
20
    if (_Py_IsMainInterpreter(interp)) {
15245
15246
20
        if (_Py_SetFileSystemEncoding(fs_codec->encoding,
15247
20
                                      fs_codec->errors) < 0) {
15248
0
            PyErr_NoMemory();
15249
0
            return -1;
15250
0
        }
15251
20
    }
15252
20
    return 0;
15253
20
}
15254
15255
15256
static PyStatus
15257
init_fs_encoding(PyThreadState *tstate)
15258
20
{
15259
20
    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
20
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15265
20
    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
20
    if (init_fs_codec(interp) < 0) {
15272
0
        return _PyStatus_ERR("cannot initialize filesystem codec");
15273
0
    }
15274
20
    return _PyStatus_OK();
15275
20
}
15276
15277
15278
PyStatus
15279
_PyUnicode_InitEncodings(PyThreadState *tstate)
15280
20
{
15281
20
    PyStatus status = _PyCodec_InitRegistry(tstate->interp);
15282
20
    if (_PyStatus_EXCEPTION(status)) {
15283
0
        return status;
15284
0
    }
15285
20
    status = init_fs_encoding(tstate);
15286
20
    if (_PyStatus_EXCEPTION(status)) {
15287
0
        return status;
15288
0
    }
15289
15290
20
    return init_stdio_encoding(tstate->interp);
15291
20
}
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
0
{
15373
0
    return PyModuleDef_Init(&_string_module);
15374
0
}
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
}