Coverage Report

Created: 2026-08-13 06:33

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
2.28M
#define MAX_UNICODE _Py_MAX_UNICODE
109
207M
#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
112M
{
119
112M
    return FT_ATOMIC_LOAD_PTR_ACQUIRE(_PyCompactUnicodeObject_CAST(op)->utf8);
120
112M
}
121
122
static inline char* PyUnicode_UTF8(PyObject *op)
123
1.29M
{
124
1.29M
    assert(_PyUnicode_CHECK(op));
125
1.29M
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
126
1.25M
        return ((char*)(_PyASCIIObject_CAST(op) + 1));
127
1.25M
    }
128
39.5k
    else {
129
39.5k
         return _PyUnicode_UTF8(op);
130
39.5k
    }
131
1.29M
}
132
133
static inline void PyUnicode_SET_UTF8(PyObject *op, char *utf8)
134
11.1k
{
135
11.1k
    FT_ATOMIC_STORE_PTR_RELEASE(_PyCompactUnicodeObject_CAST(op)->utf8, utf8);
136
11.1k
}
137
138
static inline Py_ssize_t PyUnicode_UTF8_LENGTH(PyObject *op)
139
468k
{
140
468k
    assert(_PyUnicode_CHECK(op));
141
468k
    if (PyUnicode_IS_COMPACT_ASCII(op)) {
142
468k
         return _PyASCIIObject_CAST(op)->length;
143
468k
    }
144
842
    else {
145
842
         return _PyCompactUnicodeObject_CAST(op)->utf8_length;
146
842
    }
147
468k
}
148
149
static inline void PyUnicode_SET_UTF8_LENGTH(PyObject *op, Py_ssize_t length)
150
11.1k
{
151
11.1k
    _PyCompactUnicodeObject_CAST(op)->utf8_length = length;
152
11.1k
}
153
154
#define _PyUnicode_LENGTH(op)                           \
155
37.3M
    (_PyASCIIObject_CAST(op)->length)
156
#define _PyUnicode_STATE(op)                            \
157
209M
    (_PyASCIIObject_CAST(op)->state)
158
#define _PyUnicode_HASH(op)                             \
159
30.0M
    (_PyASCIIObject_CAST(op)->hash)
160
161
30.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.95M
{
165
3.95M
    FT_ATOMIC_STORE_SSIZE_RELAXED(_PyASCIIObject_CAST(op)->hash, hash);
166
3.95M
}
167
168
#define _PyUnicode_DATA_ANY(op)                         \
169
84
    (_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
36.8M
{
182
36.8M
    return (!PyUnicode_IS_COMPACT_ASCII(op)
183
22.5M
            && _PyUnicode_UTF8(op) != NULL
184
11.0k
            && _PyUnicode_UTF8(op) != PyUnicode_DATA(op));
185
36.8M
}
186
187
188
7.53M
#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
40.3M
{
208
40.3M
    _Py_DECLARE_STR(empty, "");
209
40.3M
    return &_Py_STR(empty);
210
40.3M
}
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
683k
{
217
683k
    return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
218
683k
}
219
220
/* This hashtable holds statically allocated interned strings.
221
 * See InternalDocs/string_interning.md for details.
222
 */
223
654k
#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
720k
{
260
720k
    return unicode_hash((PyObject *)key);
261
720k
}
262
263
static int
264
hashtable_unicode_compare(const void *key1, const void *key2)
265
69.7k
{
266
69.7k
    PyObject *obj1 = (PyObject *)key1;
267
69.7k
    PyObject *obj2 = (PyObject *)key2;
268
69.7k
    if (obj1 != NULL && obj2 != NULL) {
269
69.7k
        return unicode_eq(obj1, obj2);
270
69.7k
    }
271
0
    else {
272
0
        return obj1 == obj2;
273
0
    }
274
69.7k
}
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
21
{
289
21
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
290
21
    return interp != main_interp  && interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC;
291
21
}
292
293
static int
294
init_interned_dict(PyInterpreterState *interp)
295
21
{
296
21
    assert(get_interned_dict(interp) == NULL);
297
21
    PyObject *interned;
298
21
    if (has_shared_intern_dict(interp)) {
299
0
        interned = get_interned_dict(_PyInterpreterState_Main());
300
0
        Py_INCREF(interned);
301
0
    }
302
21
    else {
303
21
        interned = PyDict_New();
304
21
        if (interned == NULL) {
305
0
            return -1;
306
0
        }
307
21
    }
308
21
    _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
309
21
    return 0;
310
21
}
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
21
{
329
21
    assert(INTERNED_STRINGS == NULL);
330
21
    _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
331
332
21
    INTERNED_STRINGS = _Py_hashtable_new_full(
333
21
        hashtable_unicode_hash,
334
21
        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
21
        NULL,
338
21
        NULL,
339
21
        &hashtable_alloc
340
21
    );
341
21
    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
21
    _PyUnicode_InitStaticStrings(interp);
354
355
5.39k
    for (int i = 0; i < 256; i++) {
356
5.37k
        PyObject *s = LATIN1(i);
357
5.37k
        _PyUnicode_InternStatic(interp, &s);
358
5.37k
        assert(s == LATIN1(i));
359
5.37k
    }
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
21
    return _PyStatus_OK();
368
21
}
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
23.7M
    do {                             \
380
23.7M
        return _PyUnicode_GetEmpty();\
381
23.7M
    } 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
46.8k
{
475
46.8k
    if (errors == NULL || strcmp(errors, "strict") == 0) {
476
35.8k
        return _Py_ERROR_STRICT;
477
35.8k
    }
478
11.0k
    if (strcmp(errors, "surrogateescape") == 0) {
479
7.39k
        return _Py_ERROR_SURROGATEESCAPE;
480
7.39k
    }
481
3.61k
    if (strcmp(errors, "replace") == 0) {
482
2.77k
        return _Py_ERROR_REPLACE;
483
2.77k
    }
484
845
    if (strcmp(errors, "ignore") == 0) {
485
0
        return _Py_ERROR_IGNORE;
486
0
    }
487
845
    if (strcmp(errors, "backslashreplace") == 0) {
488
259
        return _Py_ERROR_BACKSLASHREPLACE;
489
259
    }
490
586
    if (strcmp(errors, "surrogatepass") == 0) {
491
586
        return _Py_ERROR_SURROGATEPASS;
492
586
    }
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
252
{
503
252
    if (errors == NULL || wcscmp(errors, L"strict") == 0) {
504
0
        return _Py_ERROR_STRICT;
505
0
    }
506
252
    if (wcscmp(errors, L"surrogateescape") == 0) {
507
252
        return _Py_ERROR_SURROGATEESCAPE;
508
252
    }
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
249k
{
531
249k
    if (encoding == NULL && errors == NULL) {
532
0
        return 0;
533
0
    }
534
535
249k
    PyInterpreterState *interp = _PyInterpreterState_GET();
536
249k
#ifndef Py_DEBUG
537
    /* In release mode, only check in development mode (-X dev) */
538
249k
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
539
249k
        return 0;
540
249k
    }
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
80.7M
{
594
80.7M
#define CHECK(expr) \
595
405M
    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
80.7M
# define CHECK_IF_GIL(expr) CHECK(expr)
601
80.7M
# define CHECK_IF_FT(expr) (void)(expr)
602
80.7M
#endif
603
604
605
80.7M
    assert(op != NULL);
606
80.7M
    CHECK(PyUnicode_Check(op));
607
608
80.7M
    PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
609
0
    int kind = ascii->state.kind;
610
611
80.7M
    if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
612
35.7M
        CHECK(kind == PyUnicode_1BYTE_KIND);
613
35.7M
    }
614
44.9M
    else {
615
44.9M
        PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
616
0
        void *data;
617
618
44.9M
        if (ascii->state.compact == 1) {
619
44.9M
            data = compact + 1;
620
44.9M
            CHECK(kind == PyUnicode_1BYTE_KIND
621
44.9M
                                 || kind == PyUnicode_2BYTE_KIND
622
44.9M
                                 || kind == PyUnicode_4BYTE_KIND);
623
44.9M
            CHECK(ascii->state.ascii == 0);
624
44.9M
            CHECK(_PyUnicode_UTF8(op) != data);
625
44.9M
        }
626
42
        else {
627
42
            PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
628
629
0
            data = unicode->data.any;
630
42
            CHECK(kind == PyUnicode_1BYTE_KIND
631
42
                     || kind == PyUnicode_2BYTE_KIND
632
42
                     || kind == PyUnicode_4BYTE_KIND);
633
42
            CHECK(ascii->state.compact == 0);
634
42
            CHECK(data != NULL);
635
42
            if (ascii->state.ascii) {
636
42
                CHECK(_PyUnicode_UTF8(op) == data);
637
42
                CHECK(compact->utf8_length == ascii->length);
638
42
            }
639
0
            else {
640
0
                CHECK(_PyUnicode_UTF8(op) != data);
641
0
            }
642
42
        }
643
44.9M
#ifndef Py_GIL_DISABLED
644
44.9M
        if (_PyUnicode_UTF8(op) == NULL)
645
44.9M
            CHECK(compact->utf8_length == 0);
646
44.9M
#endif
647
44.9M
    }
648
649
    /* check that the best kind is used: O(n) operation */
650
80.7M
    if (check_content) {
651
43.3M
        Py_ssize_t i;
652
43.3M
        Py_UCS4 maxchar = 0;
653
43.3M
        const void *data;
654
43.3M
        Py_UCS4 ch;
655
656
43.3M
        data = PyUnicode_DATA(ascii);
657
26.0G
        for (i=0; i < ascii->length; i++)
658
26.0G
        {
659
26.0G
            ch = PyUnicode_READ(kind, data, i);
660
26.0G
            if (ch > maxchar)
661
59.1M
                maxchar = ch;
662
26.0G
        }
663
43.3M
        if (kind == PyUnicode_1BYTE_KIND) {
664
22.4M
            if (ascii->state.ascii == 0) {
665
1.42M
                CHECK(maxchar >= 128);
666
1.42M
                CHECK(maxchar <= 255);
667
1.42M
            }
668
21.0M
            else
669
21.0M
                CHECK(maxchar < 128);
670
22.4M
        }
671
20.9M
        else if (kind == PyUnicode_2BYTE_KIND) {
672
19.5M
            CHECK(maxchar >= 0x100);
673
19.5M
            CHECK(maxchar <= 0xFFFF);
674
19.5M
        }
675
1.46M
        else {
676
1.46M
            CHECK(maxchar >= 0x10000);
677
1.46M
            CHECK(maxchar <= MAX_UNICODE);
678
1.46M
        }
679
43.3M
        CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
680
43.3M
    }
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
80.7M
    return 1;
717
718
80.7M
#undef CHECK
719
80.7M
}
720
721
PyObject*
722
_PyUnicode_Result(PyObject *unicode)
723
2.23M
{
724
2.23M
    assert(_PyUnicode_CHECK(unicode));
725
726
2.23M
    Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
727
2.23M
    if (length == 0) {
728
2
        PyObject *empty = _PyUnicode_GetEmpty();
729
2
        if (unicode != empty) {
730
0
            Py_DECREF(unicode);
731
0
        }
732
2
        return empty;
733
2
    }
734
735
2.23M
    if (length == 1) {
736
335k
        int kind = PyUnicode_KIND(unicode);
737
335k
        if (kind == PyUnicode_1BYTE_KIND) {
738
249k
            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
739
249k
            Py_UCS1 ch = data[0];
740
249k
            PyObject *latin1_char = LATIN1(ch);
741
249k
            if (unicode != latin1_char) {
742
248k
                Py_DECREF(unicode);
743
248k
            }
744
249k
            return latin1_char;
745
249k
        }
746
335k
    }
747
748
2.23M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
749
1.98M
    return unicode;
750
1.98M
}
751
31.2k
#define unicode_result _PyUnicode_Result
752
753
static PyObject*
754
unicode_result_unchanged(PyObject *unicode)
755
177k
{
756
177k
    if (PyUnicode_CheckExact(unicode)) {
757
177k
        return Py_NewRef(unicode);
758
177k
    }
759
0
    else
760
        /* Subtype -- return genuine unicode string with the same value. */
761
0
        return _PyUnicode_Copy(unicode);
762
177k
}
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
7.44k
{
770
7.44k
    Py_ssize_t size, i;
771
7.44k
    Py_UCS4 ch;
772
7.44k
    int kind;
773
7.44k
    const void *data;
774
775
7.44k
    kind = PyUnicode_KIND(unicode);
776
7.44k
    data = PyUnicode_DATA(unicode);
777
778
7.44k
    size = 0;
779
    /* determine replacement size */
780
103k
    for (i = collstart; i < collend; ++i) {
781
96.2k
        Py_ssize_t incr;
782
783
96.2k
        ch = PyUnicode_READ(kind, data, i);
784
96.2k
        if (ch < 0x100)
785
96.2k
            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
96.2k
        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
96.2k
        size += incr;
798
96.2k
    }
799
800
7.44k
    str = PyBytesWriter_GrowAndUpdatePointer(writer, size, str);
801
7.44k
    if (str == NULL) {
802
0
        return NULL;
803
0
    }
804
805
    /* generate replacement */
806
103k
    for (i = collstart; i < collend; ++i) {
807
96.2k
        ch = PyUnicode_READ(kind, data, i);
808
96.2k
        *str++ = '\\';
809
96.2k
        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
96.2k
        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
96.2k
        else
824
96.2k
            *str++ = 'x';
825
96.2k
        *str++ = Py_hexdigits[(ch>>4)&0xf];
826
96.2k
        *str++ = Py_hexdigits[ch&0xf];
827
96.2k
    }
828
7.44k
    return str;
829
7.44k
}
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
18.3k
#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
18.0k
#define BLOOM_MASK unsigned long
910
911
static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
912
913
9.07k
#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
9.05k
{
922
9.05k
#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \
923
9.05k
    do {                                               \
924
9.05k
        TYPE *data = (TYPE *)PTR;                      \
925
9.05k
        TYPE *end = data + LEN;                        \
926
9.05k
        Py_UCS4 ch;                                    \
927
18.2k
        for (; data != end; data++) {                  \
928
9.24k
            ch = *data;                                \
929
9.24k
            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
930
9.24k
        }                                              \
931
9.05k
        break;                                         \
932
9.05k
    } while (0)
933
934
    /* calculate simple bloom-style bitmask for a given unicode string */
935
936
9.05k
    BLOOM_MASK mask;
937
938
9.05k
    mask = 0;
939
9.05k
    switch (kind) {
940
9.03k
    case PyUnicode_1BYTE_KIND:
941
9.03k
        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
942
9.03k
        break;
943
21
    case PyUnicode_2BYTE_KIND:
944
21
        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
945
21
        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
9.05k
    }
952
9.05k
    return mask;
953
954
9.05k
#undef BLOOM_UPDATE
955
9.05k
}
956
957
/* Compilation of templated routines */
958
959
1.63k
#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
28.0M
{
1012
28.0M
    switch (kind) {
1013
28.0M
    case PyUnicode_1BYTE_KIND:
1014
28.0M
        if ((Py_UCS1) ch != ch)
1015
1.72k
            return -1;
1016
28.0M
        if (direction > 0)
1017
28.0M
            return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1018
3.40k
        else
1019
3.40k
            return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
1020
25.3k
    case PyUnicode_2BYTE_KIND:
1021
25.3k
        if ((Py_UCS2) ch != ch)
1022
0
            return -1;
1023
25.3k
        if (direction > 0)
1024
24.4k
            return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1025
942
        else
1026
942
            return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
1027
2.14k
    case PyUnicode_4BYTE_KIND:
1028
2.14k
        if (direction > 0)
1029
789
            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
28.0M
    }
1035
28.0M
}
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
7.27M
{
1074
7.27M
    Py_ssize_t char_size;
1075
7.27M
    Py_ssize_t struct_size;
1076
7.27M
    Py_ssize_t new_size;
1077
7.27M
    PyObject *new_unicode;
1078
#ifdef Py_DEBUG
1079
    Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1080
#endif
1081
1082
7.27M
    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
7.27M
    assert(PyUnicode_IS_COMPACT(unicode));
1091
1092
7.27M
    char_size = PyUnicode_KIND(unicode);
1093
7.27M
    if (PyUnicode_IS_ASCII(unicode))
1094
6.20M
        struct_size = sizeof(PyASCIIObject);
1095
1.06M
    else
1096
1.06M
        struct_size = sizeof(PyCompactUnicodeObject);
1097
1098
7.27M
    if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1099
0
        PyErr_NoMemory();
1100
0
        return NULL;
1101
0
    }
1102
7.27M
    new_size = (struct_size + (length + 1) * char_size);
1103
1104
7.27M
    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
7.27M
    _PyReftracerTrack(unicode, PyRefTracer_DESTROY);
1113
1114
7.27M
    new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
1115
7.27M
    if (new_unicode == NULL) {
1116
0
        _Py_NewReferenceNoTotal(unicode);
1117
0
        PyErr_NoMemory();
1118
0
        return NULL;
1119
0
    }
1120
7.27M
    unicode = new_unicode;
1121
7.27M
    _Py_NewReferenceNoTotal(unicode);
1122
1123
7.27M
    _PyUnicode_LENGTH(unicode) = length;
1124
#ifdef Py_DEBUG
1125
    unicode_fill_invalid(unicode, old_length);
1126
#endif
1127
7.27M
    PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1128
7.27M
                    length, 0);
1129
7.27M
    assert(_PyUnicode_CheckConsistency(unicode, 0));
1130
7.27M
    return unicode;
1131
7.27M
}
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
39.3M
{
1278
    /* Optimization for empty strings */
1279
39.3M
    if (size == 0) {
1280
9.28M
        return _PyUnicode_GetEmpty();
1281
9.28M
    }
1282
1283
30.0M
    PyObject *obj;
1284
30.0M
    PyCompactUnicodeObject *unicode;
1285
30.0M
    void *data;
1286
30.0M
    int kind;
1287
30.0M
    int is_ascii;
1288
30.0M
    Py_ssize_t char_size;
1289
30.0M
    Py_ssize_t struct_size;
1290
1291
30.0M
    is_ascii = 0;
1292
30.0M
    struct_size = sizeof(PyCompactUnicodeObject);
1293
30.0M
    if (maxchar < 128) {
1294
8.55M
        kind = PyUnicode_1BYTE_KIND;
1295
8.55M
        char_size = 1;
1296
8.55M
        is_ascii = 1;
1297
8.55M
        struct_size = sizeof(PyASCIIObject);
1298
8.55M
    }
1299
21.5M
    else if (maxchar < 256) {
1300
412k
        kind = PyUnicode_1BYTE_KIND;
1301
412k
        char_size = 1;
1302
412k
    }
1303
21.0M
    else if (maxchar < 65536) {
1304
19.6M
        kind = PyUnicode_2BYTE_KIND;
1305
19.6M
        char_size = 2;
1306
19.6M
    }
1307
1.42M
    else {
1308
1.42M
        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
1.42M
        kind = PyUnicode_4BYTE_KIND;
1314
1.42M
        char_size = 4;
1315
1.42M
    }
1316
1317
    /* Ensure we won't overflow the size. */
1318
30.0M
    if (size < 0) {
1319
0
        PyErr_SetString(PyExc_SystemError,
1320
0
                        "Negative size passed to PyUnicode_New");
1321
0
        return NULL;
1322
0
    }
1323
30.0M
    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
30.0M
    obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
1331
30.0M
    if (obj == NULL) {
1332
0
        return PyErr_NoMemory();
1333
0
    }
1334
30.0M
    _PyObject_Init(obj, &PyUnicode_Type);
1335
1336
30.0M
    unicode = (PyCompactUnicodeObject *)obj;
1337
30.0M
    if (is_ascii)
1338
8.55M
        data = ((PyASCIIObject*)obj) + 1;
1339
21.5M
    else
1340
21.5M
        data = unicode + 1;
1341
30.0M
    _PyUnicode_LENGTH(unicode) = size;
1342
30.0M
    _PyUnicode_HASH(unicode) = -1;
1343
30.0M
    _PyUnicode_STATE(unicode).interned = 0;
1344
30.0M
    _PyUnicode_STATE(unicode).kind = kind;
1345
30.0M
    _PyUnicode_STATE(unicode).compact = 1;
1346
30.0M
    _PyUnicode_STATE(unicode).ascii = is_ascii;
1347
30.0M
    _PyUnicode_STATE(unicode).statically_allocated = 0;
1348
30.0M
    if (is_ascii) {
1349
8.55M
        ((char*)data)[size] = 0;
1350
8.55M
    }
1351
21.5M
    else if (kind == PyUnicode_1BYTE_KIND) {
1352
412k
        ((char*)data)[size] = 0;
1353
412k
        unicode->utf8 = NULL;
1354
412k
        unicode->utf8_length = 0;
1355
412k
    }
1356
21.0M
    else {
1357
21.0M
        unicode->utf8 = NULL;
1358
21.0M
        unicode->utf8_length = 0;
1359
21.0M
        if (kind == PyUnicode_2BYTE_KIND)
1360
19.6M
            ((Py_UCS2*)data)[size] = 0;
1361
1.42M
        else /* kind == PyUnicode_4BYTE_KIND */
1362
1.42M
            ((Py_UCS4*)data)[size] = 0;
1363
21.0M
    }
1364
#ifdef Py_DEBUG
1365
    unicode_fill_invalid((PyObject*)unicode, 0);
1366
#endif
1367
30.0M
    assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
1368
30.0M
    return obj;
1369
30.0M
}
1370
1371
static int
1372
unicode_check_modifiable(PyObject *unicode)
1373
840
{
1374
840
    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
840
    return 0;
1380
840
}
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
11.8M
{
1387
11.8M
    int from_kind, to_kind;
1388
11.8M
    const void *from_data;
1389
11.8M
    void *to_data;
1390
1391
11.8M
    assert(0 <= how_many);
1392
11.8M
    assert(0 <= from_start);
1393
11.8M
    assert(0 <= to_start);
1394
11.8M
    assert(PyUnicode_Check(from));
1395
11.8M
    assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
1396
1397
11.8M
    assert(to == NULL || PyUnicode_Check(to));
1398
1399
11.8M
    if (how_many == 0) {
1400
9.55k
        return 0;
1401
9.55k
    }
1402
1403
11.8M
    assert(to != NULL);
1404
11.8M
    assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1405
1406
11.8M
    from_kind = PyUnicode_KIND(from);
1407
11.8M
    from_data = PyUnicode_DATA(from);
1408
11.8M
    to_kind = PyUnicode_KIND(to);
1409
11.8M
    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
11.8M
    if (from_kind == to_kind) {
1426
11.4M
        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
11.4M
        memcpy((char*)to_data + to_kind * to_start,
1438
11.4M
                  (const char*)from_data + from_kind * from_start,
1439
11.4M
                  to_kind * how_many);
1440
11.4M
    }
1441
371k
    else if (from_kind == PyUnicode_1BYTE_KIND
1442
276k
             && to_kind == PyUnicode_2BYTE_KIND)
1443
198k
    {
1444
198k
        _PyUnicode_CONVERT_BYTES(
1445
198k
            Py_UCS1, Py_UCS2,
1446
198k
            PyUnicode_1BYTE_DATA(from) + from_start,
1447
198k
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448
198k
            PyUnicode_2BYTE_DATA(to) + to_start
1449
198k
            );
1450
198k
    }
1451
172k
    else if (from_kind == PyUnicode_1BYTE_KIND
1452
77.3k
             && to_kind == PyUnicode_4BYTE_KIND)
1453
77.3k
    {
1454
77.3k
        _PyUnicode_CONVERT_BYTES(
1455
77.3k
            Py_UCS1, Py_UCS4,
1456
77.3k
            PyUnicode_1BYTE_DATA(from) + from_start,
1457
77.3k
            PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458
77.3k
            PyUnicode_4BYTE_DATA(to) + to_start
1459
77.3k
            );
1460
77.3k
    }
1461
94.9k
    else if (from_kind == PyUnicode_2BYTE_KIND
1462
54.6k
             && to_kind == PyUnicode_4BYTE_KIND)
1463
47.5k
    {
1464
47.5k
        _PyUnicode_CONVERT_BYTES(
1465
47.5k
            Py_UCS2, Py_UCS4,
1466
47.5k
            PyUnicode_2BYTE_DATA(from) + from_start,
1467
47.5k
            PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468
47.5k
            PyUnicode_4BYTE_DATA(to) + to_start
1469
47.5k
            );
1470
47.5k
    }
1471
47.3k
    else {
1472
47.3k
        assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
1474
47.3k
        if (!check_maxchar) {
1475
47.3k
            if (from_kind == PyUnicode_2BYTE_KIND
1476
7.13k
                && to_kind == PyUnicode_1BYTE_KIND)
1477
7.13k
            {
1478
7.13k
                _PyUnicode_CONVERT_BYTES(
1479
7.13k
                    Py_UCS2, Py_UCS1,
1480
7.13k
                    PyUnicode_2BYTE_DATA(from) + from_start,
1481
7.13k
                    PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482
7.13k
                    PyUnicode_1BYTE_DATA(to) + to_start
1483
7.13k
                    );
1484
7.13k
            }
1485
40.2k
            else if (from_kind == PyUnicode_4BYTE_KIND
1486
40.2k
                     && to_kind == PyUnicode_1BYTE_KIND)
1487
30.3k
            {
1488
30.3k
                _PyUnicode_CONVERT_BYTES(
1489
30.3k
                    Py_UCS4, Py_UCS1,
1490
30.3k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1491
30.3k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492
30.3k
                    PyUnicode_1BYTE_DATA(to) + to_start
1493
30.3k
                    );
1494
30.3k
            }
1495
9.83k
            else if (from_kind == PyUnicode_4BYTE_KIND
1496
9.83k
                     && to_kind == PyUnicode_2BYTE_KIND)
1497
9.83k
            {
1498
9.83k
                _PyUnicode_CONVERT_BYTES(
1499
9.83k
                    Py_UCS4, Py_UCS2,
1500
9.83k
                    PyUnicode_4BYTE_DATA(from) + from_start,
1501
9.83k
                    PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502
9.83k
                    PyUnicode_2BYTE_DATA(to) + to_start
1503
9.83k
                    );
1504
9.83k
            }
1505
0
            else {
1506
0
                Py_UNREACHABLE();
1507
0
            }
1508
47.3k
        }
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
47.3k
    }
1522
11.8M
    return 0;
1523
11.8M
}
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
11.8M
{
1530
11.8M
    (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1531
11.8M
}
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
8.26k
{
1593
8.26k
    const wchar_t *iter;
1594
8.26k
    Py_UCS4 ch;
1595
1596
8.26k
    assert(num_surrogates != NULL && maxchar != NULL);
1597
8.26k
    *num_surrogates = 0;
1598
8.26k
    *maxchar = 0;
1599
1600
235k
    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
227k
        {
1613
227k
            ch = *iter;
1614
227k
            iter++;
1615
227k
        }
1616
227k
        if (ch > *maxchar) {
1617
34.6k
            *maxchar = ch;
1618
34.6k
            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
34.6k
        }
1625
227k
    }
1626
8.26k
    return 0;
1627
8.26k
}
1628
1629
static void
1630
unicode_dealloc(PyObject *unicode)
1631
29.5M
{
1632
#ifdef Py_DEBUG
1633
    if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
1634
        _Py_FatalRefcountError("deallocating an Unicode singleton");
1635
    }
1636
#endif
1637
59.1M
    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
29.5M
    switch (_PyUnicode_STATE(unicode).interned) {
1649
29.4M
        case SSTATE_NOT_INTERNED:
1650
29.4M
            break;
1651
146k
        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
146k
            assert(Py_REFCNT(unicode) == 0);
1657
146k
            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
146k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1664
146k
            PyObject *interned = get_interned_dict(interp);
1665
146k
            assert(interned != NULL);
1666
146k
            PyObject *popped;
1667
146k
            int r = PyDict_Pop(interned, unicode, &popped);
1668
146k
            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
146k
            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
146k
            assert(popped == unicode);
1691
            // Only our `popped` reference should be left; remove it too.
1692
146k
            assert(Py_REFCNT(unicode) == 1);
1693
146k
            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
146k
            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
29.5M
    }
1707
29.5M
    if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1708
11.0k
        PyMem_Free(_PyUnicode_UTF8(unicode));
1709
11.0k
    }
1710
29.5M
    if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
1711
0
        PyMem_Free(_PyUnicode_DATA_ANY(unicode));
1712
0
    }
1713
1714
29.5M
    Py_TYPE(unicode)->tp_free(unicode);
1715
29.5M
}
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.8M
{
1739
18.8M
    assert(_PyUnicode_CHECK(unicode));
1740
18.8M
    if (!_PyObject_IsUniquelyReferenced(unicode))
1741
487k
        return 0;
1742
18.3M
    if (PyUnicode_HASH(unicode) != -1)
1743
0
        return 0;
1744
18.3M
    if (PyUnicode_CHECK_INTERNED(unicode))
1745
0
        return 0;
1746
18.3M
    if (!PyUnicode_CheckExact(unicode))
1747
0
        return 0;
1748
#ifdef Py_DEBUG
1749
    /* singleton refcount is greater than 1 */
1750
    assert(!unicode_is_singleton(unicode));
1751
#endif
1752
18.3M
    return 1;
1753
18.3M
}
1754
1755
static int
1756
unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1757
5.55M
{
1758
5.55M
    PyObject *unicode;
1759
5.55M
    Py_ssize_t old_length;
1760
1761
5.55M
    assert(p_unicode != NULL);
1762
5.55M
    unicode = *p_unicode;
1763
1764
5.55M
    assert(unicode != NULL);
1765
5.55M
    assert(PyUnicode_Check(unicode));
1766
5.55M
    assert(0 <= length);
1767
1768
5.55M
    old_length = PyUnicode_GET_LENGTH(unicode);
1769
5.55M
    if (old_length == length)
1770
0
        return 0;
1771
1772
5.55M
    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.55M
    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.55M
    if (PyUnicode_IS_COMPACT(unicode)) {
1787
5.55M
        PyObject *new_unicode = _PyUnicode_ResizeCompact(unicode, length);
1788
5.55M
        if (new_unicode == NULL)
1789
0
            return -1;
1790
5.55M
        *p_unicode = new_unicode;
1791
5.55M
        return 0;
1792
5.55M
    }
1793
0
    return resize_inplace(unicode, length);
1794
5.55M
}
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
7.28M
{
1816
7.28M
    PyObject *o = LATIN1(ch);
1817
7.28M
    return o;
1818
7.28M
}
1819
1820
static PyObject*
1821
unicode_char(Py_UCS4 ch)
1822
26.5M
{
1823
26.5M
    PyObject *unicode;
1824
1825
26.5M
    assert(ch <= MAX_UNICODE);
1826
1827
26.5M
    if (ch < 256) {
1828
6.87M
        return get_latin1_char(ch);
1829
6.87M
    }
1830
1831
19.7M
    unicode = PyUnicode_New(1, ch);
1832
19.7M
    if (unicode == NULL)
1833
0
        return NULL;
1834
1835
19.7M
    assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1836
39.4M
    if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
1837
18.4M
        PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1838
18.4M
    } else {
1839
1.22M
        assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1840
1.22M
        PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1841
1.22M
    }
1842
19.7M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
1843
19.7M
    return unicode;
1844
19.7M
}
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
8.26k
{
1852
8.26k
    switch (kind) {
1853
8.26k
    case PyUnicode_1BYTE_KIND:
1854
8.26k
        _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, u, u + size, data);
1855
8.26k
        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
8.26k
    }
1899
8.26k
}
1900
1901
1902
PyObject *
1903
PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
1904
8.30k
{
1905
8.30k
    PyObject *unicode;
1906
8.30k
    Py_UCS4 maxchar = 0;
1907
8.30k
    Py_ssize_t num_surrogates;
1908
1909
8.30k
    if (u == NULL && size != 0) {
1910
0
        PyErr_BadInternalCall();
1911
0
        return NULL;
1912
0
    }
1913
1914
8.30k
    if (size == -1) {
1915
861
        size = wcslen(u);
1916
861
    }
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
8.30k
    if (size == 0)
1923
42
        _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
8.26k
    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
8.26k
    if (find_maxchar_surrogates(u, u + size,
1947
8.26k
                                &maxchar, &num_surrogates) == -1)
1948
0
        return NULL;
1949
1950
8.26k
    unicode = PyUnicode_New(size - num_surrogates, maxchar);
1951
8.26k
    if (!unicode)
1952
0
        return NULL;
1953
1954
8.26k
    unicode_write_widechar(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1955
8.26k
                           u, size, num_surrogates);
1956
1957
8.26k
    return unicode_result(unicode);
1958
8.26k
}
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
121k
{
2014
121k
    if (size < 0) {
2015
0
        PyErr_SetString(PyExc_SystemError,
2016
0
                        "Negative size passed to PyUnicode_FromStringAndSize");
2017
0
        return NULL;
2018
0
    }
2019
121k
    if (u != NULL) {
2020
121k
        return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2021
121k
    }
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
3.41M
{
2033
3.41M
    size_t size = strlen(u);
2034
3.41M
    if (size > PY_SSIZE_T_MAX) {
2035
0
        PyErr_SetString(PyExc_OverflowError, "input too long");
2036
0
        return NULL;
2037
0
    }
2038
3.41M
    return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
2039
3.41M
}
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
9.86M
{
2128
9.86M
    const unsigned char *s = (const unsigned char *)buffer;
2129
9.86M
    PyObject *unicode;
2130
9.86M
    if (size == 1) {
2131
#ifdef Py_DEBUG
2132
        assert((unsigned char)s[0] < 128);
2133
#endif
2134
132k
        return get_latin1_char(s[0]);
2135
132k
    }
2136
9.73M
    unicode = PyUnicode_New(size, 127);
2137
9.73M
    if (!unicode)
2138
0
        return NULL;
2139
9.73M
    memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2140
9.73M
    assert(_PyUnicode_CheckConsistency(unicode, 1));
2141
9.73M
    return unicode;
2142
9.73M
}
2143
2144
static Py_UCS4
2145
kind_maxchar_limit(int kind)
2146
75
{
2147
75
    switch (kind) {
2148
11
    case PyUnicode_1BYTE_KIND:
2149
11
        return 0x80;
2150
23
    case PyUnicode_2BYTE_KIND:
2151
23
        return 0x100;
2152
41
    case PyUnicode_4BYTE_KIND:
2153
41
        return 0x10000;
2154
0
    default:
2155
0
        Py_UNREACHABLE();
2156
75
    }
2157
75
}
2158
2159
static PyObject*
2160
_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
2161
5.96M
{
2162
5.96M
    PyObject *res;
2163
5.96M
    unsigned char max_char;
2164
2165
5.96M
    if (size == 0) {
2166
5.71M
        _Py_RETURN_UNICODE_EMPTY();
2167
5.71M
    }
2168
5.96M
    assert(size > 0);
2169
251k
    if (size == 1) {
2170
17.6k
        return get_latin1_char(u[0]);
2171
17.6k
    }
2172
2173
233k
    max_char = ucs1lib_find_max_char(u, u + size);
2174
233k
    res = PyUnicode_New(size, max_char);
2175
233k
    if (!res)
2176
0
        return NULL;
2177
233k
    memcpy(PyUnicode_1BYTE_DATA(res), u, size);
2178
233k
    assert(_PyUnicode_CheckConsistency(res, 1));
2179
233k
    return res;
2180
233k
}
2181
2182
static PyObject*
2183
_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
2184
7.62M
{
2185
7.62M
    PyObject *res;
2186
7.62M
    Py_UCS2 max_char;
2187
2188
7.62M
    if (size == 0)
2189
7.28M
        _Py_RETURN_UNICODE_EMPTY();
2190
7.62M
    assert(size > 0);
2191
336k
    if (size == 1)
2192
31.3k
        return unicode_char(u[0]);
2193
2194
304k
    max_char = ucs2lib_find_max_char(u, u + size);
2195
304k
    res = PyUnicode_New(size, max_char);
2196
304k
    if (!res)
2197
0
        return NULL;
2198
304k
    if (max_char >= 256)
2199
236k
        memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
2200
68.0k
    else {
2201
68.0k
        _PyUnicode_CONVERT_BYTES(
2202
68.0k
            Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2203
68.0k
    }
2204
304k
    assert(_PyUnicode_CheckConsistency(res, 1));
2205
304k
    return res;
2206
304k
}
2207
2208
static PyObject*
2209
_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
2210
11.6M
{
2211
11.6M
    PyObject *res;
2212
11.6M
    Py_UCS4 max_char;
2213
2214
11.6M
    if (size == 0)
2215
10.5M
        _Py_RETURN_UNICODE_EMPTY();
2216
11.6M
    assert(size > 0);
2217
1.09M
    if (size == 1)
2218
558k
        return unicode_char(u[0]);
2219
2220
533k
    max_char = ucs4lib_find_max_char(u, u + size);
2221
533k
    res = PyUnicode_New(size, max_char);
2222
533k
    if (!res)
2223
0
        return NULL;
2224
533k
    if (max_char < 256)
2225
408k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2226
533k
                                 PyUnicode_1BYTE_DATA(res));
2227
125k
    else if (max_char < 0x10000)
2228
99.4k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2229
125k
                                 PyUnicode_2BYTE_DATA(res));
2230
26.2k
    else
2231
26.2k
        memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
2232
533k
    assert(_PyUnicode_CheckConsistency(res, 1));
2233
533k
    return res;
2234
533k
}
2235
2236
2237
int
2238
PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *pub_writer,
2239
                          const Py_UCS4 *str,
2240
                          Py_ssize_t size)
2241
394
{
2242
394
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
2243
2244
394
    if (size < 0) {
2245
0
        PyErr_SetString(PyExc_ValueError,
2246
0
                        "size must be positive");
2247
0
        return -1;
2248
0
    }
2249
2250
394
    if (size == 0) {
2251
0
        return 0;
2252
0
    }
2253
2254
394
    Py_UCS4 max_char = ucs4lib_find_max_char(str, str + size);
2255
2256
394
    if (_PyUnicodeWriter_Prepare(writer, size, max_char) < 0) {
2257
0
        return -1;
2258
0
    }
2259
2260
394
    int kind = writer->kind;
2261
394
    void *data = (Py_UCS1*)writer->data + writer->pos * kind;
2262
394
    if (kind == PyUnicode_1BYTE_KIND) {
2263
201
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1,
2264
201
                                 str, str + size,
2265
201
                                 data);
2266
201
    }
2267
193
    else if (kind == PyUnicode_2BYTE_KIND) {
2268
193
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2,
2269
193
                                 str, str + size,
2270
193
                                 data);
2271
193
    }
2272
0
    else {
2273
0
        memcpy(data, str, size * sizeof(Py_UCS4));
2274
0
    }
2275
394
    writer->pos += size;
2276
2277
394
    return 0;
2278
394
}
2279
2280
2281
PyObject*
2282
PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2283
2.68M
{
2284
2.68M
    if (size < 0) {
2285
0
        PyErr_SetString(PyExc_ValueError, "size must be positive");
2286
0
        return NULL;
2287
0
    }
2288
2.68M
    switch (kind) {
2289
169k
    case PyUnicode_1BYTE_KIND:
2290
169k
        return _PyUnicode_FromUCS1(buffer, size);
2291
346k
    case PyUnicode_2BYTE_KIND:
2292
346k
        return _PyUnicode_FromUCS2(buffer, size);
2293
2.17M
    case PyUnicode_4BYTE_KIND:
2294
2.17M
        return _PyUnicode_FromUCS4(buffer, size);
2295
0
    default:
2296
0
        PyErr_SetString(PyExc_SystemError, "invalid kind");
2297
0
        return NULL;
2298
2.68M
    }
2299
2.68M
}
2300
2301
Py_UCS4
2302
_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2303
1.54M
{
2304
1.54M
    int kind;
2305
1.54M
    const void *startptr, *endptr;
2306
2307
1.54M
    assert(0 <= start);
2308
1.54M
    assert(end <= PyUnicode_GET_LENGTH(unicode));
2309
1.54M
    assert(start <= end);
2310
2311
1.54M
    if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2312
0
        return PyUnicode_MAX_CHAR_VALUE(unicode);
2313
2314
1.54M
    if (start == end)
2315
0
        return 127;
2316
2317
1.54M
    if (PyUnicode_IS_ASCII(unicode))
2318
1.46M
        return 127;
2319
2320
80.9k
    kind = PyUnicode_KIND(unicode);
2321
80.9k
    startptr = PyUnicode_DATA(unicode);
2322
80.9k
    endptr = (char *)startptr + end * kind;
2323
80.9k
    startptr = (char *)startptr + start * kind;
2324
80.9k
    switch(kind) {
2325
7.08k
    case PyUnicode_1BYTE_KIND:
2326
7.08k
        return ucs1lib_find_max_char(startptr, endptr);
2327
31.4k
    case PyUnicode_2BYTE_KIND:
2328
31.4k
        return ucs2lib_find_max_char(startptr, endptr);
2329
42.4k
    case PyUnicode_4BYTE_KIND:
2330
42.4k
        return ucs4lib_find_max_char(startptr, endptr);
2331
0
    default:
2332
0
        Py_UNREACHABLE();
2333
80.9k
    }
2334
80.9k
}
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
9.86k
{
2412
9.86k
    void *result;
2413
2414
9.86k
    assert(skind < kind);
2415
9.86k
    switch (kind) {
2416
3.88k
    case PyUnicode_2BYTE_KIND:
2417
3.88k
        result = PyMem_New(Py_UCS2, len);
2418
3.88k
        if (!result)
2419
0
            return PyErr_NoMemory();
2420
3.88k
        assert(skind == PyUnicode_1BYTE_KIND);
2421
3.88k
        _PyUnicode_CONVERT_BYTES(
2422
3.88k
            Py_UCS1, Py_UCS2,
2423
3.88k
            (const Py_UCS1 *)data,
2424
3.88k
            ((const Py_UCS1 *)data) + len,
2425
3.88k
            result);
2426
3.88k
        return result;
2427
5.97k
    case PyUnicode_4BYTE_KIND:
2428
5.97k
        result = PyMem_New(Py_UCS4, len);
2429
5.97k
        if (!result)
2430
0
            return PyErr_NoMemory();
2431
5.97k
        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
5.97k
        else {
2439
5.97k
            assert(skind == PyUnicode_1BYTE_KIND);
2440
5.97k
            _PyUnicode_CONVERT_BYTES(
2441
5.97k
                Py_UCS1, Py_UCS4,
2442
5.97k
                (const Py_UCS1 *)data,
2443
5.97k
                ((const Py_UCS1 *)data) + len,
2444
5.97k
                result);
2445
5.97k
        }
2446
5.97k
        return result;
2447
0
    default:
2448
0
        Py_UNREACHABLE();
2449
0
        return NULL;
2450
9.86k
    }
2451
9.86k
}
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
37.4k
{
2528
37.4k
    Py_ssize_t length, fill, arglen;
2529
37.4k
    Py_UCS4 maxchar;
2530
2531
37.4k
    length = PyUnicode_GET_LENGTH(str);
2532
37.4k
    if ((precision == -1 || precision >= length)
2533
35.9k
        && width <= length)
2534
35.9k
        return _PyUnicodeWriter_WriteStr(writer, str);
2535
2536
1.43k
    if (precision != -1)
2537
1.43k
        length = Py_MIN(precision, length);
2538
2539
1.43k
    arglen = Py_MAX(length, width);
2540
1.43k
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2541
348
        maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2542
1.09k
    else
2543
1.09k
        maxchar = writer->maxchar;
2544
2545
1.43k
    if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2546
0
        return -1;
2547
2548
1.43k
    fill = Py_MAX(width - length, 0);
2549
1.43k
    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.43k
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2556
1.43k
                                  str, 0, length);
2557
1.43k
    writer->pos += length;
2558
2559
1.43k
    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.43k
    return 0;
2566
1.43k
}
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
185k
{
2572
    /* UTF-8 */
2573
185k
    Py_ssize_t *pconsumed = NULL;
2574
185k
    Py_ssize_t length;
2575
185k
    if (precision == -1) {
2576
118k
        length = strlen(str);
2577
118k
    }
2578
67.0k
    else {
2579
67.0k
        length = 0;
2580
374k
        while (length < precision && str[length]) {
2581
307k
            length++;
2582
307k
        }
2583
67.0k
        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
3.67k
            pconsumed = &length;
2590
3.67k
        }
2591
67.0k
    }
2592
2593
185k
    if (width < 0) {
2594
185k
        return _PyUnicode_DecodeUTF8Writer(writer, str, length,
2595
185k
                                           _Py_ERROR_REPLACE, "replace", pconsumed);
2596
185k
    }
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
7.23k
#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
258k
{
2648
258k
    const char *p;
2649
258k
    Py_ssize_t len;
2650
258k
    int flags = 0;
2651
258k
    Py_ssize_t width;
2652
258k
    Py_ssize_t precision;
2653
2654
258k
    p = f;
2655
258k
    f++;
2656
258k
    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
260k
    while (1) {
2669
260k
        switch (*f++) {
2670
0
        case '-': flags |= F_LJUST; continue;
2671
2.38k
        case '0': flags |= F_ZERO; continue;
2672
0
        case '#': flags |= F_ALT; continue;
2673
260k
        }
2674
258k
        f--;
2675
258k
        break;
2676
260k
    }
2677
2678
    /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2679
258k
    width = -1;
2680
258k
    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
258k
    else if (Py_ISDIGIT((unsigned)*f)) {
2689
2.38k
        width = *f - '0';
2690
2.38k
        f++;
2691
2.38k
        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
2.38k
    }
2701
258k
    precision = -1;
2702
258k
    if (*f == '.') {
2703
71.8k
        f++;
2704
71.8k
        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
71.8k
        else if (Py_ISDIGIT((unsigned)*f)) {
2712
71.8k
            precision = (*f - '0');
2713
71.8k
            f++;
2714
207k
            while (Py_ISDIGIT((unsigned)*f)) {
2715
135k
                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
135k
                precision = (precision * 10) + (*f - '0');
2721
135k
                f++;
2722
135k
            }
2723
71.8k
        }
2724
71.8k
    }
2725
2726
258k
    int sizemod = 0;
2727
258k
    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
258k
    else if (*f == 'z') {
2738
3.61k
        sizemod = F_SIZE;
2739
3.61k
        ++f;
2740
3.61k
    }
2741
254k
    else if (*f == 't') {
2742
0
        sizemod = F_PTRDIFF;
2743
0
        ++f;
2744
0
    }
2745
254k
    else if (*f == 'j') {
2746
0
        sizemod = F_INTMAX;
2747
0
        ++f;
2748
0
    }
2749
258k
    if (f[0] != '\0' && f[1] == '\0')
2750
45.0k
        writer->overallocate = 0;
2751
2752
258k
    switch (*f) {
2753
15.7k
    case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
2754
15.7k
        break;
2755
20.2k
    case 'c': case 'p':
2756
20.2k
        if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
2757
20.2k
        break;
2758
184k
    case 's':
2759
185k
    case 'V':
2760
185k
        if (sizemod && sizemod != F_LONG) goto invalid_format;
2761
185k
        break;
2762
185k
    default:
2763
37.4k
        if (sizemod) goto invalid_format;
2764
37.4k
        break;
2765
258k
    }
2766
2767
258k
    switch (*f) {
2768
20.2k
    case 'c':
2769
20.2k
    {
2770
20.2k
        int ordinal = va_arg(*vargs, int);
2771
20.2k
        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
20.2k
        if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
2777
0
            return NULL;
2778
20.2k
        break;
2779
20.2k
    }
2780
2781
20.2k
    case 'd': case 'i':
2782
15.7k
    case 'o': case 'u': case 'x': case 'X':
2783
15.7k
    {
2784
15.7k
        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
15.7k
        #define SPRINT(SIZE_SPEC, FMT_CHAR, TYPE) \
2798
15.7k
            sprintf(buffer, "%" SIZE_SPEC FMT_CHAR, va_arg(*vargs, TYPE))
2799
2800
        // One inner switch to handle all format variants
2801
15.7k
        #define DO_SPRINTS(SIZE_SPEC, SIGNED_TYPE, UNSIGNED_TYPE)             \
2802
15.7k
            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
1.64k
                case 'x': len = SPRINT(SIZE_SPEC, "x", UNSIGNED_TYPE); break; \
2806
972
                case 'X': len = SPRINT(SIZE_SPEC, "X", UNSIGNED_TYPE); break; \
2807
13.1k
                default:  len = SPRINT(SIZE_SPEC, "d", SIGNED_TYPE); break;   \
2808
15.7k
            }
2809
2810
        // Outer switch to handle all the sizes/types
2811
15.7k
        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
3.61k
            case F_SIZE:     DO_SPRINTS("z", Py_ssize_t, size_t); break;
2815
0
            case F_PTRDIFF:  DO_SPRINTS("t", ptrdiff_t, ptrdiff_t); break;
2816
0
            case F_INTMAX:   DO_SPRINTS("j", intmax_t, uintmax_t); break;
2817
12.1k
            default:         DO_SPRINTS("", int, unsigned int); break;
2818
15.7k
        }
2819
15.7k
        #undef SPRINT
2820
15.7k
        #undef DO_SPRINTS
2821
2822
15.7k
        assert(len >= 0);
2823
2824
15.7k
        int sign = (buffer[0] == '-');
2825
15.7k
        len -= sign;
2826
2827
15.7k
        precision = Py_MAX(precision, len);
2828
15.7k
        width = Py_MAX(width, precision + sign);
2829
15.7k
        if ((flags & F_ZERO) && !(flags & F_LJUST)) {
2830
2.38k
            precision = width - sign;
2831
2.38k
        }
2832
2833
15.7k
        Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
2834
15.7k
        Py_ssize_t zeropad = Py_MAX(precision - len, 0);
2835
2836
15.7k
        if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1)
2837
0
            return NULL;
2838
2839
15.7k
        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
15.7k
        if (sign) {
2846
0
            if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
2847
0
                return NULL;
2848
0
        }
2849
2850
15.7k
        if (zeropad) {
2851
840
            if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
2852
0
                return NULL;
2853
840
            writer->pos += zeropad;
2854
840
        }
2855
2856
15.7k
        if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
2857
0
            return NULL;
2858
2859
15.7k
        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
15.7k
        break;
2865
15.7k
    }
2866
2867
15.7k
    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
184k
    case 's':
2891
184k
    {
2892
184k
        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
184k
        else {
2898
            /* UTF-8 */
2899
184k
            const char *s = va_arg(*vargs, const char*);
2900
184k
            if (unicode_fromformat_write_utf8(writer, s, width, precision, flags) < 0)
2901
0
                return NULL;
2902
184k
        }
2903
184k
        break;
2904
184k
    }
2905
2906
184k
    case 'U':
2907
30.7k
    {
2908
30.7k
        PyObject *obj = va_arg(*vargs, PyObject *);
2909
30.7k
        assert(obj && _PyUnicode_CHECK(obj));
2910
2911
30.7k
        if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
2912
0
            return NULL;
2913
30.7k
        break;
2914
30.7k
    }
2915
2916
30.7k
    case 'V':
2917
238
    {
2918
238
        PyObject *obj = va_arg(*vargs, PyObject *);
2919
238
        const char *str;
2920
238
        const wchar_t *wstr;
2921
238
        if (sizemod) {
2922
0
            wstr = va_arg(*vargs, const wchar_t*);
2923
0
        }
2924
238
        else {
2925
238
            str = va_arg(*vargs, const char *);
2926
238
        }
2927
238
        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
238
        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
238
        else {
2938
238
            assert(str != NULL);
2939
238
            if (unicode_fromformat_write_utf8(writer, str, width, precision, flags) < 0)
2940
0
                return NULL;
2941
238
        }
2942
238
        break;
2943
238
    }
2944
2945
238
    case 'S':
2946
65
    {
2947
65
        PyObject *obj = va_arg(*vargs, PyObject *);
2948
65
        PyObject *str;
2949
65
        assert(obj);
2950
65
        str = PyObject_Str(obj);
2951
65
        if (!str)
2952
0
            return NULL;
2953
65
        if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
2954
0
            Py_DECREF(str);
2955
0
            return NULL;
2956
0
        }
2957
65
        Py_DECREF(str);
2958
65
        break;
2959
65
    }
2960
2961
6.57k
    case 'R':
2962
6.57k
    {
2963
6.57k
        PyObject *obj = va_arg(*vargs, PyObject *);
2964
6.57k
        PyObject *repr;
2965
6.57k
        assert(obj);
2966
6.57k
        repr = PyObject_Repr(obj);
2967
6.57k
        if (!repr)
2968
0
            return NULL;
2969
6.57k
        if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
2970
0
            Py_DECREF(repr);
2971
0
            return NULL;
2972
0
        }
2973
6.57k
        Py_DECREF(repr);
2974
6.57k
        break;
2975
6.57k
    }
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
258k
    }
3054
3055
258k
    f++;
3056
258k
    return f;
3057
258k
}
3058
3059
static int
3060
unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
3061
161k
{
3062
161k
    Py_ssize_t len = strlen(format);
3063
161k
    writer->min_length += len + 100;
3064
161k
    writer->overallocate = 1;
3065
3066
    // Copy varags to be able to pass a reference to a subfunction.
3067
161k
    va_list vargs2;
3068
161k
    va_copy(vargs2, vargs);
3069
3070
    // _PyUnicodeWriter_WriteASCIIString() below requires the format string
3071
    // to be encoded to ASCII.
3072
161k
    int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)format, (Py_UCS1*)format + len) < 128);
3073
161k
    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
723k
    for (const char *f = format; *f; ) {
3084
561k
        if (*f == '%') {
3085
258k
            f = unicode_fromformat_arg(writer, f, &vargs2);
3086
258k
            if (f == NULL)
3087
0
                goto fail;
3088
258k
        }
3089
302k
        else {
3090
302k
            const char *p = strchr(f, '%');
3091
302k
            if (p != NULL) {
3092
186k
                len = p - f;
3093
186k
            }
3094
116k
            else {
3095
116k
                len = strlen(f);
3096
116k
                writer->overallocate = 0;
3097
116k
            }
3098
3099
302k
            if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
3100
0
                goto fail;
3101
0
            }
3102
302k
            f += len;
3103
302k
        }
3104
561k
    }
3105
161k
    va_end(vargs2);
3106
161k
    return 0;
3107
3108
0
  fail:
3109
0
    va_end(vargs2);
3110
0
    return -1;
3111
161k
}
3112
3113
PyObject *
3114
PyUnicode_FromFormatV(const char *format, va_list vargs)
3115
161k
{
3116
161k
    _PyUnicodeWriter writer;
3117
161k
    _PyUnicodeWriter_Init(&writer);
3118
3119
161k
    if (unicode_from_format(&writer, format, vargs) < 0) {
3120
0
        _PyUnicodeWriter_Dealloc(&writer);
3121
0
        return NULL;
3122
0
    }
3123
161k
    return _PyUnicodeWriter_Finish(&writer);
3124
161k
}
3125
3126
PyObject *
3127
PyUnicode_FromFormat(const char *format, ...)
3128
51.1k
{
3129
51.1k
    PyObject* ret;
3130
51.1k
    va_list vargs;
3131
3132
51.1k
    va_start(vargs, format);
3133
51.1k
    ret = PyUnicode_FromFormatV(format, vargs);
3134
51.1k
    va_end(vargs);
3135
51.1k
    return ret;
3136
51.1k
}
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.49k
{
3166
1.49k
    Py_ssize_t res;
3167
3168
1.49k
    assert(unicode != NULL);
3169
1.49k
    assert(_PyUnicode_CHECK(unicode));
3170
3171
1.49k
    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.49k
}
3185
3186
static void
3187
unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3188
1.49k
{
3189
1.49k
    assert(unicode != NULL);
3190
1.49k
    assert(_PyUnicode_CHECK(unicode));
3191
3192
2.99k
    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.99k
    if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3198
1.49k
        const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3199
63.7k
        for (; size--; ++s, ++w) {
3200
62.2k
            *w = *s;
3201
62.2k
        }
3202
1.49k
    }
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.49k
}
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
133
{
3246
133
    Py_ssize_t res;
3247
3248
133
    if (unicode == NULL) {
3249
0
        PyErr_BadInternalCall();
3250
0
        return -1;
3251
0
    }
3252
133
    if (!PyUnicode_Check(unicode)) {
3253
0
        PyErr_BadArgument();
3254
0
        return -1;
3255
0
    }
3256
3257
133
    res = unicode_get_widechar_size(unicode);
3258
133
    if (w == NULL) {
3259
0
        return res + 1;
3260
0
    }
3261
3262
133
    if (size > res) {
3263
133
        size = res + 1;
3264
133
    }
3265
0
    else {
3266
0
        res = size;
3267
0
    }
3268
133
    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
133
    return res;
3281
133
}
3282
3283
wchar_t*
3284
PyUnicode_AsWideCharString(PyObject *unicode,
3285
                           Py_ssize_t *size)
3286
1.36k
{
3287
1.36k
    wchar_t *buffer;
3288
1.36k
    Py_ssize_t buflen;
3289
3290
1.36k
    if (unicode == NULL) {
3291
0
        PyErr_BadInternalCall();
3292
0
        return NULL;
3293
0
    }
3294
1.36k
    if (!PyUnicode_Check(unicode)) {
3295
0
        PyErr_BadArgument();
3296
0
        return NULL;
3297
0
    }
3298
3299
1.36k
    buflen = unicode_get_widechar_size(unicode);
3300
1.36k
    buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
3301
1.36k
    if (buffer == NULL) {
3302
0
        PyErr_NoMemory();
3303
0
        return NULL;
3304
0
    }
3305
1.36k
    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.36k
    if (size != NULL) {
3318
840
        *size = buflen;
3319
840
    }
3320
525
    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.36k
    return buffer;
3327
1.36k
}
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
307k
{
3382
307k
    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
307k
    return unicode_char((Py_UCS4)ordinal);
3389
307k
}
3390
3391
PyObject *
3392
PyUnicode_FromObject(PyObject *obj)
3393
98.2k
{
3394
    /* XXX Perhaps we should make this API an alias of
3395
       PyObject_Str() instead ?! */
3396
98.2k
    if (PyUnicode_CheckExact(obj)) {
3397
98.2k
        return Py_NewRef(obj);
3398
98.2k
    }
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
183k
{
3415
183k
    Py_buffer buffer;
3416
183k
    PyObject *v;
3417
3418
183k
    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
183k
    if (PyBytes_Check(obj)) {
3425
183k
        if (PyBytes_GET_SIZE(obj) == 0) {
3426
83.6k
            if (unicode_check_encoding_errors(encoding, errors) < 0) {
3427
0
                return NULL;
3428
0
            }
3429
83.6k
            _Py_RETURN_UNICODE_EMPTY();
3430
83.6k
        }
3431
100k
        return PyUnicode_Decode(
3432
100k
                PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3433
100k
                encoding, errors);
3434
183k
    }
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
166k
{
3472
166k
    const char *e;
3473
166k
    char *l;
3474
166k
    char *l_end;
3475
166k
    int punct;
3476
3477
166k
    assert(encoding != NULL);
3478
3479
166k
    e = encoding;
3480
166k
    l = lower;
3481
166k
    l_end = &lower[lower_len - 1];
3482
166k
    punct = 0;
3483
1.13M
    while (1) {
3484
1.13M
        char c = *e;
3485
1.13M
        if (c == 0) {
3486
166k
            break;
3487
166k
        }
3488
3489
970k
        if (Py_ISALNUM(c) || c == '.') {
3490
951k
            if (punct && l != lower) {
3491
15.8k
                if (l == l_end) {
3492
3
                    return 0;
3493
3
                }
3494
15.8k
                *l++ = '_';
3495
15.8k
            }
3496
951k
            punct = 0;
3497
3498
951k
            if (l == l_end) {
3499
65
                return 0;
3500
65
            }
3501
951k
            *l++ = to_lower ? Py_TOLOWER(c) : c;
3502
951k
        }
3503
18.7k
        else {
3504
18.7k
            punct = 1;
3505
18.7k
        }
3506
3507
970k
        e++;
3508
970k
    }
3509
166k
    *l = '\0';
3510
166k
    return 1;
3511
166k
}
3512
3513
PyObject *
3514
PyUnicode_Decode(const char *s,
3515
                 Py_ssize_t size,
3516
                 const char *encoding,
3517
                 const char *errors)
3518
110k
{
3519
110k
    PyObject *buffer = NULL, *unicode;
3520
110k
    Py_buffer info;
3521
110k
    char buflower[11];   /* strlen("iso-8859-1\0") == 11, longest shortcut */
3522
3523
110k
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3524
0
        return NULL;
3525
0
    }
3526
3527
110k
    if (size == 0) {
3528
2
        _Py_RETURN_UNICODE_EMPTY();
3529
2
    }
3530
3531
110k
    if (encoding == NULL) {
3532
0
        return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3533
0
    }
3534
3535
    /* Shortcuts for common default encodings */
3536
110k
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3537
110k
        char *lower = buflower;
3538
3539
        /* Fast paths */
3540
110k
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3541
13.2k
            lower += 3;
3542
13.2k
            if (*lower == '_') {
3543
                /* Match "utf8" and "utf_8" */
3544
13.2k
                lower++;
3545
13.2k
            }
3546
3547
13.2k
            if (lower[0] == '8' && lower[1] == 0) {
3548
11.6k
                return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3549
11.6k
            }
3550
1.62k
            else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3551
102
                return PyUnicode_DecodeUTF16(s, size, errors, 0);
3552
102
            }
3553
1.52k
            else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3554
20
                return PyUnicode_DecodeUTF32(s, size, errors, 0);
3555
20
            }
3556
13.2k
        }
3557
96.8k
        else {
3558
96.8k
            if (strcmp(lower, "ascii") == 0
3559
68.5k
                || strcmp(lower, "us_ascii") == 0) {
3560
68.5k
                return PyUnicode_DecodeASCII(s, size, errors);
3561
68.5k
            }
3562
    #ifdef MS_WINDOWS
3563
            else if (strcmp(lower, "mbcs") == 0) {
3564
                return PyUnicode_DecodeMBCS(s, size, errors);
3565
            }
3566
    #endif
3567
28.2k
            else if (strcmp(lower, "latin1") == 0
3568
23.4k
                     || strcmp(lower, "latin_1") == 0
3569
23.4k
                     || strcmp(lower, "iso_8859_1") == 0
3570
23.4k
                     || strcmp(lower, "iso8859_1") == 0) {
3571
4.80k
                return PyUnicode_DecodeLatin1(s, size, errors);
3572
4.80k
            }
3573
96.8k
        }
3574
110k
    }
3575
3576
    /* Decode via the codec registry */
3577
25.0k
    buffer = NULL;
3578
25.0k
    if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
3579
0
        goto onError;
3580
25.0k
    buffer = PyMemoryView_FromBuffer(&info);
3581
25.0k
    if (buffer == NULL)
3582
0
        goto onError;
3583
25.0k
    unicode = _PyCodec_DecodeText(buffer, encoding, errors);
3584
25.0k
    if (unicode == NULL)
3585
2.61k
        goto onError;
3586
22.3k
    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
22.3k
    Py_DECREF(buffer);
3596
22.3k
    return unicode_result(unicode);
3597
3598
2.61k
  onError:
3599
2.61k
    Py_XDECREF(buffer);
3600
2.61k
    return NULL;
3601
22.3k
}
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
210
{
3684
210
    Py_ssize_t wlen;
3685
210
    wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3686
210
    if (wstr == NULL) {
3687
0
        return NULL;
3688
0
    }
3689
3690
210
    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
210
    char *str;
3697
210
    size_t error_pos;
3698
210
    const char *reason;
3699
210
    int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
3700
210
                                 current_locale, error_handler);
3701
210
    PyMem_Free(wstr);
3702
3703
210
    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
210
    PyObject *bytes = PyBytes_FromString(str);
3726
210
    PyMem_RawFree(str);
3727
210
    return bytes;
3728
210
}
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
7.35k
{
3740
7.35k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3741
7.35k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3742
7.35k
    if (fs_codec->utf8) {
3743
7.14k
        return unicode_encode_utf8(unicode,
3744
7.14k
                                   fs_codec->error_handler,
3745
7.14k
                                   fs_codec->errors);
3746
7.14k
    }
3747
210
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3748
210
    else if (fs_codec->encoding) {
3749
0
        return PyUnicode_AsEncodedString(unicode,
3750
0
                                         fs_codec->encoding,
3751
0
                                         fs_codec->errors);
3752
0
    }
3753
210
#endif
3754
210
    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
210
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3759
210
        const wchar_t *filesystem_errors = config->filesystem_errors;
3760
210
        assert(filesystem_errors != NULL);
3761
210
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3762
210
        assert(errors != _Py_ERROR_UNKNOWN);
3763
#ifdef _Py_FORCE_UTF8_FS_ENCODING
3764
        return unicode_encode_utf8(unicode, errors, NULL);
3765
#else
3766
210
        return unicode_encode_locale(unicode, errors, 0);
3767
210
#endif
3768
210
    }
3769
7.35k
}
3770
3771
PyObject *
3772
PyUnicode_AsEncodedString(PyObject *unicode,
3773
                          const char *encoding,
3774
                          const char *errors)
3775
55.6k
{
3776
55.6k
    PyObject *v;
3777
55.6k
    char buflower[11];   /* strlen("iso_8859_1\0") == 11, longest shortcut */
3778
3779
55.6k
    if (!PyUnicode_Check(unicode)) {
3780
0
        PyErr_BadArgument();
3781
0
        return NULL;
3782
0
    }
3783
3784
55.6k
    if (unicode_check_encoding_errors(encoding, errors) < 0) {
3785
0
        return NULL;
3786
0
    }
3787
3788
55.6k
    if (encoding == NULL) {
3789
0
        return _PyUnicode_AsUTF8String(unicode, errors);
3790
0
    }
3791
3792
    /* Shortcuts for common default encodings */
3793
55.6k
    if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower), 1)) {
3794
55.6k
        char *lower = buflower;
3795
3796
        /* Fast paths */
3797
55.6k
        if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3798
63
            lower += 3;
3799
63
            if (*lower == '_') {
3800
                /* Match "utf8" and "utf_8" */
3801
63
                lower++;
3802
63
            }
3803
3804
63
            if (lower[0] == '8' && lower[1] == 0) {
3805
63
                return _PyUnicode_AsUTF8String(unicode, errors);
3806
63
            }
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
63
        }
3814
55.5k
        else {
3815
55.5k
            if (strcmp(lower, "ascii") == 0
3816
37.8k
                || strcmp(lower, "us_ascii") == 0) {
3817
37.8k
                return _PyUnicode_AsASCIIString(unicode, errors);
3818
37.8k
            }
3819
#ifdef MS_WINDOWS
3820
            else if (strcmp(lower, "mbcs") == 0) {
3821
                return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3822
            }
3823
#endif
3824
17.6k
            else if (strcmp(lower, "latin1") == 0 ||
3825
17.6k
                     strcmp(lower, "latin_1") == 0 ||
3826
17.6k
                     strcmp(lower, "iso_8859_1") == 0 ||
3827
17.6k
                     strcmp(lower, "iso8859_1") == 0) {
3828
0
                return _PyUnicode_AsLatin1String(unicode, errors);
3829
0
            }
3830
55.5k
        }
3831
55.6k
    }
3832
3833
    /* Encode via the codec registry */
3834
17.6k
    v = _PyCodec_EncodeText(unicode, encoding, errors);
3835
17.6k
    if (v == NULL)
3836
0
        return NULL;
3837
3838
    /* The normal path */
3839
17.6k
    if (PyBytes_Check(v))
3840
17.6k
        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
7.23k
{
3909
7.23k
    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
7.23k
    wchar_t *wstr;
3915
7.23k
    size_t wlen;
3916
7.23k
    const char *reason;
3917
7.23k
    int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
3918
7.23k
                                 current_locale, errors);
3919
7.23k
    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
7.23k
    PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3942
7.23k
    PyMem_RawFree(wstr);
3943
7.23k
    return unicode;
3944
7.23k
}
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
7.21k
{
3957
7.21k
    Py_ssize_t size = (Py_ssize_t)strlen(str);
3958
7.21k
    _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3959
7.21k
    return unicode_decode_locale(str, size, error_handler, 1);
3960
7.21k
}
3961
3962
3963
PyObject*
3964
24.5k
PyUnicode_DecodeFSDefault(const char *s) {
3965
24.5k
    Py_ssize_t size = (Py_ssize_t)strlen(s);
3966
24.5k
    return PyUnicode_DecodeFSDefaultAndSize(s, size);
3967
24.5k
}
3968
3969
PyObject*
3970
PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3971
30.6k
{
3972
30.6k
    PyInterpreterState *interp = _PyInterpreterState_GET();
3973
30.6k
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3974
30.6k
    if (fs_codec->utf8) {
3975
30.6k
        return unicode_decode_utf8(s, size,
3976
30.6k
                                   fs_codec->error_handler,
3977
30.6k
                                   fs_codec->errors,
3978
30.6k
                                   NULL);
3979
30.6k
    }
3980
21
#ifndef _Py_FORCE_UTF8_FS_ENCODING
3981
21
    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
21
#endif
3987
21
    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
21
        const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3992
21
        const wchar_t *filesystem_errors = config->filesystem_errors;
3993
21
        assert(filesystem_errors != NULL);
3994
21
        _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3995
21
        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
21
        return unicode_decode_locale(s, size, errors, 0);
4000
21
#endif
4001
21
    }
4002
30.6k
}
4003
4004
4005
int
4006
PyUnicode_FSConverter(PyObject* arg, void* addr)
4007
5.79k
{
4008
5.79k
    PyObject *path = NULL;
4009
5.79k
    PyObject *output = NULL;
4010
5.79k
    Py_ssize_t size;
4011
5.79k
    const char *data;
4012
5.79k
    if (arg == NULL) {
4013
0
        Py_DECREF(*(PyObject**)addr);
4014
0
        *(PyObject**)addr = NULL;
4015
0
        return 1;
4016
0
    }
4017
5.79k
    path = PyOS_FSPath(arg);
4018
5.79k
    if (path == NULL) {
4019
0
        return 0;
4020
0
    }
4021
5.79k
    if (PyBytes_Check(path)) {
4022
0
        output = path;
4023
0
    }
4024
5.79k
    else {  // PyOS_FSPath() guarantees its returned value is bytes or str.
4025
5.79k
        output = PyUnicode_EncodeFSDefault(path);
4026
5.79k
        Py_DECREF(path);
4027
5.79k
        if (!output) {
4028
0
            return 0;
4029
0
        }
4030
5.79k
        assert(PyBytes_Check(output));
4031
5.79k
    }
4032
4033
5.79k
    size = PyBytes_GET_SIZE(output);
4034
5.79k
    data = PyBytes_AS_STRING(output);
4035
5.79k
    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
5.79k
    *(PyObject**)addr = output;
4041
5.79k
    return Py_CLEANUP_SUPPORTED;
4042
5.79k
}
4043
4044
4045
int
4046
PyUnicode_FSDecoder(PyObject* arg, void* addr)
4047
37
{
4048
37
    if (arg == NULL) {
4049
0
        Py_DECREF(*(PyObject**)addr);
4050
0
        *(PyObject**)addr = NULL;
4051
0
        return 1;
4052
0
    }
4053
4054
37
    PyObject *path = PyOS_FSPath(arg);
4055
37
    if (path == NULL) {
4056
0
        return 0;
4057
0
    }
4058
4059
37
    PyObject *output = NULL;
4060
37
    if (PyUnicode_Check(path)) {
4061
37
        output = path;
4062
37
    }
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
37
    if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
4080
37
                 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
37
    *(PyObject**)addr = output;
4086
37
    return Py_CLEANUP_SUPPORTED;
4087
37
}
4088
4089
4090
static int unicode_fill_utf8(PyObject *unicode);
4091
4092
4093
static int
4094
unicode_ensure_utf8(PyObject *unicode)
4095
633k
{
4096
633k
    int err = 0;
4097
633k
    if (PyUnicode_UTF8(unicode) == NULL) {
4098
11.0k
        Py_BEGIN_CRITICAL_SECTION(unicode);
4099
11.0k
        if (PyUnicode_UTF8(unicode) == NULL) {
4100
11.0k
            err = unicode_fill_utf8(unicode);
4101
11.0k
        }
4102
11.0k
        Py_END_CRITICAL_SECTION();
4103
11.0k
    }
4104
633k
    return err;
4105
633k
}
4106
4107
const char *
4108
PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
4109
633k
{
4110
633k
    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
633k
    if (unicode_ensure_utf8(unicode) == -1) {
4119
0
        if (psize) {
4120
0
            *psize = -1;
4121
0
        }
4122
0
        return NULL;
4123
0
    }
4124
4125
633k
    if (psize) {
4126
461k
        *psize = PyUnicode_UTF8_LENGTH(unicode);
4127
461k
    }
4128
633k
    return PyUnicode_UTF8(unicode);
4129
633k
}
4130
4131
const char *
4132
PyUnicode_AsUTF8(PyObject *unicode)
4133
171k
{
4134
171k
    return PyUnicode_AsUTF8AndSize(unicode, NULL);
4135
171k
}
4136
4137
const char *
4138
_PyUnicode_AsUTF8NoNUL(PyObject *unicode)
4139
160k
{
4140
160k
    Py_ssize_t size;
4141
160k
    const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
4142
160k
    if (s && strlen(s) != (size_t)size) {
4143
0
        PyErr_SetString(PyExc_ValueError, "embedded null character");
4144
0
        return NULL;
4145
0
    }
4146
160k
    return s;
4147
160k
}
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
629
{
4168
629
    if (!PyUnicode_Check(unicode)) {
4169
0
        PyErr_BadArgument();
4170
0
        return -1;
4171
0
    }
4172
629
    return PyUnicode_GET_LENGTH(unicode);
4173
629
}
4174
4175
Py_UCS4
4176
PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4177
29
{
4178
29
    const void *data;
4179
29
    int kind;
4180
4181
29
    if (!PyUnicode_Check(unicode)) {
4182
0
        PyErr_BadArgument();
4183
0
        return (Py_UCS4)-1;
4184
0
    }
4185
29
    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
29
    data = PyUnicode_DATA(unicode);
4190
29
    kind = PyUnicode_KIND(unicode);
4191
29
    return PyUnicode_READ(kind, data, index);
4192
29
}
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
101k
{
4230
101k
    if (*exceptionObject == NULL) {
4231
6.26k
        *exceptionObject = PyUnicodeDecodeError_Create(
4232
6.26k
            encoding, input, length, startpos, endpos, reason);
4233
6.26k
    }
4234
95.5k
    else {
4235
95.5k
        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4236
0
            goto onError;
4237
95.5k
        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4238
0
            goto onError;
4239
95.5k
        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4240
0
            goto onError;
4241
95.5k
    }
4242
101k
    return;
4243
4244
101k
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
101k
{
4383
101k
    static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
4384
4385
101k
    PyObject *restuple = NULL;
4386
101k
    PyObject *repunicode = NULL;
4387
101k
    Py_ssize_t insize;
4388
101k
    Py_ssize_t newpos;
4389
101k
    Py_ssize_t replen;
4390
101k
    Py_ssize_t remain;
4391
101k
    PyObject *inputobj = NULL;
4392
101k
    int need_to_grow = 0;
4393
101k
    const char *new_inptr;
4394
4395
101k
    if (*errorHandler == NULL) {
4396
6.26k
        *errorHandler = PyCodec_LookupError(errors);
4397
6.26k
        if (*errorHandler == NULL)
4398
0
            goto onError;
4399
6.26k
    }
4400
4401
101k
    make_decode_exception(exceptionObject,
4402
101k
        encoding,
4403
101k
        *input, *inend - *input,
4404
101k
        *startinpos, *endinpos,
4405
101k
        reason);
4406
101k
    if (*exceptionObject == NULL)
4407
0
        goto onError;
4408
4409
101k
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
4410
101k
    if (restuple == NULL)
4411
5.85k
        goto onError;
4412
95.9k
    if (!PyTuple_Check(restuple)) {
4413
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
4414
0
        goto onError;
4415
0
    }
4416
95.9k
    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
95.9k
    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4422
95.9k
    if (!inputobj)
4423
0
        goto onError;
4424
95.9k
    remain = *inend - *input - *endinpos;
4425
95.9k
    *input = PyBytes_AS_STRING(inputobj);
4426
95.9k
    insize = PyBytes_GET_SIZE(inputobj);
4427
95.9k
    *inend = *input + insize;
4428
    /* we can DECREF safely, as the exception has another reference,
4429
       so the object won't go away. */
4430
95.9k
    Py_DECREF(inputobj);
4431
4432
95.9k
    if (newpos<0)
4433
0
        newpos = insize+newpos;
4434
95.9k
    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
95.9k
    replen = PyUnicode_GET_LENGTH(repunicode);
4440
95.9k
    if (replen > 1) {
4441
0
        writer->min_length += replen - 1;
4442
0
        need_to_grow = 1;
4443
0
    }
4444
95.9k
    new_inptr = *input + newpos;
4445
95.9k
    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
60
        writer->min_length += *inend - new_inptr - remain;
4452
60
        need_to_grow = 1;
4453
60
    }
4454
95.9k
    if (need_to_grow) {
4455
60
        writer->overallocate = 1;
4456
60
        if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
4457
60
                            PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4458
0
            goto onError;
4459
60
    }
4460
95.9k
    if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
4461
0
        goto onError;
4462
4463
95.9k
    *endinpos = newpos;
4464
95.9k
    *inptr = new_inptr;
4465
4466
    /* we made it! */
4467
95.9k
    Py_DECREF(restuple);
4468
95.9k
    return 0;
4469
4470
5.85k
  onError:
4471
5.85k
    Py_XDECREF(restuple);
4472
5.85k
    return -1;
4473
95.9k
}
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
18.6k
    (((c) >= 'A' && (c) <= 'Z') ||     \
4485
18.6k
     ((c) >= 'a' && (c) <= 'z') ||     \
4486
18.6k
     ((c) >= '0' && (c) <= '9') ||     \
4487
18.6k
     (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
15.6k
    (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' :                           \
4493
15.6k
     ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 :                      \
4494
14.9k
     ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 :                      \
4495
11.3k
     (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
98.5k
    ((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
170
{
4574
170
    const char *starts = s;
4575
170
    Py_ssize_t startinpos;
4576
170
    Py_ssize_t endinpos;
4577
170
    const char *e;
4578
170
    _PyUnicodeWriter writer;
4579
170
    const char *errmsg = "";
4580
170
    int inShift = 0;
4581
170
    Py_ssize_t shiftOutStart;
4582
170
    unsigned int base64bits = 0;
4583
170
    unsigned long base64buffer = 0;
4584
170
    Py_UCS4 surrogate = 0;
4585
170
    PyObject *errorHandler = NULL;
4586
170
    PyObject *exc = NULL;
4587
4588
170
    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
170
    _PyUnicodeWriter_Init(&writer);
4596
170
    writer.min_length = size;
4597
4598
170
    shiftOutStart = 0;
4599
170
    e = s + size;
4600
4601
117k
    while (s < e) {
4602
117k
        Py_UCS4 ch;
4603
117k
      restart:
4604
117k
        ch = (unsigned char) *s;
4605
4606
117k
        if (inShift) { /* in a base-64 section */
4607
17.1k
            if (IS_BASE64(ch)) { /* consume a base-64 character */
4608
15.6k
                base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4609
15.6k
                base64bits += 6;
4610
15.6k
                s++;
4611
15.6k
                if (base64bits >= 16) {
4612
                    /* we have enough bits for a UTF-16 value */
4613
5.76k
                    Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
4614
5.76k
                    base64bits -= 16;
4615
5.76k
                    base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4616
5.76k
                    assert(outCh <= 0xffff);
4617
5.76k
                    if (surrogate) {
4618
                        /* expecting a second surrogate */
4619
516
                        if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4620
309
                            Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
4621
309
                            if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
4622
0
                                goto onError;
4623
309
                            surrogate = 0;
4624
309
                            continue;
4625
309
                        }
4626
207
                        else {
4627
207
                            if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4628
0
                                goto onError;
4629
207
                            surrogate = 0;
4630
207
                        }
4631
516
                    }
4632
5.45k
                    if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
4633
                        /* first surrogate */
4634
829
                        surrogate = outCh;
4635
829
                    }
4636
4.62k
                    else {
4637
4.62k
                        if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
4638
0
                            goto onError;
4639
4.62k
                    }
4640
5.45k
                }
4641
15.6k
            }
4642
1.49k
            else { /* now leaving a base-64 section */
4643
1.49k
                inShift = 0;
4644
1.49k
                if (base64bits > 0) { /* left-over bits */
4645
545
                    if (base64bits >= 6) {
4646
                        /* We've seen at least one base-64 character */
4647
48
                        s++;
4648
48
                        errmsg = "partial character in shift sequence";
4649
48
                        goto utf7Error;
4650
48
                    }
4651
497
                    else {
4652
                        /* Some bits remain; they should be zero */
4653
497
                        if (base64buffer != 0) {
4654
19
                            s++;
4655
19
                            errmsg = "non-zero padding bits in shift sequence";
4656
19
                            goto utf7Error;
4657
19
                        }
4658
497
                    }
4659
545
                }
4660
1.43k
                if (surrogate && DECODE_DIRECT(ch)) {
4661
305
                    if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4662
0
                        goto onError;
4663
305
                }
4664
1.43k
                surrogate = 0;
4665
1.43k
                if (ch == '-') {
4666
                    /* '-' is absorbed; other terminating
4667
                       characters are preserved */
4668
234
                    s++;
4669
234
                }
4670
1.43k
            }
4671
17.1k
        }
4672
100k
        else if ( ch == '+' ) {
4673
2.34k
            startinpos = s-starts;
4674
2.34k
            s++; /* consume '+' */
4675
2.34k
            if (s < e && *s == '-') { /* '+-' encodes '+' */
4676
831
                s++;
4677
831
                if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
4678
0
                    goto onError;
4679
831
            }
4680
1.51k
            else if (s < e && !IS_BASE64(*s)) {
4681
10
                s++;
4682
10
                errmsg = "ill-formed sequence";
4683
10
                goto utf7Error;
4684
10
            }
4685
1.50k
            else { /* begin base64-encoded section */
4686
1.50k
                inShift = 1;
4687
1.50k
                surrogate = 0;
4688
1.50k
                shiftOutStart = writer.pos;
4689
1.50k
                base64bits = 0;
4690
1.50k
                base64buffer = 0;
4691
1.50k
            }
4692
2.34k
        }
4693
98.1k
        else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
4694
98.1k
            s++;
4695
98.1k
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
4696
0
                goto onError;
4697
98.1k
        }
4698
20
        else {
4699
20
            startinpos = s-starts;
4700
20
            s++;
4701
20
            errmsg = "unexpected special character";
4702
20
            goto utf7Error;
4703
20
        }
4704
117k
        continue;
4705
117k
utf7Error:
4706
97
        endinpos = s-starts;
4707
97
        if (unicode_decode_call_errorhandler_writer(
4708
97
                errors, &errorHandler,
4709
97
                "utf7", errmsg,
4710
97
                &starts, &e, &startinpos, &endinpos, &exc, &s,
4711
97
                &writer))
4712
97
            goto onError;
4713
97
    }
4714
4715
    /* end of string */
4716
4717
73
    if (inShift && !consumed) { /* in shift sequence, no more to follow */
4718
        /* if we're in an inconsistent state, that's an error */
4719
9
        inShift = 0;
4720
9
        if (surrogate ||
4721
7
                (base64bits >= 6) ||
4722
6
                (base64bits > 0 && base64buffer != 0)) {
4723
6
            endinpos = size;
4724
6
            if (unicode_decode_call_errorhandler_writer(
4725
6
                    errors, &errorHandler,
4726
6
                    "utf7", "unterminated shift sequence",
4727
6
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
4728
6
                    &writer))
4729
6
                goto onError;
4730
0
            if (s < e)
4731
0
                goto restart;
4732
0
        }
4733
9
    }
4734
4735
    /* return state */
4736
67
    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
67
    Py_XDECREF(errorHandler);
4755
67
    Py_XDECREF(exc);
4756
67
    return _PyUnicodeWriter_Finish(&writer);
4757
4758
103
  onError:
4759
103
    Py_XDECREF(errorHandler);
4760
103
    Py_XDECREF(exc);
4761
103
    _PyUnicodeWriter_Dealloc(&writer);
4762
103
    return NULL;
4763
67
}
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
577k
{
4869
577k
    return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4870
577k
}
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.9M
# define ASCII_CHAR_MASK 0x8080808080808080ULL
4892
// used to count codepoints in UTF-8 string.
4893
28.6M
# define VECTOR_0101     0x0101010101010101ULL
4894
359k
# 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
465k
{
4908
465k
    return __builtin_ctzll((unsigned long long)v);
4909
465k
}
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
4.04M
{
4932
4.04M
    union {
4933
4.04M
        size_t s;
4934
4.04M
        unsigned char b[SIZEOF_SIZE_T];
4935
4.04M
    } u;
4936
4.04M
    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
4.04M
    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
123k
    case 7:
4947
123k
        u.b[6] = p[6];
4948
123k
        _Py_FALLTHROUGH;
4949
207k
    case 6:
4950
207k
        u.b[5] = p[5];
4951
207k
        _Py_FALLTHROUGH;
4952
1.01M
    case 5:
4953
1.01M
        u.b[4] = p[4];
4954
1.01M
        _Py_FALLTHROUGH;
4955
1.01M
#endif
4956
1.84M
    case 4:
4957
1.84M
        u.b[3] = p[3];
4958
1.84M
        _Py_FALLTHROUGH;
4959
2.10M
    case 3:
4960
2.10M
        u.b[2] = p[2];
4961
2.10M
        _Py_FALLTHROUGH;
4962
3.53M
    case 2:
4963
3.53M
        u.b[1] = p[1];
4964
3.53M
        _Py_FALLTHROUGH;
4965
3.72M
    case 1:
4966
3.72M
        u.b[0] = p[0];
4967
3.72M
        break;
4968
317k
    case 0:
4969
317k
        break;
4970
4.04M
    }
4971
4.04M
    return u.s;
4972
4.04M
}
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
4.14M
{
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
4.14M
    const unsigned char *p = start;
4991
4992
4.14M
    if (end - start >= SIZEOF_SIZE_T) {
4993
        // Avoid unaligned read.
4994
1.47M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
4995
1.47M
        size_t u;
4996
1.47M
        memcpy(&u, p, sizeof(size_t));
4997
1.47M
        u &= ASCII_CHAR_MASK;
4998
1.47M
        if (u) {
4999
76.4k
            return (ctz(u) - 7) / 8;
5000
76.4k
        }
5001
1.39M
        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.39M
        const unsigned char *e = end - SIZEOF_SIZE_T;
5013
58.6M
        while (p <= e) {
5014
57.2M
            size_t u = (*(const size_t *)p) & ASCII_CHAR_MASK;
5015
57.2M
            if (u) {
5016
21.2k
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5017
21.2k
                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
21.2k
            }
5024
57.2M
            p += SIZEOF_SIZE_T;
5025
57.2M
        }
5026
1.39M
    }
5027
4.04M
#if PY_LITTLE_ENDIAN && HAVE_CTZ
5028
4.14M
    assert((end - p) < SIZEOF_SIZE_T);
5029
    // we can not use *(const size_t*)p to avoid buffer overrun.
5030
4.04M
    size_t u = load_unaligned(p, end - p) & ASCII_CHAR_MASK;
5031
4.04M
    if (u) {
5032
367k
        return p - start + (ctz(u) - 7) / 8;
5033
367k
    }
5034
3.67M
    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
4.04M
}
5045
5046
static inline int
5047
scalar_utf8_start_char(unsigned int ch)
5048
1.54M
{
5049
    // 0xxxxxxx or 11xxxxxx are first byte.
5050
1.54M
    return (~ch >> 7 | ch >> 6) & 1;
5051
1.54M
}
5052
5053
static inline size_t
5054
vector_utf8_start_chars(size_t v)
5055
28.6M
{
5056
28.6M
    return ((~v >> 7) | (v >> 6)) & VECTOR_0101;
5057
28.6M
}
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
452k
{
5064
452k
    Py_ssize_t len = 0;
5065
5066
452k
    if (end - s >= SIZEOF_SIZE_T) {
5067
348k
        while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
5068
255k
            len += scalar_utf8_start_char(*s++);
5069
255k
        }
5070
5071
273k
        while (s + SIZEOF_SIZE_T <= end) {
5072
179k
            const unsigned char *e = end;
5073
179k
            if (e - s > SIZEOF_SIZE_T * 255) {
5074
110k
                e = s + SIZEOF_SIZE_T * 255;
5075
110k
            }
5076
179k
            Py_ssize_t vstart = 0;
5077
28.8M
            while (s + SIZEOF_SIZE_T <= e) {
5078
28.6M
                size_t v = *(size_t*)s;
5079
28.6M
                size_t vs = vector_utf8_start_chars(v);
5080
28.6M
                vstart += vs;
5081
28.6M
                s += SIZEOF_SIZE_T;
5082
28.6M
            }
5083
179k
            vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF);
5084
179k
            vstart += vstart >> 16;
5085
179k
#if SIZEOF_SIZE_T == 8
5086
179k
            vstart += vstart >> 32;
5087
179k
#endif
5088
179k
            len += vstart & 0x7ff;
5089
179k
        }
5090
93.4k
    }
5091
1.74M
    while (s < end) {
5092
1.29M
        len += scalar_utf8_start_char(*s++);
5093
1.29M
    }
5094
452k
    return len;
5095
452k
}
5096
5097
static Py_ssize_t
5098
ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
5099
333k
{
5100
333k
#if SIZEOF_SIZE_T <= SIZEOF_VOID_P
5101
333k
    if (_Py_IS_ALIGNED(start, ALIGNOF_SIZE_T)
5102
106k
        && _Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T))
5103
89.0k
    {
5104
        /* Fast path, see in STRINGLIB(utf8_decode) for
5105
           an explanation. */
5106
89.0k
        const char *p = start;
5107
89.0k
        Py_UCS1 *q = dest;
5108
3.30M
        while (p + SIZEOF_SIZE_T <= end) {
5109
3.21M
            size_t value = *(const size_t *) p;
5110
3.21M
            if (value & ASCII_CHAR_MASK)
5111
330
                break;
5112
3.21M
            *((size_t *)q) = value;
5113
3.21M
            p += SIZEOF_SIZE_T;
5114
3.21M
            q += SIZEOF_SIZE_T;
5115
3.21M
        }
5116
362k
        while (p < end) {
5117
273k
            if ((unsigned char)*p & 0x80)
5118
444
                break;
5119
273k
            *q++ = *p++;
5120
273k
        }
5121
89.0k
        return p - start;
5122
89.0k
    }
5123
244k
#endif
5124
244k
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)start,
5125
244k
                                         (const unsigned char*)end);
5126
244k
    memcpy(dest, start, pos);
5127
244k
    return pos;
5128
333k
}
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
478k
{
5137
478k
    Py_ssize_t startinpos, endinpos;
5138
478k
    const char *errmsg = "";
5139
478k
    PyObject *error_handler_obj = NULL;
5140
478k
    PyObject *exc = NULL;
5141
5142
612k
    while (s < end) {
5143
605k
        Py_UCS4 ch;
5144
605k
        int kind = writer->kind;
5145
5146
605k
        if (kind == PyUnicode_1BYTE_KIND) {
5147
306k
            if (PyUnicode_IS_ASCII(writer->buffer))
5148
13.2k
                ch = asciilib_utf8_decode(&s, end, writer->data, &writer->pos);
5149
293k
            else
5150
293k
                ch = ucs1lib_utf8_decode(&s, end, writer->data, &writer->pos);
5151
306k
        } else if (kind == PyUnicode_2BYTE_KIND) {
5152
171k
            ch = ucs2lib_utf8_decode(&s, end, writer->data, &writer->pos);
5153
171k
        } else {
5154
127k
            assert(kind == PyUnicode_4BYTE_KIND);
5155
127k
            ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos);
5156
127k
        }
5157
5158
605k
        switch (ch) {
5159
469k
        case 0:
5160
469k
            if (s == end || consumed)
5161
467k
                goto End;
5162
2.54k
            errmsg = "unexpected end of data";
5163
2.54k
            startinpos = s - starts;
5164
2.54k
            endinpos = end - starts;
5165
2.54k
            break;
5166
43.7k
        case 1:
5167
43.7k
            errmsg = "invalid start byte";
5168
43.7k
            startinpos = s - starts;
5169
43.7k
            endinpos = startinpos + 1;
5170
43.7k
            break;
5171
61.4k
        case 2:
5172
61.4k
            if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5173
16
                && (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
61.4k
            _Py_FALLTHROUGH;
5179
68.7k
        case 3:
5180
71.1k
        case 4:
5181
71.1k
            errmsg = "invalid continuation byte";
5182
71.1k
            startinpos = s - starts;
5183
71.1k
            endinpos = startinpos + ch - 1;
5184
71.1k
            break;
5185
21.2k
        default:
5186
            // ch doesn't fit into kind, so change the buffer kind to write
5187
            // the character
5188
21.2k
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
5189
0
                goto onError;
5190
21.2k
            continue;
5191
605k
        }
5192
5193
117k
        if (error_handler == _Py_ERROR_UNKNOWN)
5194
3.36k
            error_handler = _Py_GetErrorHandler(errors);
5195
5196
117k
        switch (error_handler) {
5197
0
        case _Py_ERROR_IGNORE:
5198
0
            s += (endinpos - startinpos);
5199
0
            break;
5200
5201
76.2k
        case _Py_ERROR_REPLACE:
5202
76.2k
            if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0)
5203
0
                goto onError;
5204
76.2k
            s += (endinpos - startinpos);
5205
76.2k
            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
41.1k
        default:
5224
41.1k
            if (unicode_decode_call_errorhandler_writer(
5225
41.1k
                    errors, &error_handler_obj,
5226
41.1k
                    "utf-8", errmsg,
5227
41.1k
                    &starts, &end, &startinpos, &endinpos, &exc, &s,
5228
41.1k
                    writer)) {
5229
4.84k
                goto onError;
5230
4.84k
            }
5231
5232
36.2k
            if (_PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) {
5233
0
                goto onError;
5234
0
            }
5235
117k
        }
5236
117k
    }
5237
5238
473k
End:
5239
473k
    if (consumed)
5240
66
        *consumed = s - starts;
5241
5242
473k
    Py_XDECREF(error_handler_obj);
5243
473k
    Py_XDECREF(exc);
5244
473k
    return 0;
5245
5246
4.84k
onError:
5247
4.84k
    Py_XDECREF(error_handler_obj);
5248
4.84k
    Py_XDECREF(exc);
5249
4.84k
    return -1;
5250
478k
}
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
4.26M
{
5258
4.26M
    if (size == 0) {
5259
113k
        if (consumed) {
5260
0
            *consumed = 0;
5261
0
        }
5262
113k
        _Py_RETURN_UNICODE_EMPTY();
5263
113k
    }
5264
5265
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5266
4.14M
    if (size == 1 && (unsigned char)s[0] < 128) {
5267
251k
        if (consumed) {
5268
0
            *consumed = 1;
5269
0
        }
5270
251k
        return get_latin1_char((unsigned char)s[0]);
5271
251k
    }
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
3.89M
    if (PY_SSIZE_T_MAX - sizeof(PyCompactUnicodeObject) < (size_t)size) {
5276
0
        PyErr_NoMemory();
5277
0
        return NULL;
5278
0
    }
5279
5280
3.89M
    const char *starts = s;
5281
3.89M
    const char *end = s + size;
5282
5283
3.89M
    Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end);
5284
3.89M
    if (pos == size) {  // fast path: ASCII string.
5285
3.43M
        PyObject *u = PyUnicode_New(size, 127);
5286
3.43M
        if (u == NULL) {
5287
0
            return NULL;
5288
0
        }
5289
3.43M
        memcpy(PyUnicode_1BYTE_DATA(u), s, size);
5290
3.43M
        if (consumed) {
5291
11
            *consumed = size;
5292
11
        }
5293
3.43M
        return u;
5294
3.43M
    }
5295
5296
463k
    int maxchr = 127;
5297
463k
    Py_ssize_t maxsize = size;
5298
5299
463k
    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
463k
    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
452k
        maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end);
5312
452k
        if (ch < 0xc4) { // latin1
5313
291k
            maxchr = 0xff;
5314
291k
        }
5315
161k
        else if (ch < 0xf0) { // ucs2
5316
94.1k
            maxchr = 0xffff;
5317
94.1k
        }
5318
66.8k
        else { // ucs4
5319
66.8k
            maxchr = 0x10ffff;
5320
66.8k
        }
5321
452k
    }
5322
463k
    PyObject *u = PyUnicode_New(maxsize, maxchr);
5323
463k
    if (!u) {
5324
0
        return NULL;
5325
0
    }
5326
5327
    // Use _PyUnicodeWriter after fast path is failed.
5328
463k
    _PyUnicodeWriter writer;
5329
463k
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
5330
463k
    if (maxchr <= 255) {
5331
302k
        memcpy(PyUnicode_1BYTE_DATA(u), s, pos);
5332
302k
        s += pos;
5333
302k
        writer.pos = pos;
5334
302k
    }
5335
5336
463k
    if (unicode_decode_utf8_impl(&writer, starts, s, end,
5337
463k
                                 error_handler, errors,
5338
463k
                                 consumed) < 0) {
5339
4.84k
        _PyUnicodeWriter_Dealloc(&writer);
5340
4.84k
        return NULL;
5341
4.84k
    }
5342
458k
    return _PyUnicodeWriter_Finish(&writer);
5343
463k
}
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
336k
{
5353
336k
    if (size == 0) {
5354
59.3k
        if (consumed) {
5355
0
            *consumed = 0;
5356
0
        }
5357
59.3k
        return 0;
5358
59.3k
    }
5359
5360
    // fast path: try ASCII string.
5361
277k
    if (_PyUnicodeWriter_Prepare(writer, size, 127) < 0) {
5362
0
        return -1;
5363
0
    }
5364
5365
277k
    const char *starts = s;
5366
277k
    const char *end = s + size;
5367
277k
    Py_ssize_t decoded = 0;
5368
277k
    Py_UCS1 *dest = (Py_UCS1*)writer->data + writer->pos * writer->kind;
5369
277k
    if (writer->kind == PyUnicode_1BYTE_KIND) {
5370
264k
        decoded = ascii_decode(s, end, dest);
5371
264k
        writer->pos += decoded;
5372
5373
264k
        if (decoded == size) {
5374
262k
            if (consumed) {
5375
3.61k
                *consumed = size;
5376
3.61k
            }
5377
262k
            return 0;
5378
262k
        }
5379
1.65k
        s += decoded;
5380
1.65k
    }
5381
5382
14.8k
    return unicode_decode_utf8_impl(writer, starts, s, end,
5383
14.8k
                                    error_handler, errors, consumed);
5384
277k
}
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
4.23M
{
5393
4.23M
    return unicode_decode_utf8(s, size,
5394
4.23M
                               errors ? _Py_ERROR_UNKNOWN : _Py_ERROR_STRICT,
5395
4.23M
                               errors, consumed);
5396
4.23M
}
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
147
{
5415
147
    const char *orig_s = s;
5416
147
    const char *e;
5417
147
    wchar_t *unicode;
5418
147
    Py_ssize_t outpos;
5419
5420
147
    int surrogateescape = 0;
5421
147
    int surrogatepass = 0;
5422
147
    switch (errors)
5423
147
    {
5424
0
    case _Py_ERROR_STRICT:
5425
0
        break;
5426
147
    case _Py_ERROR_SURROGATEESCAPE:
5427
147
        surrogateescape = 1;
5428
147
        break;
5429
0
    case _Py_ERROR_SURROGATEPASS:
5430
0
        surrogatepass = 1;
5431
0
        break;
5432
0
    default:
5433
0
        return -3;
5434
147
    }
5435
5436
    /* Note: size will always be longer than the resulting Unicode
5437
       character count */
5438
147
    if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1 < size) {
5439
0
        return -1;
5440
0
    }
5441
5442
147
    unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
5443
147
    if (!unicode) {
5444
0
        return -1;
5445
0
    }
5446
5447
    /* Unpack UTF-8 encoded data */
5448
147
    e = s + size;
5449
147
    outpos = 0;
5450
147
    while (s < e) {
5451
147
        Py_UCS4 ch;
5452
147
#if SIZEOF_WCHAR_T == 4
5453
147
        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
147
        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
147
        else {
5468
147
            if (!ch && s == e) {
5469
147
                break;
5470
147
            }
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
147
    }
5511
147
    unicode[outpos] = L'\0';
5512
147
    if (wlen) {
5513
147
        *wlen = outpos;
5514
147
    }
5515
147
    *wstr = unicode;
5516
147
    return 0;
5517
147
}
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
399
{
5554
399
    const Py_ssize_t max_char_size = 4;
5555
399
    Py_ssize_t len = wcslen(text);
5556
5557
399
    assert(len >= 0);
5558
5559
399
    int surrogateescape = 0;
5560
399
    int surrogatepass = 0;
5561
399
    switch (errors)
5562
399
    {
5563
84
    case _Py_ERROR_STRICT:
5564
84
        break;
5565
315
    case _Py_ERROR_SURROGATEESCAPE:
5566
315
        surrogateescape = 1;
5567
315
        break;
5568
0
    case _Py_ERROR_SURROGATEPASS:
5569
0
        surrogatepass = 1;
5570
0
        break;
5571
0
    default:
5572
0
        return -3;
5573
399
    }
5574
5575
399
    if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5576
0
        return -1;
5577
0
    }
5578
399
    char *bytes;
5579
399
    if (raw_malloc) {
5580
399
        bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5581
399
    }
5582
0
    else {
5583
0
        bytes = PyMem_Malloc((len + 1) * max_char_size);
5584
0
    }
5585
399
    if (bytes == NULL) {
5586
0
        return -1;
5587
0
    }
5588
5589
399
    char *p = bytes;
5590
399
    Py_ssize_t i;
5591
18.0k
    for (i = 0; i < len; ) {
5592
17.6k
        Py_ssize_t ch_pos = i;
5593
17.6k
        Py_UCS4 ch = text[i];
5594
17.6k
        i++;
5595
17.6k
        if (sizeof(wchar_t) == 2
5596
0
            && Py_UNICODE_IS_HIGH_SURROGATE(ch)
5597
0
            && i < len
5598
0
            && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5599
0
        {
5600
0
            ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5601
0
            i++;
5602
0
        }
5603
5604
17.6k
        if (ch < 0x80) {
5605
            /* Encode ASCII */
5606
17.6k
            *p++ = (char) ch;
5607
5608
17.6k
        }
5609
0
        else if (ch < 0x0800) {
5610
            /* Encode Latin-1 */
5611
0
            *p++ = (char)(0xc0 | (ch >> 6));
5612
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5613
0
        }
5614
0
        else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
5615
            /* surrogateescape error handler */
5616
0
            if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
5617
0
                if (error_pos != NULL) {
5618
0
                    *error_pos = (size_t)ch_pos;
5619
0
                }
5620
0
                if (reason != NULL) {
5621
0
                    *reason = "encoding error";
5622
0
                }
5623
0
                if (raw_malloc) {
5624
0
                    PyMem_RawFree(bytes);
5625
0
                }
5626
0
                else {
5627
0
                    PyMem_Free(bytes);
5628
0
                }
5629
0
                return -2;
5630
0
            }
5631
0
            *p++ = (char)(ch & 0xff);
5632
0
        }
5633
0
        else if (ch < 0x10000) {
5634
0
            *p++ = (char)(0xe0 | (ch >> 12));
5635
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5636
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5637
0
        }
5638
0
        else {  /* ch >= 0x10000 */
5639
0
            assert(ch <= MAX_UNICODE);
5640
            /* Encode UCS4 Unicode ordinals */
5641
0
            *p++ = (char)(0xf0 | (ch >> 18));
5642
0
            *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5643
0
            *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5644
0
            *p++ = (char)(0x80 | (ch & 0x3f));
5645
0
        }
5646
17.6k
    }
5647
399
    *p++ = '\0';
5648
5649
399
    size_t final_size = (p - bytes);
5650
399
    char *bytes2;
5651
399
    if (raw_malloc) {
5652
399
        bytes2 = PyMem_RawRealloc(bytes, final_size);
5653
399
    }
5654
0
    else {
5655
0
        bytes2 = PyMem_Realloc(bytes, final_size);
5656
0
    }
5657
399
    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
399
    *str = bytes2;
5670
399
    return 0;
5671
399
}
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
10.6k
{
5685
10.6k
    if (!PyUnicode_Check(unicode)) {
5686
0
        PyErr_BadArgument();
5687
0
        return NULL;
5688
0
    }
5689
5690
10.6k
    if (PyUnicode_UTF8(unicode))
5691
7.37k
        return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5692
7.37k
                                         PyUnicode_UTF8_LENGTH(unicode));
5693
5694
3.27k
    int kind = PyUnicode_KIND(unicode);
5695
3.27k
    const void *data = PyUnicode_DATA(unicode);
5696
3.27k
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5697
5698
3.27k
    PyBytesWriter *writer;
5699
3.27k
    char *end;
5700
5701
3.27k
    switch (kind) {
5702
0
    default:
5703
0
        Py_UNREACHABLE();
5704
1.09k
    case PyUnicode_1BYTE_KIND:
5705
        /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5706
1.09k
        assert(!PyUnicode_IS_ASCII(unicode));
5707
1.09k
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5708
1.09k
                                      error_handler, errors, &end);
5709
1.09k
        break;
5710
1.96k
    case PyUnicode_2BYTE_KIND:
5711
1.96k
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5712
1.96k
                                      error_handler, errors, &end);
5713
1.96k
        break;
5714
225
    case PyUnicode_4BYTE_KIND:
5715
225
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5716
225
                                      error_handler, errors, &end);
5717
225
        break;
5718
3.27k
    }
5719
5720
3.27k
    if (writer == NULL) {
5721
34
        PyBytesWriter_Discard(writer);
5722
34
        return NULL;
5723
34
    }
5724
3.24k
    return PyBytesWriter_FinishWithPointer(writer, end);
5725
3.27k
}
5726
5727
static int
5728
unicode_fill_utf8(PyObject *unicode)
5729
11.0k
{
5730
11.0k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(unicode);
5731
    /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5732
11.0k
    assert(!PyUnicode_IS_ASCII(unicode));
5733
5734
11.0k
    int kind = PyUnicode_KIND(unicode);
5735
11.0k
    const void *data = PyUnicode_DATA(unicode);
5736
11.0k
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5737
5738
11.0k
    PyBytesWriter *writer;
5739
11.0k
    char *end;
5740
5741
11.0k
    switch (kind) {
5742
0
    default:
5743
0
        Py_UNREACHABLE();
5744
6.86k
    case PyUnicode_1BYTE_KIND:
5745
6.86k
        writer = ucs1lib_utf8_encoder(unicode, data, size,
5746
6.86k
                                      _Py_ERROR_STRICT, NULL, &end);
5747
6.86k
        break;
5748
2.98k
    case PyUnicode_2BYTE_KIND:
5749
2.98k
        writer = ucs2lib_utf8_encoder(unicode, data, size,
5750
2.98k
                                      _Py_ERROR_STRICT, NULL, &end);
5751
2.98k
        break;
5752
1.24k
    case PyUnicode_4BYTE_KIND:
5753
1.24k
        writer = ucs4lib_utf8_encoder(unicode, data, size,
5754
1.24k
                                      _Py_ERROR_STRICT, NULL, &end);
5755
1.24k
        break;
5756
11.0k
    }
5757
11.0k
    if (writer == NULL) {
5758
0
        return -1;
5759
0
    }
5760
5761
11.0k
    const char *start = PyBytesWriter_GetData(writer);
5762
11.0k
    Py_ssize_t len = end - start;
5763
5764
11.0k
    char *cache = PyMem_Malloc(len + 1);
5765
11.0k
    if (cache == NULL) {
5766
0
        PyBytesWriter_Discard(writer);
5767
0
        PyErr_NoMemory();
5768
0
        return -1;
5769
0
    }
5770
11.0k
    memcpy(cache, start, len);
5771
11.0k
    cache[len] = '\0';
5772
11.0k
    PyUnicode_SET_UTF8_LENGTH(unicode, len);
5773
11.0k
    PyUnicode_SET_UTF8(unicode, cache);
5774
11.0k
    PyBytesWriter_Discard(writer);
5775
11.0k
    return 0;
5776
11.0k
}
5777
5778
PyObject *
5779
_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5780
3.50k
{
5781
3.50k
    return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5782
3.50k
}
5783
5784
5785
PyObject *
5786
PyUnicode_AsUTF8String(PyObject *unicode)
5787
3.44k
{
5788
3.44k
    return _PyUnicode_AsUTF8String(unicode, NULL);
5789
3.44k
}
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
20
{
5799
20
    return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5800
20
}
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
359
{
5809
359
    const char *starts = s;
5810
359
    Py_ssize_t startinpos;
5811
359
    Py_ssize_t endinpos;
5812
359
    _PyUnicodeWriter writer;
5813
359
    const unsigned char *q, *e;
5814
359
    int le, bo = 0;       /* assume native ordering by default */
5815
359
    const char *encoding;
5816
359
    const char *errmsg = "";
5817
359
    PyObject *errorHandler = NULL;
5818
359
    PyObject *exc = NULL;
5819
5820
359
    q = (const unsigned char *)s;
5821
359
    e = q + size;
5822
5823
359
    if (byteorder)
5824
339
        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
359
    if (bo == 0 && size >= 4) {
5831
25
        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5832
25
        if (bom == 0x0000FEFF) {
5833
2
            bo = -1;
5834
2
            q += 4;
5835
2
        }
5836
23
        else if (bom == 0xFFFE0000) {
5837
11
            bo = 1;
5838
11
            q += 4;
5839
11
        }
5840
25
        if (byteorder)
5841
5
            *byteorder = bo;
5842
25
    }
5843
5844
359
    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
357
    le = bo <= 0;
5854
357
#endif
5855
357
    encoding = le ? "utf-32-le" : "utf-32-be";
5856
5857
357
    _PyUnicodeWriter_Init(&writer);
5858
357
    writer.min_length = (e - q + 3) / 4;
5859
357
    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
174k
                do {
5873
174k
                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5874
174k
                    if (ch > maxch)
5875
251
                        break;
5876
174k
                    if (kind != PyUnicode_1BYTE_KIND &&
5877
24.1k
                        Py_UNICODE_IS_SURROGATE(ch))
5878
604
                        break;
5879
173k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5880
173k
                    q += 4;
5881
173k
                } while (q <= last);
5882
906
            }
5883
887
            else {
5884
12.3k
                do {
5885
12.3k
                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5886
12.3k
                    if (ch > maxch)
5887
250
                        break;
5888
12.0k
                    if (kind != PyUnicode_1BYTE_KIND &&
5889
4.76k
                        Py_UNICODE_IS_SURROGATE(ch))
5890
586
                        break;
5891
11.5k
                    PyUnicode_WRITE(kind, data, pos++, ch);
5892
11.5k
                    q += 4;
5893
11.5k
                } while (q <= last);
5894
887
            }
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
657
        else if (ch <= maxch) {
5904
208
            if (q == e || consumed)
5905
189
                break;
5906
            /* remaining bytes at the end? (size should be divisible by 4) */
5907
19
            errmsg = "truncated data";
5908
19
            startinpos = ((const char *)q) - starts;
5909
19
            endinpos = ((const char *)e) - starts;
5910
19
        }
5911
449
        else {
5912
449
            if (ch < 0x110000) {
5913
300
                if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
5914
0
                    goto onError;
5915
300
                q += 4;
5916
300
                continue;
5917
300
            }
5918
149
            errmsg = "code point not in range(0x110000)";
5919
149
            startinpos = ((const char *)q) - starts;
5920
149
            endinpos = startinpos + 4;
5921
149
        }
5922
5923
        /* The remaining input chars are ignored if the callback
5924
           chooses to skip the input */
5925
1.41k
        if (unicode_decode_call_errorhandler_writer(
5926
1.41k
                errors, &errorHandler,
5927
1.41k
                encoding, errmsg,
5928
1.41k
                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5929
1.41k
                &writer))
5930
168
            goto onError;
5931
1.41k
    }
5932
5933
189
    if (consumed)
5934
0
        *consumed = (const char *)q-starts;
5935
5936
189
    Py_XDECREF(errorHandler);
5937
189
    Py_XDECREF(exc);
5938
189
    return _PyUnicodeWriter_Finish(&writer);
5939
5940
168
  onError:
5941
168
    _PyUnicodeWriter_Dealloc(&writer);
5942
168
    Py_XDECREF(errorHandler);
5943
168
    Py_XDECREF(exc);
5944
168
    return NULL;
5945
357
}
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
102
{
6115
102
    return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
6116
102
}
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
800
{
6125
800
    const char *starts = s;
6126
800
    Py_ssize_t startinpos;
6127
800
    Py_ssize_t endinpos;
6128
800
    _PyUnicodeWriter writer;
6129
800
    const unsigned char *q, *e;
6130
800
    int bo = 0;       /* assume native ordering by default */
6131
800
    int native_ordering;
6132
800
    const char *errmsg = "";
6133
800
    PyObject *errorHandler = NULL;
6134
800
    PyObject *exc = NULL;
6135
800
    const char *encoding;
6136
6137
800
    q = (const unsigned char *)s;
6138
800
    e = q + size;
6139
6140
800
    if (byteorder)
6141
698
        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
800
    if (bo == 0 && size >= 2) {
6148
146
        const Py_UCS4 bom = (q[1] << 8) | q[0];
6149
146
        if (bom == 0xFEFF) {
6150
25
            q += 2;
6151
25
            bo = -1;
6152
25
        }
6153
121
        else if (bom == 0xFFFE) {
6154
31
            q += 2;
6155
31
            bo = 1;
6156
31
        }
6157
146
        if (byteorder)
6158
44
            *byteorder = bo;
6159
146
    }
6160
6161
800
    if (q == e) {
6162
2
        if (consumed)
6163
0
            *consumed = size;
6164
2
        _Py_RETURN_UNICODE_EMPTY();
6165
2
    }
6166
6167
798
#if PY_LITTLE_ENDIAN
6168
798
    native_ordering = bo <= 0;
6169
798
    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
798
    _PyUnicodeWriter_Init(&writer);
6179
798
    writer.min_length = (e - q + 1) / 2;
6180
798
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
6181
0
        goto onError;
6182
6183
60.0k
    while (1) {
6184
60.0k
        Py_UCS4 ch = 0;
6185
60.0k
        if (e - q >= 2) {
6186
59.7k
            int kind = writer.kind;
6187
59.7k
            if (kind == PyUnicode_1BYTE_KIND) {
6188
992
                if (PyUnicode_IS_ASCII(writer.buffer))
6189
796
                    ch = asciilib_utf16_decode(&q, e,
6190
796
                            (Py_UCS1*)writer.data, &writer.pos,
6191
796
                            native_ordering);
6192
196
                else
6193
196
                    ch = ucs1lib_utf16_decode(&q, e,
6194
196
                            (Py_UCS1*)writer.data, &writer.pos,
6195
196
                            native_ordering);
6196
58.7k
            } else if (kind == PyUnicode_2BYTE_KIND) {
6197
29.3k
                ch = ucs2lib_utf16_decode(&q, e,
6198
29.3k
                        (Py_UCS2*)writer.data, &writer.pos,
6199
29.3k
                        native_ordering);
6200
29.4k
            } else {
6201
29.4k
                assert(kind == PyUnicode_4BYTE_KIND);
6202
29.4k
                ch = ucs4lib_utf16_decode(&q, e,
6203
29.4k
                        (Py_UCS4*)writer.data, &writer.pos,
6204
29.4k
                        native_ordering);
6205
29.4k
            }
6206
59.7k
        }
6207
6208
60.0k
        switch (ch)
6209
60.0k
        {
6210
782
        case 0:
6211
            /* remaining byte at the end? (size should be even) */
6212
782
            if (q == e || consumed)
6213
477
                goto End;
6214
305
            errmsg = "truncated data";
6215
305
            startinpos = ((const char *)q) - starts;
6216
305
            endinpos = ((const char *)e) - starts;
6217
305
            break;
6218
            /* The remaining input chars are ignored if the callback
6219
               chooses to skip the input */
6220
170
        case 1:
6221
170
            q -= 2;
6222
170
            if (consumed)
6223
0
                goto End;
6224
170
            errmsg = "unexpected end of data";
6225
170
            startinpos = ((const char *)q) - starts;
6226
170
            endinpos = ((const char *)e) - starts;
6227
170
            break;
6228
26.1k
        case 2:
6229
26.1k
            errmsg = "illegal encoding";
6230
26.1k
            startinpos = ((const char *)q) - 2 - starts;
6231
26.1k
            endinpos = startinpos + 2;
6232
26.1k
            break;
6233
32.1k
        case 3:
6234
32.1k
            errmsg = "illegal UTF-16 surrogate";
6235
32.1k
            startinpos = ((const char *)q) - 4 - starts;
6236
32.1k
            endinpos = startinpos + 2;
6237
32.1k
            break;
6238
825
        default:
6239
825
            if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
6240
0
                goto onError;
6241
825
            continue;
6242
60.0k
        }
6243
6244
58.7k
        if (unicode_decode_call_errorhandler_writer(
6245
58.7k
                errors,
6246
58.7k
                &errorHandler,
6247
58.7k
                encoding, errmsg,
6248
58.7k
                &starts,
6249
58.7k
                (const char **)&e,
6250
58.7k
                &startinpos,
6251
58.7k
                &endinpos,
6252
58.7k
                &exc,
6253
58.7k
                (const char **)&q,
6254
58.7k
                &writer))
6255
321
            goto onError;
6256
58.7k
    }
6257
6258
477
End:
6259
477
    if (consumed)
6260
0
        *consumed = (const char *)q-starts;
6261
6262
477
    Py_XDECREF(errorHandler);
6263
477
    Py_XDECREF(exc);
6264
477
    return _PyUnicodeWriter_Finish(&writer);
6265
6266
321
  onError:
6267
321
    _PyUnicodeWriter_Dealloc(&writer);
6268
321
    Py_XDECREF(errorHandler);
6269
321
    Py_XDECREF(exc);
6270
321
    return NULL;
6271
798
}
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.91k
{
6448
5.91k
    PyInterpreterState *interp = _PyInterpreterState_GET();
6449
5.91k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6450
6451
5.91k
    ucnhash_capi = _Py_atomic_load_ptr(&interp->unicode.ucnhash_capi);
6452
5.91k
    if (ucnhash_capi == NULL) {
6453
2
        ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6454
2
                PyUnicodeData_CAPSULE_NAME, 1);
6455
6456
        // It's fine if we overwrite the value here. It's always the same value.
6457
2
        _Py_atomic_store_ptr(&interp->unicode.ucnhash_capi, ucnhash_capi);
6458
2
    }
6459
5.91k
    return ucnhash_capi;
6460
5.91k
}
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
33.9k
{
6472
33.9k
    const char *starts = s;
6473
33.9k
    const char *initial_starts = starts;
6474
33.9k
    _PyUnicodeWriter writer;
6475
33.9k
    const char *end;
6476
33.9k
    PyObject *errorHandler = NULL;
6477
33.9k
    PyObject *exc = NULL;
6478
33.9k
    _PyUnicode_Name_CAPI *ucnhash_capi;
6479
6480
    // so we can remember if we've seen an invalid escape char or not
6481
33.9k
    *first_invalid_escape_char = -1;
6482
33.9k
    *first_invalid_escape_ptr = NULL;
6483
6484
33.9k
    if (size == 0) {
6485
4.96k
        if (consumed) {
6486
0
            *consumed = 0;
6487
0
        }
6488
4.96k
        _Py_RETURN_UNICODE_EMPTY();
6489
4.96k
    }
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
29.0k
    _PyUnicodeWriter_Init(&writer);
6496
29.0k
    writer.min_length = size;
6497
29.0k
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6498
0
        goto onError;
6499
0
    }
6500
6501
29.0k
    end = s + size;
6502
21.3M
    while (s < end) {
6503
21.3M
        unsigned char c = (unsigned char) *s++;
6504
21.3M
        Py_UCS4 ch;
6505
21.3M
        int count;
6506
21.3M
        const char *message;
6507
6508
21.3M
#define WRITE_ASCII_CHAR(ch)                                                  \
6509
21.3M
            do {                                                              \
6510
5.26M
                assert(ch <= 127);                                            \
6511
5.26M
                assert(writer.pos < writer.size);                             \
6512
5.26M
                PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch);  \
6513
5.26M
            } while(0)
6514
6515
21.3M
#define WRITE_CHAR(ch)                                                        \
6516
21.3M
            do {                                                              \
6517
16.8M
                if (ch <= writer.maxchar) {                                   \
6518
16.8M
                    assert(writer.pos < writer.size);                         \
6519
16.8M
                    PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6520
16.8M
                }                                                             \
6521
16.8M
                else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6522
0
                    goto onError;                                             \
6523
0
                }                                                             \
6524
16.8M
            } while(0)
6525
6526
        /* Non-escape characters are interpreted as Unicode ordinals */
6527
21.3M
        if (c != '\\') {
6528
15.3M
            WRITE_CHAR(c);
6529
15.3M
            continue;
6530
15.3M
        }
6531
6532
5.94M
        Py_ssize_t startinpos = s - starts - 1;
6533
        /* \ - Escapes */
6534
5.94M
        if (s >= end) {
6535
0
            message = "\\ at end of string";
6536
0
            goto incomplete;
6537
0
        }
6538
5.94M
        c = (unsigned char) *s++;
6539
6540
5.94M
        assert(writer.pos < writer.size);
6541
5.94M
        switch (c) {
6542
6543
            /* \x escapes */
6544
2.06k
        case '\n': continue;
6545
506k
        case '\\': WRITE_ASCII_CHAR('\\'); continue;
6546
506k
        case '\'': WRITE_ASCII_CHAR('\''); continue;
6547
565k
        case '\"': WRITE_ASCII_CHAR('\"'); continue;
6548
565k
        case 'b': WRITE_ASCII_CHAR('\b'); continue;
6549
        /* FF */
6550
808k
        case 'f': WRITE_ASCII_CHAR('\014'); continue;
6551
808k
        case 't': WRITE_ASCII_CHAR('\t'); continue;
6552
1.36M
        case 'n': WRITE_ASCII_CHAR('\n'); continue;
6553
1.36M
        case 'r': WRITE_ASCII_CHAR('\r'); continue;
6554
        /* VT */
6555
772k
        case 'v': WRITE_ASCII_CHAR('\013'); continue;
6556
        /* BEL, not classic C */
6557
64.7k
        case 'a': WRITE_ASCII_CHAR('\007'); continue;
6558
6559
            /* \OOO (octal) escapes */
6560
144k
        case '0': case '1': case '2': case '3':
6561
177k
        case '4': case '5': case '6': case '7':
6562
177k
            ch = c - '0';
6563
177k
            if (s < end && '0' <= *s && *s <= '7') {
6564
6.48k
                ch = (ch<<3) + *s++ - '0';
6565
6.48k
                if (s < end && '0' <= *s && *s <= '7') {
6566
2.19k
                    ch = (ch<<3) + *s++ - '0';
6567
2.19k
                }
6568
6.48k
            }
6569
177k
            if (ch > 0377) {
6570
1.50k
                if (*first_invalid_escape_char == -1) {
6571
696
                    *first_invalid_escape_char = ch;
6572
696
                    if (starts == initial_starts) {
6573
                        /* Back up 3 chars, since we've already incremented s. */
6574
696
                        *first_invalid_escape_ptr = s - 3;
6575
696
                    }
6576
696
                }
6577
1.50k
            }
6578
177k
            WRITE_CHAR(ch);
6579
177k
            continue;
6580
6581
            /* hex escapes */
6582
            /* \xXX */
6583
177k
        case 'x':
6584
46
            count = 2;
6585
46
            message = "truncated \\xXX escape";
6586
46
            goto hexescape;
6587
6588
            /* \uXXXX */
6589
6.33k
        case 'u':
6590
6.33k
            count = 4;
6591
6.33k
            message = "truncated \\uXXXX escape";
6592
6.33k
            goto hexescape;
6593
6594
            /* \UXXXXXXXX */
6595
487k
        case 'U':
6596
487k
            count = 8;
6597
487k
            message = "truncated \\UXXXXXXXX escape";
6598
494k
        hexescape:
6599
4.42M
            for (ch = 0; count; ++s, --count) {
6600
3.92M
                if (s >= end) {
6601
3
                    goto incomplete;
6602
3
                }
6603
3.92M
                c = (unsigned char)*s;
6604
3.92M
                ch <<= 4;
6605
3.92M
                if (c >= '0' && c <= '9') {
6606
3.17M
                    ch += c - '0';
6607
3.17M
                }
6608
750k
                else if (c >= 'a' && c <= 'f') {
6609
748k
                    ch += c - ('a' - 10);
6610
748k
                }
6611
1.50k
                else if (c >= 'A' && c <= 'F') {
6612
1.49k
                    ch += c - ('A' - 10);
6613
1.49k
                }
6614
10
                else {
6615
10
                    goto error;
6616
10
                }
6617
3.92M
            }
6618
6619
            /* when we get here, ch is a 32-bit unicode character */
6620
494k
            if (ch > MAX_UNICODE) {
6621
1
                message = "illegal Unicode character";
6622
1
                goto error;
6623
1
            }
6624
6625
494k
            WRITE_CHAR(ch);
6626
494k
            continue;
6627
6628
            /* \N{name} */
6629
494k
        case 'N':
6630
5.91k
            ucnhash_capi = _PyUnicode_GetNameCAPI();
6631
5.91k
            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.91k
            message = "malformed \\N character escape";
6640
5.91k
            if (s >= end) {
6641
11
                goto incomplete;
6642
11
            }
6643
5.90k
            if (*s == '{') {
6644
5.90k
                const char *start = ++s;
6645
5.90k
                size_t namelen;
6646
                /* look for the closing brace */
6647
4.69M
                while (s < end && *s != '}')
6648
4.68M
                    s++;
6649
5.90k
                if (s >= end) {
6650
6
                    goto incomplete;
6651
6
                }
6652
5.89k
                namelen = s - start;
6653
5.89k
                if (namelen) {
6654
                    /* found a name.  look it up in the unicode database */
6655
5.89k
                    s++;
6656
5.89k
                    ch = 0xffffffff; /* in case 'getcode' messes up */
6657
5.89k
                    if (namelen <= INT_MAX &&
6658
5.89k
                        ucnhash_capi->getcode(start, (int)namelen,
6659
5.89k
                                              &ch, 0)) {
6660
5.83k
                        assert(ch <= MAX_UNICODE);
6661
5.83k
                        WRITE_CHAR(ch);
6662
5.83k
                        continue;
6663
5.83k
                    }
6664
55
                    message = "unknown Unicode character name";
6665
55
                }
6666
5.89k
            }
6667
60
            goto error;
6668
6669
754k
        default:
6670
754k
            if (*first_invalid_escape_char == -1) {
6671
9.61k
                *first_invalid_escape_char = c;
6672
9.61k
                if (starts == initial_starts) {
6673
                    /* Back up one char, since we've already incremented s. */
6674
9.61k
                    *first_invalid_escape_ptr = s - 1;
6675
9.61k
                }
6676
9.61k
            }
6677
754k
            WRITE_ASCII_CHAR('\\');
6678
754k
            WRITE_CHAR(c);
6679
754k
            continue;
6680
5.94M
        }
6681
6682
20
      incomplete:
6683
20
        if (consumed) {
6684
0
            *consumed = startinpos;
6685
0
            break;
6686
0
        }
6687
91
      error:;
6688
91
        Py_ssize_t endinpos = s-starts;
6689
91
        writer.min_length = end - s + writer.pos;
6690
91
        if (unicode_decode_call_errorhandler_writer(
6691
91
                errors, &errorHandler,
6692
91
                "unicodeescape", message,
6693
91
                &starts, &end, &startinpos, &endinpos, &exc, &s,
6694
91
                &writer)) {
6695
91
            goto onError;
6696
91
        }
6697
91
        assert(end - s <= writer.size - writer.pos);
6698
6699
0
#undef WRITE_ASCII_CHAR
6700
0
#undef WRITE_CHAR
6701
0
    }
6702
6703
28.9k
    Py_XDECREF(errorHandler);
6704
28.9k
    Py_XDECREF(exc);
6705
28.9k
    return _PyUnicodeWriter_Finish(&writer);
6706
6707
91
  onError:
6708
91
    _PyUnicodeWriter_Dealloc(&writer);
6709
91
    Py_XDECREF(errorHandler);
6710
91
    Py_XDECREF(exc);
6711
91
    return NULL;
6712
29.0k
}
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
5.70k
{
7083
    /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
7084
5.70k
    return _PyUnicode_FromUCS1((const unsigned char*)s, size);
7085
5.70k
}
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
35.5k
{
7095
35.5k
    if (*exceptionObject == NULL) {
7096
35.5k
        *exceptionObject = PyObject_CallFunction(
7097
35.5k
            PyExc_UnicodeEncodeError, "sOnns",
7098
35.5k
            encoding, unicode, startpos, endpos, reason);
7099
35.5k
    }
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
35.5k
}
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
35.5k
{
7121
35.5k
    make_encode_exception(exceptionObject,
7122
35.5k
                          encoding, unicode, startpos, endpos, reason);
7123
35.5k
    if (*exceptionObject != NULL)
7124
35.5k
        PyCodec_StrictErrors(*exceptionObject);
7125
35.5k
}
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
34
{
7139
34
    static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
7140
34
    Py_ssize_t len;
7141
34
    PyObject *restuple;
7142
34
    PyObject *resunicode;
7143
7144
34
    if (*errorHandler == NULL) {
7145
34
        *errorHandler = PyCodec_LookupError(errors);
7146
34
        if (*errorHandler == NULL)
7147
0
            return NULL;
7148
34
    }
7149
7150
34
    len = PyUnicode_GET_LENGTH(unicode);
7151
7152
34
    make_encode_exception(exceptionObject,
7153
34
                          encoding, unicode, startpos, endpos, reason);
7154
34
    if (*exceptionObject == NULL)
7155
0
        return NULL;
7156
7157
34
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
7158
34
    if (restuple == NULL)
7159
34
        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
35.7k
{
7192
    /* input state */
7193
35.7k
    Py_ssize_t pos=0, size;
7194
35.7k
    int kind;
7195
35.7k
    const void *data;
7196
35.7k
    const char *encoding = (limit == 256) ? "latin-1" : "ascii";
7197
35.7k
    const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
7198
35.7k
    PyObject *error_handler_obj = NULL;
7199
35.7k
    PyObject *exc = NULL;
7200
35.7k
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7201
35.7k
    PyObject *rep = NULL;
7202
7203
35.7k
    size = PyUnicode_GET_LENGTH(unicode);
7204
35.7k
    kind = PyUnicode_KIND(unicode);
7205
35.7k
    data = PyUnicode_DATA(unicode);
7206
    /* allocate enough for a simple encoding without
7207
       replacements, if we need more, we'll resize */
7208
35.7k
    if (size == 0)
7209
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
7210
7211
    /* output object */
7212
35.7k
    PyBytesWriter *writer = PyBytesWriter_Create(size);
7213
35.7k
    if (writer == NULL) {
7214
0
        return NULL;
7215
0
    }
7216
    /* pointer into the output */
7217
35.7k
    char *str = PyBytesWriter_GetData(writer);
7218
7219
3.60M
    while (pos < size) {
7220
3.60M
        Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
7221
7222
        /* can we encode this? */
7223
3.60M
        if (ch < limit) {
7224
            /* no overflow check, because we know that the space is enough */
7225
3.55M
            *str++ = (char)ch;
7226
3.55M
            ++pos;
7227
3.55M
        }
7228
42.9k
        else {
7229
42.9k
            Py_ssize_t newpos, i;
7230
            /* startpos for collecting unencodable chars */
7231
42.9k
            Py_ssize_t collstart = pos;
7232
42.9k
            Py_ssize_t collend = collstart + 1;
7233
            /* find all unecodable characters */
7234
7235
407k
            while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
7236
364k
                ++collend;
7237
7238
            /* Only overallocate the buffer if it's not the last write */
7239
42.9k
            writer->overallocate = (collend < size);
7240
7241
            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
7242
42.9k
            if (error_handler == _Py_ERROR_UNKNOWN)
7243
35.7k
                error_handler = _Py_GetErrorHandler(errors);
7244
7245
42.9k
            switch (error_handler) {
7246
35.5k
            case _Py_ERROR_STRICT:
7247
35.5k
                raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
7248
35.5k
                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
7.44k
            case _Py_ERROR_BACKSLASHREPLACE:
7259
                /* subtract preallocated bytes */
7260
7.44k
                writer->size -= (collend - collstart);
7261
7.44k
                str = backslashreplace(writer, str,
7262
7.44k
                                       unicode, collstart, collend);
7263
7.44k
                if (str == NULL)
7264
0
                    goto onError;
7265
7.44k
                pos = collend;
7266
7.44k
                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
42.9k
            }
7351
7352
            /* If overallocation was disabled, ensure that it was the last
7353
               write. Otherwise, we missed an optimization */
7354
42.9k
            assert(writer->overallocate || pos == size);
7355
7.44k
        }
7356
3.60M
    }
7357
7358
259
    Py_XDECREF(error_handler_obj);
7359
259
    Py_XDECREF(exc);
7360
259
    return PyBytesWriter_FinishWithPointer(writer, str);
7361
7362
35.5k
  onError:
7363
35.5k
    Py_XDECREF(rep);
7364
35.5k
    PyBytesWriter_Discard(writer);
7365
35.5k
    Py_XDECREF(error_handler_obj);
7366
35.5k
    Py_XDECREF(exc);
7367
35.5k
    return NULL;
7368
35.7k
}
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
74.2k
{
7400
74.2k
    const char *starts = s;
7401
74.2k
    const char *e = s + size;
7402
74.2k
    PyObject *error_handler_obj = NULL;
7403
74.2k
    PyObject *exc = NULL;
7404
74.2k
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
7405
7406
74.2k
    if (size == 0)
7407
18
        _Py_RETURN_UNICODE_EMPTY();
7408
7409
    /* ASCII is equivalent to the first 128 ordinals in Unicode. */
7410
74.2k
    if (size == 1 && (unsigned char)s[0] < 128) {
7411
4.54k
        return get_latin1_char((unsigned char)s[0]);
7412
4.54k
    }
7413
7414
    // Shortcut for simple case
7415
69.7k
    PyObject *u = PyUnicode_New(size, 127);
7416
69.7k
    if (u == NULL) {
7417
0
        return NULL;
7418
0
    }
7419
69.7k
    Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
7420
69.7k
    if (outpos == size) {
7421
69.2k
        return u;
7422
69.2k
    }
7423
7424
444
    _PyUnicodeWriter writer;
7425
444
    _PyUnicodeWriter_InitWithBuffer(&writer, u);
7426
444
    writer.pos = outpos;
7427
7428
444
    s += outpos;
7429
444
    int kind = writer.kind;
7430
444
    void *data = writer.data;
7431
444
    Py_ssize_t startinpos, endinpos;
7432
7433
7.77M
    while (s < e) {
7434
7.77M
        unsigned char c = (unsigned char)*s;
7435
7.77M
        if (c < 128) {
7436
7.66M
            PyUnicode_WRITE(kind, data, writer.pos, c);
7437
7.66M
            writer.pos++;
7438
7.66M
            ++s;
7439
7.66M
            continue;
7440
7.66M
        }
7441
7442
        /* byte outsize range 0x00..0x7f: call the error handler */
7443
7444
112k
        if (error_handler == _Py_ERROR_UNKNOWN)
7445
444
            error_handler = _Py_GetErrorHandler(errors);
7446
7447
112k
        switch (error_handler)
7448
112k
        {
7449
0
        case _Py_ERROR_REPLACE:
7450
112k
        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
112k
            if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7454
0
                goto onError;
7455
112k
            kind = writer.kind;
7456
112k
            data = writer.data;
7457
7458
112k
            if (error_handler == _Py_ERROR_REPLACE)
7459
0
                PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7460
112k
            else
7461
112k
                PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7462
112k
            writer.pos++;
7463
112k
            ++s;
7464
112k
            break;
7465
7466
0
        case _Py_ERROR_IGNORE:
7467
0
            ++s;
7468
0
            break;
7469
7470
267
        default:
7471
267
            startinpos = s-starts;
7472
267
            endinpos = startinpos + 1;
7473
267
            if (unicode_decode_call_errorhandler_writer(
7474
267
                    errors, &error_handler_obj,
7475
267
                    "ascii", "ordinal not in range(128)",
7476
267
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
7477
267
                    &writer))
7478
267
                goto onError;
7479
0
            kind = writer.kind;
7480
0
            data = writer.data;
7481
112k
        }
7482
112k
    }
7483
177
    Py_XDECREF(error_handler_obj);
7484
177
    Py_XDECREF(exc);
7485
177
    return _PyUnicodeWriter_Finish(&writer);
7486
7487
267
  onError:
7488
267
    _PyUnicodeWriter_Dealloc(&writer);
7489
267
    Py_XDECREF(error_handler_obj);
7490
267
    Py_XDECREF(exc);
7491
267
    return NULL;
7492
444
}
7493
7494
PyObject *
7495
_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
7496
38.1k
{
7497
38.1k
    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
38.1k
    if (PyUnicode_IS_ASCII(unicode))
7504
2.33k
        return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7505
2.33k
                                         PyUnicode_GET_LENGTH(unicode));
7506
35.7k
    return unicode_encode_ucs1(unicode, errors, 128);
7507
38.1k
}
7508
7509
PyObject *
7510
PyUnicode_AsASCIIString(PyObject *unicode)
7511
2
{
7512
2
    return _PyUnicode_AsASCIIString(unicode, NULL);
7513
2
}
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
122
#  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
365
{
8230
365
    iconv_t cd = iconv_open(tocode, fromcode);
8231
365
    if (cd == (iconv_t)-1) {
8232
223
        if (errno == EINVAL) {
8233
223
            PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding);
8234
223
        }
8235
0
        else {
8236
0
            PyErr_SetFromErrno(PyExc_OSError);
8237
0
        }
8238
223
    }
8239
365
    return cd;
8240
365
}
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
122
{
8254
122
    if (size < 0) {
8255
0
        PyErr_BadInternalCall();
8256
0
        return NULL;
8257
0
    }
8258
8259
122
    iconv_t cd = iconv_open_or_set_error(ICONV_PIVOT, encoding, encoding);
8260
122
    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
122
    Py_UCS4 chunk[1024];
8266
122
    const char *starts = s;
8267
122
    const char *in = s;
8268
122
    const char *inend = s + size;
8269
122
    _PyUnicodeWriter writer;
8270
122
    PyObject *errorHandler = NULL;
8271
122
    PyObject *exc = NULL;
8272
8273
122
    _PyUnicodeWriter_Init(&writer);
8274
122
    writer.min_length = size;
8275
8276
399
    while (in < inend) {
8277
399
        char *inptr = (char *)in;
8278
399
        size_t inleft = (size_t)(inend - in);
8279
399
        char *outptr = (char *)chunk;
8280
399
        size_t outleft = sizeof(chunk);
8281
8282
        /* Cast the input buffer through void*: iconv() declares its second
8283
           argument as "char **" on most systems but "const char **" on some
8284
           (e.g. illumos), and void* converts to either without a warning. */
8285
399
        size_t ret = iconv(cd, (void *)&inptr, &inleft, &outptr, &outleft);
8286
399
        int err = errno;
8287
399
        in = inptr;
8288
8289
        /* Append whatever code points this call produced. */
8290
399
        Py_ssize_t nch = (Py_UCS4 *)outptr - chunk;
8291
399
        if (nch > 0 && PyUnicodeWriter_WriteUCS4((PyUnicodeWriter *)&writer,
8292
394
                                                 chunk, nch) < 0) {
8293
0
            goto error;
8294
0
        }
8295
8296
399
        if (ret != (size_t)-1) {
8297
91
            assert(in == inend);
8298
91
            break;
8299
91
        }
8300
8301
308
        if (err == E2BIG) {
8302
            /* The scratch buffer filled up; drain it and continue. */
8303
277
            continue;
8304
277
        }
8305
8306
31
        const char *reason;
8307
31
        if (err == EINVAL) {
8308
            /* Incomplete multibyte sequence at the end of the input. */
8309
0
            if (consumed != NULL) {
8310
                /* Stateful decoding: stop and report the consumed bytes. */
8311
0
                break;
8312
0
            }
8313
0
            reason = "incomplete multibyte sequence";
8314
0
        }
8315
31
        else if (err == EILSEQ) {
8316
31
            reason = "invalid multibyte sequence";
8317
31
        }
8318
0
        else {
8319
0
            errno = err;
8320
0
            PyErr_SetFromErrno(PyExc_OSError);
8321
0
            goto error;
8322
0
        }
8323
8324
31
        Py_ssize_t startinpos = in - starts;
8325
31
        Py_ssize_t endinpos = startinpos + 1;
8326
31
        if (unicode_decode_call_errorhandler_writer(
8327
31
                errors, &errorHandler, encoding, reason,
8328
31
                &starts, &inend, &startinpos, &endinpos, &exc, &in,
8329
31
                &writer)) {
8330
31
            goto error;
8331
31
        }
8332
        /* The error handler may have skipped bytes; reset the conversion
8333
           descriptor to the initial shift state before continuing. */
8334
0
        iconv(cd, NULL, NULL, NULL, NULL);
8335
0
    }
8336
8337
91
    if (consumed != NULL) {
8338
0
        *consumed = in - starts;
8339
0
    }
8340
91
    iconv_close(cd);
8341
91
    Py_XDECREF(errorHandler);
8342
91
    Py_XDECREF(exc);
8343
91
    return _PyUnicodeWriter_Finish(&writer);
8344
8345
31
error:
8346
31
    iconv_close(cd);
8347
31
    _PyUnicodeWriter_Dealloc(&writer);
8348
31
    Py_XDECREF(errorHandler);
8349
31
    Py_XDECREF(exc);
8350
31
    return NULL;
8351
122
}
8352
8353
/* Grow the output buffer of a PyBytesWriter, keeping the raw cursor *pout and
8354
   the end pointer *poutend valid.  Returns 0 on success, -1 on error. */
8355
static int
8356
iconv_grow_writer(PyBytesWriter *writer, char **pout, char **poutend)
8357
0
{
8358
0
    char *base = PyBytesWriter_GetData(writer);
8359
0
    Py_ssize_t used = *pout - base;
8360
0
    Py_ssize_t cursize = PyBytesWriter_GetSize(writer);
8361
0
    Py_ssize_t growby = cursize > 0 ? cursize : 16;
8362
0
    if (PyBytesWriter_Grow(writer, growby) < 0) {
8363
0
        return -1;
8364
0
    }
8365
0
    base = PyBytesWriter_GetData(writer);
8366
0
    *pout = base + used;
8367
0
    *poutend = base + PyBytesWriter_GetSize(writer);
8368
0
    return 0;
8369
0
}
8370
8371
/*
8372
 * Encode a str to bytes with iconv().
8373
 *
8374
 * The string's own buffer is fed to iconv() using the source encoding for its
8375
 * kind, avoiding a widening copy: Latin-1 for 1-byte (not ASCII: it may hold
8376
 * U+0080..U+00FF), UTF-32 for 4-byte, and UCS-2 -- or a UTF-32 copy where that
8377
 * is unsafe (see ICONV_UCS2_PIVOT) -- for 2-byte.  One input unit is one code
8378
 * point, so the unit index is the string position.
8379
 */
8380
PyObject *
8381
_PyUnicode_EncodeIconv(const char *encoding, PyObject *unicode,
8382
                       const char *errors)
8383
243
{
8384
243
    if (!PyUnicode_Check(unicode)) {
8385
0
        PyErr_BadArgument();
8386
0
        return NULL;
8387
0
    }
8388
8389
243
    Py_ssize_t ulen = PyUnicode_GET_LENGTH(unicode);
8390
243
    const char *source;         /* iconv source encoding for this kind */
8391
243
    const char *data;           /* the units to encode */
8392
243
    Py_ssize_t unit;            /* bytes per code point in *data */
8393
243
    Py_UCS4 *widened = NULL;    /* owned UTF-32 copy of a 2-byte string */
8394
243
    int kind = PyUnicode_KIND(unicode);
8395
243
    if (kind == PyUnicode_1BYTE_KIND) {
8396
243
        source = "ISO-8859-1";
8397
243
        data = (const char *)PyUnicode_1BYTE_DATA(unicode);
8398
243
        unit = 1;
8399
243
    }
8400
0
    else if (kind == PyUnicode_4BYTE_KIND) {
8401
0
        source = ICONV_PIVOT;
8402
0
        data = (const char *)PyUnicode_4BYTE_DATA(unicode);
8403
0
        unit = 4;
8404
0
    }
8405
0
    else {
8406
0
#ifdef ICONV_UCS2_PIVOT
8407
        /* Known-strict UCS-2: feed the 2-byte buffer directly. */
8408
0
        source = ICONV_UCS2_PIVOT;
8409
0
        data = (const char *)PyUnicode_2BYTE_DATA(unicode);
8410
0
        unit = 2;
8411
#else
8412
        /* UCS-2 may be aliased to UTF-16 here; widen to UTF-32 to be safe. */
8413
        widened = PyUnicode_AsUCS4Copy(unicode);
8414
        if (widened == NULL) {
8415
            return NULL;
8416
        }
8417
        source = ICONV_PIVOT;
8418
        data = (const char *)widened;
8419
        unit = 4;
8420
#endif
8421
0
    }
8422
8423
243
    iconv_t cd = iconv_open_or_set_error(encoding, source, encoding);
8424
243
    if (cd == (iconv_t)-1) {
8425
223
        PyMem_Free(widened);
8426
223
        return NULL;
8427
223
    }
8428
8429
20
    PyBytesWriter *writer = NULL;
8430
20
    PyObject *errorHandler = NULL;
8431
20
    PyObject *exc = NULL;
8432
20
    PyObject *result = NULL;
8433
20
    const char *ustart = data;
8434
20
    const char *up = data;
8435
20
    const char *uend = data + (size_t)ulen * unit;
8436
20
    int flushing = 0;
8437
20
    int careful = 0;            /* feed one code point per iconv() call */
8438
8439
    /* A generous initial estimate for the output size. */
8440
20
    writer = PyBytesWriter_Create(ulen + (ulen >> 1) + 16);
8441
20
    if (writer == NULL) {
8442
0
        goto done;
8443
0
    }
8444
20
    char *out = PyBytesWriter_GetData(writer);
8445
20
    char *outend = out + PyBytesWriter_GetSize(writer);
8446
8447
40
    for (;;) {
8448
40
        char *inptr = (char *)up;
8449
40
        size_t inleft = (size_t)(uend - up);
8450
        /* One code point at a time, to pin a substitution to its position. */
8451
40
        if (careful && inleft > (size_t)unit) {
8452
0
            inleft = (size_t)unit;
8453
0
        }
8454
40
        char *out_before = out;
8455
40
        size_t outleft = (size_t)(outend - out);
8456
        /* When the whole string is converted, a final iconv() call with a
8457
           NULL input flushes any pending shift sequence (e.g. ISO-2022). */
8458
        /* See the note above on the void* cast of the iconv() input buffer. */
8459
40
        size_t ret = iconv(cd, flushing ? NULL : (void *)&inptr, &inleft, &out, &outleft);
8460
40
        if (!flushing) {
8461
20
            up = inptr;
8462
20
        }
8463
8464
40
        if (ret != (size_t)-1) {
8465
40
            if (flushing) {
8466
20
                break;
8467
20
            }
8468
            /* A positive result counts nonreversible conversions: iconv()
8469
               substituted an unencodable character instead of failing with
8470
               EILSEQ (musl and *BSD citrus do this).  Treat it as unencodable
8471
               and re-run one code point at a time to locate it. */
8472
20
            if (ret > 0) {
8473
0
                if (!careful) {
8474
0
                    careful = 1;
8475
0
                    iconv(cd, NULL, NULL, NULL, NULL);
8476
0
                    out = PyBytesWriter_GetData(writer);
8477
0
                    outend = out + PyBytesWriter_GetSize(writer);
8478
0
                    up = ustart;
8479
0
                    continue;
8480
0
                }
8481
                /* This code point was substituted; drop it and report it. */
8482
0
                out = out_before;
8483
0
                up -= unit;
8484
0
            }
8485
20
            else if (careful && up < uend) {
8486
0
                continue;
8487
0
            }
8488
20
            else {
8489
                /* All input consumed; switch to flushing the shift state. */
8490
20
                flushing = 1;
8491
20
                continue;
8492
20
            }
8493
20
        }
8494
0
        else if (errno == E2BIG) {
8495
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8496
0
                goto done;
8497
0
            }
8498
0
            continue;
8499
0
        }
8500
0
        else if (errno != EILSEQ && errno != EINVAL) {
8501
0
            PyErr_SetFromErrno(PyExc_OSError);
8502
0
            goto done;
8503
0
        }
8504
8505
        /* An unencodable code point at *up; one input unit is one code point. */
8506
0
        Py_ssize_t pos = (up - ustart) / unit;
8507
0
        Py_ssize_t newpos;
8508
0
        PyObject *rep = unicode_encode_call_errorhandler(
8509
0
                errors, &errorHandler, encoding, "invalid character",
8510
0
                unicode, &exc, pos, pos + 1, &newpos);
8511
0
        if (rep == NULL) {
8512
0
            goto done;
8513
0
        }
8514
8515
0
        const char *repdata;
8516
0
        Py_ssize_t replen;
8517
0
        PyObject *repbytes = NULL;
8518
0
        if (PyBytes_Check(rep)) {
8519
0
            repdata = PyBytes_AS_STRING(rep);
8520
0
            replen = PyBytes_GET_SIZE(rep);
8521
0
        }
8522
0
        else {
8523
            /* A str replacement is encoded through the same codec, but
8524
               strictly: handling its errors in turn could never terminate. */
8525
0
            assert(PyUnicode_Check(rep));
8526
0
            repbytes = _PyUnicode_EncodeIconv(encoding, rep, NULL);
8527
0
            Py_DECREF(rep);
8528
0
            if (repbytes == NULL) {
8529
0
                if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
8530
                    /* Report the input the caller knows about, not the
8531
                       replacement. */
8532
0
                    PyErr_Clear();
8533
0
                    raise_encode_exception(&exc, encoding, unicode, pos, pos + 1,
8534
0
                            "unable to encode error handler result");
8535
0
                }
8536
0
                goto done;
8537
0
            }
8538
0
            repdata = PyBytes_AS_STRING(repbytes);
8539
0
            replen = PyBytes_GET_SIZE(repbytes);
8540
0
        }
8541
8542
0
        while (outend - out < replen) {
8543
0
            if (iconv_grow_writer(writer, &out, &outend) < 0) {
8544
0
                if (repbytes != NULL) {
8545
0
                    Py_DECREF(repbytes);
8546
0
                }
8547
0
                else {
8548
0
                    Py_DECREF(rep);
8549
0
                }
8550
0
                goto done;
8551
0
            }
8552
0
        }
8553
0
        memcpy(out, repdata, replen);
8554
0
        out += replen;
8555
0
        if (repbytes != NULL) {
8556
0
            Py_DECREF(repbytes);
8557
0
        }
8558
0
        else {
8559
0
            Py_DECREF(rep);
8560
0
        }
8561
0
        up = ustart + (size_t)newpos * unit;
8562
        /* Reset the shift state after the injected replacement bytes. */
8563
0
        iconv(cd, NULL, NULL, NULL, NULL);
8564
0
    }
8565
8566
20
    if (PyBytesWriter_Resize(writer, out - (char *)PyBytesWriter_GetData(writer)) < 0) {
8567
0
        goto done;
8568
0
    }
8569
20
    result = PyBytesWriter_Finish(writer);
8570
20
    writer = NULL;
8571
8572
20
done:
8573
20
    if (writer != NULL) {
8574
0
        PyBytesWriter_Discard(writer);
8575
0
    }
8576
20
    iconv_close(cd);
8577
20
    PyMem_Free(widened);
8578
20
    Py_XDECREF(errorHandler);
8579
20
    Py_XDECREF(exc);
8580
20
    return result;
8581
20
}
8582
8583
#endif /* HAVE_ICONV */
8584
8585
/* --- Character Mapping Codec -------------------------------------------- */
8586
8587
static int
8588
charmap_decode_string(const char *s,
8589
                      Py_ssize_t size,
8590
                      PyObject *mapping,
8591
                      const char *errors,
8592
                      _PyUnicodeWriter *writer)
8593
1.68k
{
8594
1.68k
    const char *starts = s;
8595
1.68k
    const char *e;
8596
1.68k
    Py_ssize_t startinpos, endinpos;
8597
1.68k
    PyObject *errorHandler = NULL, *exc = NULL;
8598
1.68k
    Py_ssize_t maplen;
8599
1.68k
    int mapkind;
8600
1.68k
    const void *mapdata;
8601
1.68k
    Py_UCS4 x;
8602
1.68k
    unsigned char ch;
8603
8604
1.68k
    maplen = PyUnicode_GET_LENGTH(mapping);
8605
1.68k
    mapdata = PyUnicode_DATA(mapping);
8606
1.68k
    mapkind = PyUnicode_KIND(mapping);
8607
8608
0
    e = s + size;
8609
8610
1.68k
    if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
8611
        /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
8612
         * is disabled in encoding aliases, latin1 is preferred because
8613
         * its implementation is faster. */
8614
16
        const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
8615
16
        Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8616
16
        Py_UCS4 maxchar = writer->maxchar;
8617
8618
16
        assert (writer->kind == PyUnicode_1BYTE_KIND);
8619
2.05k
        while (s < e) {
8620
2.03k
            ch = *s;
8621
2.03k
            x = mapdata_ucs1[ch];
8622
2.03k
            if (x > maxchar) {
8623
16
                if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8624
0
                    goto onError;
8625
16
                maxchar = writer->maxchar;
8626
16
                outdata = (Py_UCS1 *)writer->data;
8627
16
            }
8628
2.03k
            outdata[writer->pos] = x;
8629
2.03k
            writer->pos++;
8630
2.03k
            ++s;
8631
2.03k
        }
8632
16
        return 0;
8633
16
    }
8634
8635
4.42k
    while (s < e) {
8636
4.41k
        if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8637
4.41k
            int outkind = writer->kind;
8638
4.41k
            const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
8639
4.41k
            if (outkind == PyUnicode_1BYTE_KIND) {
8640
2.99k
                Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8641
2.99k
                Py_UCS4 maxchar = writer->maxchar;
8642
541k
                while (s < e) {
8643
541k
                    ch = *s;
8644
541k
                    x = mapdata_ucs2[ch];
8645
541k
                    if (x > maxchar)
8646
2.76k
                        goto Error;
8647
538k
                    outdata[writer->pos] = x;
8648
538k
                    writer->pos++;
8649
538k
                    ++s;
8650
538k
                }
8651
236
                break;
8652
2.99k
            }
8653
1.41k
            else if (outkind == PyUnicode_2BYTE_KIND) {
8654
1.41k
                Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8655
3.67M
                while (s < e) {
8656
3.67M
                    ch = *s;
8657
3.67M
                    x = mapdata_ucs2[ch];
8658
3.67M
                    if (x == 0xFFFE)
8659
14
                        goto Error;
8660
3.67M
                    outdata[writer->pos] = x;
8661
3.67M
                    writer->pos++;
8662
3.67M
                    ++s;
8663
3.67M
                }
8664
1.40k
                break;
8665
1.41k
            }
8666
4.41k
        }
8667
0
        ch = *s;
8668
8669
0
        if (ch < maplen)
8670
0
            x = PyUnicode_READ(mapkind, mapdata, ch);
8671
0
        else
8672
0
            x = 0xfffe; /* invalid value */
8673
2.77k
Error:
8674
2.77k
        if (x == 0xfffe)
8675
24
        {
8676
            /* undefined mapping */
8677
24
            startinpos = s-starts;
8678
24
            endinpos = startinpos+1;
8679
24
            if (unicode_decode_call_errorhandler_writer(
8680
24
                    errors, &errorHandler,
8681
24
                    "charmap", "character maps to <undefined>",
8682
24
                    &starts, &e, &startinpos, &endinpos, &exc, &s,
8683
24
                    writer)) {
8684
24
                goto onError;
8685
24
            }
8686
0
            continue;
8687
24
        }
8688
8689
2.75k
        if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8690
0
            goto onError;
8691
2.75k
        ++s;
8692
2.75k
    }
8693
1.64k
    Py_XDECREF(errorHandler);
8694
1.64k
    Py_XDECREF(exc);
8695
1.64k
    return 0;
8696
8697
24
onError:
8698
24
    Py_XDECREF(errorHandler);
8699
24
    Py_XDECREF(exc);
8700
24
    return -1;
8701
1.66k
}
8702
8703
static int
8704
charmap_decode_mapping(const char *s,
8705
                       Py_ssize_t size,
8706
                       PyObject *mapping,
8707
                       const char *errors,
8708
                       _PyUnicodeWriter *writer)
8709
0
{
8710
0
    const char *starts = s;
8711
0
    const char *e;
8712
0
    Py_ssize_t startinpos, endinpos;
8713
0
    PyObject *errorHandler = NULL, *exc = NULL;
8714
0
    unsigned char ch;
8715
0
    PyObject *key, *item = NULL;
8716
8717
0
    e = s + size;
8718
8719
0
    while (s < e) {
8720
0
        ch = *s;
8721
8722
        /* Get mapping (char ordinal -> integer, Unicode char or None) */
8723
0
        key = PyLong_FromLong((long)ch);
8724
0
        if (key == NULL)
8725
0
            goto onError;
8726
8727
0
        int rc = PyMapping_GetOptionalItem(mapping, key, &item);
8728
0
        Py_DECREF(key);
8729
0
        if (rc == 0) {
8730
            /* No mapping found means: mapping is undefined. */
8731
0
            goto Undefined;
8732
0
        }
8733
0
        if (item == NULL) {
8734
0
            if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8735
                /* No mapping found means: mapping is undefined. */
8736
0
                PyErr_Clear();
8737
0
                goto Undefined;
8738
0
            } else
8739
0
                goto onError;
8740
0
        }
8741
8742
        /* Apply mapping */
8743
0
        if (item == Py_None)
8744
0
            goto Undefined;
8745
0
        if (PyLong_Check(item)) {
8746
0
            long value = PyLong_AsLong(item);
8747
0
            if (value == 0xFFFE)
8748
0
                goto Undefined;
8749
0
            if (value < 0 || value > MAX_UNICODE) {
8750
0
                PyErr_Format(PyExc_TypeError,
8751
0
                             "character mapping must be in range(0x%lx)",
8752
0
                             (unsigned long)MAX_UNICODE + 1);
8753
0
                goto onError;
8754
0
            }
8755
8756
0
            if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8757
0
                goto onError;
8758
0
        }
8759
0
        else if (PyUnicode_Check(item)) {
8760
0
            if (PyUnicode_GET_LENGTH(item) == 1) {
8761
0
                Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8762
0
                if (value == 0xFFFE)
8763
0
                    goto Undefined;
8764
0
                if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8765
0
                    goto onError;
8766
0
            }
8767
0
            else {
8768
0
                writer->overallocate = 1;
8769
0
                if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8770
0
                    goto onError;
8771
0
            }
8772
0
        }
8773
0
        else {
8774
            /* wrong return value */
8775
0
            PyErr_SetString(PyExc_TypeError,
8776
0
                            "character mapping must return integer, None or str");
8777
0
            goto onError;
8778
0
        }
8779
0
        Py_CLEAR(item);
8780
0
        ++s;
8781
0
        continue;
8782
8783
0
Undefined:
8784
        /* undefined mapping */
8785
0
        Py_CLEAR(item);
8786
0
        startinpos = s-starts;
8787
0
        endinpos = startinpos+1;
8788
0
        if (unicode_decode_call_errorhandler_writer(
8789
0
                errors, &errorHandler,
8790
0
                "charmap", "character maps to <undefined>",
8791
0
                &starts, &e, &startinpos, &endinpos, &exc, &s,
8792
0
                writer)) {
8793
0
            goto onError;
8794
0
        }
8795
0
    }
8796
0
    Py_XDECREF(errorHandler);
8797
0
    Py_XDECREF(exc);
8798
0
    return 0;
8799
8800
0
onError:
8801
0
    Py_XDECREF(item);
8802
0
    Py_XDECREF(errorHandler);
8803
0
    Py_XDECREF(exc);
8804
0
    return -1;
8805
0
}
8806
8807
PyObject *
8808
PyUnicode_DecodeCharmap(const char *s,
8809
                        Py_ssize_t size,
8810
                        PyObject *mapping,
8811
                        const char *errors)
8812
1.68k
{
8813
1.68k
    _PyUnicodeWriter writer;
8814
8815
    /* Default to Latin-1 */
8816
1.68k
    if (mapping == NULL)
8817
0
        return PyUnicode_DecodeLatin1(s, size, errors);
8818
8819
1.68k
    if (size == 0)
8820
0
        _Py_RETURN_UNICODE_EMPTY();
8821
1.68k
    _PyUnicodeWriter_Init(&writer);
8822
1.68k
    writer.min_length = size;
8823
1.68k
    if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
8824
0
        goto onError;
8825
8826
1.68k
    if (PyUnicode_CheckExact(mapping)) {
8827
1.68k
        if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8828
24
            goto onError;
8829
1.68k
    }
8830
0
    else {
8831
0
        if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8832
0
            goto onError;
8833
0
    }
8834
1.65k
    return _PyUnicodeWriter_Finish(&writer);
8835
8836
24
  onError:
8837
24
    _PyUnicodeWriter_Dealloc(&writer);
8838
24
    return NULL;
8839
1.68k
}
8840
8841
/* Charmap encoding: the lookup table */
8842
8843
/*[clinic input]
8844
class EncodingMap "struct encoding_map *" "&EncodingMapType"
8845
[clinic start generated code]*/
8846
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=14e46bbb6c522d22]*/
8847
8848
struct encoding_map {
8849
    PyObject_HEAD
8850
    unsigned char level1[32];
8851
    int count2, count3;
8852
    unsigned char level23[1];
8853
};
8854
8855
/*[clinic input]
8856
EncodingMap.size
8857
8858
Return the size (in bytes) of this object.
8859
[clinic start generated code]*/
8860
8861
static PyObject *
8862
EncodingMap_size_impl(struct encoding_map *self)
8863
/*[clinic end generated code: output=c4c969e4c99342a4 input=004ff13f26bb5366]*/
8864
0
{
8865
0
    return PyLong_FromLong((sizeof(*self) - 1) + 16*self->count2 +
8866
0
                           128*self->count3);
8867
0
}
8868
8869
static PyMethodDef encoding_map_methods[] = {
8870
    ENCODINGMAP_SIZE_METHODDEF
8871
    {NULL, NULL}
8872
};
8873
8874
static PyTypeObject EncodingMapType = {
8875
    PyVarObject_HEAD_INIT(NULL, 0)
8876
    .tp_name = "EncodingMap",
8877
    .tp_basicsize = sizeof(struct encoding_map),
8878
    /* methods */
8879
    .tp_flags = Py_TPFLAGS_DEFAULT,
8880
    .tp_methods = encoding_map_methods,
8881
};
8882
8883
PyObject*
8884
PyUnicode_BuildEncodingMap(PyObject* string)
8885
20
{
8886
20
    PyObject *result;
8887
20
    struct encoding_map *mresult;
8888
20
    int i;
8889
20
    int need_dict = 0;
8890
20
    unsigned char level1[32];
8891
20
    unsigned char level2[512];
8892
20
    unsigned char *mlevel1, *mlevel2, *mlevel3;
8893
20
    int count2 = 0, count3 = 0;
8894
20
    int kind;
8895
20
    const void *data;
8896
20
    int length;
8897
20
    Py_UCS4 ch;
8898
8899
20
    if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
8900
0
        PyErr_BadArgument();
8901
0
        return NULL;
8902
0
    }
8903
20
    kind = PyUnicode_KIND(string);
8904
20
    data = PyUnicode_DATA(string);
8905
20
    length = (int)Py_MIN(PyUnicode_GET_LENGTH(string), 256);
8906
20
    memset(level1, 0xFF, sizeof level1);
8907
20
    memset(level2, 0xFF, sizeof level2);
8908
8909
    /* If there isn't a one-to-one mapping of NULL to \0,
8910
       or if there are non-BMP characters, we need to use
8911
       a mapping dictionary. */
8912
20
    if (PyUnicode_READ(kind, data, 0) != 0)
8913
0
        need_dict = 1;
8914
5.12k
    for (i = 1; i < length; i++) {
8915
5.10k
        int l1, l2;
8916
5.10k
        ch = PyUnicode_READ(kind, data, i);
8917
5.10k
        if (ch == 0 || ch > 0xFFFF) {
8918
0
            need_dict = 1;
8919
0
            break;
8920
0
        }
8921
5.10k
        if (ch == 0xFFFE)
8922
            /* unmapped character */
8923
110
            continue;
8924
4.99k
        l1 = ch >> 11;
8925
4.99k
        l2 = ch >> 7;
8926
4.99k
        if (level1[l1] == 0xFF)
8927
35
            level1[l1] = count2++;
8928
4.99k
        if (level2[l2] == 0xFF)
8929
98
            level2[l2] = count3++;
8930
4.99k
    }
8931
8932
20
    if (count2 >= 0xFF || count3 >= 0xFF)
8933
0
        need_dict = 1;
8934
8935
20
    if (need_dict) {
8936
0
        PyObject *result = PyDict_New();
8937
0
        if (!result)
8938
0
            return NULL;
8939
0
        for (i = 0; i < length; i++) {
8940
0
            Py_UCS4 c = PyUnicode_READ(kind, data, i);
8941
0
            PyObject *key = PyLong_FromLong(c);
8942
0
            if (key == NULL) {
8943
0
                Py_DECREF(result);
8944
0
                return NULL;
8945
0
            }
8946
0
            PyObject *value = PyLong_FromLong(i);
8947
0
            if (value == NULL) {
8948
0
                Py_DECREF(key);
8949
0
                Py_DECREF(result);
8950
0
                return NULL;
8951
0
            }
8952
0
            int rc = PyDict_SetItem(result, key, value);
8953
0
            Py_DECREF(key);
8954
0
            Py_DECREF(value);
8955
0
            if (rc < 0) {
8956
0
                Py_DECREF(result);
8957
0
                return NULL;
8958
0
            }
8959
0
        }
8960
0
        return result;
8961
0
    }
8962
8963
    /* Create a three-level trie */
8964
20
    result = PyObject_Malloc(sizeof(struct encoding_map) +
8965
20
                             16*count2 + 128*count3 - 1);
8966
20
    if (!result) {
8967
0
        return PyErr_NoMemory();
8968
0
    }
8969
8970
20
    _PyObject_Init(result, &EncodingMapType);
8971
20
    mresult = (struct encoding_map*)result;
8972
20
    mresult->count2 = count2;
8973
20
    mresult->count3 = count3;
8974
20
    mlevel1 = mresult->level1;
8975
20
    mlevel2 = mresult->level23;
8976
20
    mlevel3 = mresult->level23 + 16*count2;
8977
20
    memcpy(mlevel1, level1, 32);
8978
20
    memset(mlevel2, 0xFF, 16*count2);
8979
20
    memset(mlevel3, 0, 128*count3);
8980
20
    count3 = 0;
8981
5.12k
    for (i = 1; i < length; i++) {
8982
5.10k
        int o1, o2, o3, i2, i3;
8983
5.10k
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8984
5.10k
        if (ch == 0xFFFE)
8985
            /* unmapped character */
8986
110
            continue;
8987
4.99k
        o1 = ch>>11;
8988
4.99k
        o2 = (ch>>7) & 0xF;
8989
4.99k
        i2 = 16*mlevel1[o1] + o2;
8990
4.99k
        if (mlevel2[i2] == 0xFF)
8991
98
            mlevel2[i2] = count3++;
8992
4.99k
        o3 = ch & 0x7F;
8993
4.99k
        i3 = 128*mlevel2[i2] + o3;
8994
4.99k
        mlevel3[i3] = i;
8995
4.99k
    }
8996
20
    return result;
8997
20
}
8998
8999
static int
9000
encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
9001
0
{
9002
0
    struct encoding_map *map = (struct encoding_map*)mapping;
9003
0
    int l1 = c>>11;
9004
0
    int l2 = (c>>7) & 0xF;
9005
0
    int l3 = c & 0x7F;
9006
0
    int i;
9007
9008
0
    if (c > 0xFFFF)
9009
0
        return -1;
9010
0
    if (c == 0)
9011
0
        return 0;
9012
    /* level 1*/
9013
0
    i = map->level1[l1];
9014
0
    if (i == 0xFF) {
9015
0
        return -1;
9016
0
    }
9017
    /* level 2*/
9018
0
    i = map->level23[16*i+l2];
9019
0
    if (i == 0xFF) {
9020
0
        return -1;
9021
0
    }
9022
    /* level 3 */
9023
0
    i = map->level23[16*map->count2 + 128*i + l3];
9024
0
    if (i == 0) {
9025
0
        return -1;
9026
0
    }
9027
0
    return i;
9028
0
}
9029
9030
/* Lookup the character in the mapping.
9031
   On success, return PyLong, PyBytes or None (if the character can't be found).
9032
   If the result is PyLong, put its value in replace.
9033
   On error, return NULL.
9034
   */
9035
static PyObject *
9036
charmapencode_lookup(Py_UCS4 c, PyObject *mapping, unsigned char *replace)
9037
0
{
9038
0
    PyObject *w = PyLong_FromLong((long)c);
9039
0
    PyObject *x;
9040
9041
0
    if (w == NULL)
9042
0
        return NULL;
9043
0
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9044
0
    Py_DECREF(w);
9045
0
    if (rc == 0) {
9046
        /* No mapping found means: mapping is undefined. */
9047
0
        Py_RETURN_NONE;
9048
0
    }
9049
0
    if (x == NULL) {
9050
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9051
            /* No mapping found means: mapping is undefined. */
9052
0
            PyErr_Clear();
9053
0
            Py_RETURN_NONE;
9054
0
        } else
9055
0
            return NULL;
9056
0
    }
9057
0
    else if (x == Py_None)
9058
0
        return x;
9059
0
    else if (PyLong_Check(x)) {
9060
0
        long value = PyLong_AsLong(x);
9061
0
        if (value < 0 || value > 255) {
9062
0
            PyErr_SetString(PyExc_TypeError,
9063
0
                            "character mapping must be in range(256)");
9064
0
            Py_DECREF(x);
9065
0
            return NULL;
9066
0
        }
9067
0
        *replace = (unsigned char)value;
9068
0
        return x;
9069
0
    }
9070
0
    else if (PyBytes_Check(x))
9071
0
        return x;
9072
0
    else {
9073
        /* wrong return value */
9074
0
        PyErr_Format(PyExc_TypeError,
9075
0
                     "character mapping must return integer, bytes or None, not %.400s",
9076
0
                     Py_TYPE(x)->tp_name);
9077
0
        Py_DECREF(x);
9078
0
        return NULL;
9079
0
    }
9080
0
}
9081
9082
static int
9083
charmapencode_resize(PyBytesWriter *writer, Py_ssize_t *outpos, Py_ssize_t requiredsize)
9084
0
{
9085
0
    Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9086
    /* exponentially overallocate to minimize reallocations */
9087
0
    if (requiredsize < 2 * outsize)
9088
0
        requiredsize = 2 * outsize;
9089
0
    return PyBytesWriter_Resize(writer, requiredsize);
9090
0
}
9091
9092
typedef enum charmapencode_result {
9093
    enc_SUCCESS, enc_FAILED, enc_EXCEPTION
9094
} charmapencode_result;
9095
/* lookup the character, put the result in the output string and adjust
9096
   various state variables. Resize the output bytes object if not enough
9097
   space is available. Return a new reference to the object that
9098
   was put in the output buffer, or Py_None, if the mapping was undefined
9099
   (in which case no character was written) or NULL, if a
9100
   reallocation error occurred. The caller must decref the result */
9101
static charmapencode_result
9102
charmapencode_output(Py_UCS4 c, PyObject *mapping,
9103
                     PyBytesWriter *writer, Py_ssize_t *outpos)
9104
0
{
9105
0
    PyObject *rep;
9106
0
    unsigned char replace;
9107
0
    char *outstart;
9108
0
    Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9109
9110
0
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9111
0
        int res = encoding_map_lookup(c, mapping);
9112
0
        Py_ssize_t requiredsize = *outpos+1;
9113
0
        if (res == -1) {
9114
0
            return enc_FAILED;
9115
0
        }
9116
9117
0
        if (outsize<requiredsize) {
9118
0
            if (charmapencode_resize(writer, outpos, requiredsize)) {
9119
0
                return enc_EXCEPTION;
9120
0
            }
9121
0
        }
9122
0
        outstart = _PyBytesWriter_GetData(writer);
9123
0
        outstart[(*outpos)++] = (char)res;
9124
0
        return enc_SUCCESS;
9125
0
    }
9126
9127
0
    rep = charmapencode_lookup(c, mapping, &replace);
9128
0
    if (rep==NULL)
9129
0
        return enc_EXCEPTION;
9130
0
    else if (rep==Py_None) {
9131
0
        Py_DECREF(rep);
9132
0
        return enc_FAILED;
9133
0
    } else {
9134
0
        if (PyLong_Check(rep)) {
9135
0
            Py_ssize_t requiredsize = *outpos+1;
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
            outstart[(*outpos)++] = (char)replace;
9143
0
        }
9144
0
        else {
9145
0
            const char *repchars = PyBytes_AS_STRING(rep);
9146
0
            Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
9147
0
            Py_ssize_t requiredsize = *outpos+repsize;
9148
0
            if (outsize<requiredsize)
9149
0
                if (charmapencode_resize(writer, outpos, requiredsize)) {
9150
0
                    Py_DECREF(rep);
9151
0
                    return enc_EXCEPTION;
9152
0
                }
9153
0
            outstart = _PyBytesWriter_GetData(writer);
9154
0
            memcpy(outstart + *outpos, repchars, repsize);
9155
0
            *outpos += repsize;
9156
0
        }
9157
0
    }
9158
0
    Py_DECREF(rep);
9159
0
    return enc_SUCCESS;
9160
0
}
9161
9162
/* handle an error in _PyUnicode_EncodeCharmap()
9163
   Return 0 on success, -1 on error */
9164
static int
9165
charmap_encoding_error(
9166
    PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
9167
    PyObject **exceptionObject,
9168
    _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
9169
    PyBytesWriter *writer, Py_ssize_t *respos)
9170
0
{
9171
0
    PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9172
0
    Py_ssize_t size, repsize;
9173
0
    Py_ssize_t newpos;
9174
0
    int kind;
9175
0
    const void *data;
9176
0
    Py_ssize_t index;
9177
    /* startpos for collecting unencodable chars */
9178
0
    Py_ssize_t collstartpos = *inpos;
9179
0
    Py_ssize_t collendpos = *inpos+1;
9180
0
    Py_ssize_t collpos;
9181
0
    const char *encoding = "charmap";
9182
0
    const char *reason = "character maps to <undefined>";
9183
0
    charmapencode_result x;
9184
0
    Py_UCS4 ch;
9185
0
    int val;
9186
9187
0
    size = PyUnicode_GET_LENGTH(unicode);
9188
    /* find all unencodable characters */
9189
0
    while (collendpos < size) {
9190
0
        PyObject *rep;
9191
0
        unsigned char replace;
9192
0
        if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9193
0
            ch = PyUnicode_READ_CHAR(unicode, collendpos);
9194
0
            val = encoding_map_lookup(ch, mapping);
9195
0
            if (val != -1)
9196
0
                break;
9197
0
            ++collendpos;
9198
0
            continue;
9199
0
        }
9200
9201
0
        ch = PyUnicode_READ_CHAR(unicode, collendpos);
9202
0
        rep = charmapencode_lookup(ch, mapping, &replace);
9203
0
        if (rep==NULL)
9204
0
            return -1;
9205
0
        else if (rep!=Py_None) {
9206
0
            Py_DECREF(rep);
9207
0
            break;
9208
0
        }
9209
0
        Py_DECREF(rep);
9210
0
        ++collendpos;
9211
0
    }
9212
    /* cache callback name lookup
9213
     * (if not done yet, i.e. it's the first error) */
9214
0
    if (*error_handler == _Py_ERROR_UNKNOWN)
9215
0
        *error_handler = _Py_GetErrorHandler(errors);
9216
9217
0
    switch (*error_handler) {
9218
0
    case _Py_ERROR_STRICT:
9219
0
        raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9220
0
        return -1;
9221
9222
0
    case _Py_ERROR_REPLACE:
9223
0
        for (collpos = collstartpos; collpos<collendpos; ++collpos) {
9224
0
            x = charmapencode_output('?', mapping, writer, respos);
9225
0
            if (x==enc_EXCEPTION) {
9226
0
                return -1;
9227
0
            }
9228
0
            else if (x==enc_FAILED) {
9229
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9230
0
                return -1;
9231
0
            }
9232
0
        }
9233
0
        _Py_FALLTHROUGH;
9234
0
    case _Py_ERROR_IGNORE:
9235
0
        *inpos = collendpos;
9236
0
        break;
9237
9238
0
    case _Py_ERROR_XMLCHARREFREPLACE:
9239
        /* generate replacement (temporarily (mis)uses p) */
9240
0
        for (collpos = collstartpos; collpos < collendpos; ++collpos) {
9241
0
            char buffer[2+29+1+1];
9242
0
            char *cp;
9243
0
            sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
9244
0
            for (cp = buffer; *cp; ++cp) {
9245
0
                x = charmapencode_output(*cp, mapping, writer, respos);
9246
0
                if (x==enc_EXCEPTION)
9247
0
                    return -1;
9248
0
                else if (x==enc_FAILED) {
9249
0
                    raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9250
0
                    return -1;
9251
0
                }
9252
0
            }
9253
0
        }
9254
0
        *inpos = collendpos;
9255
0
        break;
9256
9257
0
    default:
9258
0
        repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
9259
0
                                                      encoding, reason, unicode, exceptionObject,
9260
0
                                                      collstartpos, collendpos, &newpos);
9261
0
        if (repunicode == NULL)
9262
0
            return -1;
9263
0
        if (PyBytes_Check(repunicode)) {
9264
            /* Directly copy bytes result to output. */
9265
0
            Py_ssize_t outsize = PyBytesWriter_GetSize(writer);
9266
0
            Py_ssize_t requiredsize;
9267
0
            repsize = PyBytes_Size(repunicode);
9268
0
            requiredsize = *respos + repsize;
9269
0
            if (requiredsize > outsize)
9270
                /* Make room for all additional bytes. */
9271
0
                if (charmapencode_resize(writer, respos, requiredsize)) {
9272
0
                    Py_DECREF(repunicode);
9273
0
                    return -1;
9274
0
                }
9275
0
            memcpy((char*)PyBytesWriter_GetData(writer) + *respos,
9276
0
                   PyBytes_AsString(repunicode),  repsize);
9277
0
            *respos += repsize;
9278
0
            *inpos = newpos;
9279
0
            Py_DECREF(repunicode);
9280
0
            break;
9281
0
        }
9282
        /* generate replacement  */
9283
0
        repsize = PyUnicode_GET_LENGTH(repunicode);
9284
0
        data = PyUnicode_DATA(repunicode);
9285
0
        kind = PyUnicode_KIND(repunicode);
9286
0
        for (index = 0; index < repsize; index++) {
9287
0
            Py_UCS4 repch = PyUnicode_READ(kind, data, index);
9288
0
            x = charmapencode_output(repch, mapping, writer, respos);
9289
0
            if (x==enc_EXCEPTION) {
9290
0
                Py_DECREF(repunicode);
9291
0
                return -1;
9292
0
            }
9293
0
            else if (x==enc_FAILED) {
9294
0
                Py_DECREF(repunicode);
9295
0
                raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
9296
0
                return -1;
9297
0
            }
9298
0
        }
9299
0
        *inpos = newpos;
9300
0
        Py_DECREF(repunicode);
9301
0
    }
9302
0
    return 0;
9303
0
}
9304
9305
PyObject *
9306
_PyUnicode_EncodeCharmap(PyObject *unicode,
9307
                         PyObject *mapping,
9308
                         const char *errors)
9309
0
{
9310
    /* Default to Latin-1 */
9311
0
    if (mapping == NULL) {
9312
0
        return unicode_encode_ucs1(unicode, errors, 256);
9313
0
    }
9314
9315
0
    Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
9316
0
    if (size == 0) {
9317
0
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
9318
0
    }
9319
0
    const void *data = PyUnicode_DATA(unicode);
9320
0
    int kind = PyUnicode_KIND(unicode);
9321
9322
0
    PyObject *error_handler_obj = NULL;
9323
0
    PyObject *exc = NULL;
9324
9325
    /* output object */
9326
0
    PyBytesWriter *writer;
9327
    /* allocate enough for a simple encoding without
9328
       replacements, if we need more, we'll resize */
9329
0
    writer = PyBytesWriter_Create(size);
9330
0
    if (writer == NULL) {
9331
0
        goto onError;
9332
0
    }
9333
9334
    /* current input position */
9335
0
    Py_ssize_t inpos = 0;
9336
    /* current output position */
9337
0
    Py_ssize_t respos = 0;
9338
0
    _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
9339
9340
0
    if (Py_IS_TYPE(mapping, &EncodingMapType)) {
9341
0
        char *outstart = _PyBytesWriter_GetData(writer);
9342
0
        Py_ssize_t outsize = _PyBytesWriter_GetSize(writer);
9343
9344
0
        while (inpos<size) {
9345
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9346
9347
            /* try to encode it */
9348
0
            int res = encoding_map_lookup(ch, mapping);
9349
0
            Py_ssize_t requiredsize = respos+1;
9350
0
            if (res == -1) {
9351
0
                goto enc_FAILED;
9352
0
            }
9353
9354
0
            if (outsize<requiredsize) {
9355
0
                if (charmapencode_resize(writer, &respos, requiredsize)) {
9356
0
                    goto onError;
9357
0
                }
9358
0
                outstart = _PyBytesWriter_GetData(writer);
9359
0
                outsize = _PyBytesWriter_GetSize(writer);
9360
0
            }
9361
0
            outstart[respos++] = (char)res;
9362
9363
            /* done with this character => adjust input position */
9364
0
            ++inpos;
9365
0
            continue;
9366
9367
0
enc_FAILED:
9368
0
            if (charmap_encoding_error(unicode, &inpos, mapping,
9369
0
                                       &exc,
9370
0
                                       &error_handler, &error_handler_obj, errors,
9371
0
                                       writer, &respos)) {
9372
0
                goto onError;
9373
0
            }
9374
0
            outstart = _PyBytesWriter_GetData(writer);
9375
0
            outsize = _PyBytesWriter_GetSize(writer);
9376
0
        }
9377
0
    }
9378
0
    else {
9379
0
        while (inpos<size) {
9380
0
            Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
9381
            /* try to encode it */
9382
0
            charmapencode_result x = charmapencode_output(ch, mapping, writer, &respos);
9383
0
            if (x==enc_EXCEPTION) { /* error */
9384
0
                goto onError;
9385
0
            }
9386
0
            if (x==enc_FAILED) { /* unencodable character */
9387
0
                if (charmap_encoding_error(unicode, &inpos, mapping,
9388
0
                                           &exc,
9389
0
                                           &error_handler, &error_handler_obj, errors,
9390
0
                                           writer, &respos)) {
9391
0
                    goto onError;
9392
0
                }
9393
0
            }
9394
0
            else {
9395
                /* done with this character => adjust input position */
9396
0
                ++inpos;
9397
0
            }
9398
0
        }
9399
0
    }
9400
9401
0
    Py_XDECREF(exc);
9402
0
    Py_XDECREF(error_handler_obj);
9403
9404
    /* Resize if we allocated too much */
9405
0
    return PyBytesWriter_FinishWithSize(writer, respos);
9406
9407
0
  onError:
9408
0
    PyBytesWriter_Discard(writer);
9409
0
    Py_XDECREF(exc);
9410
0
    Py_XDECREF(error_handler_obj);
9411
0
    return NULL;
9412
0
}
9413
9414
PyObject *
9415
PyUnicode_AsCharmapString(PyObject *unicode,
9416
                          PyObject *mapping)
9417
0
{
9418
0
    if (!PyUnicode_Check(unicode) || mapping == NULL) {
9419
0
        PyErr_BadArgument();
9420
0
        return NULL;
9421
0
    }
9422
0
    return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
9423
0
}
9424
9425
/* create or adjust a UnicodeTranslateError */
9426
static void
9427
make_translate_exception(PyObject **exceptionObject,
9428
                         PyObject *unicode,
9429
                         Py_ssize_t startpos, Py_ssize_t endpos,
9430
                         const char *reason)
9431
0
{
9432
0
    if (*exceptionObject == NULL) {
9433
0
        *exceptionObject = _PyUnicodeTranslateError_Create(
9434
0
            unicode, startpos, endpos, reason);
9435
0
    }
9436
0
    else {
9437
0
        if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
9438
0
            goto onError;
9439
0
        if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
9440
0
            goto onError;
9441
0
        if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
9442
0
            goto onError;
9443
0
        return;
9444
0
      onError:
9445
0
        Py_CLEAR(*exceptionObject);
9446
0
    }
9447
0
}
9448
9449
/* error handling callback helper:
9450
   build arguments, call the callback and check the arguments,
9451
   put the result into newpos and return the replacement string, which
9452
   has to be freed by the caller */
9453
static PyObject *
9454
unicode_translate_call_errorhandler(const char *errors,
9455
                                    PyObject **errorHandler,
9456
                                    const char *reason,
9457
                                    PyObject *unicode, PyObject **exceptionObject,
9458
                                    Py_ssize_t startpos, Py_ssize_t endpos,
9459
                                    Py_ssize_t *newpos)
9460
0
{
9461
0
    static const char *argparse = "Un;translating error handler must return (str, int) tuple";
9462
9463
0
    Py_ssize_t i_newpos;
9464
0
    PyObject *restuple;
9465
0
    PyObject *resunicode;
9466
9467
0
    if (*errorHandler == NULL) {
9468
0
        *errorHandler = PyCodec_LookupError(errors);
9469
0
        if (*errorHandler == NULL)
9470
0
            return NULL;
9471
0
    }
9472
9473
0
    make_translate_exception(exceptionObject,
9474
0
                             unicode, startpos, endpos, reason);
9475
0
    if (*exceptionObject == NULL)
9476
0
        return NULL;
9477
9478
0
    restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
9479
0
    if (restuple == NULL)
9480
0
        return NULL;
9481
0
    if (!PyTuple_Check(restuple)) {
9482
0
        PyErr_SetString(PyExc_TypeError, &argparse[3]);
9483
0
        Py_DECREF(restuple);
9484
0
        return NULL;
9485
0
    }
9486
0
    if (!PyArg_ParseTuple(restuple, argparse,
9487
0
                          &resunicode, &i_newpos)) {
9488
0
        Py_DECREF(restuple);
9489
0
        return NULL;
9490
0
    }
9491
0
    if (i_newpos<0)
9492
0
        *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
9493
0
    else
9494
0
        *newpos = i_newpos;
9495
0
    if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
9496
0
        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
9497
0
        Py_DECREF(restuple);
9498
0
        return NULL;
9499
0
    }
9500
0
    Py_INCREF(resunicode);
9501
0
    Py_DECREF(restuple);
9502
0
    return resunicode;
9503
0
}
9504
9505
/* Lookup the character ch in the mapping and put the result in result,
9506
   which must be decrefed by the caller.
9507
   The result can be PyLong, PyUnicode, None or NULL.
9508
   If the result is PyLong, put its value in replace.
9509
   Return 0 on success, -1 on error */
9510
static int
9511
charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result, Py_UCS4 *replace)
9512
282
{
9513
282
    PyObject *w = PyLong_FromLong((long)c);
9514
282
    PyObject *x;
9515
9516
282
    if (w == NULL)
9517
0
        return -1;
9518
282
    int rc = PyMapping_GetOptionalItem(mapping, w, &x);
9519
282
    Py_DECREF(w);
9520
282
    if (rc == 0) {
9521
        /* No mapping found means: use 1:1 mapping. */
9522
126
        *result = NULL;
9523
126
        return 0;
9524
126
    }
9525
156
    if (x == NULL) {
9526
0
        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
9527
            /* No mapping found means: use 1:1 mapping. */
9528
0
            PyErr_Clear();
9529
0
            *result = NULL;
9530
0
            return 0;
9531
0
        } else
9532
0
            return -1;
9533
0
    }
9534
156
    else if (x == Py_None) {
9535
0
        *result = x;
9536
0
        return 0;
9537
0
    }
9538
156
    else if (PyLong_Check(x)) {
9539
0
        long value = PyLong_AsLong(x);
9540
0
        if (value < 0 || value > MAX_UNICODE) {
9541
0
            PyErr_Format(PyExc_ValueError,
9542
0
                         "character mapping must be in range(0x%lx)",
9543
0
                         (unsigned long)MAX_UNICODE + 1);
9544
0
            Py_DECREF(x);
9545
0
            return -1;
9546
0
        }
9547
0
        *result = x;
9548
0
        *replace = (Py_UCS4)value;
9549
0
        return 0;
9550
0
    }
9551
156
    else if (PyUnicode_Check(x)) {
9552
156
        *result = x;
9553
156
        return 0;
9554
156
    }
9555
0
    else {
9556
        /* wrong return value */
9557
0
        PyErr_SetString(PyExc_TypeError,
9558
0
                        "character mapping must return integer, None or str");
9559
0
        Py_DECREF(x);
9560
0
        return -1;
9561
0
    }
9562
156
}
9563
9564
/* lookup the character, write the result into the writer.
9565
   Return 1 if the result was written into the writer, return 0 if the mapping
9566
   was undefined, raise an exception return -1 on error. */
9567
static int
9568
charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
9569
                        _PyUnicodeWriter *writer)
9570
108
{
9571
108
    PyObject *item;
9572
108
    Py_UCS4 replace;
9573
9574
108
    if (charmaptranslate_lookup(ch, mapping, &item, &replace))
9575
0
        return -1;
9576
9577
108
    if (item == NULL) {
9578
        /* not found => default to 1:1 mapping */
9579
24
        if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
9580
0
            return -1;
9581
0
        }
9582
24
        return 1;
9583
24
    }
9584
9585
84
    if (item == Py_None) {
9586
0
        Py_DECREF(item);
9587
0
        return 0;
9588
0
    }
9589
9590
84
    if (PyLong_Check(item)) {
9591
0
        if (_PyUnicodeWriter_WriteCharInline(writer, replace) < 0) {
9592
0
            Py_DECREF(item);
9593
0
            return -1;
9594
0
        }
9595
0
        Py_DECREF(item);
9596
0
        return 1;
9597
0
    }
9598
9599
84
    if (!PyUnicode_Check(item)) {
9600
0
        Py_DECREF(item);
9601
0
        return -1;
9602
0
    }
9603
9604
84
    if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
9605
0
        Py_DECREF(item);
9606
0
        return -1;
9607
0
    }
9608
9609
84
    Py_DECREF(item);
9610
84
    return 1;
9611
84
}
9612
9613
static int
9614
unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
9615
                              Py_UCS1 *translate)
9616
174
{
9617
174
    PyObject *item = NULL;
9618
174
    Py_UCS4 replace;
9619
174
    int ret = 0;
9620
9621
174
    if (charmaptranslate_lookup(ch, mapping, &item, &replace)) {
9622
0
        return -1;
9623
0
    }
9624
9625
174
    if (item == Py_None) {
9626
        /* deletion */
9627
0
        translate[ch] = 0xfe;
9628
0
    }
9629
174
    else if (item == NULL) {
9630
        /* not found => default to 1:1 mapping */
9631
102
        translate[ch] = ch;
9632
102
        return 1;
9633
102
    }
9634
72
    else if (PyLong_Check(item)) {
9635
0
        if (replace > 127) {
9636
            /* invalid character or character outside ASCII:
9637
               skip the fast translate */
9638
0
            goto exit;
9639
0
        }
9640
0
        translate[ch] = (Py_UCS1)replace;
9641
0
    }
9642
72
    else if (PyUnicode_Check(item)) {
9643
72
        if (PyUnicode_GET_LENGTH(item) != 1)
9644
72
            goto exit;
9645
9646
0
        replace = PyUnicode_READ_CHAR(item, 0);
9647
0
        if (replace > 127)
9648
0
            goto exit;
9649
0
        translate[ch] = (Py_UCS1)replace;
9650
0
    }
9651
0
    else {
9652
        /* not None, NULL, long or unicode */
9653
0
        goto exit;
9654
0
    }
9655
0
    ret = 1;
9656
9657
72
  exit:
9658
72
    Py_DECREF(item);
9659
72
    return ret;
9660
0
}
9661
9662
/* Fast path for ascii => ascii translation. Return 1 if the whole string
9663
   was translated into writer, return 0 if the input string was partially
9664
   translated into writer, raise an exception and return -1 on error. */
9665
static int
9666
unicode_fast_translate(PyObject *input, PyObject *mapping,
9667
                       _PyUnicodeWriter *writer, int ignore,
9668
                       Py_ssize_t *input_pos)
9669
144
{
9670
144
    Py_UCS1 ascii_table[128], ch, ch2;
9671
144
    Py_ssize_t len;
9672
144
    const Py_UCS1 *in, *end;
9673
144
    Py_UCS1 *out;
9674
144
    int res = 0;
9675
9676
144
    len = PyUnicode_GET_LENGTH(input);
9677
9678
144
    memset(ascii_table, 0xff, 128);
9679
9680
144
    in = PyUnicode_1BYTE_DATA(input);
9681
144
    end = in + len;
9682
9683
144
    assert(PyUnicode_IS_ASCII(writer->buffer));
9684
144
    assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9685
144
    out = PyUnicode_1BYTE_DATA(writer->buffer);
9686
9687
267
    for (; in < end; in++) {
9688
195
        ch = *in;
9689
195
        ch2 = ascii_table[ch];
9690
195
        if (ch2 == 0xff) {
9691
174
            int translate = unicode_fast_translate_lookup(mapping, ch,
9692
174
                                                          ascii_table);
9693
174
            if (translate < 0)
9694
0
                return -1;
9695
174
            if (translate == 0)
9696
72
                goto exit;
9697
102
            ch2 = ascii_table[ch];
9698
102
        }
9699
123
        if (ch2 == 0xfe) {
9700
0
            if (ignore)
9701
0
                continue;
9702
0
            goto exit;
9703
0
        }
9704
123
        assert(ch2 < 128);
9705
123
        *out = ch2;
9706
123
        out++;
9707
123
    }
9708
72
    res = 1;
9709
9710
144
exit:
9711
144
    writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
9712
144
    *input_pos = in - PyUnicode_1BYTE_DATA(input);
9713
144
    return res;
9714
72
}
9715
9716
static PyObject *
9717
_PyUnicode_TranslateCharmap(PyObject *input,
9718
                            PyObject *mapping,
9719
                            const char *errors)
9720
144
{
9721
    /* input object */
9722
144
    const void *data;
9723
144
    Py_ssize_t size, i;
9724
144
    int kind;
9725
    /* output buffer */
9726
144
    _PyUnicodeWriter writer;
9727
    /* error handler */
9728
144
    const char *reason = "character maps to <undefined>";
9729
144
    PyObject *errorHandler = NULL;
9730
144
    PyObject *exc = NULL;
9731
144
    int ignore;
9732
144
    int res;
9733
9734
144
    if (mapping == NULL) {
9735
0
        PyErr_BadArgument();
9736
0
        return NULL;
9737
0
    }
9738
9739
144
    data = PyUnicode_DATA(input);
9740
144
    kind = PyUnicode_KIND(input);
9741
144
    size = PyUnicode_GET_LENGTH(input);
9742
9743
144
    if (size == 0)
9744
0
        return PyUnicode_FromObject(input);
9745
9746
    /* allocate enough for a simple 1:1 translation without
9747
       replacements, if we need more, we'll resize */
9748
144
    _PyUnicodeWriter_Init(&writer);
9749
144
    if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
9750
0
        goto onError;
9751
9752
144
    ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9753
9754
144
    if (PyUnicode_IS_ASCII(input)) {
9755
144
        res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9756
144
        if (res < 0) {
9757
0
            _PyUnicodeWriter_Dealloc(&writer);
9758
0
            return NULL;
9759
0
        }
9760
144
        if (res == 1)
9761
72
            return _PyUnicodeWriter_Finish(&writer);
9762
144
    }
9763
0
    else {
9764
0
        i = 0;
9765
0
    }
9766
9767
180
    while (i<size) {
9768
        /* try to encode it */
9769
108
        int translate;
9770
108
        PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9771
108
        Py_ssize_t newpos;
9772
        /* startpos for collecting untranslatable chars */
9773
108
        Py_ssize_t collstart;
9774
108
        Py_ssize_t collend;
9775
108
        Py_UCS4 ch;
9776
9777
108
        ch = PyUnicode_READ(kind, data, i);
9778
108
        translate = charmaptranslate_output(ch, mapping, &writer);
9779
108
        if (translate < 0)
9780
0
            goto onError;
9781
9782
108
        if (translate != 0) {
9783
            /* it worked => adjust input pointer */
9784
108
            ++i;
9785
108
            continue;
9786
108
        }
9787
9788
        /* untranslatable character */
9789
0
        collstart = i;
9790
0
        collend = i+1;
9791
9792
        /* find all untranslatable characters */
9793
0
        while (collend < size) {
9794
0
            PyObject *x;
9795
0
            Py_UCS4 replace;
9796
0
            ch = PyUnicode_READ(kind, data, collend);
9797
0
            if (charmaptranslate_lookup(ch, mapping, &x, &replace))
9798
0
                goto onError;
9799
0
            Py_XDECREF(x);
9800
0
            if (x != Py_None)
9801
0
                break;
9802
0
            ++collend;
9803
0
        }
9804
9805
0
        if (ignore) {
9806
0
            i = collend;
9807
0
        }
9808
0
        else {
9809
0
            repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9810
0
                                                             reason, input, &exc,
9811
0
                                                             collstart, collend, &newpos);
9812
0
            if (repunicode == NULL)
9813
0
                goto onError;
9814
0
            if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
9815
0
                Py_DECREF(repunicode);
9816
0
                goto onError;
9817
0
            }
9818
0
            Py_DECREF(repunicode);
9819
0
            i = newpos;
9820
0
        }
9821
0
    }
9822
72
    Py_XDECREF(exc);
9823
72
    Py_XDECREF(errorHandler);
9824
72
    return _PyUnicodeWriter_Finish(&writer);
9825
9826
0
  onError:
9827
0
    _PyUnicodeWriter_Dealloc(&writer);
9828
0
    Py_XDECREF(exc);
9829
0
    Py_XDECREF(errorHandler);
9830
0
    return NULL;
9831
72
}
9832
9833
PyObject *
9834
PyUnicode_Translate(PyObject *str,
9835
                    PyObject *mapping,
9836
                    const char *errors)
9837
0
{
9838
0
    if (ensure_unicode(str) < 0)
9839
0
        return NULL;
9840
0
    return _PyUnicode_TranslateCharmap(str, mapping, errors);
9841
0
}
9842
9843
PyObject *
9844
_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9845
194k
{
9846
194k
    if (!PyUnicode_Check(unicode)) {
9847
0
        PyErr_BadInternalCall();
9848
0
        return NULL;
9849
0
    }
9850
194k
    if (PyUnicode_IS_ASCII(unicode)) {
9851
        /* If the string is already ASCII, just return the same string */
9852
192k
        return Py_NewRef(unicode);
9853
192k
    }
9854
9855
1.58k
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9856
1.58k
    PyObject *result = PyUnicode_New(len, 127);
9857
1.58k
    if (result == NULL) {
9858
0
        return NULL;
9859
0
    }
9860
9861
1.58k
    Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9862
1.58k
    int kind = PyUnicode_KIND(unicode);
9863
1.58k
    const void *data = PyUnicode_DATA(unicode);
9864
1.58k
    Py_ssize_t i;
9865
1.22M
    for (i = 0; i < len; ++i) {
9866
1.22M
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9867
1.22M
        if (ch < 127) {
9868
1.21M
            out[i] = ch;
9869
1.21M
        }
9870
8.66k
        else if (Py_UNICODE_ISSPACE(ch)) {
9871
6.72k
            out[i] = ' ';
9872
6.72k
        }
9873
1.94k
        else {
9874
1.94k
            int decimal = Py_UNICODE_TODECIMAL(ch);
9875
1.94k
            if (decimal < 0) {
9876
1.31k
                out[i] = '?';
9877
1.31k
                out[i+1] = '\0';
9878
1.31k
                _PyUnicode_LENGTH(result) = i + 1;
9879
0
                break;
9880
1.31k
            }
9881
623
            out[i] = '0' + decimal;
9882
623
        }
9883
1.22M
    }
9884
9885
1.58k
    assert(_PyUnicode_CheckConsistency(result, 1));
9886
1.58k
    return result;
9887
1.58k
}
9888
9889
/* --- Helpers ------------------------------------------------------------ */
9890
9891
/* helper macro to fixup start/end slice values */
9892
#define ADJUST_INDICES(start, end, len) \
9893
3.18M
    do {                                \
9894
3.18M
        if (end > len) {                \
9895
359k
            end = len;                  \
9896
359k
        }                               \
9897
3.18M
        else if (end < 0) {             \
9898
0
            end += len;                 \
9899
0
            if (end < 0) {              \
9900
0
                end = 0;                \
9901
0
            }                           \
9902
0
        }                               \
9903
3.18M
        if (start < 0) {                \
9904
0
            start += len;               \
9905
0
            if (start < 0) {            \
9906
0
                start = 0;              \
9907
0
            }                           \
9908
0
        }                               \
9909
3.18M
    } while (0)
9910
9911
static Py_ssize_t
9912
any_find_slice(PyObject* s1, PyObject* s2,
9913
               Py_ssize_t start,
9914
               Py_ssize_t end,
9915
               int direction)
9916
12.6k
{
9917
12.6k
    int kind1, kind2;
9918
12.6k
    const void *buf1, *buf2;
9919
12.6k
    Py_ssize_t len1, len2, result;
9920
9921
12.6k
    kind1 = PyUnicode_KIND(s1);
9922
12.6k
    kind2 = PyUnicode_KIND(s2);
9923
12.6k
    if (kind1 < kind2)
9924
0
        return -1;
9925
9926
12.6k
    len1 = PyUnicode_GET_LENGTH(s1);
9927
12.6k
    len2 = PyUnicode_GET_LENGTH(s2);
9928
12.6k
    ADJUST_INDICES(start, end, len1);
9929
12.6k
    if (end - start < len2)
9930
1.33k
        return -1;
9931
9932
11.2k
    buf1 = PyUnicode_DATA(s1);
9933
11.2k
    buf2 = PyUnicode_DATA(s2);
9934
11.2k
    if (len2 == 1) {
9935
11.2k
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9936
11.2k
        result = findchar((const char *)buf1 + kind1*start,
9937
11.2k
                          kind1, end - start, ch, direction);
9938
11.2k
        if (result == -1)
9939
10.1k
            return -1;
9940
1.16k
        else
9941
1.16k
            return start + result;
9942
11.2k
    }
9943
9944
0
    if (kind2 != kind1) {
9945
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
9946
0
        if (!buf2)
9947
0
            return -2;
9948
0
    }
9949
9950
0
    if (direction > 0) {
9951
0
        switch (kind1) {
9952
0
        case PyUnicode_1BYTE_KIND:
9953
0
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9954
0
                result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9955
0
            else
9956
0
                result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9957
0
            break;
9958
0
        case PyUnicode_2BYTE_KIND:
9959
0
            result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9960
0
            break;
9961
0
        case PyUnicode_4BYTE_KIND:
9962
0
            result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9963
0
            break;
9964
0
        default:
9965
0
            Py_UNREACHABLE();
9966
0
        }
9967
0
    }
9968
0
    else {
9969
0
        switch (kind1) {
9970
0
        case PyUnicode_1BYTE_KIND:
9971
0
            if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9972
0
                result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9973
0
            else
9974
0
                result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9975
0
            break;
9976
0
        case PyUnicode_2BYTE_KIND:
9977
0
            result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9978
0
            break;
9979
0
        case PyUnicode_4BYTE_KIND:
9980
0
            result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9981
0
            break;
9982
0
        default:
9983
0
            Py_UNREACHABLE();
9984
0
        }
9985
0
    }
9986
9987
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
9988
0
    if (kind2 != kind1)
9989
0
        PyMem_Free((void *)buf2);
9990
9991
0
    return result;
9992
0
}
9993
9994
9995
Py_ssize_t
9996
PyUnicode_Count(PyObject *str,
9997
                PyObject *substr,
9998
                Py_ssize_t start,
9999
                Py_ssize_t end)
10000
0
{
10001
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10002
0
        return -1;
10003
10004
0
    return unicode_count_impl(str, substr, start, end);
10005
0
}
10006
10007
Py_ssize_t
10008
PyUnicode_Find(PyObject *str,
10009
               PyObject *substr,
10010
               Py_ssize_t start,
10011
               Py_ssize_t end,
10012
               int direction)
10013
5.82k
{
10014
5.82k
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10015
0
        return -2;
10016
10017
5.82k
    return any_find_slice(str, substr, start, end, direction);
10018
5.82k
}
10019
10020
Py_ssize_t
10021
PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
10022
                   Py_ssize_t start, Py_ssize_t end,
10023
                   int direction)
10024
2.80M
{
10025
2.80M
    int kind;
10026
2.80M
    Py_ssize_t len, result;
10027
2.80M
    len = PyUnicode_GET_LENGTH(str);
10028
2.80M
    ADJUST_INDICES(start, end, len);
10029
2.80M
    if (end - start < 1)
10030
0
        return -1;
10031
2.80M
    kind = PyUnicode_KIND(str);
10032
2.80M
    result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
10033
2.80M
                      kind, end-start, ch, direction);
10034
2.80M
    if (result == -1)
10035
2.44M
        return -1;
10036
361k
    else
10037
361k
        return start + result;
10038
2.80M
}
10039
10040
static int
10041
tailmatch(PyObject *self,
10042
          PyObject *substring,
10043
          Py_ssize_t start,
10044
          Py_ssize_t end,
10045
          int direction)
10046
358k
{
10047
358k
    int kind_self;
10048
358k
    int kind_sub;
10049
358k
    const void *data_self;
10050
358k
    const void *data_sub;
10051
358k
    Py_ssize_t offset;
10052
358k
    Py_ssize_t i;
10053
358k
    Py_ssize_t end_sub;
10054
10055
358k
    ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
10056
358k
    end -= PyUnicode_GET_LENGTH(substring);
10057
358k
    if (end < start)
10058
69.3k
        return 0;
10059
10060
289k
    if (PyUnicode_GET_LENGTH(substring) == 0)
10061
0
        return 1;
10062
10063
289k
    kind_self = PyUnicode_KIND(self);
10064
289k
    data_self = PyUnicode_DATA(self);
10065
289k
    kind_sub = PyUnicode_KIND(substring);
10066
289k
    data_sub = PyUnicode_DATA(substring);
10067
289k
    end_sub = PyUnicode_GET_LENGTH(substring) - 1;
10068
10069
289k
    if (direction > 0)
10070
113k
        offset = end;
10071
176k
    else
10072
176k
        offset = start;
10073
10074
289k
    if (PyUnicode_READ(kind_self, data_self, offset) ==
10075
289k
        PyUnicode_READ(kind_sub, data_sub, 0) &&
10076
276k
        PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
10077
276k
        PyUnicode_READ(kind_sub, data_sub, end_sub)) {
10078
        /* If both are of the same kind, memcmp is sufficient */
10079
227k
        if (kind_self == kind_sub) {
10080
226k
            return ! memcmp((char *)data_self +
10081
226k
                                (offset * PyUnicode_KIND(substring)),
10082
0
                            data_sub,
10083
226k
                            PyUnicode_GET_LENGTH(substring) *
10084
226k
                                PyUnicode_KIND(substring));
10085
226k
        }
10086
        /* otherwise we have to compare each character by first accessing it */
10087
1.64k
        else {
10088
            /* We do not need to compare 0 and len(substring)-1 because
10089
               the if statement above ensured already that they are equal
10090
               when we end up here. */
10091
2.87k
            for (i = 1; i < end_sub; ++i) {
10092
2.86k
                if (PyUnicode_READ(kind_self, data_self, offset + i) !=
10093
2.86k
                    PyUnicode_READ(kind_sub, data_sub, i))
10094
1.63k
                    return 0;
10095
2.86k
            }
10096
5
            return 1;
10097
1.64k
        }
10098
227k
    }
10099
10100
61.7k
    return 0;
10101
289k
}
10102
10103
Py_ssize_t
10104
PyUnicode_Tailmatch(PyObject *str,
10105
                    PyObject *substr,
10106
                    Py_ssize_t start,
10107
                    Py_ssize_t end,
10108
                    int direction)
10109
0
{
10110
0
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
10111
0
        return -1;
10112
10113
0
    return tailmatch(str, substr, start, end, direction);
10114
0
}
10115
10116
static PyObject *
10117
ascii_upper_or_lower(PyObject *self, int lower)
10118
142k
{
10119
142k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
10120
142k
    const char *data = PyUnicode_DATA(self);
10121
142k
    char *resdata;
10122
142k
    PyObject *res;
10123
10124
142k
    res = PyUnicode_New(len, 127);
10125
142k
    if (res == NULL)
10126
0
        return NULL;
10127
142k
    resdata = PyUnicode_DATA(res);
10128
142k
    if (lower)
10129
141k
        _Py_bytes_lower(resdata, data, len);
10130
153
    else
10131
153
        _Py_bytes_upper(resdata, data, len);
10132
142k
    return res;
10133
142k
}
10134
10135
static Py_UCS4
10136
handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
10137
38
{
10138
38
    Py_ssize_t j;
10139
38
    int final_sigma;
10140
38
    Py_UCS4 c = 0;   /* initialize to prevent gcc warning */
10141
    /* U+03A3 is in the Final_Sigma context when, it is found like this:
10142
10143
     \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
10144
10145
    where ! is a negation and \p{xxx} is a character with property xxx.
10146
    */
10147
38
    for (j = i - 1; j >= 0; j--) {
10148
0
        c = PyUnicode_READ(kind, data, j);
10149
0
        if (!_PyUnicode_IsCaseIgnorable(c))
10150
0
            break;
10151
0
    }
10152
38
    final_sigma = j >= 0 && _PyUnicode_IsCased(c);
10153
38
    if (final_sigma) {
10154
0
        for (j = i + 1; j < length; j++) {
10155
0
            c = PyUnicode_READ(kind, data, j);
10156
0
            if (!_PyUnicode_IsCaseIgnorable(c))
10157
0
                break;
10158
0
        }
10159
0
        final_sigma = j == length || !_PyUnicode_IsCased(c);
10160
0
    }
10161
38
    return (final_sigma) ? 0x3C2 : 0x3C3;
10162
38
}
10163
10164
static int
10165
lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
10166
           Py_UCS4 c, Py_UCS4 *mapped)
10167
692k
{
10168
    /* Obscure special case. */
10169
692k
    if (c == 0x3A3) {
10170
38
        mapped[0] = handle_capital_sigma(kind, data, length, i);
10171
38
        return 1;
10172
38
    }
10173
692k
    return _PyUnicode_ToLowerFull(c, mapped);
10174
692k
}
10175
10176
static Py_ssize_t
10177
do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10178
0
{
10179
0
    Py_ssize_t i, k = 0;
10180
0
    int n_res, j;
10181
0
    Py_UCS4 c, mapped[3];
10182
10183
0
    c = PyUnicode_READ(kind, data, 0);
10184
0
    n_res = _PyUnicode_ToTitleFull(c, mapped);
10185
0
    for (j = 0; j < n_res; j++) {
10186
0
        *maxchar = Py_MAX(*maxchar, mapped[j]);
10187
0
        res[k++] = mapped[j];
10188
0
    }
10189
0
    for (i = 1; i < length; i++) {
10190
0
        c = PyUnicode_READ(kind, data, i);
10191
0
        n_res = lower_ucs4(kind, data, length, i, c, mapped);
10192
0
        for (j = 0; j < n_res; j++) {
10193
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10194
0
            res[k++] = mapped[j];
10195
0
        }
10196
0
    }
10197
0
    return k;
10198
0
}
10199
10200
static Py_ssize_t
10201
0
do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
10202
0
    Py_ssize_t i, k = 0;
10203
10204
0
    for (i = 0; i < length; i++) {
10205
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10206
0
        int n_res, j;
10207
0
        if (Py_UNICODE_ISUPPER(c)) {
10208
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10209
0
        }
10210
0
        else if (Py_UNICODE_ISLOWER(c)) {
10211
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10212
0
        }
10213
0
        else {
10214
0
            n_res = 1;
10215
0
            mapped[0] = c;
10216
0
        }
10217
0
        for (j = 0; j < n_res; j++) {
10218
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10219
0
            res[k++] = mapped[j];
10220
0
        }
10221
0
    }
10222
0
    return k;
10223
0
}
10224
10225
static Py_ssize_t
10226
do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
10227
                  Py_UCS4 *maxchar, int lower)
10228
432k
{
10229
432k
    Py_ssize_t i, k = 0;
10230
10231
1.12M
    for (i = 0; i < length; i++) {
10232
692k
        Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
10233
692k
        int n_res, j;
10234
692k
        if (lower)
10235
692k
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10236
0
        else
10237
0
            n_res = _PyUnicode_ToUpperFull(c, mapped);
10238
1.38M
        for (j = 0; j < n_res; j++) {
10239
692k
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10240
692k
            res[k++] = mapped[j];
10241
692k
        }
10242
692k
    }
10243
432k
    return k;
10244
432k
}
10245
10246
static Py_ssize_t
10247
do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10248
0
{
10249
0
    return do_upper_or_lower(kind, data, length, res, maxchar, 0);
10250
0
}
10251
10252
static Py_ssize_t
10253
do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10254
432k
{
10255
432k
    return do_upper_or_lower(kind, data, length, res, maxchar, 1);
10256
432k
}
10257
10258
static Py_ssize_t
10259
do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10260
0
{
10261
0
    Py_ssize_t i, k = 0;
10262
10263
0
    for (i = 0; i < length; i++) {
10264
0
        Py_UCS4 c = PyUnicode_READ(kind, data, i);
10265
0
        Py_UCS4 mapped[3];
10266
0
        int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
10267
0
        for (j = 0; j < n_res; j++) {
10268
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10269
0
            res[k++] = mapped[j];
10270
0
        }
10271
0
    }
10272
0
    return k;
10273
0
}
10274
10275
static Py_ssize_t
10276
do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
10277
0
{
10278
0
    Py_ssize_t i, k = 0;
10279
0
    int previous_is_cased;
10280
10281
0
    previous_is_cased = 0;
10282
0
    for (i = 0; i < length; i++) {
10283
0
        const Py_UCS4 c = PyUnicode_READ(kind, data, i);
10284
0
        Py_UCS4 mapped[3];
10285
0
        int n_res, j;
10286
10287
0
        if (previous_is_cased)
10288
0
            n_res = lower_ucs4(kind, data, length, i, c, mapped);
10289
0
        else
10290
0
            n_res = _PyUnicode_ToTitleFull(c, mapped);
10291
10292
0
        for (j = 0; j < n_res; j++) {
10293
0
            *maxchar = Py_MAX(*maxchar, mapped[j]);
10294
0
            res[k++] = mapped[j];
10295
0
        }
10296
10297
0
        previous_is_cased = _PyUnicode_IsCased(c);
10298
0
    }
10299
0
    return k;
10300
0
}
10301
10302
static PyObject *
10303
case_operation(PyObject *self,
10304
               Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
10305
432k
{
10306
432k
    PyObject *res = NULL;
10307
432k
    Py_ssize_t length, newlength = 0;
10308
432k
    int kind, outkind;
10309
432k
    const void *data;
10310
432k
    void *outdata;
10311
432k
    Py_UCS4 maxchar = 0, *tmp, *tmpend;
10312
10313
432k
    kind = PyUnicode_KIND(self);
10314
432k
    data = PyUnicode_DATA(self);
10315
432k
    length = PyUnicode_GET_LENGTH(self);
10316
432k
    if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
10317
0
        PyErr_SetString(PyExc_OverflowError, "string is too long");
10318
0
        return NULL;
10319
0
    }
10320
432k
    tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
10321
432k
    if (tmp == NULL)
10322
0
        return PyErr_NoMemory();
10323
432k
    newlength = perform(kind, data, length, tmp, &maxchar);
10324
432k
    res = PyUnicode_New(newlength, maxchar);
10325
432k
    if (res == NULL)
10326
0
        goto leave;
10327
432k
    tmpend = tmp + newlength;
10328
432k
    outdata = PyUnicode_DATA(res);
10329
432k
    outkind = PyUnicode_KIND(res);
10330
0
    switch (outkind) {
10331
38.9k
    case PyUnicode_1BYTE_KIND:
10332
38.9k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10333
38.9k
        break;
10334
346k
    case PyUnicode_2BYTE_KIND:
10335
346k
        _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10336
346k
        break;
10337
47.6k
    case PyUnicode_4BYTE_KIND:
10338
47.6k
        memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10339
47.6k
        break;
10340
0
    default:
10341
0
        Py_UNREACHABLE();
10342
432k
    }
10343
432k
  leave:
10344
432k
    PyMem_Free(tmp);
10345
432k
    return res;
10346
432k
}
10347
10348
PyObject *
10349
PyUnicode_Join(PyObject *separator, PyObject *seq)
10350
276k
{
10351
276k
    PyObject *res;
10352
276k
    PyObject *fseq;
10353
276k
    Py_ssize_t seqlen;
10354
276k
    PyObject **items;
10355
10356
276k
    fseq = PySequence_Fast(seq, "can only join an iterable");
10357
276k
    if (fseq == NULL) {
10358
0
        return NULL;
10359
0
    }
10360
10361
276k
    Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(seq);
10362
10363
276k
    items = PySequence_Fast_ITEMS(fseq);
10364
276k
    seqlen = PySequence_Fast_GET_SIZE(fseq);
10365
276k
    res = _PyUnicode_JoinArray(separator, items, seqlen);
10366
10367
276k
    Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
10368
10369
276k
    Py_DECREF(fseq);
10370
276k
    return res;
10371
276k
}
10372
10373
PyObject *
10374
_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
10375
627k
{
10376
627k
    PyObject *res = NULL; /* the result */
10377
627k
    PyObject *sep = NULL;
10378
627k
    Py_ssize_t seplen;
10379
627k
    PyObject *item;
10380
627k
    Py_ssize_t sz, i, res_offset;
10381
627k
    Py_UCS4 maxchar;
10382
627k
    Py_UCS4 item_maxchar;
10383
627k
    int use_memcpy;
10384
627k
    unsigned char *res_data = NULL, *sep_data = NULL;
10385
627k
    PyObject *last_obj;
10386
627k
    int kind = 0;
10387
10388
    /* If empty sequence, return u"". */
10389
627k
    if (seqlen == 0) {
10390
0
        _Py_RETURN_UNICODE_EMPTY();
10391
0
    }
10392
10393
    /* If singleton sequence with an exact Unicode, return that. */
10394
627k
    last_obj = NULL;
10395
627k
    if (seqlen == 1) {
10396
236k
        if (PyUnicode_CheckExact(items[0])) {
10397
236k
            res = items[0];
10398
236k
            return Py_NewRef(res);
10399
236k
        }
10400
0
        seplen = 0;
10401
0
        maxchar = 0;
10402
0
    }
10403
391k
    else {
10404
        /* Set up sep and seplen */
10405
391k
        if (separator == NULL) {
10406
            /* fall back to a blank space separator */
10407
0
            sep = PyUnicode_FromOrdinal(' ');
10408
0
            if (!sep)
10409
0
                goto onError;
10410
0
            seplen = 1;
10411
0
            maxchar = 32;
10412
0
        }
10413
391k
        else {
10414
391k
            if (!PyUnicode_Check(separator)) {
10415
0
                PyErr_Format(PyExc_TypeError,
10416
0
                             "separator: expected str instance,"
10417
0
                             " %.80s found",
10418
0
                             Py_TYPE(separator)->tp_name);
10419
0
                goto onError;
10420
0
            }
10421
391k
            sep = separator;
10422
391k
            seplen = PyUnicode_GET_LENGTH(separator);
10423
391k
            maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10424
            /* inc refcount to keep this code path symmetric with the
10425
               above case of a blank separator */
10426
391k
            Py_INCREF(sep);
10427
391k
        }
10428
391k
        last_obj = sep;
10429
391k
    }
10430
10431
    /* There are at least two things to join, or else we have a subclass
10432
     * of str in the sequence.
10433
     * Do a pre-pass to figure out the total amount of space we'll
10434
     * need (sz), and see whether all argument are strings.
10435
     */
10436
391k
    sz = 0;
10437
#ifdef Py_DEBUG
10438
    use_memcpy = 0;
10439
#else
10440
391k
    use_memcpy = 1;
10441
391k
#endif
10442
3.55M
    for (i = 0; i < seqlen; i++) {
10443
3.16M
        size_t add_sz;
10444
3.16M
        item = items[i];
10445
3.16M
        if (!PyUnicode_Check(item)) {
10446
0
            PyErr_Format(PyExc_TypeError,
10447
0
                         "sequence item %zd: expected str instance,"
10448
0
                         " %.80s found",
10449
0
                         i, Py_TYPE(item)->tp_name);
10450
0
            goto onError;
10451
0
        }
10452
3.16M
        add_sz = PyUnicode_GET_LENGTH(item);
10453
3.16M
        item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
10454
3.16M
        maxchar = Py_MAX(maxchar, item_maxchar);
10455
3.16M
        if (i != 0) {
10456
2.77M
            add_sz += seplen;
10457
2.77M
        }
10458
3.16M
        if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
10459
0
            PyErr_SetString(PyExc_OverflowError,
10460
0
                            "join() result is too long for a Python string");
10461
0
            goto onError;
10462
0
        }
10463
3.16M
        sz += add_sz;
10464
3.16M
        if (use_memcpy && last_obj != NULL) {
10465
5.77M
            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10466
28.0k
                use_memcpy = 0;
10467
2.88M
        }
10468
0
        last_obj = item;
10469
3.16M
    }
10470
10471
391k
    res = PyUnicode_New(sz, maxchar);
10472
391k
    if (res == NULL)
10473
0
        goto onError;
10474
10475
    /* Catenate everything. */
10476
#ifdef Py_DEBUG
10477
    use_memcpy = 0;
10478
#else
10479
391k
    if (use_memcpy) {
10480
363k
        res_data = PyUnicode_1BYTE_DATA(res);
10481
363k
        kind = PyUnicode_KIND(res);
10482
363k
        if (seplen != 0)
10483
4.84k
            sep_data = PyUnicode_1BYTE_DATA(sep);
10484
363k
    }
10485
391k
#endif
10486
391k
    if (use_memcpy) {
10487
3.20M
        for (i = 0; i < seqlen; ++i) {
10488
2.83M
            Py_ssize_t itemlen;
10489
2.83M
            item = items[i];
10490
10491
            /* Copy item, and maybe the separator. */
10492
2.83M
            if (i && seplen != 0) {
10493
7.98k
                memcpy(res_data,
10494
7.98k
                          sep_data,
10495
7.98k
                          kind * seplen);
10496
7.98k
                res_data += kind * seplen;
10497
7.98k
            }
10498
10499
2.83M
            itemlen = PyUnicode_GET_LENGTH(item);
10500
2.83M
            if (itemlen != 0) {
10501
2.83M
                memcpy(res_data,
10502
2.83M
                          PyUnicode_DATA(item),
10503
2.83M
                          kind * itemlen);
10504
2.83M
                res_data += kind * itemlen;
10505
2.83M
            }
10506
2.83M
        }
10507
363k
        assert(res_data == PyUnicode_1BYTE_DATA(res)
10508
363k
                           + kind * PyUnicode_GET_LENGTH(res));
10509
363k
    }
10510
28.0k
    else {
10511
354k
        for (i = 0, res_offset = 0; i < seqlen; ++i) {
10512
326k
            Py_ssize_t itemlen;
10513
326k
            item = items[i];
10514
10515
            /* Copy item, and maybe the separator. */
10516
326k
            if (i && seplen != 0) {
10517
47.6k
                _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10518
47.6k
                res_offset += seplen;
10519
47.6k
            }
10520
10521
326k
            itemlen = PyUnicode_GET_LENGTH(item);
10522
326k
            if (itemlen != 0) {
10523
292k
                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
10524
292k
                res_offset += itemlen;
10525
292k
            }
10526
326k
        }
10527
28.0k
        assert(res_offset == PyUnicode_GET_LENGTH(res));
10528
28.0k
    }
10529
10530
391k
    Py_XDECREF(sep);
10531
391k
    assert(_PyUnicode_CheckConsistency(res, 1));
10532
391k
    return res;
10533
10534
0
  onError:
10535
0
    Py_XDECREF(sep);
10536
0
    Py_XDECREF(res);
10537
0
    return NULL;
10538
391k
}
10539
10540
void
10541
_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10542
                    Py_UCS4 fill_char)
10543
840
{
10544
840
    const int kind = PyUnicode_KIND(unicode);
10545
840
    void *data = PyUnicode_DATA(unicode);
10546
840
    assert(_PyUnicode_IsModifiable(unicode));
10547
840
    assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10548
840
    assert(start >= 0);
10549
840
    assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10550
840
    _PyUnicode_Fill(kind, data, fill_char, start, length);
10551
840
}
10552
10553
Py_ssize_t
10554
PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10555
               Py_UCS4 fill_char)
10556
840
{
10557
840
    Py_ssize_t maxlen;
10558
10559
840
    if (!PyUnicode_Check(unicode)) {
10560
0
        PyErr_BadInternalCall();
10561
0
        return -1;
10562
0
    }
10563
840
    if (unicode_check_modifiable(unicode))
10564
0
        return -1;
10565
10566
840
    if (start < 0) {
10567
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
10568
0
        return -1;
10569
0
    }
10570
840
    if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10571
0
        PyErr_SetString(PyExc_ValueError,
10572
0
                         "fill character is bigger than "
10573
0
                         "the string maximum character");
10574
0
        return -1;
10575
0
    }
10576
10577
840
    maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10578
840
    length = Py_MIN(maxlen, length);
10579
840
    if (length <= 0)
10580
0
        return 0;
10581
10582
840
    _PyUnicode_FastFill(unicode, start, length, fill_char);
10583
840
    return length;
10584
840
}
10585
10586
static PyObject *
10587
pad(PyObject *self,
10588
    Py_ssize_t left,
10589
    Py_ssize_t right,
10590
    Py_UCS4 fill)
10591
0
{
10592
0
    PyObject *u;
10593
0
    Py_UCS4 maxchar;
10594
0
    int kind;
10595
0
    void *data;
10596
10597
0
    if (left < 0)
10598
0
        left = 0;
10599
0
    if (right < 0)
10600
0
        right = 0;
10601
10602
0
    if (left == 0 && right == 0)
10603
0
        return unicode_result_unchanged(self);
10604
10605
0
    if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10606
0
        right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
10607
0
        PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10608
0
        return NULL;
10609
0
    }
10610
0
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10611
0
    maxchar = Py_MAX(maxchar, fill);
10612
0
    u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
10613
0
    if (!u)
10614
0
        return NULL;
10615
10616
0
    kind = PyUnicode_KIND(u);
10617
0
    data = PyUnicode_DATA(u);
10618
0
    if (left)
10619
0
        _PyUnicode_Fill(kind, data, fill, 0, left);
10620
0
    if (right)
10621
0
        _PyUnicode_Fill(kind, data, fill,
10622
0
                        left + _PyUnicode_LENGTH(self), right);
10623
0
    _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
10624
0
    assert(_PyUnicode_CheckConsistency(u, 1));
10625
0
    return u;
10626
0
}
10627
10628
PyObject *
10629
PyUnicode_Splitlines(PyObject *string, int keepends)
10630
0
{
10631
0
    PyObject *list;
10632
10633
0
    if (ensure_unicode(string) < 0)
10634
0
        return NULL;
10635
10636
0
    switch (PyUnicode_KIND(string)) {
10637
0
    case PyUnicode_1BYTE_KIND:
10638
0
        if (PyUnicode_IS_ASCII(string))
10639
0
            list = asciilib_splitlines(
10640
0
                string, PyUnicode_1BYTE_DATA(string),
10641
0
                PyUnicode_GET_LENGTH(string), keepends);
10642
0
        else
10643
0
            list = ucs1lib_splitlines(
10644
0
                string, PyUnicode_1BYTE_DATA(string),
10645
0
                PyUnicode_GET_LENGTH(string), keepends);
10646
0
        break;
10647
0
    case PyUnicode_2BYTE_KIND:
10648
0
        list = ucs2lib_splitlines(
10649
0
            string, PyUnicode_2BYTE_DATA(string),
10650
0
            PyUnicode_GET_LENGTH(string), keepends);
10651
0
        break;
10652
0
    case PyUnicode_4BYTE_KIND:
10653
0
        list = ucs4lib_splitlines(
10654
0
            string, PyUnicode_4BYTE_DATA(string),
10655
0
            PyUnicode_GET_LENGTH(string), keepends);
10656
0
        break;
10657
0
    default:
10658
0
        Py_UNREACHABLE();
10659
0
    }
10660
0
    return list;
10661
0
}
10662
10663
static PyObject *
10664
split(PyObject *self,
10665
      PyObject *substring,
10666
      Py_ssize_t maxcount)
10667
2.07k
{
10668
2.07k
    int kind1, kind2;
10669
2.07k
    const void *buf1, *buf2;
10670
2.07k
    Py_ssize_t len1, len2;
10671
2.07k
    PyObject* out;
10672
2.07k
    len1 = PyUnicode_GET_LENGTH(self);
10673
2.07k
    kind1 = PyUnicode_KIND(self);
10674
10675
2.07k
    if (substring == NULL) {
10676
7
        if (maxcount < 0) {
10677
7
            maxcount = (len1 - 1) / 2 + 1;
10678
7
        }
10679
7
        switch (kind1) {
10680
7
        case PyUnicode_1BYTE_KIND:
10681
7
            if (PyUnicode_IS_ASCII(self))
10682
7
                return asciilib_split_whitespace(
10683
7
                    self,  PyUnicode_1BYTE_DATA(self),
10684
7
                    len1, maxcount
10685
7
                    );
10686
0
            else
10687
0
                return ucs1lib_split_whitespace(
10688
0
                    self,  PyUnicode_1BYTE_DATA(self),
10689
0
                    len1, maxcount
10690
0
                    );
10691
0
        case PyUnicode_2BYTE_KIND:
10692
0
            return ucs2lib_split_whitespace(
10693
0
                self,  PyUnicode_2BYTE_DATA(self),
10694
0
                len1, maxcount
10695
0
                );
10696
0
        case PyUnicode_4BYTE_KIND:
10697
0
            return ucs4lib_split_whitespace(
10698
0
                self,  PyUnicode_4BYTE_DATA(self),
10699
0
                len1, maxcount
10700
0
                );
10701
0
        default:
10702
0
            Py_UNREACHABLE();
10703
7
        }
10704
7
    }
10705
10706
2.06k
    kind2 = PyUnicode_KIND(substring);
10707
2.06k
    len2 = PyUnicode_GET_LENGTH(substring);
10708
2.06k
    if (maxcount < 0) {
10709
        // if len2 == 0, it will raise ValueError.
10710
2.06k
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10711
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10712
2.06k
        maxcount = maxcount < 0 ? len1 : maxcount;
10713
2.06k
    }
10714
2.06k
    if (kind1 < kind2 || len1 < len2) {
10715
1
        out = PyList_New(1);
10716
1
        if (out == NULL)
10717
0
            return NULL;
10718
1
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10719
1
        return out;
10720
1
    }
10721
2.06k
    buf1 = PyUnicode_DATA(self);
10722
2.06k
    buf2 = PyUnicode_DATA(substring);
10723
2.06k
    if (kind2 != kind1) {
10724
1.05k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10725
1.05k
        if (!buf2)
10726
0
            return NULL;
10727
1.05k
    }
10728
10729
2.06k
    switch (kind1) {
10730
1.01k
    case PyUnicode_1BYTE_KIND:
10731
1.01k
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10732
738
            out = asciilib_split(
10733
738
                self,  buf1, len1, buf2, len2, maxcount);
10734
275
        else
10735
275
            out = ucs1lib_split(
10736
275
                self,  buf1, len1, buf2, len2, maxcount);
10737
1.01k
        break;
10738
535
    case PyUnicode_2BYTE_KIND:
10739
535
        out = ucs2lib_split(
10740
535
            self,  buf1, len1, buf2, len2, maxcount);
10741
535
        break;
10742
516
    case PyUnicode_4BYTE_KIND:
10743
516
        out = ucs4lib_split(
10744
516
            self,  buf1, len1, buf2, len2, maxcount);
10745
516
        break;
10746
0
    default:
10747
0
        out = NULL;
10748
2.06k
    }
10749
2.06k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10750
2.06k
    if (kind2 != kind1)
10751
1.05k
        PyMem_Free((void *)buf2);
10752
2.06k
    return out;
10753
2.06k
}
10754
10755
static PyObject *
10756
rsplit(PyObject *self,
10757
       PyObject *substring,
10758
       Py_ssize_t maxcount)
10759
0
{
10760
0
    int kind1, kind2;
10761
0
    const void *buf1, *buf2;
10762
0
    Py_ssize_t len1, len2;
10763
0
    PyObject* out;
10764
10765
0
    len1 = PyUnicode_GET_LENGTH(self);
10766
0
    kind1 = PyUnicode_KIND(self);
10767
10768
0
    if (substring == NULL) {
10769
0
        if (maxcount < 0) {
10770
0
            maxcount = (len1 - 1) / 2 + 1;
10771
0
        }
10772
0
        switch (kind1) {
10773
0
        case PyUnicode_1BYTE_KIND:
10774
0
            if (PyUnicode_IS_ASCII(self))
10775
0
                return asciilib_rsplit_whitespace(
10776
0
                    self,  PyUnicode_1BYTE_DATA(self),
10777
0
                    len1, maxcount
10778
0
                    );
10779
0
            else
10780
0
                return ucs1lib_rsplit_whitespace(
10781
0
                    self,  PyUnicode_1BYTE_DATA(self),
10782
0
                    len1, maxcount
10783
0
                    );
10784
0
        case PyUnicode_2BYTE_KIND:
10785
0
            return ucs2lib_rsplit_whitespace(
10786
0
                self,  PyUnicode_2BYTE_DATA(self),
10787
0
                len1, maxcount
10788
0
                );
10789
0
        case PyUnicode_4BYTE_KIND:
10790
0
            return ucs4lib_rsplit_whitespace(
10791
0
                self,  PyUnicode_4BYTE_DATA(self),
10792
0
                len1, maxcount
10793
0
                );
10794
0
        default:
10795
0
            Py_UNREACHABLE();
10796
0
        }
10797
0
    }
10798
0
    kind2 = PyUnicode_KIND(substring);
10799
0
    len2 = PyUnicode_GET_LENGTH(substring);
10800
0
    if (maxcount < 0) {
10801
        // if len2 == 0, it will raise ValueError.
10802
0
        maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
10803
        // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
10804
0
        maxcount = maxcount < 0 ? len1 : maxcount;
10805
0
    }
10806
0
    if (kind1 < kind2 || len1 < len2) {
10807
0
        out = PyList_New(1);
10808
0
        if (out == NULL)
10809
0
            return NULL;
10810
0
        PyList_SET_ITEM(out, 0, Py_NewRef(self));
10811
0
        return out;
10812
0
    }
10813
0
    buf1 = PyUnicode_DATA(self);
10814
0
    buf2 = PyUnicode_DATA(substring);
10815
0
    if (kind2 != kind1) {
10816
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
10817
0
        if (!buf2)
10818
0
            return NULL;
10819
0
    }
10820
10821
0
    switch (kind1) {
10822
0
    case PyUnicode_1BYTE_KIND:
10823
0
        if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10824
0
            out = asciilib_rsplit(
10825
0
                self,  buf1, len1, buf2, len2, maxcount);
10826
0
        else
10827
0
            out = ucs1lib_rsplit(
10828
0
                self,  buf1, len1, buf2, len2, maxcount);
10829
0
        break;
10830
0
    case PyUnicode_2BYTE_KIND:
10831
0
        out = ucs2lib_rsplit(
10832
0
            self,  buf1, len1, buf2, len2, maxcount);
10833
0
        break;
10834
0
    case PyUnicode_4BYTE_KIND:
10835
0
        out = ucs4lib_rsplit(
10836
0
            self,  buf1, len1, buf2, len2, maxcount);
10837
0
        break;
10838
0
    default:
10839
0
        out = NULL;
10840
0
    }
10841
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
10842
0
    if (kind2 != kind1)
10843
0
        PyMem_Free((void *)buf2);
10844
0
    return out;
10845
0
}
10846
10847
static Py_ssize_t
10848
anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
10849
            PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
10850
65.3k
{
10851
65.3k
    switch (kind) {
10852
39.2k
    case PyUnicode_1BYTE_KIND:
10853
39.2k
        if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10854
29.4k
            return asciilib_find(buf1, len1, buf2, len2, offset);
10855
9.82k
        else
10856
9.82k
            return ucs1lib_find(buf1, len1, buf2, len2, offset);
10857
9.59k
    case PyUnicode_2BYTE_KIND:
10858
9.59k
        return ucs2lib_find(buf1, len1, buf2, len2, offset);
10859
16.4k
    case PyUnicode_4BYTE_KIND:
10860
16.4k
        return ucs4lib_find(buf1, len1, buf2, len2, offset);
10861
65.3k
    }
10862
65.3k
    Py_UNREACHABLE();
10863
65.3k
}
10864
10865
static Py_ssize_t
10866
anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
10867
             PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
10868
60.7k
{
10869
60.7k
    switch (kind) {
10870
57.0k
    case PyUnicode_1BYTE_KIND:
10871
57.0k
        return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10872
1.47k
    case PyUnicode_2BYTE_KIND:
10873
1.47k
        return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10874
2.20k
    case PyUnicode_4BYTE_KIND:
10875
2.20k
        return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10876
60.7k
    }
10877
60.7k
    Py_UNREACHABLE();
10878
60.7k
}
10879
10880
static void
10881
replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10882
                      Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10883
137
{
10884
137
    int kind = PyUnicode_KIND(u);
10885
137
    void *data = PyUnicode_DATA(u);
10886
137
    Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10887
137
    if (kind == PyUnicode_1BYTE_KIND) {
10888
137
        ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10889
137
                                      (Py_UCS1 *)data + len,
10890
137
                                      u1, u2, maxcount);
10891
137
    }
10892
0
    else if (kind == PyUnicode_2BYTE_KIND) {
10893
0
        ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10894
0
                                      (Py_UCS2 *)data + len,
10895
0
                                      u1, u2, maxcount);
10896
0
    }
10897
0
    else {
10898
0
        assert(kind == PyUnicode_4BYTE_KIND);
10899
0
        ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10900
0
                                      (Py_UCS4 *)data + len,
10901
0
                                      u1, u2, maxcount);
10902
0
    }
10903
137
}
10904
10905
static PyObject *
10906
replace(PyObject *self, PyObject *str1,
10907
        PyObject *str2, Py_ssize_t maxcount)
10908
66.3k
{
10909
66.3k
    PyObject *u;
10910
66.3k
    const char *sbuf = PyUnicode_DATA(self);
10911
66.3k
    const void *buf1 = PyUnicode_DATA(str1);
10912
66.3k
    const void *buf2 = PyUnicode_DATA(str2);
10913
66.3k
    int srelease = 0, release1 = 0, release2 = 0;
10914
66.3k
    int skind = PyUnicode_KIND(self);
10915
66.3k
    int kind1 = PyUnicode_KIND(str1);
10916
66.3k
    int kind2 = PyUnicode_KIND(str2);
10917
66.3k
    Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10918
66.3k
    Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10919
66.3k
    Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
10920
66.3k
    int mayshrink;
10921
66.3k
    Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
10922
10923
66.3k
    if (slen < len1)
10924
5.02k
        goto nothing;
10925
10926
61.3k
    if (maxcount < 0)
10927
61.3k
        maxcount = PY_SSIZE_T_MAX;
10928
0
    else if (maxcount == 0)
10929
0
        goto nothing;
10930
10931
61.3k
    if (str1 == str2)
10932
0
        goto nothing;
10933
10934
61.3k
    maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10935
61.3k
    maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10936
61.3k
    if (maxchar < maxchar_str1)
10937
        /* substring too wide to be present */
10938
0
        goto nothing;
10939
61.3k
    maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10940
    /* Replacing str1 with str2 may cause a maxchar reduction in the
10941
       result string. */
10942
61.3k
    mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
10943
61.3k
    maxchar = Py_MAX(maxchar, maxchar_str2);
10944
10945
61.3k
    if (len1 == len2) {
10946
        /* same length */
10947
639
        if (len1 == 0)
10948
0
            goto nothing;
10949
639
        if (len1 == 1) {
10950
            /* replace characters */
10951
639
            Py_UCS4 u1, u2;
10952
639
            Py_ssize_t pos;
10953
10954
639
            u1 = PyUnicode_READ(kind1, buf1, 0);
10955
639
            pos = findchar(sbuf, skind, slen, u1, 1);
10956
639
            if (pos < 0)
10957
502
                goto nothing;
10958
137
            u2 = PyUnicode_READ(kind2, buf2, 0);
10959
137
            u = PyUnicode_New(slen, maxchar);
10960
137
            if (!u)
10961
0
                goto error;
10962
10963
137
            _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10964
137
            replace_1char_inplace(u, pos, u1, u2, maxcount);
10965
137
        }
10966
0
        else {
10967
0
            int rkind = skind;
10968
0
            char *res;
10969
0
            Py_ssize_t i;
10970
10971
0
            if (kind1 < rkind) {
10972
                /* widen substring */
10973
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
10974
0
                if (!buf1) goto error;
10975
0
                release1 = 1;
10976
0
            }
10977
0
            i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
10978
0
            if (i < 0)
10979
0
                goto nothing;
10980
0
            if (rkind > kind2) {
10981
                /* widen replacement */
10982
0
                buf2 = unicode_askind(kind2, buf2, len2, rkind);
10983
0
                if (!buf2) goto error;
10984
0
                release2 = 1;
10985
0
            }
10986
0
            else if (rkind < kind2) {
10987
                /* widen self and buf1 */
10988
0
                rkind = kind2;
10989
0
                if (release1) {
10990
0
                    assert(buf1 != PyUnicode_DATA(str1));
10991
0
                    PyMem_Free((void *)buf1);
10992
0
                    buf1 = PyUnicode_DATA(str1);
10993
0
                    release1 = 0;
10994
0
                }
10995
0
                sbuf = unicode_askind(skind, sbuf, slen, rkind);
10996
0
                if (!sbuf) goto error;
10997
0
                srelease = 1;
10998
0
                buf1 = unicode_askind(kind1, buf1, len1, rkind);
10999
0
                if (!buf1) goto error;
11000
0
                release1 = 1;
11001
0
            }
11002
0
            u = PyUnicode_New(slen, maxchar);
11003
0
            if (!u)
11004
0
                goto error;
11005
0
            assert(PyUnicode_KIND(u) == rkind);
11006
0
            res = PyUnicode_DATA(u);
11007
11008
0
            memcpy(res, sbuf, rkind * slen);
11009
            /* change everything in-place, starting with this one */
11010
0
            memcpy(res + rkind * i,
11011
0
                   buf2,
11012
0
                   rkind * len2);
11013
0
            i += len1;
11014
11015
0
            while ( --maxcount > 0) {
11016
0
                i = anylib_find(rkind, self,
11017
0
                                sbuf+rkind*i, slen-i,
11018
0
                                str1, buf1, len1, i);
11019
0
                if (i == -1)
11020
0
                    break;
11021
0
                memcpy(res + rkind * i,
11022
0
                       buf2,
11023
0
                       rkind * len2);
11024
0
                i += len1;
11025
0
            }
11026
0
        }
11027
639
    }
11028
60.7k
    else {
11029
60.7k
        Py_ssize_t n, i, j, ires;
11030
60.7k
        Py_ssize_t new_size;
11031
60.7k
        int rkind = skind;
11032
60.7k
        char *res;
11033
11034
60.7k
        if (kind1 < rkind) {
11035
            /* widen substring */
11036
3.67k
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11037
3.67k
            if (!buf1) goto error;
11038
3.67k
            release1 = 1;
11039
3.67k
        }
11040
60.7k
        n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
11041
60.7k
        if (n == 0)
11042
49.6k
            goto nothing;
11043
11.0k
        if (kind2 < rkind) {
11044
            /* widen replacement */
11045
2.84k
            buf2 = unicode_askind(kind2, buf2, len2, rkind);
11046
2.84k
            if (!buf2) goto error;
11047
2.84k
            release2 = 1;
11048
2.84k
        }
11049
8.22k
        else if (kind2 > rkind) {
11050
            /* widen self and buf1 */
11051
0
            rkind = kind2;
11052
0
            sbuf = unicode_askind(skind, sbuf, slen, rkind);
11053
0
            if (!sbuf) goto error;
11054
0
            srelease = 1;
11055
0
            if (release1) {
11056
0
                assert(buf1 != PyUnicode_DATA(str1));
11057
0
                PyMem_Free((void *)buf1);
11058
0
                buf1 = PyUnicode_DATA(str1);
11059
0
                release1 = 0;
11060
0
            }
11061
0
            buf1 = unicode_askind(kind1, buf1, len1, rkind);
11062
0
            if (!buf1) goto error;
11063
0
            release1 = 1;
11064
0
        }
11065
        /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
11066
           PyUnicode_GET_LENGTH(str1)); */
11067
11.0k
        if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
11068
0
                PyErr_SetString(PyExc_OverflowError,
11069
0
                                "replace string is too long");
11070
0
                goto error;
11071
0
        }
11072
11.0k
        new_size = slen + n * (len2 - len1);
11073
11.0k
        if (new_size == 0) {
11074
0
            u = _PyUnicode_GetEmpty();
11075
0
            goto done;
11076
0
        }
11077
11.0k
        if (new_size > (PY_SSIZE_T_MAX / rkind)) {
11078
0
            PyErr_SetString(PyExc_OverflowError,
11079
0
                            "replace string is too long");
11080
0
            goto error;
11081
0
        }
11082
11.0k
        u = PyUnicode_New(new_size, maxchar);
11083
11.0k
        if (!u)
11084
0
            goto error;
11085
11.0k
        assert(PyUnicode_KIND(u) == rkind);
11086
11.0k
        res = PyUnicode_DATA(u);
11087
11.0k
        ires = i = 0;
11088
11.0k
        if (len1 > 0) {
11089
76.3k
            while (n-- > 0) {
11090
                /* look for next match */
11091
65.3k
                j = anylib_find(rkind, self,
11092
65.3k
                                sbuf + rkind * i, slen-i,
11093
65.3k
                                str1, buf1, len1, i);
11094
65.3k
                if (j == -1)
11095
0
                    break;
11096
65.3k
                else if (j > i) {
11097
                    /* copy unchanged part [i:j] */
11098
23.6k
                    memcpy(res + rkind * ires,
11099
23.6k
                           sbuf + rkind * i,
11100
23.6k
                           rkind * (j-i));
11101
23.6k
                    ires += j - i;
11102
23.6k
                }
11103
                /* copy substitution string */
11104
65.3k
                if (len2 > 0) {
11105
58.9k
                    memcpy(res + rkind * ires,
11106
58.9k
                           buf2,
11107
58.9k
                           rkind * len2);
11108
58.9k
                    ires += len2;
11109
58.9k
                }
11110
65.3k
                i = j + len1;
11111
65.3k
            }
11112
11.0k
            if (i < slen)
11113
                /* copy tail [i:] */
11114
7.48k
                memcpy(res + rkind * ires,
11115
7.48k
                       sbuf + rkind * i,
11116
7.48k
                       rkind * (slen-i));
11117
11.0k
        }
11118
0
        else {
11119
            /* interleave */
11120
0
            while (n > 0) {
11121
0
                memcpy(res + rkind * ires,
11122
0
                       buf2,
11123
0
                       rkind * len2);
11124
0
                ires += len2;
11125
0
                if (--n <= 0)
11126
0
                    break;
11127
0
                memcpy(res + rkind * ires,
11128
0
                       sbuf + rkind * i,
11129
0
                       rkind);
11130
0
                ires++;
11131
0
                i++;
11132
0
            }
11133
0
            memcpy(res + rkind * ires,
11134
0
                   sbuf + rkind * i,
11135
0
                   rkind * (slen-i));
11136
0
        }
11137
11.0k
    }
11138
11139
11.2k
    if (mayshrink) {
11140
0
        unicode_adjust_maxchar(&u);
11141
0
        if (u == NULL)
11142
0
            goto error;
11143
0
    }
11144
11145
11.2k
  done:
11146
11.2k
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11147
11.2k
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11148
11.2k
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11149
11.2k
    if (srelease)
11150
0
        PyMem_Free((void *)sbuf);
11151
11.2k
    if (release1)
11152
2.84k
        PyMem_Free((void *)buf1);
11153
11.2k
    if (release2)
11154
2.84k
        PyMem_Free((void *)buf2);
11155
11.2k
    assert(_PyUnicode_CheckConsistency(u, 1));
11156
11.2k
    return u;
11157
11158
55.1k
  nothing:
11159
    /* nothing to replace; return original string (when possible) */
11160
55.1k
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11161
55.1k
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11162
55.1k
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11163
55.1k
    if (srelease)
11164
0
        PyMem_Free((void *)sbuf);
11165
55.1k
    if (release1)
11166
826
        PyMem_Free((void *)buf1);
11167
55.1k
    if (release2)
11168
0
        PyMem_Free((void *)buf2);
11169
55.1k
    return unicode_result_unchanged(self);
11170
11171
0
  error:
11172
0
    assert(srelease == (sbuf != NULL && sbuf != PyUnicode_DATA(self)));
11173
0
    assert(release1 == (buf1 != NULL && buf1 != PyUnicode_DATA(str1)));
11174
0
    assert(release2 == (buf2 != NULL && buf2 != PyUnicode_DATA(str2)));
11175
0
    if (srelease)
11176
0
        PyMem_Free((void *)sbuf);
11177
0
    if (release1)
11178
0
        PyMem_Free((void *)buf1);
11179
0
    if (release2)
11180
0
        PyMem_Free((void *)buf2);
11181
0
    return NULL;
11182
0
}
11183
11184
/* --- Unicode Object Methods --------------------------------------------- */
11185
11186
/*[clinic input]
11187
str.title as unicode_title
11188
11189
Return a version of the string where each word is titlecased.
11190
11191
More specifically, words start with uppercased characters and all
11192
remaining cased characters have lower case.
11193
[clinic start generated code]*/
11194
11195
static PyObject *
11196
unicode_title_impl(PyObject *self)
11197
/*[clinic end generated code: output=c75ae03809574902 input=2a07e2c7df94627a]*/
11198
0
{
11199
0
    return case_operation(self, do_title);
11200
0
}
11201
11202
/*[clinic input]
11203
str.capitalize as unicode_capitalize
11204
11205
Return a capitalized version of the string.
11206
11207
More specifically, make the first character have upper case and the
11208
rest lower case.
11209
[clinic start generated code]*/
11210
11211
static PyObject *
11212
unicode_capitalize_impl(PyObject *self)
11213
/*[clinic end generated code: output=e49a4c333cdb7667 input=e50e50ed45a654cf]*/
11214
0
{
11215
0
    if (PyUnicode_GET_LENGTH(self) == 0)
11216
0
        return unicode_result_unchanged(self);
11217
0
    return case_operation(self, do_capitalize);
11218
0
}
11219
11220
/*[clinic input]
11221
str.casefold as unicode_casefold
11222
11223
Return a version of the string suitable for caseless comparisons.
11224
[clinic start generated code]*/
11225
11226
static PyObject *
11227
unicode_casefold_impl(PyObject *self)
11228
/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
11229
0
{
11230
0
    if (PyUnicode_IS_ASCII(self))
11231
0
        return ascii_upper_or_lower(self, 1);
11232
0
    return case_operation(self, do_casefold);
11233
0
}
11234
11235
11236
/* Argument converter. Accepts a single Unicode character. */
11237
11238
static int
11239
convert_uc(PyObject *obj, void *addr)
11240
0
{
11241
0
    Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
11242
11243
0
    if (!PyUnicode_Check(obj)) {
11244
0
        PyErr_Format(PyExc_TypeError,
11245
0
                     "The fill character must be a unicode character, "
11246
0
                     "not %.100s", Py_TYPE(obj)->tp_name);
11247
0
        return 0;
11248
0
    }
11249
0
    if (PyUnicode_GET_LENGTH(obj) != 1) {
11250
0
        PyErr_SetString(PyExc_TypeError,
11251
0
                        "The fill character must be exactly one character long");
11252
0
        return 0;
11253
0
    }
11254
0
    *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
11255
0
    return 1;
11256
0
}
11257
11258
/*[clinic input]
11259
str.center as unicode_center
11260
11261
    width: Py_ssize_t
11262
    fillchar: Py_UCS4 = ' '
11263
    /
11264
11265
Return a centered string of length width.
11266
11267
Padding is done using the specified fill character (default is
11268
a space).
11269
[clinic start generated code]*/
11270
11271
static PyObject *
11272
unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
11273
/*[clinic end generated code: output=420c8859effc7c0c input=df91017dfd186a78]*/
11274
0
{
11275
0
    Py_ssize_t marg, left;
11276
11277
0
    if (PyUnicode_GET_LENGTH(self) >= width)
11278
0
        return unicode_result_unchanged(self);
11279
11280
0
    marg = width - PyUnicode_GET_LENGTH(self);
11281
0
    left = marg / 2 + (marg & width & 1);
11282
11283
0
    return pad(self, left, marg - left, fillchar);
11284
0
}
11285
11286
/* This function assumes that str1 and str2 are readied by the caller. */
11287
11288
static int
11289
unicode_compare(PyObject *str1, PyObject *str2)
11290
13.9M
{
11291
13.9M
#define COMPARE(TYPE1, TYPE2) \
11292
13.9M
    do { \
11293
11.9M
        TYPE1* p1 = (TYPE1 *)data1; \
11294
11.9M
        TYPE2* p2 = (TYPE2 *)data2; \
11295
11.9M
        TYPE1* end = p1 + len; \
11296
11.9M
        Py_UCS4 c1, c2; \
11297
12.6M
        for (; p1 != end; p1++, p2++) { \
11298
12.6M
            c1 = *p1; \
11299
12.6M
            c2 = *p2; \
11300
12.6M
            if (c1 != c2) \
11301
12.6M
                return (c1 < c2) ? -1 : 1; \
11302
12.6M
        } \
11303
11.9M
    } \
11304
11.9M
    while (0)
11305
11306
13.9M
    int kind1, kind2;
11307
13.9M
    const void *data1, *data2;
11308
13.9M
    Py_ssize_t len1, len2, len;
11309
11310
13.9M
    kind1 = PyUnicode_KIND(str1);
11311
13.9M
    kind2 = PyUnicode_KIND(str2);
11312
13.9M
    data1 = PyUnicode_DATA(str1);
11313
13.9M
    data2 = PyUnicode_DATA(str2);
11314
13.9M
    len1 = PyUnicode_GET_LENGTH(str1);
11315
13.9M
    len2 = PyUnicode_GET_LENGTH(str2);
11316
13.9M
    len = Py_MIN(len1, len2);
11317
11318
13.9M
    switch(kind1) {
11319
4.50M
    case PyUnicode_1BYTE_KIND:
11320
4.50M
    {
11321
4.50M
        switch(kind2) {
11322
1.46M
        case PyUnicode_1BYTE_KIND:
11323
1.46M
        {
11324
1.46M
            int cmp = memcmp(data1, data2, len);
11325
            /* normalize result of memcmp() into the range [-1; 1] */
11326
1.46M
            if (cmp < 0)
11327
872k
                return -1;
11328
594k
            if (cmp > 0)
11329
505k
                return 1;
11330
88.8k
            break;
11331
594k
        }
11332
2.96M
        case PyUnicode_2BYTE_KIND:
11333
2.96M
            COMPARE(Py_UCS1, Py_UCS2);
11334
8.09k
            break;
11335
64.0k
        case PyUnicode_4BYTE_KIND:
11336
64.0k
            COMPARE(Py_UCS1, Py_UCS4);
11337
22
            break;
11338
22
        default:
11339
0
            Py_UNREACHABLE();
11340
4.50M
        }
11341
96.9k
        break;
11342
4.50M
    }
11343
8.86M
    case PyUnicode_2BYTE_KIND:
11344
8.86M
    {
11345
8.86M
        switch(kind2) {
11346
57.5k
        case PyUnicode_1BYTE_KIND:
11347
57.5k
            COMPARE(Py_UCS2, Py_UCS1);
11348
5.44k
            break;
11349
8.74M
        case PyUnicode_2BYTE_KIND:
11350
8.74M
        {
11351
8.74M
            COMPARE(Py_UCS2, Py_UCS2);
11352
21.2k
            break;
11353
8.74M
        }
11354
68.1k
        case PyUnicode_4BYTE_KIND:
11355
68.1k
            COMPARE(Py_UCS2, Py_UCS4);
11356
8
            break;
11357
8
        default:
11358
0
            Py_UNREACHABLE();
11359
8.86M
        }
11360
26.6k
        break;
11361
8.86M
    }
11362
545k
    case PyUnicode_4BYTE_KIND:
11363
545k
    {
11364
545k
        switch(kind2) {
11365
920
        case PyUnicode_1BYTE_KIND:
11366
920
            COMPARE(Py_UCS4, Py_UCS1);
11367
22
            break;
11368
76.1k
        case PyUnicode_2BYTE_KIND:
11369
76.1k
            COMPARE(Py_UCS4, Py_UCS2);
11370
6
            break;
11371
468k
        case PyUnicode_4BYTE_KIND:
11372
468k
        {
11373
468k
#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11374
468k
            int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11375
            /* normalize result of wmemcmp() into the range [-1; 1] */
11376
468k
            if (cmp < 0)
11377
218k
                return -1;
11378
250k
            if (cmp > 0)
11379
250k
                return 1;
11380
#else
11381
            COMPARE(Py_UCS4, Py_UCS4);
11382
#endif
11383
52
            break;
11384
250k
        }
11385
52
        default:
11386
0
            Py_UNREACHABLE();
11387
545k
        }
11388
80
        break;
11389
545k
    }
11390
80
    default:
11391
0
        Py_UNREACHABLE();
11392
13.9M
    }
11393
11394
123k
    if (len1 == len2)
11395
195
        return 0;
11396
123k
    if (len1 < len2)
11397
59.5k
        return -1;
11398
63.9k
    else
11399
63.9k
        return 1;
11400
11401
123k
#undef COMPARE
11402
123k
}
11403
11404
11405
int
11406
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
11407
83.7M
{
11408
83.7M
    assert(PyUnicode_Check(str1));
11409
83.7M
    assert(PyUnicode_Check(str2));
11410
83.7M
    if (str1 == str2) {
11411
11.1M
        return 1;
11412
11.1M
    }
11413
72.5M
    return unicode_eq(str1, str2);
11414
83.7M
}
11415
11416
11417
int
11418
PyUnicode_Equal(PyObject *str1, PyObject *str2)
11419
0
{
11420
0
    if (!PyUnicode_Check(str1)) {
11421
0
        PyErr_Format(PyExc_TypeError,
11422
0
                     "first argument must be str, not %T", str1);
11423
0
        return -1;
11424
0
    }
11425
0
    if (!PyUnicode_Check(str2)) {
11426
0
        PyErr_Format(PyExc_TypeError,
11427
0
                     "second argument must be str, not %T", str2);
11428
0
        return -1;
11429
0
    }
11430
11431
0
    return _PyUnicode_Equal(str1, str2);
11432
0
}
11433
11434
11435
int
11436
PyUnicode_Compare(PyObject *left, PyObject *right)
11437
309k
{
11438
309k
    if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11439
        /* a string is equal to itself */
11440
309k
        if (left == right)
11441
57
            return 0;
11442
11443
309k
        return unicode_compare(left, right);
11444
309k
    }
11445
0
    PyErr_Format(PyExc_TypeError,
11446
0
                 "Can't compare %.100s and %.100s",
11447
0
                 Py_TYPE(left)->tp_name,
11448
0
                 Py_TYPE(right)->tp_name);
11449
0
    return -1;
11450
309k
}
11451
11452
int
11453
PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11454
1.13M
{
11455
1.13M
    Py_ssize_t i;
11456
1.13M
    int kind;
11457
1.13M
    Py_UCS4 chr;
11458
11459
1.13M
    assert(_PyUnicode_CHECK(uni));
11460
1.13M
    kind = PyUnicode_KIND(uni);
11461
1.13M
    if (kind == PyUnicode_1BYTE_KIND) {
11462
1.12M
        const void *data = PyUnicode_1BYTE_DATA(uni);
11463
1.12M
        size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
11464
1.12M
        size_t len, len2 = strlen(str);
11465
1.12M
        int cmp;
11466
11467
1.12M
        len = Py_MIN(len1, len2);
11468
1.12M
        cmp = memcmp(data, str, len);
11469
1.12M
        if (cmp != 0) {
11470
580k
            if (cmp < 0)
11471
24.6k
                return -1;
11472
555k
            else
11473
555k
                return 1;
11474
580k
        }
11475
549k
        if (len1 > len2)
11476
1.40k
            return 1; /* uni is longer */
11477
548k
        if (len1 < len2)
11478
4.50k
            return -1; /* str is longer */
11479
543k
        return 0;
11480
548k
    }
11481
3.58k
    else {
11482
3.58k
        const void *data = PyUnicode_DATA(uni);
11483
        /* Compare Unicode string and source character set string */
11484
6.60k
        for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
11485
5.90k
            if (chr != (unsigned char)str[i])
11486
2.88k
                return (chr < (unsigned char)(str[i])) ? -1 : 1;
11487
        /* This check keeps Python strings that end in '\0' from comparing equal
11488
         to C strings identical up to that point. */
11489
698
        if (PyUnicode_GET_LENGTH(uni) != i || chr)
11490
698
            return 1; /* uni is longer */
11491
0
        if (str[i])
11492
0
            return -1; /* str is longer */
11493
0
        return 0;
11494
0
    }
11495
1.13M
}
11496
11497
int
11498
PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
11499
2
{
11500
2
    return PyUnicode_EqualToUTF8AndSize(unicode, str, strlen(str));
11501
2
}
11502
11503
int
11504
PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t size)
11505
2
{
11506
2
    assert(_PyUnicode_CHECK(unicode));
11507
2
    assert(str);
11508
11509
2
    if (PyUnicode_IS_ASCII(unicode)) {
11510
2
        Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11511
2
        return size == len &&
11512
0
            memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11513
2
    }
11514
0
    if (PyUnicode_UTF8(unicode) != NULL) {
11515
0
        Py_ssize_t len = PyUnicode_UTF8_LENGTH(unicode);
11516
0
        return size == len &&
11517
0
            memcmp(PyUnicode_UTF8(unicode), str, len) == 0;
11518
0
    }
11519
11520
0
    Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
11521
0
    if ((size_t)len >= (size_t)size || (size_t)len < (size_t)size / 4) {
11522
0
        return 0;
11523
0
    }
11524
0
    const unsigned char *s = (const unsigned char *)str;
11525
0
    const unsigned char *ends = s + (size_t)size;
11526
0
    int kind = PyUnicode_KIND(unicode);
11527
0
    const void *data = PyUnicode_DATA(unicode);
11528
    /* Compare Unicode string and UTF-8 string */
11529
0
    for (Py_ssize_t i = 0; i < len; i++) {
11530
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11531
0
        if (ch < 0x80) {
11532
0
            if (ends == s || s[0] != ch) {
11533
0
                return 0;
11534
0
            }
11535
0
            s += 1;
11536
0
        }
11537
0
        else if (ch < 0x800) {
11538
0
            if ((ends - s) < 2 ||
11539
0
                s[0] != (0xc0 | (ch >> 6)) ||
11540
0
                s[1] != (0x80 | (ch & 0x3f)))
11541
0
            {
11542
0
                return 0;
11543
0
            }
11544
0
            s += 2;
11545
0
        }
11546
0
        else if (ch < 0x10000) {
11547
0
            if (Py_UNICODE_IS_SURROGATE(ch) ||
11548
0
                (ends - s) < 3 ||
11549
0
                s[0] != (0xe0 | (ch >> 12)) ||
11550
0
                s[1] != (0x80 | ((ch >> 6) & 0x3f)) ||
11551
0
                s[2] != (0x80 | (ch & 0x3f)))
11552
0
            {
11553
0
                return 0;
11554
0
            }
11555
0
            s += 3;
11556
0
        }
11557
0
        else {
11558
0
            assert(ch <= MAX_UNICODE);
11559
0
            if ((ends - s) < 4 ||
11560
0
                s[0] != (0xf0 | (ch >> 18)) ||
11561
0
                s[1] != (0x80 | ((ch >> 12) & 0x3f)) ||
11562
0
                s[2] != (0x80 | ((ch >> 6) & 0x3f)) ||
11563
0
                s[3] != (0x80 | (ch & 0x3f)))
11564
0
            {
11565
0
                return 0;
11566
0
            }
11567
0
            s += 4;
11568
0
        }
11569
0
    }
11570
0
    return s == ends;
11571
0
}
11572
11573
int
11574
_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11575
5.14M
{
11576
5.14M
    size_t len;
11577
5.14M
    assert(_PyUnicode_CHECK(unicode));
11578
5.14M
    assert(str);
11579
5.14M
#ifndef NDEBUG
11580
32.5M
    for (const char *p = str; *p; p++) {
11581
27.4M
        assert((unsigned char)*p < 128);
11582
27.4M
    }
11583
5.14M
#endif
11584
5.14M
    if (!PyUnicode_IS_ASCII(unicode))
11585
284k
        return 0;
11586
4.85M
    len = (size_t)PyUnicode_GET_LENGTH(unicode);
11587
4.85M
    return strlen(str) == len &&
11588
512k
           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11589
5.14M
}
11590
11591
PyObject *
11592
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
11593
15.1M
{
11594
15.1M
    int result;
11595
11596
15.1M
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11597
11.7k
        Py_RETURN_NOTIMPLEMENTED;
11598
11599
15.1M
    if (left == right) {
11600
313
        switch (op) {
11601
268
        case Py_EQ:
11602
268
        case Py_LE:
11603
268
        case Py_GE:
11604
            /* a string is equal to itself */
11605
268
            Py_RETURN_TRUE;
11606
45
        case Py_NE:
11607
45
        case Py_LT:
11608
45
        case Py_GT:
11609
45
            Py_RETURN_FALSE;
11610
0
        default:
11611
0
            PyErr_BadArgument();
11612
0
            return NULL;
11613
313
        }
11614
313
    }
11615
15.1M
    else if (op == Py_EQ || op == Py_NE) {
11616
1.57M
        result = unicode_eq(left, right);
11617
1.57M
        result ^= (op == Py_NE);
11618
1.57M
        return PyBool_FromLong(result);
11619
1.57M
    }
11620
13.6M
    else {
11621
13.6M
        result = unicode_compare(left, right);
11622
13.6M
        Py_RETURN_RICHCOMPARE(result, 0, op);
11623
13.6M
    }
11624
15.1M
}
11625
11626
int
11627
PyUnicode_Contains(PyObject *str, PyObject *substr)
11628
206M
{
11629
206M
    int kind1, kind2;
11630
206M
    const void *buf1, *buf2;
11631
206M
    Py_ssize_t len1, len2;
11632
206M
    int result;
11633
11634
206M
    if (!PyUnicode_Check(substr)) {
11635
0
        PyErr_Format(PyExc_TypeError,
11636
0
                     "'in <string>' requires string as left operand, not %.100s",
11637
0
                     Py_TYPE(substr)->tp_name);
11638
0
        return -1;
11639
0
    }
11640
206M
    if (ensure_unicode(str) < 0)
11641
0
        return -1;
11642
11643
206M
    kind1 = PyUnicode_KIND(str);
11644
206M
    kind2 = PyUnicode_KIND(substr);
11645
206M
    if (kind1 < kind2)
11646
3
        return 0;
11647
206M
    len1 = PyUnicode_GET_LENGTH(str);
11648
206M
    len2 = PyUnicode_GET_LENGTH(substr);
11649
206M
    if (len1 < len2)
11650
42
        return 0;
11651
206M
    buf1 = PyUnicode_DATA(str);
11652
206M
    buf2 = PyUnicode_DATA(substr);
11653
206M
    if (len2 == 1) {
11654
25.2M
        Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11655
25.2M
        result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11656
25.2M
        return result;
11657
25.2M
    }
11658
181M
    if (kind2 != kind1) {
11659
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11660
0
        if (!buf2)
11661
0
            return -1;
11662
0
    }
11663
11664
181M
    switch (kind1) {
11665
181M
    case PyUnicode_1BYTE_KIND:
11666
181M
        result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11667
181M
        break;
11668
0
    case PyUnicode_2BYTE_KIND:
11669
0
        result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11670
0
        break;
11671
0
    case PyUnicode_4BYTE_KIND:
11672
0
        result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11673
0
        break;
11674
0
    default:
11675
0
        Py_UNREACHABLE();
11676
181M
    }
11677
11678
181M
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
11679
181M
    if (kind2 != kind1)
11680
0
        PyMem_Free((void *)buf2);
11681
11682
181M
    return result;
11683
181M
}
11684
11685
/* Concat to string or Unicode object giving a new Unicode object. */
11686
11687
PyObject *
11688
PyUnicode_Concat(PyObject *left, PyObject *right)
11689
1.17M
{
11690
1.17M
    PyObject *result;
11691
1.17M
    Py_UCS4 maxchar, maxchar2;
11692
1.17M
    Py_ssize_t left_len, right_len, new_len;
11693
11694
1.17M
    if (ensure_unicode(left) < 0)
11695
0
        return NULL;
11696
11697
1.17M
    if (!PyUnicode_Check(right)) {
11698
733
        PyErr_Format(PyExc_TypeError,
11699
733
            "can only concatenate str (not \"%.200s\") to str",
11700
733
            Py_TYPE(right)->tp_name);
11701
733
        return NULL;
11702
733
    }
11703
11704
    /* Shortcuts */
11705
1.17M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11706
1.17M
    if (left == empty) {
11707
33.9k
        return PyUnicode_FromObject(right);
11708
33.9k
    }
11709
1.14M
    if (right == empty) {
11710
49.7k
        return PyUnicode_FromObject(left);
11711
49.7k
    }
11712
11713
1.09M
    left_len = PyUnicode_GET_LENGTH(left);
11714
1.09M
    right_len = PyUnicode_GET_LENGTH(right);
11715
1.09M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11716
0
        PyErr_SetString(PyExc_OverflowError,
11717
0
                        "strings are too large to concat");
11718
0
        return NULL;
11719
0
    }
11720
1.09M
    new_len = left_len + right_len;
11721
11722
1.09M
    maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11723
1.09M
    maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11724
1.09M
    maxchar = Py_MAX(maxchar, maxchar2);
11725
11726
    /* Concat the two Unicode strings */
11727
1.09M
    result = PyUnicode_New(new_len, maxchar);
11728
1.09M
    if (result == NULL)
11729
0
        return NULL;
11730
1.09M
    _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11731
1.09M
    _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11732
1.09M
    assert(_PyUnicode_CheckConsistency(result, 1));
11733
1.09M
    return result;
11734
1.09M
}
11735
11736
void
11737
PyUnicode_Append(PyObject **p_left, PyObject *right)
11738
6.10M
{
11739
6.10M
    PyObject *left, *res;
11740
6.10M
    Py_UCS4 maxchar, maxchar2;
11741
6.10M
    Py_ssize_t left_len, right_len, new_len;
11742
11743
6.10M
    if (p_left == NULL) {
11744
0
        if (!PyErr_Occurred())
11745
0
            PyErr_BadInternalCall();
11746
0
        return;
11747
0
    }
11748
6.10M
    left = *p_left;
11749
6.10M
    if (right == NULL || left == NULL
11750
6.10M
        || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
11751
0
        if (!PyErr_Occurred())
11752
0
            PyErr_BadInternalCall();
11753
0
        goto error;
11754
0
    }
11755
11756
    /* Shortcuts */
11757
6.10M
    PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
11758
6.10M
    if (left == empty) {
11759
58.0k
        Py_DECREF(left);
11760
58.0k
        *p_left = Py_NewRef(right);
11761
58.0k
        return;
11762
58.0k
    }
11763
6.04M
    if (right == empty) {
11764
2.50k
        return;
11765
2.50k
    }
11766
11767
6.04M
    left_len = PyUnicode_GET_LENGTH(left);
11768
6.04M
    right_len = PyUnicode_GET_LENGTH(right);
11769
6.04M
    if (left_len > PY_SSIZE_T_MAX - right_len) {
11770
0
        PyErr_SetString(PyExc_OverflowError,
11771
0
                        "strings are too large to concat");
11772
0
        goto error;
11773
0
    }
11774
6.04M
    new_len = left_len + right_len;
11775
11776
6.04M
    if (_PyUnicode_IsModifiable(left)
11777
6.04M
        && PyUnicode_CheckExact(right)
11778
11.1M
        && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
11779
        /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11780
           to change the structure size, but characters are stored just after
11781
           the structure, and so it requires to move all characters which is
11782
           not so different than duplicating the string. */
11783
5.55M
        && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11784
5.55M
    {
11785
        /* append inplace */
11786
5.55M
        if (unicode_resize(p_left, new_len) != 0)
11787
0
            goto error;
11788
11789
        /* copy 'right' into the newly allocated area of 'left' */
11790
5.55M
        _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
11791
5.55M
    }
11792
488k
    else {
11793
488k
        maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11794
488k
        maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11795
488k
        maxchar = Py_MAX(maxchar, maxchar2);
11796
11797
        /* Concat the two Unicode strings */
11798
488k
        res = PyUnicode_New(new_len, maxchar);
11799
488k
        if (res == NULL)
11800
0
            goto error;
11801
488k
        _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11802
488k
        _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
11803
488k
        Py_DECREF(left);
11804
488k
        *p_left = res;
11805
488k
    }
11806
6.04M
    assert(_PyUnicode_CheckConsistency(*p_left, 1));
11807
6.04M
    return;
11808
11809
6.04M
error:
11810
0
    Py_CLEAR(*p_left);
11811
0
}
11812
11813
void
11814
PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11815
0
{
11816
0
    PyUnicode_Append(pleft, right);
11817
0
    Py_XDECREF(right);
11818
0
}
11819
11820
/*[clinic input]
11821
@permit_long_summary
11822
@text_signature "($self, sub[, start[, end]], /)"
11823
str.count as unicode_count -> Py_ssize_t
11824
11825
    self as str: self
11826
    sub as substr: unicode
11827
    start: slice_index(accept={int, NoneType}, c_default='0') = None
11828
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
11829
    /
11830
11831
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
11832
11833
Optional arguments start and end are interpreted as in slice
11834
notation.
11835
[clinic start generated code]*/
11836
11837
static Py_ssize_t
11838
unicode_count_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
11839
                   Py_ssize_t end)
11840
/*[clinic end generated code: output=8fcc3aef0b18edbf input=c9209e05438cc352]*/
11841
6.52k
{
11842
6.52k
    assert(PyUnicode_Check(str));
11843
6.52k
    assert(PyUnicode_Check(substr));
11844
11845
6.52k
    Py_ssize_t result;
11846
6.52k
    int kind1, kind2;
11847
6.52k
    const void *buf1 = NULL, *buf2 = NULL;
11848
6.52k
    Py_ssize_t len1, len2;
11849
11850
6.52k
    kind1 = PyUnicode_KIND(str);
11851
6.52k
    kind2 = PyUnicode_KIND(substr);
11852
6.52k
    if (kind1 < kind2)
11853
0
        return 0;
11854
11855
6.52k
    len1 = PyUnicode_GET_LENGTH(str);
11856
6.52k
    len2 = PyUnicode_GET_LENGTH(substr);
11857
6.52k
    ADJUST_INDICES(start, end, len1);
11858
6.52k
    if (end - start < len2)
11859
1.33k
        return 0;
11860
11861
5.18k
    buf1 = PyUnicode_DATA(str);
11862
5.18k
    buf2 = PyUnicode_DATA(substr);
11863
5.18k
    if (kind2 != kind1) {
11864
2.29k
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
11865
2.29k
        if (!buf2)
11866
0
            goto onError;
11867
2.29k
    }
11868
11869
    // We don't reuse `anylib_count` here because of the explicit casts.
11870
5.18k
    switch (kind1) {
11871
2.89k
    case PyUnicode_1BYTE_KIND:
11872
2.89k
        result = ucs1lib_count(
11873
2.89k
            ((const Py_UCS1*)buf1) + start, end - start,
11874
2.89k
            buf2, len2, PY_SSIZE_T_MAX
11875
2.89k
            );
11876
2.89k
        break;
11877
942
    case PyUnicode_2BYTE_KIND:
11878
942
        result = ucs2lib_count(
11879
942
            ((const Py_UCS2*)buf1) + start, end - start,
11880
942
            buf2, len2, PY_SSIZE_T_MAX
11881
942
            );
11882
942
        break;
11883
1.35k
    case PyUnicode_4BYTE_KIND:
11884
1.35k
        result = ucs4lib_count(
11885
1.35k
            ((const Py_UCS4*)buf1) + start, end - start,
11886
1.35k
            buf2, len2, PY_SSIZE_T_MAX
11887
1.35k
            );
11888
1.35k
        break;
11889
0
    default:
11890
0
        Py_UNREACHABLE();
11891
5.18k
    }
11892
11893
5.18k
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11894
5.18k
    if (kind2 != kind1)
11895
2.29k
        PyMem_Free((void *)buf2);
11896
11897
5.18k
    return result;
11898
0
  onError:
11899
0
    assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
11900
0
    if (kind2 != kind1)
11901
0
        PyMem_Free((void *)buf2);
11902
0
    return -1;
11903
0
}
11904
11905
/*[clinic input]
11906
str.encode as unicode_encode
11907
11908
    encoding: str(c_default="NULL") = 'utf-8'
11909
        The encoding in which to encode the string.
11910
    errors: str(c_default="NULL") = 'strict'
11911
        The error handling scheme to use for encoding errors.
11912
        The default is 'strict' meaning that encoding errors raise a
11913
        UnicodeEncodeError.  Other possible values are 'ignore', 'replace'
11914
        and 'xmlcharrefreplace' as well as any other name registered with
11915
        codecs.register_error that can handle UnicodeEncodeErrors.
11916
11917
Encode the string using the codec registered for encoding.
11918
[clinic start generated code]*/
11919
11920
static PyObject *
11921
unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
11922
/*[clinic end generated code: output=bf78b6e2a9470e3c input=b85a9645cb33b729]*/
11923
55.2k
{
11924
55.2k
    return PyUnicode_AsEncodedString(self, encoding, errors);
11925
55.2k
}
11926
11927
/*[clinic input]
11928
str.expandtabs as unicode_expandtabs
11929
11930
    tabsize: int = 8
11931
11932
Return a copy where all tab characters are expanded using spaces.
11933
11934
If tabsize is not given, a tab size of 8 characters is assumed.
11935
[clinic start generated code]*/
11936
11937
static PyObject *
11938
unicode_expandtabs_impl(PyObject *self, int tabsize)
11939
/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
11940
1.94k
{
11941
1.94k
    Py_ssize_t i, j, line_pos, src_len, incr;
11942
1.94k
    Py_UCS4 ch;
11943
1.94k
    PyObject *u;
11944
1.94k
    const void *src_data;
11945
1.94k
    void *dest_data;
11946
1.94k
    int kind;
11947
1.94k
    int found;
11948
11949
    /* First pass: determine size of output string */
11950
1.94k
    src_len = PyUnicode_GET_LENGTH(self);
11951
1.94k
    i = j = line_pos = 0;
11952
1.94k
    kind = PyUnicode_KIND(self);
11953
1.94k
    src_data = PyUnicode_DATA(self);
11954
1.94k
    found = 0;
11955
196k
    for (; i < src_len; i++) {
11956
194k
        ch = PyUnicode_READ(kind, src_data, i);
11957
194k
        if (ch == '\t') {
11958
5.43k
            found = 1;
11959
5.43k
            if (tabsize > 0) {
11960
5.43k
                incr = tabsize - (line_pos % tabsize); /* cannot overflow */
11961
5.43k
                if (j > PY_SSIZE_T_MAX - incr)
11962
0
                    goto overflow;
11963
5.43k
                line_pos += incr;
11964
5.43k
                j += incr;
11965
5.43k
            }
11966
5.43k
        }
11967
189k
        else {
11968
189k
            if (j > PY_SSIZE_T_MAX - 1)
11969
0
                goto overflow;
11970
189k
            line_pos++;
11971
189k
            j++;
11972
189k
            if (ch == '\n' || ch == '\r')
11973
29.0k
                line_pos = 0;
11974
189k
        }
11975
194k
    }
11976
1.94k
    if (!found)
11977
1.36k
        return unicode_result_unchanged(self);
11978
11979
    /* Second pass: create output string and fill it */
11980
586
    u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
11981
586
    if (!u)
11982
0
        return NULL;
11983
586
    dest_data = PyUnicode_DATA(u);
11984
11985
586
    i = j = line_pos = 0;
11986
11987
172k
    for (; i < src_len; i++) {
11988
171k
        ch = PyUnicode_READ(kind, src_data, i);
11989
171k
        if (ch == '\t') {
11990
5.43k
            if (tabsize > 0) {
11991
5.43k
                incr = tabsize - (line_pos % tabsize);
11992
5.43k
                line_pos += incr;
11993
5.43k
                _PyUnicode_Fill(kind, dest_data, ' ', j, incr);
11994
5.43k
                j += incr;
11995
5.43k
            }
11996
5.43k
        }
11997
166k
        else {
11998
166k
            line_pos++;
11999
166k
            PyUnicode_WRITE(kind, dest_data, j, ch);
12000
166k
            j++;
12001
166k
            if (ch == '\n' || ch == '\r')
12002
23.7k
                line_pos = 0;
12003
166k
        }
12004
171k
    }
12005
586
    assert (j == PyUnicode_GET_LENGTH(u));
12006
586
    return unicode_result(u);
12007
12008
0
  overflow:
12009
0
    PyErr_SetString(PyExc_OverflowError, "new string is too long");
12010
0
    return NULL;
12011
586
}
12012
12013
/*[clinic input]
12014
@permit_long_summary
12015
str.find as unicode_find = str.count
12016
12017
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12018
12019
Optional arguments start and end are interpreted as in slice
12020
notation.  Return -1 on failure.
12021
[clinic start generated code]*/
12022
12023
static Py_ssize_t
12024
unicode_find_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12025
                  Py_ssize_t end)
12026
/*[clinic end generated code: output=51dbe6255712e278 input=f57e93c59d1ee927]*/
12027
21
{
12028
21
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12029
21
    if (result < 0) {
12030
0
        return -1;
12031
0
    }
12032
21
    return result;
12033
21
}
12034
12035
static PyObject *
12036
unicode_getitem(PyObject *self, Py_ssize_t index)
12037
12.1M
{
12038
12.1M
    const void *data;
12039
12.1M
    int kind;
12040
12.1M
    Py_UCS4 ch;
12041
12042
12.1M
    if (!PyUnicode_Check(self)) {
12043
0
        PyErr_BadArgument();
12044
0
        return NULL;
12045
0
    }
12046
12.1M
    if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
12047
5.48k
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12048
5.48k
        return NULL;
12049
5.48k
    }
12050
12.1M
    kind = PyUnicode_KIND(self);
12051
12.1M
    data = PyUnicode_DATA(self);
12052
12.1M
    ch = PyUnicode_READ(kind, data, index);
12053
12.1M
    return unicode_char(ch);
12054
12.1M
}
12055
12056
/* Believe it or not, this produces the same value for ASCII strings
12057
   as bytes_hash(). */
12058
static Py_hash_t
12059
unicode_hash(PyObject *self)
12060
12.4M
{
12061
12.4M
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
12062
12063
#ifdef Py_DEBUG
12064
    assert(_Py_HashSecret_Initialized);
12065
#endif
12066
12.4M
    Py_hash_t hash = PyUnicode_HASH(self);
12067
12.4M
    if (hash != -1) {
12068
8.52M
        return hash;
12069
8.52M
    }
12070
3.95M
    x = Py_HashBuffer(PyUnicode_DATA(self),
12071
3.95M
                      PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
12072
12073
0
    PyUnicode_SET_HASH(self, x);
12074
3.95M
    return x;
12075
3.95M
}
12076
12077
/*[clinic input]
12078
@permit_long_summary
12079
str.index as unicode_index = str.count
12080
12081
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
12082
12083
Optional arguments start and end are interpreted as in slice
12084
notation.  Raises ValueError when the substring is not found.
12085
[clinic start generated code]*/
12086
12087
static Py_ssize_t
12088
unicode_index_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
12089
                   Py_ssize_t end)
12090
/*[clinic end generated code: output=77558288837cdf40 input=5900ab84de55e628]*/
12091
0
{
12092
0
    Py_ssize_t result = any_find_slice(str, substr, start, end, 1);
12093
0
    if (result == -1) {
12094
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
12095
0
    }
12096
0
    else if (result < 0) {
12097
0
        return -1;
12098
0
    }
12099
0
    return result;
12100
0
}
12101
12102
/*[clinic input]
12103
@permit_long_summary
12104
str.isascii as unicode_isascii
12105
12106
Return True if all characters in the string are ASCII, False otherwise.
12107
12108
ASCII characters have code points in the range U+0000-U+007F.
12109
Empty string is ASCII too.
12110
[clinic start generated code]*/
12111
12112
static PyObject *
12113
unicode_isascii_impl(PyObject *self)
12114
/*[clinic end generated code: output=c5910d64b5a8003f input=dc74e1ced821159f]*/
12115
4.70k
{
12116
4.70k
    return PyBool_FromLong(PyUnicode_IS_ASCII(self));
12117
4.70k
}
12118
12119
/*[clinic input]
12120
str.islower as unicode_islower
12121
12122
Return True if the string is a lowercase string, False otherwise.
12123
12124
A string is lowercase if all cased characters in the string are
12125
lowercase and there is at least one cased character in the string.
12126
[clinic start generated code]*/
12127
12128
static PyObject *
12129
unicode_islower_impl(PyObject *self)
12130
/*[clinic end generated code: output=dbd41995bd005b81 input=1879b48dfc628366]*/
12131
0
{
12132
0
    Py_ssize_t i, length;
12133
0
    int kind;
12134
0
    const void *data;
12135
0
    int cased;
12136
12137
0
    length = PyUnicode_GET_LENGTH(self);
12138
0
    kind = PyUnicode_KIND(self);
12139
0
    data = PyUnicode_DATA(self);
12140
12141
    /* Shortcut for single character strings */
12142
0
    if (length == 1)
12143
0
        return PyBool_FromLong(
12144
0
            Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
12145
12146
    /* Special case for empty strings */
12147
0
    if (length == 0)
12148
0
        Py_RETURN_FALSE;
12149
12150
0
    cased = 0;
12151
0
    for (i = 0; i < length; i++) {
12152
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12153
12154
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
12155
0
            Py_RETURN_FALSE;
12156
0
        else if (!cased && Py_UNICODE_ISLOWER(ch))
12157
0
            cased = 1;
12158
0
    }
12159
0
    return PyBool_FromLong(cased);
12160
0
}
12161
12162
/*[clinic input]
12163
str.isupper as unicode_isupper
12164
12165
Return True if the string is an uppercase string, False otherwise.
12166
12167
A string is uppercase if all cased characters in the string are
12168
uppercase and there is at least one cased character in the string.
12169
[clinic start generated code]*/
12170
12171
static PyObject *
12172
unicode_isupper_impl(PyObject *self)
12173
/*[clinic end generated code: output=049209c8e7f15f59 input=77d29904aef0e3a0]*/
12174
0
{
12175
0
    Py_ssize_t i, length;
12176
0
    int kind;
12177
0
    const void *data;
12178
0
    int cased;
12179
12180
0
    length = PyUnicode_GET_LENGTH(self);
12181
0
    kind = PyUnicode_KIND(self);
12182
0
    data = PyUnicode_DATA(self);
12183
12184
    /* Shortcut for single character strings */
12185
0
    if (length == 1)
12186
0
        return PyBool_FromLong(
12187
0
            Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
12188
12189
    /* Special case for empty strings */
12190
0
    if (length == 0)
12191
0
        Py_RETURN_FALSE;
12192
12193
0
    cased = 0;
12194
0
    for (i = 0; i < length; i++) {
12195
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12196
12197
0
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
12198
0
            Py_RETURN_FALSE;
12199
0
        else if (!cased && Py_UNICODE_ISUPPER(ch))
12200
0
            cased = 1;
12201
0
    }
12202
0
    return PyBool_FromLong(cased);
12203
0
}
12204
12205
/*[clinic input]
12206
str.istitle as unicode_istitle
12207
12208
Return True if the string is a title-cased string, False otherwise.
12209
12210
In a title-cased string, upper- and title-case characters may only
12211
follow uncased characters and lowercase characters only cased ones.
12212
[clinic start generated code]*/
12213
12214
static PyObject *
12215
unicode_istitle_impl(PyObject *self)
12216
/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
12217
0
{
12218
0
    Py_ssize_t i, length;
12219
0
    int kind;
12220
0
    const void *data;
12221
0
    int cased, previous_is_cased;
12222
12223
0
    length = PyUnicode_GET_LENGTH(self);
12224
0
    kind = PyUnicode_KIND(self);
12225
0
    data = PyUnicode_DATA(self);
12226
12227
    /* Shortcut for single character strings */
12228
0
    if (length == 1) {
12229
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12230
0
        return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
12231
0
                               (Py_UNICODE_ISUPPER(ch) != 0));
12232
0
    }
12233
12234
    /* Special case for empty strings */
12235
0
    if (length == 0)
12236
0
        Py_RETURN_FALSE;
12237
12238
0
    cased = 0;
12239
0
    previous_is_cased = 0;
12240
0
    for (i = 0; i < length; i++) {
12241
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12242
12243
0
        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
12244
0
            if (previous_is_cased)
12245
0
                Py_RETURN_FALSE;
12246
0
            previous_is_cased = 1;
12247
0
            cased = 1;
12248
0
        }
12249
0
        else if (Py_UNICODE_ISLOWER(ch)) {
12250
0
            if (!previous_is_cased)
12251
0
                Py_RETURN_FALSE;
12252
0
            previous_is_cased = 1;
12253
0
            cased = 1;
12254
0
        }
12255
0
        else
12256
0
            previous_is_cased = 0;
12257
0
    }
12258
0
    return PyBool_FromLong(cased);
12259
0
}
12260
12261
/*[clinic input]
12262
str.isspace as unicode_isspace
12263
12264
Return True if the string is a whitespace string, False otherwise.
12265
12266
A string is whitespace if all characters in the string are
12267
whitespace and there is at least one character in the string.
12268
[clinic start generated code]*/
12269
12270
static PyObject *
12271
unicode_isspace_impl(PyObject *self)
12272
/*[clinic end generated code: output=163a63bfa08ac2b9 input=29e09560fc23fbeb]*/
12273
0
{
12274
0
    Py_ssize_t i, length;
12275
0
    int kind;
12276
0
    const void *data;
12277
12278
0
    length = PyUnicode_GET_LENGTH(self);
12279
0
    kind = PyUnicode_KIND(self);
12280
0
    data = PyUnicode_DATA(self);
12281
12282
    /* Shortcut for single character strings */
12283
0
    if (length == 1)
12284
0
        return PyBool_FromLong(
12285
0
            Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
12286
12287
    /* Special case for empty strings */
12288
0
    if (length == 0)
12289
0
        Py_RETURN_FALSE;
12290
12291
0
    for (i = 0; i < length; i++) {
12292
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12293
0
        if (!Py_UNICODE_ISSPACE(ch))
12294
0
            Py_RETURN_FALSE;
12295
0
    }
12296
0
    Py_RETURN_TRUE;
12297
0
}
12298
12299
/*[clinic input]
12300
str.isalpha as unicode_isalpha
12301
12302
Return True if the string is an alphabetic string, False otherwise.
12303
12304
A string is alphabetic if all characters in the string are
12305
alphabetic and there is at least one character in the string.
12306
[clinic start generated code]*/
12307
12308
static PyObject *
12309
unicode_isalpha_impl(PyObject *self)
12310
/*[clinic end generated code: output=cc81b9ac3883ec4f input=9906a07f3e04892e]*/
12311
14
{
12312
14
    Py_ssize_t i, length;
12313
14
    int kind;
12314
14
    const void *data;
12315
12316
14
    length = PyUnicode_GET_LENGTH(self);
12317
14
    kind = PyUnicode_KIND(self);
12318
14
    data = PyUnicode_DATA(self);
12319
12320
    /* Shortcut for single character strings */
12321
14
    if (length == 1)
12322
11
        return PyBool_FromLong(
12323
11
            Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
12324
12325
    /* Special case for empty strings */
12326
3
    if (length == 0)
12327
0
        Py_RETURN_FALSE;
12328
12329
3
    for (i = 0; i < length; i++) {
12330
3
        if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
12331
3
            Py_RETURN_FALSE;
12332
3
    }
12333
3
    Py_RETURN_TRUE;
12334
3
}
12335
12336
/*[clinic input]
12337
@permit_long_summary
12338
str.isalnum as unicode_isalnum
12339
12340
Return True if the string is an alpha-numeric string, False otherwise.
12341
12342
A string is alpha-numeric if all characters in the string are
12343
alpha-numeric and there is at least one character in the string.
12344
[clinic start generated code]*/
12345
12346
static PyObject *
12347
unicode_isalnum_impl(PyObject *self)
12348
/*[clinic end generated code: output=a5a23490ffc3660c input=892f64ebc171fd4f]*/
12349
128
{
12350
128
    int kind;
12351
128
    const void *data;
12352
128
    Py_ssize_t len, i;
12353
12354
128
    kind = PyUnicode_KIND(self);
12355
128
    data = PyUnicode_DATA(self);
12356
128
    len = PyUnicode_GET_LENGTH(self);
12357
12358
    /* Shortcut for single character strings */
12359
128
    if (len == 1) {
12360
128
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12361
128
        return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12362
128
    }
12363
12364
    /* Special case for empty strings */
12365
0
    if (len == 0)
12366
0
        Py_RETURN_FALSE;
12367
12368
0
    for (i = 0; i < len; i++) {
12369
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12370
0
        if (!Py_UNICODE_ISALNUM(ch))
12371
0
            Py_RETURN_FALSE;
12372
0
    }
12373
0
    Py_RETURN_TRUE;
12374
0
}
12375
12376
/*[clinic input]
12377
str.isdecimal as unicode_isdecimal
12378
12379
Return True if the string is a decimal string, False otherwise.
12380
12381
A string is a decimal string if all characters in the string are
12382
decimal and there is at least one character in the string.
12383
[clinic start generated code]*/
12384
12385
static PyObject *
12386
unicode_isdecimal_impl(PyObject *self)
12387
/*[clinic end generated code: output=fb2dcdb62d3fc548 input=63b0453c48cad0af]*/
12388
3.89k
{
12389
3.89k
    Py_ssize_t i, length;
12390
3.89k
    int kind;
12391
3.89k
    const void *data;
12392
12393
3.89k
    length = PyUnicode_GET_LENGTH(self);
12394
3.89k
    kind = PyUnicode_KIND(self);
12395
3.89k
    data = PyUnicode_DATA(self);
12396
12397
    /* Shortcut for single character strings */
12398
3.89k
    if (length == 1)
12399
2.63k
        return PyBool_FromLong(
12400
2.63k
            Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
12401
12402
    /* Special case for empty strings */
12403
1.25k
    if (length == 0)
12404
0
        Py_RETURN_FALSE;
12405
12406
739k
    for (i = 0; i < length; i++) {
12407
738k
        if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
12408
334
            Py_RETURN_FALSE;
12409
738k
    }
12410
1.25k
    Py_RETURN_TRUE;
12411
1.25k
}
12412
12413
/*[clinic input]
12414
str.isdigit as unicode_isdigit
12415
12416
Return True if the string is a digit string, False otherwise.
12417
12418
A string is a digit string if all characters in the string are
12419
digits and there is at least one character in the string.
12420
[clinic start generated code]*/
12421
12422
static PyObject *
12423
unicode_isdigit_impl(PyObject *self)
12424
/*[clinic end generated code: output=10a6985311da6858 input=353b03747b062e4b]*/
12425
0
{
12426
0
    Py_ssize_t i, length;
12427
0
    int kind;
12428
0
    const void *data;
12429
12430
0
    length = PyUnicode_GET_LENGTH(self);
12431
0
    kind = PyUnicode_KIND(self);
12432
0
    data = PyUnicode_DATA(self);
12433
12434
    /* Shortcut for single character strings */
12435
0
    if (length == 1) {
12436
0
        const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12437
0
        return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12438
0
    }
12439
12440
    /* Special case for empty strings */
12441
0
    if (length == 0)
12442
0
        Py_RETURN_FALSE;
12443
12444
0
    for (i = 0; i < length; i++) {
12445
0
        if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
12446
0
            Py_RETURN_FALSE;
12447
0
    }
12448
0
    Py_RETURN_TRUE;
12449
0
}
12450
12451
/*[clinic input]
12452
str.isnumeric as unicode_isnumeric
12453
12454
Return True if the string is a numeric string, False otherwise.
12455
12456
A string is numeric if all characters in the string are numeric and
12457
there is at least one character in the string.
12458
[clinic start generated code]*/
12459
12460
static PyObject *
12461
unicode_isnumeric_impl(PyObject *self)
12462
/*[clinic end generated code: output=9172a32d9013051a input=83b2a072ed7aff48]*/
12463
0
{
12464
0
    Py_ssize_t i, length;
12465
0
    int kind;
12466
0
    const void *data;
12467
12468
0
    length = PyUnicode_GET_LENGTH(self);
12469
0
    kind = PyUnicode_KIND(self);
12470
0
    data = PyUnicode_DATA(self);
12471
12472
    /* Shortcut for single character strings */
12473
0
    if (length == 1)
12474
0
        return PyBool_FromLong(
12475
0
            Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
12476
12477
    /* Special case for empty strings */
12478
0
    if (length == 0)
12479
0
        Py_RETURN_FALSE;
12480
12481
0
    for (i = 0; i < length; i++) {
12482
0
        if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
12483
0
            Py_RETURN_FALSE;
12484
0
    }
12485
0
    Py_RETURN_TRUE;
12486
0
}
12487
12488
Py_ssize_t
12489
_PyUnicode_ScanIdentifier(PyObject *self)
12490
97.6k
{
12491
97.6k
    Py_ssize_t i;
12492
97.6k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12493
97.6k
    if (len == 0) {
12494
        /* an empty string is not a valid identifier */
12495
0
        return 0;
12496
0
    }
12497
12498
97.6k
    int kind = PyUnicode_KIND(self);
12499
97.6k
    const void *data = PyUnicode_DATA(self);
12500
97.6k
    Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12501
    /* PEP 3131 says that the first character must be in
12502
       XID_Start and subsequent characters in XID_Continue,
12503
       and for the ASCII range, the 2.x rules apply (i.e
12504
       start with letters and underscore, continue with
12505
       letters, digits, underscore). However, given the current
12506
       definition of XID_Start and XID_Continue, it is sufficient
12507
       to check just for these, except that _ must be allowed
12508
       as starting an identifier.  */
12509
97.6k
    if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12510
303
        return 0;
12511
303
    }
12512
12513
14.9M
    for (i = 1; i < len; i++) {
12514
14.8M
        ch = PyUnicode_READ(kind, data, i);
12515
14.8M
        if (!_PyUnicode_IsXidContinue(ch)) {
12516
150
            return i;
12517
150
        }
12518
14.8M
    }
12519
97.2k
    return i;
12520
97.3k
}
12521
12522
int
12523
PyUnicode_IsIdentifier(PyObject *self)
12524
1.58k
{
12525
1.58k
    Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12526
1.58k
    Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12527
    /* an empty string is not a valid identifier */
12528
1.58k
    return len && i == len;
12529
1.58k
}
12530
12531
/*[clinic input]
12532
@permit_long_summary
12533
str.isidentifier as unicode_isidentifier
12534
12535
Return True if the string is a valid Python identifier, False otherwise.
12536
12537
Call keyword.iskeyword(s) to test whether string s is a reserved
12538
identifier, such as "def" or "class".
12539
[clinic start generated code]*/
12540
12541
static PyObject *
12542
unicode_isidentifier_impl(PyObject *self)
12543
/*[clinic end generated code: output=fe585a9666572905 input=cabde62c20a3be6b]*/
12544
1.27k
{
12545
1.27k
    return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12546
1.27k
}
12547
12548
/*[clinic input]
12549
@permit_long_summary
12550
str.isprintable as unicode_isprintable
12551
12552
Return True if all characters in the string are printable, False otherwise.
12553
12554
A character is printable if repr() may use it in its output.
12555
[clinic start generated code]*/
12556
12557
static PyObject *
12558
unicode_isprintable_impl(PyObject *self)
12559
/*[clinic end generated code: output=3ab9626cd32dd1a0 input=18345ba847084ec5]*/
12560
0
{
12561
0
    Py_ssize_t i, length;
12562
0
    int kind;
12563
0
    const void *data;
12564
12565
0
    length = PyUnicode_GET_LENGTH(self);
12566
0
    kind = PyUnicode_KIND(self);
12567
0
    data = PyUnicode_DATA(self);
12568
12569
    /* Shortcut for single character strings */
12570
0
    if (length == 1)
12571
0
        return PyBool_FromLong(
12572
0
            Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
12573
12574
0
    for (i = 0; i < length; i++) {
12575
0
        if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
12576
0
            Py_RETURN_FALSE;
12577
0
        }
12578
0
    }
12579
0
    Py_RETURN_TRUE;
12580
0
}
12581
12582
/*[clinic input]
12583
str.join as unicode_join
12584
12585
    iterable: object
12586
    /
12587
12588
Concatenate any number of strings.
12589
12590
The string whose method is called is inserted in between each given
12591
string.  The result is returned as a new string.
12592
12593
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12594
[clinic start generated code]*/
12595
12596
static PyObject *
12597
unicode_join(PyObject *self, PyObject *iterable)
12598
/*[clinic end generated code: output=6857e7cecfe7bf98 input=fd330a11ee845fb2]*/
12599
276k
{
12600
276k
    return PyUnicode_Join(self, iterable);
12601
276k
}
12602
12603
static Py_ssize_t
12604
unicode_length(PyObject *self)
12605
5.66M
{
12606
5.66M
    return PyUnicode_GET_LENGTH(self);
12607
5.66M
}
12608
12609
/*[clinic input]
12610
str.ljust as unicode_ljust
12611
12612
    width: Py_ssize_t
12613
    fillchar: Py_UCS4 = ' '
12614
    /
12615
12616
Return a left-justified string of length width.
12617
12618
Padding is done using the specified fill character (default is
12619
a space).
12620
[clinic start generated code]*/
12621
12622
static PyObject *
12623
unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12624
/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=8a55f06694c20ed6]*/
12625
0
{
12626
0
    if (PyUnicode_GET_LENGTH(self) >= width)
12627
0
        return unicode_result_unchanged(self);
12628
12629
0
    return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
12630
0
}
12631
12632
/*[clinic input]
12633
str.lower as unicode_lower
12634
12635
Return a copy of the string converted to lowercase.
12636
[clinic start generated code]*/
12637
12638
static PyObject *
12639
unicode_lower_impl(PyObject *self)
12640
/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
12641
574k
{
12642
574k
    if (PyUnicode_IS_ASCII(self))
12643
141k
        return ascii_upper_or_lower(self, 1);
12644
432k
    return case_operation(self, do_lower);
12645
574k
}
12646
12647
243k
#define LEFTSTRIP 0
12648
272k
#define RIGHTSTRIP 1
12649
215k
#define BOTHSTRIP 2
12650
12651
/* Arrays indexed by above */
12652
static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
12653
12654
0
#define STRIPNAME(i) (stripfuncnames[i])
12655
12656
/* externally visible for str.strip(unicode) */
12657
PyObject *
12658
_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
12659
9.03k
{
12660
9.03k
    const void *data;
12661
9.03k
    int kind;
12662
9.03k
    Py_ssize_t i, j, len;
12663
9.03k
    BLOOM_MASK sepmask;
12664
9.03k
    Py_ssize_t seplen;
12665
12666
9.03k
    kind = PyUnicode_KIND(self);
12667
9.03k
    data = PyUnicode_DATA(self);
12668
9.03k
    len = PyUnicode_GET_LENGTH(self);
12669
9.03k
    seplen = PyUnicode_GET_LENGTH(sepobj);
12670
9.03k
    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12671
9.03k
                              PyUnicode_DATA(sepobj),
12672
9.03k
                              seplen);
12673
12674
0
    i = 0;
12675
9.03k
    if (striptype != RIGHTSTRIP) {
12676
45
        while (i < len) {
12677
41
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12678
41
            if (!BLOOM(sepmask, ch))
12679
37
                break;
12680
4
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12681
0
                break;
12682
4
            i++;
12683
4
        }
12684
41
    }
12685
12686
9.03k
    j = len;
12687
9.03k
    if (striptype != LEFTSTRIP) {
12688
8.99k
        j--;
12689
9.03k
        while (j >= i) {
12690
9.03k
            Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12691
9.03k
            if (!BLOOM(sepmask, ch))
12692
5.72k
                break;
12693
3.31k
            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12694
3.27k
                break;
12695
42
            j--;
12696
42
        }
12697
12698
8.99k
        j++;
12699
8.99k
    }
12700
12701
9.03k
    return PyUnicode_Substring(self, i, j);
12702
9.03k
}
12703
12704
PyObject*
12705
_PyUnicode_BinarySlice(PyObject *container, PyObject *start_o, PyObject *stop_o)
12706
502k
{
12707
502k
    assert(PyUnicode_CheckExact(container));
12708
502k
    Py_ssize_t len = PyUnicode_GET_LENGTH(container);
12709
502k
    Py_ssize_t istart, istop;
12710
502k
    if (!_PyEval_UnpackIndices(start_o, stop_o, len, &istart, &istop)) {
12711
0
        return NULL;
12712
0
    }
12713
502k
    return PyUnicode_Substring(container, istart, istop);
12714
502k
}
12715
12716
PyObject*
12717
PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12718
1.55M
{
12719
1.55M
    const unsigned char *data;
12720
1.55M
    int kind;
12721
1.55M
    Py_ssize_t length;
12722
12723
1.55M
    length = PyUnicode_GET_LENGTH(self);
12724
1.55M
    end = Py_MIN(end, length);
12725
12726
1.55M
    if (start == 0 && end == length)
12727
119k
        return unicode_result_unchanged(self);
12728
12729
1.44M
    if (start < 0 || end < 0) {
12730
0
        PyErr_SetString(PyExc_IndexError, "string index out of range");
12731
0
        return NULL;
12732
0
    }
12733
1.44M
    if (start >= length || end < start)
12734
35.5k
        _Py_RETURN_UNICODE_EMPTY();
12735
12736
1.40M
    length = end - start;
12737
1.40M
    if (PyUnicode_IS_ASCII(self)) {
12738
618k
        data = PyUnicode_1BYTE_DATA(self);
12739
618k
        return _PyUnicode_FromASCII((const char*)(data + start), length);
12740
618k
    }
12741
786k
    else {
12742
786k
        kind = PyUnicode_KIND(self);
12743
786k
        data = PyUnicode_1BYTE_DATA(self);
12744
786k
        return PyUnicode_FromKindAndData(kind,
12745
786k
                                         data + kind * start,
12746
786k
                                         length);
12747
786k
    }
12748
1.40M
}
12749
12750
static PyObject *
12751
do_strip(PyObject *self, int striptype)
12752
234k
{
12753
234k
    Py_ssize_t len, i, j;
12754
12755
234k
    len = PyUnicode_GET_LENGTH(self);
12756
12757
234k
    if (PyUnicode_IS_ASCII(self)) {
12758
234k
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12759
12760
234k
        i = 0;
12761
234k
        if (striptype != RIGHTSTRIP) {
12762
1.91M
            while (i < len) {
12763
1.91M
                Py_UCS1 ch = data[i];
12764
1.91M
                if (!_Py_ascii_whitespace[ch])
12765
215k
                    break;
12766
1.69M
                i++;
12767
1.69M
            }
12768
215k
        }
12769
12770
234k
        j = len;
12771
234k
        if (striptype != LEFTSTRIP) {
12772
234k
            j--;
12773
449k
            while (j >= i) {
12774
449k
                Py_UCS1 ch = data[j];
12775
449k
                if (!_Py_ascii_whitespace[ch])
12776
234k
                    break;
12777
215k
                j--;
12778
215k
            }
12779
234k
            j++;
12780
234k
        }
12781
234k
    }
12782
0
    else {
12783
0
        int kind = PyUnicode_KIND(self);
12784
0
        const void *data = PyUnicode_DATA(self);
12785
12786
0
        i = 0;
12787
0
        if (striptype != RIGHTSTRIP) {
12788
0
            while (i < len) {
12789
0
                Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12790
0
                if (!Py_UNICODE_ISSPACE(ch))
12791
0
                    break;
12792
0
                i++;
12793
0
            }
12794
0
        }
12795
12796
0
        j = len;
12797
0
        if (striptype != LEFTSTRIP) {
12798
0
            j--;
12799
0
            while (j >= i) {
12800
0
                Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12801
0
                if (!Py_UNICODE_ISSPACE(ch))
12802
0
                    break;
12803
0
                j--;
12804
0
            }
12805
0
            j++;
12806
0
        }
12807
0
    }
12808
12809
234k
    return PyUnicode_Substring(self, i, j);
12810
234k
}
12811
12812
12813
static PyObject *
12814
do_argstrip(PyObject *self, int striptype, PyObject *sep)
12815
243k
{
12816
243k
    if (sep != Py_None) {
12817
9.03k
        if (PyUnicode_Check(sep))
12818
9.03k
            return _PyUnicode_XStrip(self, striptype, sep);
12819
0
        else {
12820
0
            PyErr_Format(PyExc_TypeError,
12821
0
                         "%s arg must be None or str",
12822
0
                         STRIPNAME(striptype));
12823
0
            return NULL;
12824
0
        }
12825
9.03k
    }
12826
12827
234k
    return do_strip(self, striptype);
12828
243k
}
12829
12830
12831
/*[clinic input]
12832
@permit_long_summary
12833
str.strip as unicode_strip
12834
12835
    chars: object = None
12836
    /
12837
12838
Return a copy of the string with leading and trailing whitespace removed.
12839
12840
If chars is given and not None, remove characters in chars instead.
12841
[clinic start generated code]*/
12842
12843
static PyObject *
12844
unicode_strip_impl(PyObject *self, PyObject *chars)
12845
/*[clinic end generated code: output=ca19018454345d57 input=8bc6353450345fbd]*/
12846
215k
{
12847
215k
    return do_argstrip(self, BOTHSTRIP, chars);
12848
215k
}
12849
12850
12851
/*[clinic input]
12852
str.lstrip as unicode_lstrip
12853
12854
    chars: object = None
12855
    /
12856
12857
Return a copy of the string with leading whitespace removed.
12858
12859
If chars is given and not None, remove characters in chars instead.
12860
[clinic start generated code]*/
12861
12862
static PyObject *
12863
unicode_lstrip_impl(PyObject *self, PyObject *chars)
12864
/*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
12865
41
{
12866
41
    return do_argstrip(self, LEFTSTRIP, chars);
12867
41
}
12868
12869
12870
/*[clinic input]
12871
str.rstrip as unicode_rstrip
12872
12873
    chars: object = None
12874
    /
12875
12876
Return a copy of the string with trailing whitespace removed.
12877
12878
If chars is given and not None, remove characters in chars instead.
12879
[clinic start generated code]*/
12880
12881
static PyObject *
12882
unicode_rstrip_impl(PyObject *self, PyObject *chars)
12883
/*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
12884
28.5k
{
12885
28.5k
    return do_argstrip(self, RIGHTSTRIP, chars);
12886
28.5k
}
12887
12888
12889
PyObject *
12890
_PyUnicode_Repeat(PyObject *str, Py_ssize_t len)
12891
12.6k
{
12892
12.6k
    PyObject *u;
12893
12.6k
    Py_ssize_t nchars, n;
12894
12895
12.6k
    if (len < 1)
12896
251
        _Py_RETURN_UNICODE_EMPTY();
12897
12898
    /* no repeat, return original string */
12899
12.4k
    if (len == 1)
12900
2.17k
        return unicode_result_unchanged(str);
12901
12902
10.2k
    if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
12903
0
        PyErr_SetString(PyExc_OverflowError,
12904
0
                        "repeated string is too long");
12905
0
        return NULL;
12906
0
    }
12907
10.2k
    nchars = len * PyUnicode_GET_LENGTH(str);
12908
12909
10.2k
    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
12910
10.2k
    if (!u)
12911
0
        return NULL;
12912
10.2k
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
12913
12914
10.2k
    if (PyUnicode_GET_LENGTH(str) == 1) {
12915
2.64k
        int kind = PyUnicode_KIND(str);
12916
2.64k
        Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12917
2.64k
        if (kind == PyUnicode_1BYTE_KIND) {
12918
2.36k
            void *to = PyUnicode_DATA(u);
12919
2.36k
            memset(to, (unsigned char)fill_char, len);
12920
2.36k
        }
12921
280
        else if (kind == PyUnicode_2BYTE_KIND) {
12922
236
            Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
12923
801
            for (n = 0; n < len; ++n)
12924
565
                ucs2[n] = fill_char;
12925
236
        } else {
12926
44
            Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12927
44
            assert(kind == PyUnicode_4BYTE_KIND);
12928
8.99k
            for (n = 0; n < len; ++n)
12929
8.94k
                ucs4[n] = fill_char;
12930
44
        }
12931
2.64k
    }
12932
7.62k
    else {
12933
7.62k
        Py_ssize_t char_size = PyUnicode_KIND(str);
12934
7.62k
        char *to = (char *) PyUnicode_DATA(u);
12935
7.62k
        _PyBytes_RepeatBuffer(to, nchars * char_size, PyUnicode_DATA(str),
12936
7.62k
            PyUnicode_GET_LENGTH(str) * char_size);
12937
7.62k
    }
12938
12939
10.2k
    assert(_PyUnicode_CheckConsistency(u, 1));
12940
10.2k
    return u;
12941
10.2k
}
12942
12943
PyObject *
12944
PyUnicode_Replace(PyObject *str,
12945
                  PyObject *substr,
12946
                  PyObject *replstr,
12947
                  Py_ssize_t maxcount)
12948
45.9k
{
12949
45.9k
    if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12950
45.9k
            ensure_unicode(replstr) < 0)
12951
0
        return NULL;
12952
45.9k
    return replace(str, substr, replstr, maxcount);
12953
45.9k
}
12954
12955
/*[clinic input]
12956
str.replace as unicode_replace
12957
12958
    old: unicode
12959
    new: unicode
12960
    /
12961
    count: Py_ssize_t = -1
12962
        Maximum number of occurrences to replace.
12963
        -1 (the default value) means replace all occurrences.
12964
12965
Return a copy with all occurrences of substring old replaced by new.
12966
12967
If count is given, only the first count occurrences are replaced.
12968
If count is not specified or -1, then all occurrences are replaced.
12969
[clinic start generated code]*/
12970
12971
static PyObject *
12972
unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12973
                     Py_ssize_t count)
12974
/*[clinic end generated code: output=b63f1a8b5eebf448 input=d15a6886b05e2edc]*/
12975
20.4k
{
12976
20.4k
    return replace(self, old, new, count);
12977
20.4k
}
12978
12979
/*[clinic input]
12980
str.removeprefix as unicode_removeprefix
12981
12982
    prefix: unicode
12983
    /
12984
12985
Return a str with the given prefix string removed if present.
12986
12987
If the string starts with the prefix string, return
12988
string[len(prefix):].  Otherwise, return a copy of the original
12989
string.
12990
[clinic start generated code]*/
12991
12992
static PyObject *
12993
unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
12994
/*[clinic end generated code: output=f1e5945e9763bcb9 input=90d162724944bfa7]*/
12995
0
{
12996
0
    int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
12997
0
    if (match == -1) {
12998
0
        return NULL;
12999
0
    }
13000
0
    if (match) {
13001
0
        return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
13002
0
                                   PyUnicode_GET_LENGTH(self));
13003
0
    }
13004
0
    return unicode_result_unchanged(self);
13005
0
}
13006
13007
/*[clinic input]
13008
str.removesuffix as unicode_removesuffix
13009
13010
    suffix: unicode
13011
    /
13012
13013
Return a str with the given suffix string removed if present.
13014
13015
If the string ends with the suffix string and that suffix is not
13016
empty, return string[:-len(suffix)].  Otherwise, return a copy of
13017
the original string.
13018
[clinic start generated code]*/
13019
13020
static PyObject *
13021
unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
13022
/*[clinic end generated code: output=d36629e227636822 input=6efc96152d4bfcd5]*/
13023
0
{
13024
0
    int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
13025
0
    if (match == -1) {
13026
0
        return NULL;
13027
0
    }
13028
0
    if (match) {
13029
0
        return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
13030
0
                                            - PyUnicode_GET_LENGTH(suffix));
13031
0
    }
13032
0
    return unicode_result_unchanged(self);
13033
0
}
13034
13035
static PyObject *
13036
unicode_repr(PyObject *unicode)
13037
13.1k
{
13038
13.1k
    Py_ssize_t isize = PyUnicode_GET_LENGTH(unicode);
13039
13.1k
    const void *idata = PyUnicode_DATA(unicode);
13040
13041
    /* Compute length of output, quote characters, and
13042
       maximum character */
13043
13.1k
    Py_ssize_t osize = 0;
13044
13.1k
    Py_UCS4 maxch = 127;
13045
13.1k
    Py_ssize_t squote = 0;
13046
13.1k
    Py_ssize_t dquote = 0;
13047
13.1k
    int ikind = PyUnicode_KIND(unicode);
13048
23.3M
    for (Py_ssize_t i = 0; i < isize; i++) {
13049
23.3M
        Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
13050
23.3M
        Py_ssize_t incr = 1;
13051
23.3M
        switch (ch) {
13052
87.3k
        case '\'': squote++; break;
13053
115k
        case '"':  dquote++; break;
13054
56.2k
        case '\\': case '\t': case '\r': case '\n':
13055
56.2k
            incr = 2;
13056
56.2k
            break;
13057
23.1M
        default:
13058
            /* Fast-path ASCII */
13059
23.1M
            if (ch < ' ' || ch == 0x7f)
13060
1.31M
                incr = 4; /* \xHH */
13061
21.8M
            else if (ch < 0x7f)
13062
20.9M
                ;
13063
844k
            else if (Py_UNICODE_ISPRINTABLE(ch))
13064
220k
                maxch = (ch > maxch) ? ch : maxch;
13065
623k
            else if (ch < 0x100)
13066
611k
                incr = 4; /* \xHH */
13067
11.8k
            else if (ch < 0x10000)
13068
9.03k
                incr = 6; /* \uHHHH */
13069
2.80k
            else
13070
2.80k
                incr = 10; /* \uHHHHHHHH */
13071
23.3M
        }
13072
23.3M
        if (osize > PY_SSIZE_T_MAX - incr) {
13073
0
            PyErr_SetString(PyExc_OverflowError,
13074
0
                            "string is too long to generate repr");
13075
0
            return NULL;
13076
0
        }
13077
23.3M
        osize += incr;
13078
23.3M
    }
13079
13080
13.1k
    Py_UCS4 quote = '\'';
13081
13.1k
    int changed = (osize != isize);
13082
13.1k
    if (squote) {
13083
1.56k
        changed = 1;
13084
1.56k
        if (dquote)
13085
            /* Both squote and dquote present. Use squote,
13086
               and escape them */
13087
919
            osize += squote;
13088
642
        else
13089
642
            quote = '"';
13090
1.56k
    }
13091
13.1k
    osize += 2;   /* quotes */
13092
13093
13.1k
    PyObject *repr = PyUnicode_New(osize, maxch);
13094
13.1k
    if (repr == NULL)
13095
0
        return NULL;
13096
13.1k
    int okind = PyUnicode_KIND(repr);
13097
13.1k
    void *odata = PyUnicode_DATA(repr);
13098
13099
13.1k
    if (!changed) {
13100
7.75k
        PyUnicode_WRITE(okind, odata, 0, quote);
13101
13102
7.75k
        _PyUnicode_FastCopyCharacters(repr, 1,
13103
7.75k
                                      unicode, 0,
13104
7.75k
                                      isize);
13105
13106
7.75k
        PyUnicode_WRITE(okind, odata, osize-1, quote);
13107
7.75k
    }
13108
5.41k
    else {
13109
5.41k
        switch (okind) {
13110
3.44k
        case PyUnicode_1BYTE_KIND:
13111
3.44k
            ucs1lib_repr(unicode, quote, odata);
13112
3.44k
            break;
13113
979
        case PyUnicode_2BYTE_KIND:
13114
979
            ucs2lib_repr(unicode, quote, odata);
13115
979
            break;
13116
982
        default:
13117
982
            assert(okind == PyUnicode_4BYTE_KIND);
13118
982
            ucs4lib_repr(unicode, quote, odata);
13119
5.41k
        }
13120
5.41k
    }
13121
13122
13.1k
    assert(_PyUnicode_CheckConsistency(repr, 1));
13123
13.1k
    return repr;
13124
13.1k
}
13125
13126
/*[clinic input]
13127
@permit_long_summary
13128
str.rfind as unicode_rfind = str.count
13129
13130
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13131
13132
Optional arguments start and end are interpreted as in slice
13133
notation.  Return -1 on failure.
13134
[clinic start generated code]*/
13135
13136
static Py_ssize_t
13137
unicode_rfind_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13138
                   Py_ssize_t end)
13139
/*[clinic end generated code: output=880b29f01dd014c8 input=2e67789533baf2f5]*/
13140
6.78k
{
13141
6.78k
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13142
6.78k
    if (result < 0) {
13143
5.77k
        return -1;
13144
5.77k
    }
13145
1.01k
    return result;
13146
6.78k
}
13147
13148
/*[clinic input]
13149
@permit_long_summary
13150
str.rindex as unicode_rindex = str.count
13151
13152
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
13153
13154
Optional arguments start and end are interpreted as in slice
13155
notation.  Raises ValueError when the substring is not found.
13156
[clinic start generated code]*/
13157
13158
static Py_ssize_t
13159
unicode_rindex_impl(PyObject *str, PyObject *substr, Py_ssize_t start,
13160
                    Py_ssize_t end)
13161
/*[clinic end generated code: output=5f3aef124c867fe1 input=e29d446c8234c9d9]*/
13162
0
{
13163
0
    Py_ssize_t result = any_find_slice(str, substr, start, end, -1);
13164
0
    if (result == -1) {
13165
0
        PyErr_SetString(PyExc_ValueError, "substring not found");
13166
0
    }
13167
0
    else if (result < 0) {
13168
0
        return -1;
13169
0
    }
13170
0
    return result;
13171
0
}
13172
13173
/*[clinic input]
13174
str.rjust as unicode_rjust
13175
13176
    width: Py_ssize_t
13177
    fillchar: Py_UCS4 = ' '
13178
    /
13179
13180
Return a right-justified string of length width.
13181
13182
Padding is done using the specified fill character (default is
13183
a space).
13184
[clinic start generated code]*/
13185
13186
static PyObject *
13187
unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
13188
/*[clinic end generated code: output=804a1a57fbe8d5cf input=1256a8d659589907]*/
13189
0
{
13190
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13191
0
        return unicode_result_unchanged(self);
13192
13193
0
    return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
13194
0
}
13195
13196
PyObject *
13197
PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13198
0
{
13199
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13200
0
        return NULL;
13201
13202
0
    return split(s, sep, maxsplit);
13203
0
}
13204
13205
/*[clinic input]
13206
@permit_long_summary
13207
str.split as unicode_split
13208
13209
    sep: object = None
13210
        The separator used to split the string.
13211
13212
        When set to None (the default value), will split on any
13213
        whitespace character (including \n \r \t \f and spaces) and
13214
        will discard empty strings from the result.
13215
    maxsplit: Py_ssize_t = -1
13216
        Maximum number of splits.
13217
        -1 (the default value) means no limit.
13218
13219
Return a list of the substrings in the string, using sep as the separator string.
13220
13221
Splitting starts at the front of the string and works to the end.
13222
13223
Note, str.split() is mainly useful for data that has been
13224
intentionally delimited.  With natural text that includes
13225
punctuation, consider using the regular expression module.
13226
13227
[clinic start generated code]*/
13228
13229
static PyObject *
13230
unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13231
/*[clinic end generated code: output=3a65b1db356948dc input=288cfd6bc8828f5a]*/
13232
2.07k
{
13233
2.07k
    if (sep == Py_None)
13234
7
        return split(self, NULL, maxsplit);
13235
2.06k
    if (PyUnicode_Check(sep))
13236
2.06k
        return split(self, sep, maxsplit);
13237
13238
0
    PyErr_Format(PyExc_TypeError,
13239
0
                 "must be str or None, not %.100s",
13240
0
                 Py_TYPE(sep)->tp_name);
13241
0
    return NULL;
13242
2.06k
}
13243
13244
PyObject *
13245
PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
13246
0
{
13247
0
    PyObject* out;
13248
0
    int kind1, kind2;
13249
0
    const void *buf1, *buf2;
13250
0
    Py_ssize_t len1, len2;
13251
13252
0
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13253
0
        return NULL;
13254
13255
0
    kind1 = PyUnicode_KIND(str_obj);
13256
0
    kind2 = PyUnicode_KIND(sep_obj);
13257
0
    len1 = PyUnicode_GET_LENGTH(str_obj);
13258
0
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13259
0
    if (kind1 < kind2 || len1 < len2) {
13260
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13261
0
        return PyTuple_Pack(3, str_obj, empty, empty);
13262
0
    }
13263
0
    buf1 = PyUnicode_DATA(str_obj);
13264
0
    buf2 = PyUnicode_DATA(sep_obj);
13265
0
    if (kind2 != kind1) {
13266
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13267
0
        if (!buf2)
13268
0
            return NULL;
13269
0
    }
13270
13271
0
    switch (kind1) {
13272
0
    case PyUnicode_1BYTE_KIND:
13273
0
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13274
0
            out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13275
0
        else
13276
0
            out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13277
0
        break;
13278
0
    case PyUnicode_2BYTE_KIND:
13279
0
        out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13280
0
        break;
13281
0
    case PyUnicode_4BYTE_KIND:
13282
0
        out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13283
0
        break;
13284
0
    default:
13285
0
        Py_UNREACHABLE();
13286
0
    }
13287
13288
0
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13289
0
    if (kind2 != kind1)
13290
0
        PyMem_Free((void *)buf2);
13291
13292
0
    return out;
13293
0
}
13294
13295
13296
PyObject *
13297
PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
13298
2.98k
{
13299
2.98k
    PyObject* out;
13300
2.98k
    int kind1, kind2;
13301
2.98k
    const void *buf1, *buf2;
13302
2.98k
    Py_ssize_t len1, len2;
13303
13304
2.98k
    if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
13305
0
        return NULL;
13306
13307
2.98k
    kind1 = PyUnicode_KIND(str_obj);
13308
2.98k
    kind2 = PyUnicode_KIND(sep_obj);
13309
2.98k
    len1 = PyUnicode_GET_LENGTH(str_obj);
13310
2.98k
    len2 = PyUnicode_GET_LENGTH(sep_obj);
13311
2.98k
    if (kind1 < kind2 || len1 < len2) {
13312
0
        PyObject *empty = _PyUnicode_GetEmpty();  // Borrowed reference
13313
0
        return PyTuple_Pack(3, empty, empty, str_obj);
13314
0
    }
13315
2.98k
    buf1 = PyUnicode_DATA(str_obj);
13316
2.98k
    buf2 = PyUnicode_DATA(sep_obj);
13317
2.98k
    if (kind2 != kind1) {
13318
0
        buf2 = unicode_askind(kind2, buf2, len2, kind1);
13319
0
        if (!buf2)
13320
0
            return NULL;
13321
0
    }
13322
13323
2.98k
    switch (kind1) {
13324
2.98k
    case PyUnicode_1BYTE_KIND:
13325
2.98k
        if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13326
2.98k
            out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13327
0
        else
13328
0
            out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13329
2.98k
        break;
13330
0
    case PyUnicode_2BYTE_KIND:
13331
0
        out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13332
0
        break;
13333
0
    case PyUnicode_4BYTE_KIND:
13334
0
        out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13335
0
        break;
13336
0
    default:
13337
0
        Py_UNREACHABLE();
13338
2.98k
    }
13339
13340
2.98k
    assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
13341
2.98k
    if (kind2 != kind1)
13342
0
        PyMem_Free((void *)buf2);
13343
13344
2.98k
    return out;
13345
2.98k
}
13346
13347
/*[clinic input]
13348
str.partition as unicode_partition
13349
13350
    sep: object
13351
    /
13352
13353
Partition the string into three parts using the given separator.
13354
13355
This will search for the separator in the string.  If the separator
13356
is found, returns a 3-tuple containing the part before the
13357
separator, the separator itself, and the part after it.
13358
13359
If the separator is not found, returns a 3-tuple containing
13360
the original string and two empty strings.
13361
[clinic start generated code]*/
13362
13363
static PyObject *
13364
unicode_partition(PyObject *self, PyObject *sep)
13365
/*[clinic end generated code: output=e4ced7bd253ca3c4 input=e45faa8c26270cb1]*/
13366
0
{
13367
0
    return PyUnicode_Partition(self, sep);
13368
0
}
13369
13370
/*[clinic input]
13371
str.rpartition as unicode_rpartition = str.partition
13372
13373
Partition the string into three parts using the given separator.
13374
13375
This will search for the separator in the string, starting at the
13376
end.  If the separator is found, returns a 3-tuple containing the
13377
part before the separator, the separator itself, and the part after
13378
it.
13379
13380
If the separator is not found, returns a 3-tuple containing two
13381
empty strings and the original string.
13382
[clinic start generated code]*/
13383
13384
static PyObject *
13385
unicode_rpartition(PyObject *self, PyObject *sep)
13386
/*[clinic end generated code: output=1aa13cf1156572aa input=53a7f8cb19975b7c]*/
13387
2.98k
{
13388
2.98k
    return PyUnicode_RPartition(self, sep);
13389
2.98k
}
13390
13391
PyObject *
13392
PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
13393
0
{
13394
0
    if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
13395
0
        return NULL;
13396
13397
0
    return rsplit(s, sep, maxsplit);
13398
0
}
13399
13400
/*[clinic input]
13401
@permit_long_summary
13402
str.rsplit as unicode_rsplit = str.split
13403
13404
Return a list of the substrings in the string, using sep as the separator string.
13405
13406
Splitting starts at the end of the string and works to the front.
13407
[clinic start generated code]*/
13408
13409
static PyObject *
13410
unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13411
/*[clinic end generated code: output=c2b815c63bcabffc input=0f762e30d267fa83]*/
13412
0
{
13413
0
    if (sep == Py_None)
13414
0
        return rsplit(self, NULL, maxsplit);
13415
0
    if (PyUnicode_Check(sep))
13416
0
        return rsplit(self, sep, maxsplit);
13417
13418
0
    PyErr_Format(PyExc_TypeError,
13419
0
                 "must be str or None, not %.100s",
13420
0
                 Py_TYPE(sep)->tp_name);
13421
0
    return NULL;
13422
0
}
13423
13424
/*[clinic input]
13425
@permit_long_summary
13426
str.splitlines as unicode_splitlines
13427
13428
    keepends: bool = False
13429
13430
Return a list of the lines in the string, breaking at line boundaries.
13431
13432
Line breaks are not included in the resulting list unless keepends
13433
is given and true.
13434
[clinic start generated code]*/
13435
13436
static PyObject *
13437
unicode_splitlines_impl(PyObject *self, int keepends)
13438
/*[clinic end generated code: output=f664dcdad153ec40 input=b45ea0f87645a06d]*/
13439
0
{
13440
0
    return PyUnicode_Splitlines(self, keepends);
13441
0
}
13442
13443
static
13444
PyObject *unicode_str(PyObject *self)
13445
0
{
13446
0
    return unicode_result_unchanged(self);
13447
0
}
13448
13449
/*[clinic input]
13450
@permit_long_summary
13451
str.swapcase as unicode_swapcase
13452
13453
Convert uppercase characters to lowercase and lowercase characters to uppercase.
13454
[clinic start generated code]*/
13455
13456
static PyObject *
13457
unicode_swapcase_impl(PyObject *self)
13458
/*[clinic end generated code: output=5d28966bf6d7b2af input=85bc39a9b4e8ee91]*/
13459
0
{
13460
0
    return case_operation(self, do_swapcase);
13461
0
}
13462
13463
static int
13464
unicode_maketrans_from_dict(PyObject *x, PyObject *newdict)
13465
0
{
13466
0
    PyObject *key, *value;
13467
0
    Py_ssize_t i = 0;
13468
0
    int res;
13469
0
    while (PyDict_Next(x, &i, &key, &value)) {
13470
0
        if (PyUnicode_Check(key)) {
13471
0
            PyObject *newkey;
13472
0
            int kind;
13473
0
            const void *data;
13474
0
            if (PyUnicode_GET_LENGTH(key) != 1) {
13475
0
                PyErr_SetString(PyExc_ValueError, "string keys in translate"
13476
0
                                "table must be of length 1");
13477
0
                return -1;
13478
0
            }
13479
0
            kind = PyUnicode_KIND(key);
13480
0
            data = PyUnicode_DATA(key);
13481
0
            newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
13482
0
            if (!newkey)
13483
0
                return -1;
13484
0
            res = PyDict_SetItem(newdict, newkey, value);
13485
0
            Py_DECREF(newkey);
13486
0
            if (res < 0)
13487
0
                return -1;
13488
0
        }
13489
0
        else if (PyLong_Check(key)) {
13490
0
            if (PyDict_SetItem(newdict, key, value) < 0)
13491
0
                return -1;
13492
0
        }
13493
0
        else {
13494
0
            PyErr_SetString(PyExc_TypeError, "keys in translate table must"
13495
0
                            "be strings or integers");
13496
0
            return -1;
13497
0
        }
13498
0
    }
13499
0
    return 0;
13500
0
}
13501
13502
/*[clinic input]
13503
13504
@staticmethod
13505
str.maketrans as unicode_maketrans
13506
13507
  x: object
13508
13509
  y: unicode=NULL
13510
13511
  z: unicode=NULL
13512
13513
  /
13514
13515
Return a translation table usable for str.translate().
13516
13517
If there is only one argument, it must be a dictionary mapping
13518
Unicode ordinals (integers) or characters to Unicode ordinals,
13519
strings or None.  Character keys will be then converted to ordinals.
13520
If there are two arguments, they must be strings of equal length,
13521
and in the resulting dictionary, each character in x will be mapped
13522
to the character at the same position in y.  If there is a third
13523
argument, it must be a string, whose characters will be mapped to
13524
None in the result.
13525
[clinic start generated code]*/
13526
13527
static PyObject *
13528
unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
13529
/*[clinic end generated code: output=a925c89452bd5881 input=66bc00a1b4258a6e]*/
13530
0
{
13531
0
    PyObject *new = NULL, *key, *value;
13532
0
    Py_ssize_t i = 0;
13533
0
    int res;
13534
13535
0
    new = PyDict_New();
13536
0
    if (!new)
13537
0
        return NULL;
13538
0
    if (y != NULL) {
13539
0
        int x_kind, y_kind, z_kind;
13540
0
        const void *x_data, *y_data, *z_data;
13541
13542
        /* x must be a string too, of equal length */
13543
0
        if (!PyUnicode_Check(x)) {
13544
0
            PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13545
0
                            "be a string if there is a second argument");
13546
0
            goto err;
13547
0
        }
13548
0
        if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
13549
0
            PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13550
0
                            "arguments must have equal length");
13551
0
            goto err;
13552
0
        }
13553
        /* create entries for translating chars in x to those in y */
13554
0
        x_kind = PyUnicode_KIND(x);
13555
0
        y_kind = PyUnicode_KIND(y);
13556
0
        x_data = PyUnicode_DATA(x);
13557
0
        y_data = PyUnicode_DATA(y);
13558
0
        for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13559
0
            key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
13560
0
            if (!key)
13561
0
                goto err;
13562
0
            value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
13563
0
            if (!value) {
13564
0
                Py_DECREF(key);
13565
0
                goto err;
13566
0
            }
13567
0
            res = PyDict_SetItem(new, key, value);
13568
0
            Py_DECREF(key);
13569
0
            Py_DECREF(value);
13570
0
            if (res < 0)
13571
0
                goto err;
13572
0
        }
13573
        /* create entries for deleting chars in z */
13574
0
        if (z != NULL) {
13575
0
            z_kind = PyUnicode_KIND(z);
13576
0
            z_data = PyUnicode_DATA(z);
13577
0
            for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
13578
0
                key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
13579
0
                if (!key)
13580
0
                    goto err;
13581
0
                res = PyDict_SetItem(new, key, Py_None);
13582
0
                Py_DECREF(key);
13583
0
                if (res < 0)
13584
0
                    goto err;
13585
0
            }
13586
0
        }
13587
0
    } else {
13588
        /* x must be a dict */
13589
0
        if (!PyAnyDict_CheckExact(x)) {
13590
0
            PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13591
0
                            "to maketrans it must be a dict");
13592
0
            goto err;
13593
0
        }
13594
        /* copy entries into the new dict, converting string keys to int keys */
13595
0
        int errcode;
13596
0
        Py_BEGIN_CRITICAL_SECTION(x);
13597
0
        errcode = unicode_maketrans_from_dict(x, new);
13598
0
        Py_END_CRITICAL_SECTION();
13599
0
        if (errcode < 0)
13600
0
            goto err;
13601
0
    }
13602
0
    return new;
13603
0
  err:
13604
0
    Py_DECREF(new);
13605
0
    return NULL;
13606
0
}
13607
13608
/*[clinic input]
13609
@permit_long_summary
13610
str.translate as unicode_translate
13611
13612
    table: object
13613
        Translation table, which must be a mapping of Unicode ordinals
13614
        to Unicode ordinals, strings, or None.
13615
    /
13616
13617
Replace each character in the string using the given translation table.
13618
13619
The table must implement lookup/indexing via __getitem__, for
13620
instance a dictionary or list.  If this operation raises
13621
LookupError, the character is left untouched.  Characters mapped to
13622
None are deleted.
13623
[clinic start generated code]*/
13624
13625
static PyObject *
13626
unicode_translate(PyObject *self, PyObject *table)
13627
/*[clinic end generated code: output=3cb448ff2fd96bf3 input=48cf0efe06bc1b75]*/
13628
144
{
13629
144
    return _PyUnicode_TranslateCharmap(self, table, "ignore");
13630
144
}
13631
13632
/*[clinic input]
13633
str.upper as unicode_upper
13634
13635
Return a copy of the string converted to uppercase.
13636
[clinic start generated code]*/
13637
13638
static PyObject *
13639
unicode_upper_impl(PyObject *self)
13640
/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
13641
153
{
13642
153
    if (PyUnicode_IS_ASCII(self))
13643
153
        return ascii_upper_or_lower(self, 0);
13644
0
    return case_operation(self, do_upper);
13645
153
}
13646
13647
/*[clinic input]
13648
@permit_long_summary
13649
str.zfill as unicode_zfill
13650
13651
    width: Py_ssize_t
13652
    /
13653
13654
Pad a numeric string with zeros on the left, to fill a field of the given width.
13655
13656
The string is never truncated.
13657
[clinic start generated code]*/
13658
13659
static PyObject *
13660
unicode_zfill_impl(PyObject *self, Py_ssize_t width)
13661
/*[clinic end generated code: output=e13fb6bdf8e3b9df input=25a4ee0ea3e58ce0]*/
13662
0
{
13663
0
    Py_ssize_t fill;
13664
0
    PyObject *u;
13665
0
    int kind;
13666
0
    const void *data;
13667
0
    Py_UCS4 chr;
13668
13669
0
    if (PyUnicode_GET_LENGTH(self) >= width)
13670
0
        return unicode_result_unchanged(self);
13671
13672
0
    fill = width - PyUnicode_GET_LENGTH(self);
13673
13674
0
    u = pad(self, fill, 0, '0');
13675
13676
0
    if (u == NULL)
13677
0
        return NULL;
13678
13679
0
    kind = PyUnicode_KIND(u);
13680
0
    data = PyUnicode_DATA(u);
13681
0
    chr = PyUnicode_READ(kind, data, fill);
13682
13683
0
    if (chr == '+' || chr == '-') {
13684
        /* move sign to beginning of string */
13685
0
        PyUnicode_WRITE(kind, data, 0, chr);
13686
0
        PyUnicode_WRITE(kind, data, fill, '0');
13687
0
    }
13688
13689
0
    assert(_PyUnicode_CheckConsistency(u, 1));
13690
0
    return u;
13691
0
}
13692
13693
/*[clinic input]
13694
@permit_long_summary
13695
@text_signature "($self, prefix[, start[, end]], /)"
13696
str.startswith as unicode_startswith
13697
13698
    prefix as subobj: object
13699
        A string or a tuple of strings to try.
13700
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13701
        Optional start position. Default: start of the string.
13702
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13703
        Optional stop position. Default: end of the string.
13704
    /
13705
13706
Return True if the string starts with the specified prefix, False otherwise.
13707
[clinic start generated code]*/
13708
13709
static PyObject *
13710
unicode_startswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13711
                        Py_ssize_t end)
13712
/*[clinic end generated code: output=4bd7cfd0803051d4 input=766bdbd33df251dc]*/
13713
245k
{
13714
245k
    if (PyTuple_Check(subobj)) {
13715
93
        Py_ssize_t i;
13716
651
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13717
558
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13718
558
            if (!PyUnicode_Check(substring)) {
13719
0
                PyErr_Format(PyExc_TypeError,
13720
0
                             "tuple for startswith must only contain str, "
13721
0
                             "not %.100s",
13722
0
                             Py_TYPE(substring)->tp_name);
13723
0
                return NULL;
13724
0
            }
13725
558
            int result = tailmatch(self, substring, start, end, -1);
13726
558
            if (result < 0) {
13727
0
                return NULL;
13728
0
            }
13729
558
            if (result) {
13730
0
                Py_RETURN_TRUE;
13731
0
            }
13732
558
        }
13733
        /* nothing matched */
13734
93
        Py_RETURN_FALSE;
13735
93
    }
13736
245k
    if (!PyUnicode_Check(subobj)) {
13737
0
        PyErr_Format(PyExc_TypeError,
13738
0
                     "startswith first arg must be str or "
13739
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13740
0
        return NULL;
13741
0
    }
13742
245k
    int result = tailmatch(self, subobj, start, end, -1);
13743
245k
    if (result < 0) {
13744
0
        return NULL;
13745
0
    }
13746
245k
    return PyBool_FromLong(result);
13747
245k
}
13748
13749
13750
/*[clinic input]
13751
@permit_long_summary
13752
@text_signature "($self, suffix[, start[, end]], /)"
13753
str.endswith as unicode_endswith
13754
13755
    suffix as subobj: object
13756
        A string or a tuple of strings to try.
13757
    start: slice_index(accept={int, NoneType}, c_default='0') = None
13758
        Optional start position. Default: start of the string.
13759
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
13760
        Optional stop position. Default: end of the string.
13761
    /
13762
13763
Return True if the string ends with the specified suffix, False otherwise.
13764
[clinic start generated code]*/
13765
13766
static PyObject *
13767
unicode_endswith_impl(PyObject *self, PyObject *subobj, Py_ssize_t start,
13768
                      Py_ssize_t end)
13769
/*[clinic end generated code: output=cce6f8ceb0102ca9 input=b66bf6d5547ba1aa]*/
13770
113k
{
13771
113k
    if (PyTuple_Check(subobj)) {
13772
0
        Py_ssize_t i;
13773
0
        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
13774
0
            PyObject *substring = PyTuple_GET_ITEM(subobj, i);
13775
0
            if (!PyUnicode_Check(substring)) {
13776
0
                PyErr_Format(PyExc_TypeError,
13777
0
                             "tuple for endswith must only contain str, "
13778
0
                             "not %.100s",
13779
0
                             Py_TYPE(substring)->tp_name);
13780
0
                return NULL;
13781
0
            }
13782
0
            int result = tailmatch(self, substring, start, end, +1);
13783
0
            if (result < 0) {
13784
0
                return NULL;
13785
0
            }
13786
0
            if (result) {
13787
0
                Py_RETURN_TRUE;
13788
0
            }
13789
0
        }
13790
0
        Py_RETURN_FALSE;
13791
0
    }
13792
113k
    if (!PyUnicode_Check(subobj)) {
13793
0
        PyErr_Format(PyExc_TypeError,
13794
0
                     "endswith first arg must be str or "
13795
0
                     "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
13796
0
        return NULL;
13797
0
    }
13798
113k
    int result = tailmatch(self, subobj, start, end, +1);
13799
113k
    if (result < 0) {
13800
0
        return NULL;
13801
0
    }
13802
113k
    return PyBool_FromLong(result);
13803
113k
}
13804
13805
13806
#include "stringlib/unicode_format.h"
13807
13808
PyDoc_STRVAR(format__doc__,
13809
             "format($self, /, *args, **kwargs)\n\
13810
--\n\
13811
\n\
13812
Return a formatted version of the string, using substitutions from args and kwargs.\n\
13813
The substitutions are identified by braces ('{' and '}').");
13814
13815
PyDoc_STRVAR(format_map__doc__,
13816
             "format_map($self, mapping, /)\n\
13817
--\n\
13818
\n\
13819
Return a formatted version of the string, using substitutions from mapping.\n\
13820
The substitutions are identified by braces ('{' and '}').");
13821
13822
/*[clinic input]
13823
@permit_long_summary
13824
str.__format__ as unicode___format__
13825
13826
    format_spec: unicode
13827
    /
13828
13829
Return a formatted version of the string as described by format_spec.
13830
[clinic start generated code]*/
13831
13832
static PyObject *
13833
unicode___format___impl(PyObject *self, PyObject *format_spec)
13834
/*[clinic end generated code: output=45fceaca6d2ba4c8 input=77a2a19f3f7969f2]*/
13835
0
{
13836
0
    _PyUnicodeWriter writer;
13837
0
    int ret;
13838
13839
0
    _PyUnicodeWriter_Init(&writer);
13840
0
    ret = _PyUnicode_FormatAdvancedWriter(&writer,
13841
0
                                          self, format_spec, 0,
13842
0
                                          PyUnicode_GET_LENGTH(format_spec));
13843
0
    if (ret == -1) {
13844
0
        _PyUnicodeWriter_Dealloc(&writer);
13845
0
        return NULL;
13846
0
    }
13847
0
    return _PyUnicodeWriter_Finish(&writer);
13848
0
}
13849
13850
/*[clinic input]
13851
str.__sizeof__ as unicode_sizeof
13852
13853
Return the size of the string in memory, in bytes.
13854
[clinic start generated code]*/
13855
13856
static PyObject *
13857
unicode_sizeof_impl(PyObject *self)
13858
/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
13859
0
{
13860
0
    Py_ssize_t size;
13861
13862
    /* If it's a compact object, account for base structure +
13863
       character data. */
13864
0
    if (PyUnicode_IS_COMPACT_ASCII(self)) {
13865
0
        size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13866
0
    }
13867
0
    else if (PyUnicode_IS_COMPACT(self)) {
13868
0
        size = sizeof(PyCompactUnicodeObject) +
13869
0
            (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
13870
0
    }
13871
0
    else {
13872
        /* If it is a two-block object, account for base object, and
13873
           for character block if present. */
13874
0
        size = sizeof(PyUnicodeObject);
13875
0
        if (_PyUnicode_DATA_ANY(self))
13876
0
            size += (PyUnicode_GET_LENGTH(self) + 1) *
13877
0
                PyUnicode_KIND(self);
13878
0
    }
13879
0
    if (_PyUnicode_HAS_UTF8_MEMORY(self))
13880
0
        size += PyUnicode_UTF8_LENGTH(self) + 1;
13881
13882
0
    return PyLong_FromSsize_t(size);
13883
0
}
13884
13885
static PyObject *
13886
unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
13887
0
{
13888
0
    PyObject *copy = _PyUnicode_Copy(v);
13889
0
    if (!copy)
13890
0
        return NULL;
13891
0
    return Py_BuildValue("(N)", copy);
13892
0
}
13893
13894
/*
13895
This function searchs the longest common leading whitespace
13896
of all lines in the [src, end).
13897
It returns the length of the common leading whitespace and sets `output` to
13898
point to the beginning of the common leading whitespace if length > 0.
13899
*/
13900
static Py_ssize_t
13901
search_longest_common_leading_whitespace(
13902
    const char *const src,
13903
    const char *const end,
13904
    const char **output)
13905
0
{
13906
    // [_start, _start + _len)
13907
    // describes the current longest common leading whitespace
13908
0
    const char *_start = NULL;
13909
0
    Py_ssize_t _len = 0;
13910
13911
0
    for (const char *iter = src; iter < end; ++iter) {
13912
0
        const char *line_start = iter;
13913
0
        const char *leading_whitespace_end = NULL;
13914
13915
        // scan the whole line
13916
0
        while (iter < end && *iter != '\n') {
13917
0
            if (!leading_whitespace_end && *iter != ' ' && *iter != '\t') {
13918
                /* `iter` points to the first non-whitespace character
13919
                   in this line */
13920
0
                if (iter == line_start) {
13921
                    // some line has no indent, fast exit!
13922
0
                    return 0;
13923
0
                }
13924
0
                leading_whitespace_end = iter;
13925
0
            }
13926
0
            ++iter;
13927
0
        }
13928
13929
        // if this line has all white space, skip it
13930
0
        if (!leading_whitespace_end) {
13931
0
            continue;
13932
0
        }
13933
13934
0
        if (!_start) {
13935
            // update the first leading whitespace
13936
0
            _start = line_start;
13937
0
            _len = leading_whitespace_end - line_start;
13938
0
            assert(_len > 0);
13939
0
        }
13940
0
        else {
13941
            /* We then compare with the current longest leading whitespace.
13942
13943
               [line_start, leading_whitespace_end) is the leading
13944
               whitespace of this line,
13945
13946
               [_start, _start + _len) is the leading whitespace of the
13947
               current longest leading whitespace. */
13948
0
            Py_ssize_t new_len = 0;
13949
0
            const char *_iter = _start, *line_iter = line_start;
13950
13951
0
            while (_iter < _start + _len && line_iter < leading_whitespace_end
13952
0
                   && *_iter == *line_iter)
13953
0
            {
13954
0
                ++_iter;
13955
0
                ++line_iter;
13956
0
                ++new_len;
13957
0
            }
13958
13959
0
            _len = new_len;
13960
0
            if (_len == 0) {
13961
                // No common things now, fast exit!
13962
0
                return 0;
13963
0
            }
13964
0
        }
13965
0
    }
13966
13967
0
    assert(_len >= 0);
13968
0
    if (_len > 0) {
13969
0
        *output = _start;
13970
0
    }
13971
0
    return _len;
13972
0
}
13973
13974
/* Dedent a string.
13975
   Intended to dedent Python source. Unlike `textwrap.dedent`, this
13976
   only supports spaces and tabs and doesn't normalize empty lines.
13977
   Return a new reference on success, NULL with exception set on error.
13978
   */
13979
PyObject *
13980
_PyUnicode_Dedent(PyObject *unicode)
13981
0
{
13982
0
    Py_ssize_t src_len = 0;
13983
0
    const char *src = PyUnicode_AsUTF8AndSize(unicode, &src_len);
13984
0
    if (!src) {
13985
0
        return NULL;
13986
0
    }
13987
0
    assert(src_len >= 0);
13988
0
    if (src_len == 0) {
13989
0
        return Py_NewRef(unicode);
13990
0
    }
13991
13992
0
    const char *const end = src + src_len;
13993
13994
    // [whitespace_start, whitespace_start + whitespace_len)
13995
    // describes the current longest common leading whitespace
13996
0
    const char *whitespace_start = NULL;
13997
0
    Py_ssize_t whitespace_len = search_longest_common_leading_whitespace(
13998
0
        src, end, &whitespace_start);
13999
14000
0
    if (whitespace_len == 0) {
14001
0
        return Py_NewRef(unicode);
14002
0
    }
14003
14004
    // now we should trigger a dedent
14005
0
    char *dest = PyMem_Malloc(src_len);
14006
0
    if (!dest) {
14007
0
        PyErr_NoMemory();
14008
0
        return NULL;
14009
0
    }
14010
0
    char *dest_iter = dest;
14011
14012
0
    for (const char *iter = src; iter < end; ++iter) {
14013
0
        const char *line_start = iter;
14014
0
        bool in_leading_space = true;
14015
14016
        // iterate over a line to find the end of a line
14017
0
        while (iter < end && *iter != '\n') {
14018
0
            if (in_leading_space && *iter != ' ' && *iter != '\t') {
14019
0
                in_leading_space = false;
14020
0
            }
14021
0
            ++iter;
14022
0
        }
14023
14024
        // invariant: *iter == '\n' or iter == end
14025
0
        bool append_newline = iter < end;
14026
14027
        // if this line has all white space, write '\n' and continue
14028
0
        if (in_leading_space && append_newline) {
14029
0
            *dest_iter++ = '\n';
14030
0
            continue;
14031
0
        }
14032
14033
        /* copy [new_line_start + whitespace_len, iter) to buffer, then
14034
            conditionally append '\n' */
14035
14036
0
        Py_ssize_t new_line_len = iter - line_start - whitespace_len;
14037
0
        assert(new_line_len >= 0);
14038
0
        memcpy(dest_iter, line_start + whitespace_len, new_line_len);
14039
14040
0
        dest_iter += new_line_len;
14041
14042
0
        if (append_newline) {
14043
0
            *dest_iter++ = '\n';
14044
0
        }
14045
0
    }
14046
14047
0
    PyObject *res = PyUnicode_FromStringAndSize(dest, dest_iter - dest);
14048
0
    PyMem_Free(dest);
14049
0
    return res;
14050
0
}
14051
14052
static PyMethodDef unicode_methods[] = {
14053
    UNICODE_ENCODE_METHODDEF
14054
    UNICODE_REPLACE_METHODDEF
14055
    UNICODE_SPLIT_METHODDEF
14056
    UNICODE_RSPLIT_METHODDEF
14057
    UNICODE_JOIN_METHODDEF
14058
    UNICODE_CAPITALIZE_METHODDEF
14059
    UNICODE_CASEFOLD_METHODDEF
14060
    UNICODE_TITLE_METHODDEF
14061
    UNICODE_CENTER_METHODDEF
14062
    UNICODE_COUNT_METHODDEF
14063
    UNICODE_EXPANDTABS_METHODDEF
14064
    UNICODE_FIND_METHODDEF
14065
    UNICODE_PARTITION_METHODDEF
14066
    UNICODE_INDEX_METHODDEF
14067
    UNICODE_LJUST_METHODDEF
14068
    UNICODE_LOWER_METHODDEF
14069
    UNICODE_LSTRIP_METHODDEF
14070
    UNICODE_RFIND_METHODDEF
14071
    UNICODE_RINDEX_METHODDEF
14072
    UNICODE_RJUST_METHODDEF
14073
    UNICODE_RSTRIP_METHODDEF
14074
    UNICODE_RPARTITION_METHODDEF
14075
    UNICODE_SPLITLINES_METHODDEF
14076
    UNICODE_STRIP_METHODDEF
14077
    UNICODE_SWAPCASE_METHODDEF
14078
    UNICODE_TRANSLATE_METHODDEF
14079
    UNICODE_UPPER_METHODDEF
14080
    UNICODE_STARTSWITH_METHODDEF
14081
    UNICODE_ENDSWITH_METHODDEF
14082
    UNICODE_REMOVEPREFIX_METHODDEF
14083
    UNICODE_REMOVESUFFIX_METHODDEF
14084
    UNICODE_ISASCII_METHODDEF
14085
    UNICODE_ISLOWER_METHODDEF
14086
    UNICODE_ISUPPER_METHODDEF
14087
    UNICODE_ISTITLE_METHODDEF
14088
    UNICODE_ISSPACE_METHODDEF
14089
    UNICODE_ISDECIMAL_METHODDEF
14090
    UNICODE_ISDIGIT_METHODDEF
14091
    UNICODE_ISNUMERIC_METHODDEF
14092
    UNICODE_ISALPHA_METHODDEF
14093
    UNICODE_ISALNUM_METHODDEF
14094
    UNICODE_ISIDENTIFIER_METHODDEF
14095
    UNICODE_ISPRINTABLE_METHODDEF
14096
    UNICODE_ZFILL_METHODDEF
14097
    {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
14098
    {"format_map", do_string_format_map, METH_O, format_map__doc__},
14099
    UNICODE___FORMAT___METHODDEF
14100
    UNICODE_MAKETRANS_METHODDEF
14101
    UNICODE_SIZEOF_METHODDEF
14102
    {"__getnewargs__",  unicode_getnewargs, METH_NOARGS},
14103
    {NULL, NULL}
14104
};
14105
14106
static PyObject *
14107
unicode_mod(PyObject *v, PyObject *w)
14108
1.46M
{
14109
1.46M
    if (!PyUnicode_Check(v))
14110
77
        Py_RETURN_NOTIMPLEMENTED;
14111
1.46M
    return PyUnicode_Format(v, w);
14112
1.46M
}
14113
14114
static PyNumberMethods unicode_as_number = {
14115
    0,              /*nb_add*/
14116
    0,              /*nb_subtract*/
14117
    0,              /*nb_multiply*/
14118
    unicode_mod,            /*nb_remainder*/
14119
};
14120
14121
static PySequenceMethods unicode_as_sequence = {
14122
    unicode_length,     /* sq_length */
14123
    PyUnicode_Concat,   /* sq_concat */
14124
    _PyUnicode_Repeat,  /* sq_repeat */
14125
    unicode_getitem,    /* sq_item */
14126
    0,                  /* sq_slice */
14127
    0,                  /* sq_ass_item */
14128
    0,                  /* sq_ass_slice */
14129
    PyUnicode_Contains, /* sq_contains */
14130
};
14131
14132
static PyObject*
14133
unicode_subscript(PyObject* self, PyObject* item)
14134
12.2M
{
14135
12.2M
    if (_PyIndex_Check(item)) {
14136
12.1M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
14137
12.1M
        if (i == -1 && PyErr_Occurred())
14138
306
            return NULL;
14139
12.1M
        if (i < 0)
14140
1.24k
            i += PyUnicode_GET_LENGTH(self);
14141
12.1M
        return unicode_getitem(self, i);
14142
12.1M
    } else if (PySlice_Check(item)) {
14143
129k
        Py_ssize_t start, stop, step, slicelength, i;
14144
129k
        size_t cur;
14145
129k
        PyObject *result;
14146
129k
        const void *src_data;
14147
129k
        void *dest_data;
14148
129k
        int src_kind, dest_kind;
14149
129k
        Py_UCS4 ch, max_char, kind_limit;
14150
14151
129k
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
14152
143
            return NULL;
14153
143
        }
14154
129k
        slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14155
129k
                                            &start, &stop, step);
14156
14157
129k
        if (slicelength <= 0) {
14158
622
            _Py_RETURN_UNICODE_EMPTY();
14159
128k
        } else if (start == 0 && step == 1 &&
14160
600
                   slicelength == PyUnicode_GET_LENGTH(self)) {
14161
71
            return unicode_result_unchanged(self);
14162
128k
        } else if (step == 1) {
14163
128k
            return PyUnicode_Substring(self,
14164
128k
                                       start, start + slicelength);
14165
128k
        }
14166
        /* General case */
14167
144
        src_kind = PyUnicode_KIND(self);
14168
144
        src_data = PyUnicode_DATA(self);
14169
144
        if (!PyUnicode_IS_ASCII(self)) {
14170
75
            kind_limit = kind_maxchar_limit(src_kind);
14171
75
            max_char = 0;
14172
7.51k
            for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14173
7.48k
                ch = PyUnicode_READ(src_kind, src_data, cur);
14174
7.48k
                if (ch > max_char) {
14175
175
                    max_char = ch;
14176
175
                    if (max_char >= kind_limit)
14177
44
                        break;
14178
175
                }
14179
7.48k
            }
14180
75
        }
14181
69
        else
14182
69
            max_char = 127;
14183
144
        result = PyUnicode_New(slicelength, max_char);
14184
144
        if (result == NULL)
14185
0
            return NULL;
14186
144
        dest_kind = PyUnicode_KIND(result);
14187
144
        dest_data = PyUnicode_DATA(result);
14188
14189
9.51k
        for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14190
9.37k
            Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14191
9.37k
            PyUnicode_WRITE(dest_kind, dest_data, i, ch);
14192
9.37k
        }
14193
144
        assert(_PyUnicode_CheckConsistency(result, 1));
14194
144
        return result;
14195
149
    } else {
14196
149
        PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
14197
149
                     Py_TYPE(item)->tp_name);
14198
149
        return NULL;
14199
149
    }
14200
12.2M
}
14201
14202
static PyMappingMethods unicode_as_mapping = {
14203
    unicode_length,     /* mp_length */
14204
    unicode_subscript,  /* mp_subscript */
14205
    0,                  /* mp_ass_subscript */
14206
};
14207
14208
14209
static PyObject *
14210
unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
14211
14212
/*[clinic input]
14213
@classmethod
14214
str.__new__ as unicode_new
14215
14216
    object as x: object = NULL
14217
    encoding: str = NULL
14218
    errors: str = NULL
14219
14220
[clinic start generated code]*/
14221
14222
static PyObject *
14223
unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
14224
                 const char *errors)
14225
/*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
14226
42
{
14227
42
    PyObject *unicode;
14228
42
    if (x == NULL) {
14229
0
        unicode = _PyUnicode_GetEmpty();
14230
0
    }
14231
42
    else if (encoding == NULL && errors == NULL) {
14232
42
        unicode = PyObject_Str(x);
14233
42
    }
14234
0
    else {
14235
0
        unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
14236
0
    }
14237
14238
42
    if (unicode != NULL && type != &PyUnicode_Type) {
14239
42
        Py_SETREF(unicode, unicode_subtype_new(type, unicode));
14240
42
    }
14241
42
    return unicode;
14242
42
}
14243
14244
static const char *
14245
arg_as_utf8(PyObject *obj, const char *name)
14246
158k
{
14247
158k
    if (!PyUnicode_Check(obj)) {
14248
0
        PyErr_Format(PyExc_TypeError,
14249
0
                     "str() argument '%s' must be str, not %T",
14250
0
                     name, obj);
14251
0
        return NULL;
14252
0
    }
14253
158k
    return _PyUnicode_AsUTF8NoNUL(obj);
14254
158k
}
14255
14256
static PyObject *
14257
unicode_vectorcall(PyObject *type, PyObject *const *args,
14258
                   size_t nargsf, PyObject *kwnames)
14259
154k
{
14260
154k
    assert(Py_Is(_PyType_CAST(type), &PyUnicode_Type));
14261
14262
154k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
14263
154k
    if (kwnames != NULL && PyTuple_GET_SIZE(kwnames) != 0) {
14264
        // Fallback to unicode_new()
14265
0
        PyObject *tuple = PyTuple_FromArray(args, nargs);
14266
0
        if (tuple == NULL) {
14267
0
            return NULL;
14268
0
        }
14269
0
        PyObject *dict = _PyStack_AsDict(args + nargs, kwnames);
14270
0
        if (dict == NULL) {
14271
0
            Py_DECREF(tuple);
14272
0
            return NULL;
14273
0
        }
14274
0
        PyObject *ret = unicode_new(_PyType_CAST(type), tuple, dict);
14275
0
        Py_DECREF(tuple);
14276
0
        Py_DECREF(dict);
14277
0
        return ret;
14278
0
    }
14279
154k
    if (!_PyArg_CheckPositional("str", nargs, 0, 3)) {
14280
0
        return NULL;
14281
0
    }
14282
154k
    if (nargs == 0) {
14283
0
        return _PyUnicode_GetEmpty();
14284
0
    }
14285
154k
    PyObject *object = args[0];
14286
154k
    if (nargs == 1) {
14287
105
        return PyObject_Str(object);
14288
105
    }
14289
154k
    const char *encoding = arg_as_utf8(args[1], "encoding");
14290
154k
    if (encoding == NULL) {
14291
0
        return NULL;
14292
0
    }
14293
154k
    const char *errors = NULL;
14294
154k
    if (nargs == 3) {
14295
4.14k
        errors = arg_as_utf8(args[2], "errors");
14296
4.14k
        if (errors == NULL) {
14297
0
            return NULL;
14298
0
        }
14299
4.14k
    }
14300
154k
    return PyUnicode_FromEncodedObject(object, encoding, errors);
14301
154k
}
14302
14303
static PyObject *
14304
unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
14305
42
{
14306
42
    PyObject *self;
14307
42
    Py_ssize_t length, char_size;
14308
42
    int share_utf8;
14309
42
    int kind;
14310
42
    void *data;
14311
14312
42
    assert(PyType_IsSubtype(type, &PyUnicode_Type));
14313
42
    assert(_PyUnicode_CHECK(unicode));
14314
14315
42
    self = type->tp_alloc(type, 0);
14316
42
    if (self == NULL) {
14317
0
        return NULL;
14318
0
    }
14319
42
    kind = PyUnicode_KIND(unicode);
14320
42
    length = PyUnicode_GET_LENGTH(unicode);
14321
14322
42
    _PyUnicode_LENGTH(self) = length;
14323
#ifdef Py_DEBUG
14324
    _PyUnicode_HASH(self) = -1;
14325
#else
14326
42
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14327
0
#endif
14328
42
    _PyUnicode_STATE(self).interned = 0;
14329
42
    _PyUnicode_STATE(self).kind = kind;
14330
42
    _PyUnicode_STATE(self).compact = 0;
14331
42
    _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
14332
42
    _PyUnicode_STATE(self).statically_allocated = 0;
14333
0
    PyUnicode_SET_UTF8_LENGTH(self, 0);
14334
42
    PyUnicode_SET_UTF8(self, NULL);
14335
42
    _PyUnicode_DATA_ANY(self) = NULL;
14336
14337
0
    share_utf8 = 0;
14338
42
    if (kind == PyUnicode_1BYTE_KIND) {
14339
42
        char_size = 1;
14340
42
        if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14341
42
            share_utf8 = 1;
14342
42
    }
14343
0
    else if (kind == PyUnicode_2BYTE_KIND) {
14344
0
        char_size = 2;
14345
0
    }
14346
0
    else {
14347
0
        assert(kind == PyUnicode_4BYTE_KIND);
14348
0
        char_size = 4;
14349
0
    }
14350
14351
    /* Ensure we won't overflow the length. */
14352
42
    if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14353
0
        PyErr_NoMemory();
14354
0
        goto onError;
14355
0
    }
14356
42
    data = PyMem_Malloc((length + 1) * char_size);
14357
42
    if (data == NULL) {
14358
0
        PyErr_NoMemory();
14359
0
        goto onError;
14360
0
    }
14361
14362
84
    _PyUnicode_DATA_ANY(self) = data;
14363
42
    if (share_utf8) {
14364
42
        PyUnicode_SET_UTF8_LENGTH(self, length);
14365
42
        PyUnicode_SET_UTF8(self, data);
14366
42
    }
14367
14368
84
    memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
14369
84
    assert(_PyUnicode_CheckConsistency(self, 1));
14370
#ifdef Py_DEBUG
14371
    _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14372
#endif
14373
42
    return self;
14374
14375
0
onError:
14376
0
    Py_DECREF(self);
14377
0
    return NULL;
14378
84
}
14379
14380
static _PyObjectIndexPair
14381
unicode_iteritem(PyObject *obj, Py_ssize_t index)
14382
13.6M
{
14383
13.6M
    if (index >= PyUnicode_GET_LENGTH(obj)) {
14384
446k
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
14385
446k
    }
14386
13.2M
    const void *data = PyUnicode_DATA(obj);
14387
13.2M
    int kind = PyUnicode_KIND(obj);
14388
13.2M
    Py_UCS4 ch = PyUnicode_READ(kind, data, index);
14389
13.2M
    PyObject *result = unicode_char(ch);
14390
13.2M
    index = (result == NULL) ? -1 : index + 1;
14391
13.2M
    return (_PyObjectIndexPair) { .object = result, .index = index };
14392
13.2M
}
14393
14394
void
14395
_PyUnicode_ExactDealloc(PyObject *op)
14396
1.91M
{
14397
1.91M
    assert(PyUnicode_CheckExact(op));
14398
1.91M
    unicode_dealloc(op);
14399
1.91M
}
14400
14401
PyDoc_STRVAR(unicode_doc,
14402
"str(object='') -> str\n\
14403
str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
14404
\n\
14405
Create a new string object from the given object. If encoding or\n\
14406
errors is specified, then the object must expose a data buffer\n\
14407
that will be decoded using the given encoding and error handler.\n\
14408
Otherwise, returns the result of object.__str__() (if defined)\n\
14409
or repr(object).\n\
14410
encoding defaults to 'utf-8'.\n\
14411
errors defaults to 'strict'.");
14412
14413
static PyObject *unicode_iter(PyObject *seq);
14414
14415
PyTypeObject PyUnicode_Type = {
14416
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
14417
    "str",                        /* tp_name */
14418
    sizeof(PyUnicodeObject),      /* tp_basicsize */
14419
    0,                            /* tp_itemsize */
14420
    /* Slots */
14421
    unicode_dealloc,              /* tp_dealloc */
14422
    0,                            /* tp_vectorcall_offset */
14423
    0,                            /* tp_getattr */
14424
    0,                            /* tp_setattr */
14425
    0,                            /* tp_as_async */
14426
    unicode_repr,                 /* tp_repr */
14427
    &unicode_as_number,           /* tp_as_number */
14428
    &unicode_as_sequence,         /* tp_as_sequence */
14429
    &unicode_as_mapping,          /* tp_as_mapping */
14430
    unicode_hash,                 /* tp_hash*/
14431
    0,                            /* tp_call*/
14432
    unicode_str,                  /* tp_str */
14433
    PyObject_GenericGetAttr,      /* tp_getattro */
14434
    0,                            /* tp_setattro */
14435
    0,                            /* tp_as_buffer */
14436
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
14437
        Py_TPFLAGS_UNICODE_SUBCLASS |
14438
        _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
14439
    unicode_doc,                  /* tp_doc */
14440
    0,                            /* tp_traverse */
14441
    0,                            /* tp_clear */
14442
    PyUnicode_RichCompare,        /* tp_richcompare */
14443
    0,                            /* tp_weaklistoffset */
14444
    unicode_iter,                 /* tp_iter */
14445
    0,                            /* tp_iternext */
14446
    unicode_methods,              /* tp_methods */
14447
    0,                            /* tp_members */
14448
    0,                            /* tp_getset */
14449
    0,                            /* tp_base */
14450
    0,                            /* tp_dict */
14451
    0,                            /* tp_descr_get */
14452
    0,                            /* tp_descr_set */
14453
    0,                            /* tp_dictoffset */
14454
    0,                            /* tp_init */
14455
    0,                            /* tp_alloc */
14456
    unicode_new,                  /* tp_new */
14457
    PyObject_Free,                /* tp_free */
14458
    .tp_vectorcall = unicode_vectorcall,
14459
    ._tp_iteritem = unicode_iteritem,
14460
};
14461
14462
/* Initialize the Unicode implementation */
14463
14464
static void
14465
_init_global_state(void)
14466
21
{
14467
21
    static int initialized = 0;
14468
21
    if (initialized) {
14469
0
        return;
14470
0
    }
14471
21
    initialized = 1;
14472
14473
    /* initialize the linebreak bloom filter */
14474
21
    const Py_UCS2 linebreak[] = {
14475
21
        0x000A, /* LINE FEED */
14476
21
        0x000D, /* CARRIAGE RETURN */
14477
21
        0x001C, /* FILE SEPARATOR */
14478
21
        0x001D, /* GROUP SEPARATOR */
14479
21
        0x001E, /* RECORD SEPARATOR */
14480
21
        0x0085, /* NEXT LINE */
14481
21
        0x2028, /* LINE SEPARATOR */
14482
21
        0x2029, /* PARAGRAPH SEPARATOR */
14483
21
    };
14484
21
    bloom_linebreak = make_bloom_mask(
14485
21
        PyUnicode_2BYTE_KIND, linebreak,
14486
21
        Py_ARRAY_LENGTH(linebreak));
14487
21
}
14488
14489
void
14490
_PyUnicode_InitState(PyInterpreterState *interp)
14491
21
{
14492
21
    if (!_Py_IsMainInterpreter(interp)) {
14493
0
        return;
14494
0
    }
14495
21
    _init_global_state();
14496
21
}
14497
14498
14499
PyStatus
14500
_PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
14501
21
{
14502
21
    if (_Py_IsMainInterpreter(interp)) {
14503
21
        PyStatus status = init_global_interned_strings(interp);
14504
21
        if (_PyStatus_EXCEPTION(status)) {
14505
0
            return status;
14506
0
        }
14507
21
    }
14508
21
    assert(INTERNED_STRINGS);
14509
14510
21
    if (init_interned_dict(interp)) {
14511
0
        PyErr_Clear();
14512
0
        return _PyStatus_ERR("failed to create interned dict");
14513
0
    }
14514
14515
21
    return _PyStatus_OK();
14516
21
}
14517
14518
14519
PyStatus
14520
_PyUnicode_InitTypes(PyInterpreterState *interp)
14521
21
{
14522
21
    if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
14523
0
        goto error;
14524
0
    }
14525
21
    if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
14526
0
        goto error;
14527
0
    }
14528
21
    if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
14529
0
        goto error;
14530
0
    }
14531
21
    return _PyStatus_OK();
14532
14533
0
error:
14534
0
    return _PyStatus_ERR("Can't initialize unicode types");
14535
21
}
14536
14537
static /* non-null */ PyObject*
14538
intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
14539
23.6k
{
14540
    // Note that this steals a reference to `s`, but in many cases that
14541
    // stolen ref is returned, requiring no decref/incref.
14542
14543
23.6k
    assert(s != NULL);
14544
23.6k
    assert(_PyUnicode_CHECK(s));
14545
23.6k
    assert(_PyUnicode_STATE(s).statically_allocated);
14546
23.6k
    assert(!PyUnicode_CHECK_INTERNED(s));
14547
14548
#ifdef Py_DEBUG
14549
    /* We must not add process-global interned string if there's already a
14550
     * per-interpreter interned_dict, which might contain duplicates.
14551
     */
14552
    PyObject *interned = get_interned_dict(interp);
14553
    assert(interned == NULL);
14554
#endif
14555
14556
    /* Look in the global cache first. */
14557
23.6k
    PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14558
    /* We should only init each string once */
14559
23.6k
    assert(r == NULL);
14560
    /* but just in case (for the non-debug build), handle this */
14561
23.6k
    if (r != NULL && r != s) {
14562
0
        assert(_PyUnicode_STATE(r).interned == SSTATE_INTERNED_IMMORTAL_STATIC);
14563
0
        assert(_PyUnicode_CHECK(r));
14564
0
        Py_DECREF(s);
14565
0
        return Py_NewRef(r);
14566
0
    }
14567
14568
23.6k
    if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < -1) {
14569
0
        Py_FatalError("failed to intern static string");
14570
0
    }
14571
14572
23.6k
    _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
14573
0
    return s;
14574
23.6k
}
14575
14576
void
14577
_PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
14578
23.6k
{
14579
    // This should only be called as part of runtime initialization
14580
23.6k
    assert(!Py_IsInitialized());
14581
14582
23.6k
    *p = intern_static(interp, *p);
14583
23.6k
    assert(*p);
14584
23.6k
}
14585
14586
static void
14587
immortalize_interned(PyObject *s)
14588
101k
{
14589
101k
    assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
14590
101k
    assert(!_Py_IsImmortal(s));
14591
#ifdef Py_REF_DEBUG
14592
    /* The reference count value should be excluded from the RefTotal.
14593
       The decrements to these objects will not be registered so they
14594
       need to be accounted for in here. */
14595
    for (Py_ssize_t i = 0; i < Py_REFCNT(s); i++) {
14596
        _Py_DecRefTotal(_PyThreadState_GET());
14597
    }
14598
#endif
14599
101k
    _Py_SetImmortal(s);
14600
    // The switch to SSTATE_INTERNED_IMMORTAL must be the last thing done here
14601
    // to synchronize with the check in intern_common() that avoids locking if
14602
    // the string is already immortal.
14603
101k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_IMMORTAL);
14604
101k
}
14605
14606
#ifdef Py_GIL_DISABLED
14607
static bool
14608
can_immortalize_safely(PyObject *s)
14609
{
14610
    if (_Py_IsOwnedByCurrentThread(s) || _Py_IsImmortal(s)) {
14611
        return true;
14612
    }
14613
    Py_ssize_t shared = _Py_atomic_load_ssize(&s->ob_ref_shared);
14614
    return _Py_REF_IS_MERGED(shared);
14615
}
14616
#endif
14617
14618
static /* non-null */ PyObject*
14619
intern_common(PyInterpreterState *interp, PyObject *s /* stolen */,
14620
              bool immortalize)
14621
4.07M
{
14622
    // Note that this steals a reference to `s`, but in many cases that
14623
    // stolen ref is returned, requiring no decref/incref.
14624
14625
#ifdef Py_DEBUG
14626
    assert(s != NULL);
14627
    assert(_PyUnicode_CHECK(s));
14628
#else
14629
4.07M
    if (s == NULL || !PyUnicode_Check(s)) {
14630
0
        return s;
14631
0
    }
14632
4.07M
#endif
14633
14634
    /* If it's a subclass, we don't really know what putting
14635
       it in the interned dict might do. */
14636
4.07M
    if (!PyUnicode_CheckExact(s)) {
14637
0
        return s;
14638
0
    }
14639
14640
    /* Is it already interned? */
14641
4.07M
    switch (PyUnicode_CHECK_INTERNED(s)) {
14642
607k
        case SSTATE_NOT_INTERNED:
14643
            // no, go on
14644
607k
            break;
14645
51.5k
        case SSTATE_INTERNED_MORTAL:
14646
51.5k
#ifndef Py_GIL_DISABLED
14647
            // yes but we might need to make it immortal
14648
51.5k
            if (immortalize) {
14649
85
                immortalize_interned(s);
14650
85
            }
14651
51.5k
            return s;
14652
#else
14653
            // not fully interned yet; fall through to the locking path
14654
            break;
14655
#endif
14656
3.41M
        default:
14657
            // all done
14658
3.41M
            return s;
14659
4.07M
    }
14660
14661
    /* Statically allocated strings must be already interned. */
14662
4.07M
    assert(!_PyUnicode_STATE(s).statically_allocated);
14663
14664
#if Py_GIL_DISABLED
14665
    /* In the free-threaded build, all interned strings are immortal */
14666
    immortalize = 1;
14667
#endif
14668
14669
    /* If it's already immortal, intern it as such */
14670
607k
    if (_Py_IsImmortal(s)) {
14671
0
        immortalize = 1;
14672
0
    }
14673
14674
    /* if it's a short string, get the singleton */
14675
607k
    if (PyUnicode_GET_LENGTH(s) == 1 &&
14676
1.54k
                PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) {
14677
10
        PyObject *r = LATIN1(*(unsigned char*)PyUnicode_DATA(s));
14678
10
        assert(PyUnicode_CHECK_INTERNED(r));
14679
10
        Py_DECREF(s);
14680
10
        return r;
14681
10
    }
14682
#ifdef Py_DEBUG
14683
    assert(!unicode_is_singleton(s));
14684
#endif
14685
14686
    /* Look in the global cache now. */
14687
607k
    {
14688
607k
        PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
14689
607k
        if (r != NULL) {
14690
69.7k
            assert(_PyUnicode_STATE(r).statically_allocated);
14691
69.7k
            assert(r != s);  // r must be statically_allocated; s is not
14692
69.7k
            Py_DECREF(s);
14693
69.7k
            return Py_NewRef(r);
14694
69.7k
        }
14695
607k
    }
14696
14697
    /* Do a setdefault on the per-interpreter cache. */
14698
537k
    PyObject *interned = get_interned_dict(interp);
14699
537k
    assert(interned != NULL);
14700
#ifdef Py_GIL_DISABLED
14701
#  define INTERN_MUTEX &_Py_INTERP_CACHED_OBJECT(interp, interned_mutex)
14702
    // Lock-free fast path: check if there's already an interned copy that
14703
    // is in its final immortal state.
14704
    PyObject *r;
14705
    int res = PyDict_GetItemRef(interned, s, &r);
14706
    if (res < 0) {
14707
        PyErr_Clear();
14708
        return s;
14709
    }
14710
    if (res > 0) {
14711
        unsigned int state = _Py_atomic_load_uint8(&_PyUnicode_STATE(r).interned);
14712
        if (state == SSTATE_INTERNED_IMMORTAL) {
14713
            Py_DECREF(s);
14714
            return r;
14715
        }
14716
        // Not yet fully interned; fall through to the locking path.
14717
        Py_DECREF(r);
14718
    }
14719
#endif
14720
14721
#ifdef Py_GIL_DISABLED
14722
    // Immortalization writes to the refcount fields non-atomically. That
14723
    // races with Py_INCREF / Py_DECREF on the thread that owns `s`. If we
14724
    // don't own it (and its refcount hasn't been merged), intern a copy
14725
    // we own instead.
14726
    if (!can_immortalize_safely(s)) {
14727
        PyObject *copy = _PyUnicode_Copy(s);
14728
        if (copy == NULL) {
14729
            PyErr_Clear();
14730
            return s;
14731
        }
14732
        Py_DECREF(s);
14733
        s = copy;
14734
    }
14735
#endif
14736
14737
    // Why _Py_LOCK_DONT_DETACH is used here: waiting for the interned mutex
14738
    // must not detach the thread state. Extension code is expected to
14739
    // detach before blocking on opaque external synchronization. However,
14740
    // the lock used for C++ static initialization is hidden, making
14741
    // that difficult, and it is common for C++ extensions to call
14742
    // PyUnicode_InternFromString() from static initializers. Detaching here
14743
    // can therefore deadlock: a stop-the-world pause may prevent the lock
14744
    // owner from reattaching while the pause waits for another attached
14745
    // thread blocked on the hidden lock.
14746
537k
    FT_MUTEX_LOCK_FLAGS(INTERN_MUTEX, _Py_LOCK_DONT_DETACH);
14747
537k
    PyObject *t;
14748
537k
    {
14749
537k
        int res = PyDict_SetDefaultRef(interned, s, s, &t);
14750
537k
        if (res < 0) {
14751
0
            PyErr_Clear();
14752
0
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14753
0
            return s;
14754
0
        }
14755
537k
        else if (res == 1) {
14756
            // value was already present (not inserted)
14757
277k
            Py_DECREF(s);
14758
277k
            if (immortalize &&
14759
111k
                    PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
14760
3.63k
                immortalize_interned(t);
14761
3.63k
            }
14762
277k
            FT_MUTEX_UNLOCK(INTERN_MUTEX);
14763
277k
            return t;
14764
277k
        }
14765
259k
        else {
14766
            // value was newly inserted
14767
259k
            assert (s == t);
14768
259k
            Py_DECREF(t);
14769
259k
        }
14770
537k
    }
14771
14772
    /* NOT_INTERNED -> INTERNED_MORTAL */
14773
14774
537k
    assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
14775
14776
259k
    if (!_Py_IsImmortal(s)) {
14777
        /* The two references in interned dict (key and value) are not counted.
14778
        unicode_dealloc() and _PyUnicode_ClearInterned() take care of this. */
14779
259k
        Py_DECREF(s);
14780
259k
        Py_DECREF(s);
14781
259k
    }
14782
259k
    FT_ATOMIC_STORE_UINT8(_PyUnicode_STATE(s).interned, SSTATE_INTERNED_MORTAL);
14783
14784
    /* INTERNED_MORTAL -> INTERNED_IMMORTAL (if needed) */
14785
14786
#ifdef Py_DEBUG
14787
    if (_Py_IsImmortal(s)) {
14788
        assert(immortalize);
14789
    }
14790
#endif
14791
259k
    if (immortalize) {
14792
97.7k
        immortalize_interned(s);
14793
97.7k
    }
14794
14795
259k
    FT_MUTEX_UNLOCK(INTERN_MUTEX);
14796
259k
    return s;
14797
259k
}
14798
14799
void
14800
_PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
14801
799k
{
14802
799k
    *p = intern_common(interp, *p, 1);
14803
799k
    assert(*p);
14804
799k
}
14805
14806
void
14807
_PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
14808
3.27M
{
14809
3.27M
    *p = intern_common(interp, *p, 0);
14810
3.27M
    assert(*p);
14811
3.27M
}
14812
14813
14814
void
14815
_PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
14816
0
{
14817
0
    _PyUnicode_InternImmortal(interp, p);
14818
0
    return;
14819
0
}
14820
14821
void
14822
PyUnicode_InternInPlace(PyObject **p)
14823
0
{
14824
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14825
0
    _PyUnicode_InternMortal(interp, p);
14826
0
}
14827
14828
// Public-looking name kept for the stable ABI; user should not call this:
14829
PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
14830
void
14831
PyUnicode_InternImmortal(PyObject **p)
14832
0
{
14833
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
14834
0
    _PyUnicode_InternImmortal(interp, p);
14835
0
}
14836
14837
PyObject *
14838
PyUnicode_InternFromString(const char *cp)
14839
292k
{
14840
292k
    PyObject *s = PyUnicode_FromString(cp);
14841
292k
    if (s == NULL) {
14842
0
        return NULL;
14843
0
    }
14844
292k
    PyInterpreterState *interp = _PyInterpreterState_GET();
14845
292k
    _PyUnicode_InternMortal(interp, &s);
14846
292k
    return s;
14847
292k
}
14848
14849
14850
void
14851
_PyUnicode_ClearInterned(PyInterpreterState *interp)
14852
0
{
14853
0
    PyObject *interned = get_interned_dict(interp);
14854
0
    if (interned == NULL) {
14855
0
        return;
14856
0
    }
14857
0
    assert(PyDict_CheckExact(interned));
14858
14859
0
    if (has_shared_intern_dict(interp)) {
14860
        // the dict doesn't belong to this interpreter, skip the debug
14861
        // checks on it and just clear the pointer to it
14862
0
        clear_interned_dict(interp);
14863
0
        return;
14864
0
    }
14865
14866
#ifdef INTERNED_STATS
14867
    fprintf(stderr, "releasing %zd interned strings\n",
14868
            PyDict_GET_SIZE(interned));
14869
14870
    Py_ssize_t total_length = 0;
14871
#endif
14872
0
    Py_ssize_t pos = 0;
14873
0
    PyObject *s, *ignored_value;
14874
0
    while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
14875
0
        int shared = 0;
14876
0
        switch (PyUnicode_CHECK_INTERNED(s)) {
14877
0
        case SSTATE_INTERNED_IMMORTAL:
14878
            /* Make immortal interned strings mortal again. */
14879
            // Skip the Immortal Instance check and restore
14880
            // the two references (key and value) ignored
14881
            // by PyUnicode_InternInPlace().
14882
0
            _Py_SetMortal(s, 2);
14883
#ifdef Py_REF_DEBUG
14884
            /* let's be pedantic with the ref total */
14885
            _Py_IncRefTotal(_PyThreadState_GET());
14886
            _Py_IncRefTotal(_PyThreadState_GET());
14887
#endif
14888
#ifdef INTERNED_STATS
14889
            total_length += PyUnicode_GET_LENGTH(s);
14890
#endif
14891
0
            break;
14892
0
        case SSTATE_INTERNED_IMMORTAL_STATIC:
14893
            /* It is shared between interpreters, so we should unmark it
14894
               only when this is the last interpreter in which it's
14895
               interned.  We immortalize all the statically initialized
14896
               strings during startup, so we can rely on the
14897
               main interpreter to be the last one. */
14898
0
            if (!_Py_IsMainInterpreter(interp)) {
14899
0
                shared = 1;
14900
0
            }
14901
0
            break;
14902
0
        case SSTATE_INTERNED_MORTAL:
14903
            // Restore 2 references held by the interned dict; these will
14904
            // be decref'd by clear_interned_dict's PyDict_Clear.
14905
0
            _Py_RefcntAdd(s, 2);
14906
#ifdef Py_REF_DEBUG
14907
            /* let's be pedantic with the ref total */
14908
            _Py_IncRefTotal(_PyThreadState_GET());
14909
            _Py_IncRefTotal(_PyThreadState_GET());
14910
#endif
14911
0
            break;
14912
0
        case SSTATE_NOT_INTERNED:
14913
0
            _Py_FALLTHROUGH;
14914
0
        default:
14915
0
            Py_UNREACHABLE();
14916
0
        }
14917
0
        if (!shared) {
14918
0
            FT_ATOMIC_STORE_UINT8_RELAXED(_PyUnicode_STATE(s).interned, SSTATE_NOT_INTERNED);
14919
0
        }
14920
0
    }
14921
#ifdef INTERNED_STATS
14922
    fprintf(stderr,
14923
            "total length of all interned strings: %zd characters\n",
14924
            total_length);
14925
#endif
14926
14927
0
    struct _Py_unicode_state *state = &interp->unicode;
14928
0
    struct _Py_unicode_ids *ids = &state->ids;
14929
0
    for (Py_ssize_t i=0; i < ids->size; i++) {
14930
0
        Py_XINCREF(ids->array[i]);
14931
0
    }
14932
0
    clear_interned_dict(interp);
14933
0
    if (_Py_IsMainInterpreter(interp)) {
14934
0
        clear_global_interned_strings();
14935
0
    }
14936
0
}
14937
14938
14939
/********************* Unicode Iterator **************************/
14940
14941
typedef struct {
14942
    PyObject_HEAD
14943
    Py_ssize_t it_index;
14944
    PyObject *it_seq;    /* Set to NULL when iterator is exhausted */
14945
} unicodeiterobject;
14946
14947
static void
14948
unicodeiter_dealloc(PyObject *op)
14949
18.5k
{
14950
18.5k
    unicodeiterobject *it = (unicodeiterobject *)op;
14951
18.5k
    _PyObject_GC_UNTRACK(it);
14952
18.5k
    Py_XDECREF(it->it_seq);
14953
18.5k
    PyObject_GC_Del(it);
14954
18.5k
}
14955
14956
static int
14957
unicodeiter_traverse(PyObject *op, visitproc visit, void *arg)
14958
0
{
14959
0
    unicodeiterobject *it = (unicodeiterobject *)op;
14960
0
    Py_VISIT(it->it_seq);
14961
0
    return 0;
14962
0
}
14963
14964
static PyObject *
14965
unicodeiter_next(PyObject *op)
14966
305k
{
14967
305k
    unicodeiterobject *it = (unicodeiterobject *)op;
14968
305k
    PyObject *seq;
14969
14970
305k
    assert(it != NULL);
14971
305k
    seq = it->it_seq;
14972
305k
    if (seq == NULL)
14973
0
        return NULL;
14974
305k
    assert(_PyUnicode_CHECK(seq));
14975
14976
305k
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14977
287k
        int kind = PyUnicode_KIND(seq);
14978
287k
        const void *data = PyUnicode_DATA(seq);
14979
287k
        Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14980
287k
        it->it_index++;
14981
287k
        return unicode_char(chr);
14982
287k
    }
14983
14984
18.2k
    it->it_seq = NULL;
14985
18.2k
    Py_DECREF(seq);
14986
18.2k
    return NULL;
14987
305k
}
14988
14989
static PyObject *
14990
unicode_ascii_iter_next(PyObject *op)
14991
1.69k
{
14992
1.69k
    unicodeiterobject *it = (unicodeiterobject *)op;
14993
1.69k
    assert(it != NULL);
14994
1.69k
    PyObject *seq = it->it_seq;
14995
1.69k
    if (seq == NULL) {
14996
0
        return NULL;
14997
0
    }
14998
1.69k
    assert(_PyUnicode_CHECK(seq));
14999
1.69k
    assert(PyUnicode_IS_COMPACT_ASCII(seq));
15000
1.69k
    if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15001
1.57k
        const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
15002
1.57k
        Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
15003
1.57k
                                              data, it->it_index);
15004
1.57k
        it->it_index++;
15005
1.57k
        return (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
15006
1.57k
    }
15007
114
    it->it_seq = NULL;
15008
114
    Py_DECREF(seq);
15009
114
    return NULL;
15010
1.69k
}
15011
15012
static PyObject *
15013
unicodeiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
15014
0
{
15015
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15016
0
    Py_ssize_t len = 0;
15017
0
    if (it->it_seq)
15018
0
        len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
15019
0
    return PyLong_FromSsize_t(len);
15020
0
}
15021
15022
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15023
15024
static PyObject *
15025
unicodeiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
15026
0
{
15027
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15028
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
15029
15030
    /* _PyEval_GetBuiltin can invoke arbitrary code,
15031
     * call must be before access of iterator pointers.
15032
     * see issue #101765 */
15033
15034
0
    if (it->it_seq != NULL) {
15035
0
        return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
15036
0
    } else {
15037
0
        PyObject *u = _PyUnicode_GetEmpty();
15038
0
        if (u == NULL) {
15039
0
            Py_XDECREF(iter);
15040
0
            return NULL;
15041
0
        }
15042
0
        return Py_BuildValue("N(N)", iter, u);
15043
0
    }
15044
0
}
15045
15046
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15047
15048
static PyObject *
15049
unicodeiter_setstate(PyObject *op, PyObject *state)
15050
0
{
15051
0
    unicodeiterobject *it = (unicodeiterobject *)op;
15052
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
15053
0
    if (index == -1 && PyErr_Occurred())
15054
0
        return NULL;
15055
0
    if (it->it_seq != NULL) {
15056
0
        if (index < 0)
15057
0
            index = 0;
15058
0
        else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15059
0
            index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15060
0
        it->it_index = index;
15061
0
    }
15062
0
    Py_RETURN_NONE;
15063
0
}
15064
15065
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15066
15067
static PyMethodDef unicodeiter_methods[] = {
15068
    {"__length_hint__", unicodeiter_len, METH_NOARGS, length_hint_doc},
15069
    {"__reduce__",      unicodeiter_reduce, METH_NOARGS, reduce_doc},
15070
    {"__setstate__",    unicodeiter_setstate, METH_O, setstate_doc},
15071
    {NULL,      NULL}       /* sentinel */
15072
};
15073
15074
PyTypeObject PyUnicodeIter_Type = {
15075
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15076
    "str_iterator",         /* tp_name */
15077
    sizeof(unicodeiterobject),      /* tp_basicsize */
15078
    0,                  /* tp_itemsize */
15079
    /* methods */
15080
    unicodeiter_dealloc,/* tp_dealloc */
15081
    0,                  /* tp_vectorcall_offset */
15082
    0,                  /* tp_getattr */
15083
    0,                  /* tp_setattr */
15084
    0,                  /* tp_as_async */
15085
    0,                  /* tp_repr */
15086
    0,                  /* tp_as_number */
15087
    0,                  /* tp_as_sequence */
15088
    0,                  /* tp_as_mapping */
15089
    0,                  /* tp_hash */
15090
    0,                  /* tp_call */
15091
    0,                  /* tp_str */
15092
    PyObject_GenericGetAttr,        /* tp_getattro */
15093
    0,                  /* tp_setattro */
15094
    0,                  /* tp_as_buffer */
15095
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15096
    0,                  /* tp_doc */
15097
    unicodeiter_traverse, /* tp_traverse */
15098
    0,                  /* tp_clear */
15099
    0,                  /* tp_richcompare */
15100
    0,                  /* tp_weaklistoffset */
15101
    PyObject_SelfIter,          /* tp_iter */
15102
    unicodeiter_next,   /* tp_iternext */
15103
    unicodeiter_methods,            /* tp_methods */
15104
    0,
15105
};
15106
15107
PyTypeObject _PyUnicodeASCIIIter_Type = {
15108
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
15109
    .tp_name = "str_ascii_iterator",
15110
    .tp_basicsize = sizeof(unicodeiterobject),
15111
    .tp_dealloc = unicodeiter_dealloc,
15112
    .tp_getattro = PyObject_GenericGetAttr,
15113
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
15114
    .tp_traverse = unicodeiter_traverse,
15115
    .tp_iter = PyObject_SelfIter,
15116
    .tp_iternext = unicode_ascii_iter_next,
15117
    .tp_methods = unicodeiter_methods,
15118
};
15119
15120
static PyObject *
15121
unicode_iter(PyObject *seq)
15122
18.5k
{
15123
18.5k
    unicodeiterobject *it;
15124
15125
18.5k
    if (!PyUnicode_Check(seq)) {
15126
0
        PyErr_BadInternalCall();
15127
0
        return NULL;
15128
0
    }
15129
18.5k
    if (PyUnicode_IS_COMPACT_ASCII(seq)) {
15130
135
        it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
15131
135
    }
15132
18.3k
    else {
15133
18.3k
        it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15134
18.3k
    }
15135
18.5k
    if (it == NULL)
15136
0
        return NULL;
15137
18.5k
    it->it_index = 0;
15138
18.5k
    it->it_seq = Py_NewRef(seq);
15139
18.5k
    _PyObject_GC_TRACK(it);
15140
18.5k
    return (PyObject *)it;
15141
18.5k
}
15142
15143
static int
15144
encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
15145
84
{
15146
84
    int res;
15147
84
    res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
15148
84
    if (res == -2) {
15149
0
        PyErr_Format(PyExc_RuntimeError, "cannot encode %s", name);
15150
0
        return -1;
15151
0
    }
15152
84
    if (res < 0) {
15153
0
        PyErr_NoMemory();
15154
0
        return -1;
15155
0
    }
15156
84
    return 0;
15157
84
}
15158
15159
15160
static int
15161
config_get_codec_name(wchar_t **config_encoding)
15162
42
{
15163
42
    char *encoding;
15164
42
    if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15165
0
        return -1;
15166
0
    }
15167
15168
42
    PyObject *name_obj = NULL;
15169
42
    PyObject *codec = _PyCodec_Lookup(encoding);
15170
42
    PyMem_RawFree(encoding);
15171
15172
42
    if (!codec)
15173
0
        goto error;
15174
15175
42
    name_obj = PyObject_GetAttrString(codec, "name");
15176
42
    Py_CLEAR(codec);
15177
42
    if (!name_obj) {
15178
0
        goto error;
15179
0
    }
15180
15181
42
    wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
15182
42
    Py_DECREF(name_obj);
15183
42
    if (wname == NULL) {
15184
0
        goto error;
15185
0
    }
15186
15187
42
    wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
15188
42
    if (raw_wname == NULL) {
15189
0
        PyMem_Free(wname);
15190
0
        PyErr_NoMemory();
15191
0
        goto error;
15192
0
    }
15193
15194
42
    PyMem_RawFree(*config_encoding);
15195
42
    *config_encoding = raw_wname;
15196
15197
42
    PyMem_Free(wname);
15198
42
    return 0;
15199
15200
0
error:
15201
0
    Py_XDECREF(codec);
15202
0
    Py_XDECREF(name_obj);
15203
0
    return -1;
15204
42
}
15205
15206
15207
static PyStatus
15208
init_stdio_encoding(PyInterpreterState *interp)
15209
21
{
15210
    /* Update the stdio encoding to the normalized Python codec name. */
15211
21
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15212
21
    if (config_get_codec_name(&config->stdio_encoding) < 0) {
15213
0
        return _PyStatus_ERR("failed to get the Python codec name "
15214
0
                             "of the stdio encoding");
15215
0
    }
15216
21
    return _PyStatus_OK();
15217
21
}
15218
15219
15220
static int
15221
init_fs_codec(PyInterpreterState *interp)
15222
21
{
15223
21
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
15224
15225
21
    _Py_error_handler error_handler;
15226
21
    error_handler = get_error_handler_wide(config->filesystem_errors);
15227
21
    if (error_handler == _Py_ERROR_UNKNOWN) {
15228
0
        PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
15229
0
        return -1;
15230
0
    }
15231
15232
21
    char *encoding, *errors;
15233
21
    if (encode_wstr_utf8(config->filesystem_encoding,
15234
21
                         &encoding,
15235
21
                         "filesystem_encoding") < 0) {
15236
0
        return -1;
15237
0
    }
15238
15239
21
    if (encode_wstr_utf8(config->filesystem_errors,
15240
21
                         &errors,
15241
21
                         "filesystem_errors") < 0) {
15242
0
        PyMem_RawFree(encoding);
15243
0
        return -1;
15244
0
    }
15245
15246
21
    struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
15247
21
    PyMem_RawFree(fs_codec->encoding);
15248
21
    fs_codec->encoding = encoding;
15249
    /* encoding has been normalized by init_fs_encoding() */
15250
21
    fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
15251
21
    PyMem_RawFree(fs_codec->errors);
15252
21
    fs_codec->errors = errors;
15253
21
    fs_codec->error_handler = error_handler;
15254
15255
#ifdef _Py_FORCE_UTF8_FS_ENCODING
15256
    assert(fs_codec->utf8 == 1);
15257
#endif
15258
15259
    /* At this point, PyUnicode_EncodeFSDefault() and
15260
       PyUnicode_DecodeFSDefault() can now use the Python codec rather than
15261
       the C implementation of the filesystem encoding. */
15262
15263
    /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
15264
       global configuration variables. */
15265
21
    if (_Py_IsMainInterpreter(interp)) {
15266
15267
21
        if (_Py_SetFileSystemEncoding(fs_codec->encoding,
15268
21
                                      fs_codec->errors) < 0) {
15269
0
            PyErr_NoMemory();
15270
0
            return -1;
15271
0
        }
15272
21
    }
15273
21
    return 0;
15274
21
}
15275
15276
15277
static PyStatus
15278
init_fs_encoding(PyThreadState *tstate)
15279
21
{
15280
21
    PyInterpreterState *interp = tstate->interp;
15281
15282
    /* Update the filesystem encoding to the normalized Python codec name.
15283
       For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
15284
       (Python codec name). */
15285
21
    PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
15286
21
    if (config_get_codec_name(&config->filesystem_encoding) < 0) {
15287
0
        _Py_DumpPathConfig(tstate);
15288
0
        return _PyStatus_ERR("failed to get the Python codec "
15289
0
                             "of the filesystem encoding");
15290
0
    }
15291
15292
21
    if (init_fs_codec(interp) < 0) {
15293
0
        return _PyStatus_ERR("cannot initialize filesystem codec");
15294
0
    }
15295
21
    return _PyStatus_OK();
15296
21
}
15297
15298
15299
PyStatus
15300
_PyUnicode_InitEncodings(PyThreadState *tstate)
15301
21
{
15302
21
    PyStatus status = _PyCodec_InitRegistry(tstate->interp);
15303
21
    if (_PyStatus_EXCEPTION(status)) {
15304
0
        return status;
15305
0
    }
15306
21
    status = init_fs_encoding(tstate);
15307
21
    if (_PyStatus_EXCEPTION(status)) {
15308
0
        return status;
15309
0
    }
15310
15311
21
    return init_stdio_encoding(tstate->interp);
15312
21
}
15313
15314
15315
static void
15316
_PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
15317
0
{
15318
0
    PyMem_RawFree(fs_codec->encoding);
15319
0
    fs_codec->encoding = NULL;
15320
0
    fs_codec->utf8 = 0;
15321
0
    PyMem_RawFree(fs_codec->errors);
15322
0
    fs_codec->errors = NULL;
15323
0
    fs_codec->error_handler = _Py_ERROR_UNKNOWN;
15324
0
}
15325
15326
15327
#ifdef Py_DEBUG
15328
static inline int
15329
unicode_is_finalizing(void)
15330
{
15331
    return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
15332
}
15333
#endif
15334
15335
15336
void
15337
_PyUnicode_FiniTypes(PyInterpreterState *interp)
15338
0
{
15339
0
    _PyStaticType_FiniBuiltin(interp, &EncodingMapType);
15340
0
    _PyStaticType_FiniBuiltin(interp, &PyFieldNameIter_Type);
15341
0
    _PyStaticType_FiniBuiltin(interp, &PyFormatterIter_Type);
15342
0
}
15343
15344
15345
void
15346
_PyUnicode_Fini(PyInterpreterState *interp)
15347
0
{
15348
0
    struct _Py_unicode_state *state = &interp->unicode;
15349
15350
0
    if (!has_shared_intern_dict(interp)) {
15351
        // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
15352
0
        assert(get_interned_dict(interp) == NULL);
15353
0
    }
15354
15355
0
    _PyUnicode_FiniEncodings(&state->fs_codec);
15356
15357
    // bpo-47182: force a unicodedata CAPI capsule re-import on
15358
    // subsequent initialization of interpreter.
15359
0
    interp->unicode.ucnhash_capi = NULL;
15360
15361
0
    unicode_clear_identifiers(state);
15362
0
}
15363
15364
/* A _string module, to export formatter_parser and formatter_field_name_split
15365
   to the string.Formatter class implemented in Python. */
15366
15367
static PyMethodDef _string_methods[] = {
15368
    {"formatter_field_name_split", formatter_field_name_split,
15369
     METH_O, PyDoc_STR("split the argument as a field name")},
15370
    {"formatter_parser", formatter_parser,
15371
     METH_O, PyDoc_STR("parse the argument as a format string")},
15372
    {NULL, NULL}
15373
};
15374
15375
static PyModuleDef_Slot module_slots[] = {
15376
    _Py_ABI_SLOT,
15377
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
15378
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
15379
    {0, NULL}
15380
};
15381
15382
static struct PyModuleDef _string_module = {
15383
    PyModuleDef_HEAD_INIT,
15384
    .m_name = "_string",
15385
    .m_doc = PyDoc_STR("string helper module"),
15386
    .m_size = 0,
15387
    .m_methods = _string_methods,
15388
    .m_slots = module_slots,
15389
};
15390
15391
PyMODINIT_FUNC
15392
PyInit__string(void)
15393
0
{
15394
0
    return PyModuleDef_Init(&_string_module);
15395
0
}
15396
15397
15398
#undef PyUnicode_KIND
15399
int PyUnicode_KIND(PyObject *op)
15400
0
{
15401
0
    if (!PyUnicode_Check(op)) {
15402
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15403
0
        return -1;
15404
0
    }
15405
0
    return _PyASCIIObject_CAST(op)->state.kind;
15406
0
}
15407
15408
#undef PyUnicode_DATA
15409
void* PyUnicode_DATA(PyObject *op)
15410
0
{
15411
0
    if (!PyUnicode_Check(op)) {
15412
0
        PyErr_Format(PyExc_TypeError, "expect str, got %T", op);
15413
0
        return NULL;
15414
0
    }
15415
0
    return _PyUnicode_DATA(op);
15416
0
}