Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/unicode_writer.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_freelist.h"      // _Py_FREELIST_FREE()
43
#include "pycore_long.h"          // _PyLong_FormatWriter()
44
#include "pycore_unicodeobject.h" // _PyUnicode_Result()
45
46
47
#ifdef MS_WINDOWS
48
   /* On Windows, overallocate by 50% is the best factor */
49
#  define OVERALLOCATE_FACTOR 2
50
#else
51
   /* On Linux, overallocate by 25% is the best factor */
52
18.8M
#  define OVERALLOCATE_FACTOR 4
53
#endif
54
55
56
/* Compilation of templated routines */
57
58
#define STRINGLIB_GET_EMPTY() _PyUnicode_GetEmpty()
59
60
#include "stringlib/ucs1lib.h"
61
#include "stringlib/find_max_char.h"
62
#include "stringlib/undef.h"
63
64
65
void
66
_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
67
52.0M
{
68
52.0M
    memset(writer, 0, sizeof(*writer));
69
70
    /* ASCII is the bare minimum */
71
52.0M
    writer->min_char = 127;
72
73
    /* use a kind value smaller than PyUnicode_1BYTE_KIND so
74
       _PyUnicodeWriter_PrepareKind() will copy the buffer. */
75
52.0M
    assert(writer->kind == 0);
76
52.0M
    assert(writer->kind < PyUnicode_1BYTE_KIND);
77
52.0M
}
78
79
80
PyUnicodeWriter*
81
PyUnicodeWriter_Create(Py_ssize_t length)
82
4.47M
{
83
4.47M
    if (length < 0) {
84
0
        PyErr_SetString(PyExc_ValueError,
85
0
                        "length must be positive");
86
0
        return NULL;
87
0
    }
88
89
4.47M
    const size_t size = sizeof(_PyUnicodeWriter);
90
4.47M
    PyUnicodeWriter *pub_writer;
91
4.47M
    pub_writer = _Py_FREELIST_POP_MEM(unicode_writers);
92
4.47M
    if (pub_writer == NULL) {
93
2.33M
        pub_writer = (PyUnicodeWriter *)PyMem_Malloc(size);
94
2.33M
        if (pub_writer == NULL) {
95
0
            return (PyUnicodeWriter *)PyErr_NoMemory();
96
0
        }
97
2.33M
    }
98
4.47M
    _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer;
99
100
4.47M
    _PyUnicodeWriter_Init(writer);
101
    // The buffer is created lazily at the first write, except if
102
    // the read-only optimization is used.
103
4.47M
    writer->min_length = length;
104
4.47M
    writer->overallocate = 1;
105
106
4.47M
    return pub_writer;
107
4.47M
}
108
109
110
void
111
PyUnicodeWriter_Discard(PyUnicodeWriter *writer)
112
81.0k
{
113
81.0k
    if (writer == NULL) {
114
80.3k
        return;
115
80.3k
    }
116
710
    _PyUnicodeWriter_Dealloc((_PyUnicodeWriter*)writer);
117
710
    _Py_FREELIST_FREE(unicode_writers, writer, PyMem_Free);
118
710
}
119
120
121
// Initialize _PyUnicodeWriter with initial buffer
122
void
123
_PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer)
124
10.8M
{
125
10.8M
    assert(PyUnstable_Object_IsUniquelyReferenced(buffer));
126
127
10.8M
    memset(writer, 0, sizeof(*writer));
128
10.8M
    _PyUnicodeWriter_SetBuffer(writer, buffer);
129
10.8M
    writer->min_length = writer->size;
130
10.8M
    assert(_PyUnicodeWriter_CanWrite(writer));
131
10.8M
}
132
133
134
int
135
_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
136
                                 Py_ssize_t length, Py_UCS4 maxchar)
137
69.9M
{
138
69.9M
    assert(length >= 0);
139
69.9M
    assert(maxchar <= _Py_MAX_UNICODE);
140
141
    // Check that _PyUnicodeWriter_Prepare() or _PyUnicodeWriter_PrepareKind()
142
    // was used
143
69.9M
    assert(maxchar > writer->maxchar
144
69.9M
           || (length > (writer->size - writer->pos) && length >= 1));
145
146
69.9M
    if (length > PY_SSIZE_T_MAX - writer->pos) {
147
0
        PyErr_NoMemory();
148
0
        return -1;
149
0
    }
150
69.9M
    Py_ssize_t alloc = writer->pos + length;
151
152
69.9M
    maxchar = Py_MAX(maxchar, writer->min_char);
153
154
69.9M
    PyObject *new_buffer;
155
69.9M
    if (writer->buffer == NULL) {
156
38.3M
        assert(!writer->readonly);
157
158
        // Do not overallocate at the first allocation, but use min_length
159
38.3M
        if (alloc < writer->min_length) {
160
25.8M
            alloc = writer->min_length;
161
25.8M
        }
162
163
38.3M
        new_buffer = PyUnicode_New(alloc, maxchar);
164
38.3M
        if (new_buffer == NULL) {
165
0
            return -1;
166
0
        }
167
38.3M
    }
168
31.5M
    else if (alloc > writer->size) {
169
        // Do not overallocate at the first allocation, but use min_length
170
22.6M
        int overallocate = (writer->overallocate && !writer->readonly);
171
22.6M
        if (overallocate
172
9.43M
            && alloc <= (PY_SSIZE_T_MAX - alloc / OVERALLOCATE_FACTOR)) {
173
            /* overallocate to limit the number of realloc() */
174
9.43M
            alloc += alloc / OVERALLOCATE_FACTOR;
175
9.43M
        }
176
22.6M
        if (alloc < writer->min_length) {
177
8.84M
            alloc = writer->min_length;
178
8.84M
        }
179
180
22.6M
        if (maxchar > writer->maxchar || writer->readonly) {
181
            /* resize + widen */
182
14.4M
            maxchar = Py_MAX(maxchar, writer->maxchar);
183
14.4M
            new_buffer = PyUnicode_New(alloc, maxchar);
184
14.4M
            if (new_buffer == NULL) {
185
0
                return -1;
186
0
            }
187
14.4M
            _PyUnicode_FastCopyCharacters(new_buffer, 0,
188
14.4M
                                          writer->buffer, 0, writer->pos);
189
14.4M
        }
190
8.17M
        else {
191
8.17M
            new_buffer = _PyUnicode_ResizeCompact(writer->buffer, alloc);
192
8.17M
            if (new_buffer == NULL) {
193
0
                return -1;
194
0
            }
195
            // Do not DECREF the old buffer
196
8.17M
            writer->buffer = NULL;
197
8.17M
        }
198
22.6M
    }
199
8.95M
    else {
200
8.95M
        assert(maxchar > writer->maxchar);
201
8.95M
        assert(!writer->readonly);
202
203
8.95M
        new_buffer = PyUnicode_New(writer->size, maxchar);
204
8.95M
        if (new_buffer == NULL) {
205
0
            return -1;
206
0
        }
207
8.95M
        _PyUnicode_FastCopyCharacters(new_buffer, 0,
208
8.95M
                                      writer->buffer, 0, writer->pos);
209
8.95M
    }
210
211
69.9M
    _PyUnicodeWriter_SetBuffer(writer, new_buffer);
212
69.9M
    return 0;
213
214
69.9M
#undef OVERALLOCATE_FACTOR
215
69.9M
}
216
217
int
218
_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
219
                                     int kind)
220
230k
{
221
230k
    Py_UCS4 maxchar;
222
223
    /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
224
230k
    assert(writer->kind < kind);
225
226
230k
    switch (kind)
227
230k
    {
228
0
    case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
229
230k
    case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
230
0
    case PyUnicode_4BYTE_KIND: maxchar = _Py_MAX_UNICODE; break;
231
0
    default:
232
0
        Py_UNREACHABLE();
233
230k
    }
234
235
230k
    return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
236
230k
}
237
238
239
int
240
_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
241
75.7M
{
242
75.7M
    return _PyUnicodeWriter_WriteCharInline(writer, ch);
243
75.7M
}
244
245
246
int
247
PyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch)
248
75.7M
{
249
75.7M
    if (ch > _Py_MAX_UNICODE) {
250
0
        PyErr_SetString(PyExc_ValueError,
251
0
                        "character must be in range(0x110000)");
252
0
        return -1;
253
0
    }
254
255
75.7M
    return _PyUnicodeWriter_WriteChar((_PyUnicodeWriter*)writer, ch);
256
75.7M
}
257
258
259
int
260
_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
261
53.5M
{
262
53.5M
    assert(PyUnicode_Check(str));
263
264
53.5M
    Py_ssize_t len = PyUnicode_GET_LENGTH(str);
265
53.5M
    if (len == 0) {
266
7.35M
        return 0;
267
7.35M
    }
268
46.2M
    Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
269
270
46.2M
    if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
271
18.1M
        if (writer->buffer == NULL && PyUnicode_CheckExact(str)) {
272
8.77M
            assert(_PyUnicode_CheckConsistency(str, 1));
273
8.77M
            _PyUnicodeWriter_SetReadOnly(writer, Py_NewRef(str), len);
274
8.77M
            return 0;
275
8.77M
        }
276
9.38M
        if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
277
0
            return -1;
278
9.38M
    }
279
280
46.2M
    assert(_PyUnicodeWriter_CanWrite(writer));
281
37.4M
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
282
37.4M
                                  str, 0, len);
283
37.4M
    writer->pos += len;
284
37.4M
    return 0;
285
46.2M
}
286
287
288
int
289
PyUnicodeWriter_WriteStr(PyUnicodeWriter *pub_writer, PyObject *obj)
290
14.6M
{
291
14.6M
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
292
14.6M
    PyTypeObject *type = Py_TYPE(obj);
293
14.6M
    if (type == &PyUnicode_Type) {
294
9.83M
        return _PyUnicodeWriter_WriteStr(writer, obj);
295
9.83M
    }
296
297
4.81M
    if (type == &PyLong_Type) {
298
0
        return _PyLong_FormatWriter(writer, obj, 10, 0);
299
0
    }
300
301
4.81M
    PyObject *str = PyObject_Str(obj);
302
4.81M
    if (str == NULL) {
303
0
        return -1;
304
0
    }
305
306
4.81M
    int res = _PyUnicodeWriter_WriteStr(writer, str);
307
4.81M
    Py_DECREF(str);
308
4.81M
    return res;
309
4.81M
}
310
311
312
int
313
PyUnicodeWriter_WriteRepr(PyUnicodeWriter *pub_writer, PyObject *obj)
314
8.44M
{
315
8.44M
    _PyUnicodeWriter *writer = (_PyUnicodeWriter*)pub_writer;
316
8.44M
    if (obj == NULL) {
317
0
        return _PyUnicodeWriter_WriteASCIIString(writer, "<NULL>", 6);
318
0
    }
319
320
8.44M
    if (Py_TYPE(obj) == &PyLong_Type) {
321
748k
        return _PyLong_FormatWriter(writer, obj, 10, 0);
322
748k
    }
323
    // Fast path for None; see gh-159813 for the rationale.
324
7.69M
    if (obj == Py_None) {
325
42.5k
        return _PyUnicodeWriter_WriteASCIIString(writer, "None", 4);
326
42.5k
    }
327
328
7.65M
    PyObject *repr = PyObject_Repr(obj);
329
7.65M
    if (repr == NULL) {
330
0
        return -1;
331
0
    }
332
333
7.65M
    int res = _PyUnicodeWriter_WriteStr(writer, repr);
334
7.65M
    Py_DECREF(repr);
335
7.65M
    return res;
336
7.65M
}
337
338
339
int
340
_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
341
                                Py_ssize_t start, Py_ssize_t end)
342
45.0M
{
343
45.0M
    assert(0 <= start);
344
45.0M
    assert(start <= end);
345
45.0M
    assert(end <= PyUnicode_GET_LENGTH(str));
346
347
45.0M
    if (start == 0 && end == PyUnicode_GET_LENGTH(str)) {
348
8
        return _PyUnicodeWriter_WriteStr(writer, str);
349
8
    }
350
351
45.0M
    Py_ssize_t len = end - start;
352
45.0M
    if (len == 0) {
353
0
        return 0;
354
0
    }
355
356
45.0M
    Py_UCS4 maxchar;
357
45.0M
    if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar) {
358
12.9M
        maxchar = _PyUnicode_FindMaxChar(str, start, end);
359
12.9M
    }
360
32.1M
    else {
361
32.1M
        maxchar = writer->maxchar;
362
32.1M
    }
363
45.0M
    if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0) {
364
0
        return -1;
365
0
    }
366
45.0M
    assert(_PyUnicodeWriter_CanWrite(writer));
367
368
45.0M
    _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
369
45.0M
                                  str, start, len);
370
45.0M
    writer->pos += len;
371
45.0M
    return 0;
372
45.0M
}
373
374
375
int
376
PyUnicodeWriter_WriteSubstring(PyUnicodeWriter *writer, PyObject *str,
377
                               Py_ssize_t start, Py_ssize_t end)
378
650k
{
379
650k
    if (!PyUnicode_Check(str)) {
380
0
        PyErr_Format(PyExc_TypeError, "expect str, not %T", str);
381
0
        return -1;
382
0
    }
383
650k
    if (start < 0 || start > end) {
384
0
        PyErr_Format(PyExc_ValueError, "invalid start argument");
385
0
        return -1;
386
0
    }
387
650k
    if (end > PyUnicode_GET_LENGTH(str)) {
388
0
        PyErr_Format(PyExc_ValueError, "invalid end argument");
389
0
        return -1;
390
0
    }
391
392
650k
    return _PyUnicodeWriter_WriteSubstring((_PyUnicodeWriter*)writer, str,
393
650k
                                           start, end);
394
650k
}
395
396
397
int
398
_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
399
                                  const char *ascii, Py_ssize_t len)
400
47.7M
{
401
47.7M
    if (len == -1)
402
0
        len = strlen(ascii);
403
404
47.7M
    if (len == 0) {
405
82.0k
        return 0;
406
82.0k
    }
407
408
47.7M
    assert(ucs1lib_find_max_char((const Py_UCS1*)ascii, (const Py_UCS1*)ascii + len) <= 127);
409
410
47.6M
    if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
411
0
        return -1;
412
0
    }
413
47.6M
    assert(_PyUnicodeWriter_CanWrite(writer));
414
415
47.6M
    switch (writer->kind)
416
47.6M
    {
417
47.6M
    case PyUnicode_1BYTE_KIND:
418
47.6M
    {
419
47.6M
        const Py_UCS1 *str = (const Py_UCS1 *)ascii;
420
47.6M
        Py_UCS1 *data = writer->data;
421
422
47.6M
        memcpy(data + writer->pos, str, len);
423
47.6M
        break;
424
0
    }
425
14.8k
    case PyUnicode_2BYTE_KIND:
426
14.8k
    {
427
14.8k
        _PyUnicode_CONVERT_BYTES(
428
14.8k
            Py_UCS1, Py_UCS2,
429
14.8k
            ascii, ascii + len,
430
14.8k
            (Py_UCS2 *)writer->data + writer->pos);
431
14.8k
        break;
432
0
    }
433
9.25k
    case PyUnicode_4BYTE_KIND:
434
9.25k
    {
435
9.25k
        _PyUnicode_CONVERT_BYTES(
436
9.25k
            Py_UCS1, Py_UCS4,
437
9.25k
            ascii, ascii + len,
438
9.25k
            (Py_UCS4 *)writer->data + writer->pos);
439
9.25k
        break;
440
0
    }
441
0
    default:
442
0
        Py_UNREACHABLE();
443
47.6M
    }
444
445
47.6M
    writer->pos += len;
446
47.6M
    return 0;
447
47.6M
}
448
449
450
int
451
PyUnicodeWriter_WriteASCII(PyUnicodeWriter *writer,
452
                           const char *str,
453
                           Py_ssize_t size)
454
556k
{
455
556k
    assert(writer != NULL);
456
556k
    _Py_AssertHoldsTstate();
457
458
556k
    return _PyUnicodeWriter_WriteASCIIString((_PyUnicodeWriter*)writer, str, size);
459
556k
}
460
461
462
int
463
PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer,
464
                          const char *str,
465
                          Py_ssize_t size)
466
0
{
467
0
    if (size < 0) {
468
0
        size = strlen(str);
469
0
    }
470
471
0
    return _PyUnicode_DecodeUTF8Writer((_PyUnicodeWriter*)writer, str, size,
472
0
                                       _Py_ERROR_STRICT, NULL, NULL);
473
0
}
474
475
476
int
477
PyUnicodeWriter_DecodeUTF8Stateful(PyUnicodeWriter *writer,
478
                                   const char *str,
479
                                   Py_ssize_t size,
480
                                   const char *errors,
481
                                   Py_ssize_t *consumed)
482
0
{
483
0
    if (size < 0) {
484
0
        size = strlen(str);
485
0
    }
486
487
0
    return _PyUnicode_DecodeUTF8Writer((_PyUnicodeWriter*)writer, str, size,
488
0
                                       _Py_ERROR_UNKNOWN, errors,
489
0
                                       consumed);
490
0
}
491
492
493
int
494
_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
495
                                   const char *str, Py_ssize_t len)
496
0
{
497
0
    if (len == 0) {
498
0
        return 0;
499
0
    }
500
501
0
    const Py_UCS1 *ucs1 = (const Py_UCS1 *)str;
502
0
    Py_UCS4 maxchar = ucs1lib_find_max_char(ucs1, ucs1 + len);
503
0
    if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0) {
504
0
        return -1;
505
0
    }
506
0
    assert(_PyUnicodeWriter_CanWrite(writer));
507
508
0
    Py_ssize_t index = writer->pos;
509
0
    switch (writer->kind) {
510
0
    case PyUnicode_1BYTE_KIND: {
511
0
        memcpy((Py_UCS1 *)writer->data + index, ucs1, len);
512
0
        break;
513
0
    }
514
0
    case PyUnicode_2BYTE_KIND: {
515
0
        Py_UCS2 *ucs2 = (Py_UCS2 *)writer->data + index;
516
0
        const Py_UCS1 *end = ucs1 + len;
517
0
        for (; ucs1 < end; ++ucs2, ++ucs1) {
518
0
            *ucs2 = (Py_UCS2)*ucs1;
519
0
        }
520
0
        break;
521
0
    }
522
0
    case PyUnicode_4BYTE_KIND: {
523
0
        Py_UCS4 *ucs4 = (Py_UCS4 *)writer->data + index;
524
0
        const Py_UCS1 *end = ucs1 + len;
525
0
        for (; ucs1 < end; ++ucs4, ++ucs1) {
526
0
            *ucs4 = (Py_UCS4)*ucs1;
527
0
        }
528
0
        break;
529
0
    }
530
0
    default:
531
0
        Py_UNREACHABLE();
532
0
    }
533
534
0
    writer->pos += len;
535
0
    return 0;
536
0
}
537
538
539
PyObject *
540
_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
541
59.4M
{
542
#ifdef Py_DEBUG
543
    // Check for buffer overflow
544
    if (writer->buffer != NULL) {
545
        Py_ssize_t pos = PyUnicode_GET_LENGTH(writer->buffer);
546
        Py_UCS4 ch = PyUnicode_READ_CHAR(writer->buffer, pos);
547
        if (ch != 0) {
548
            _Py_FatalErrorFormat(__func__,
549
                                 "Buffer overflow detected in "
550
                                 "PyUnicodeWriter %p at position %zd",
551
                                 writer, pos);
552
        }
553
    }
554
#endif
555
556
59.4M
    PyObject *str = writer->buffer;
557
59.4M
    writer->buffer = NULL;
558
559
59.4M
    Py_ssize_t final_size = writer->pos;
560
59.4M
    if (final_size == 0) {
561
        // Get the empty string singleton
562
1.53k
        PyObject *empty = _PyUnicode_GetEmpty();
563
1.53k
        Py_XDECREF(str);  // writer->buffer can be NULL if the position is 0
564
1.53k
        return empty;
565
1.53k
    }
566
567
59.4M
    if (writer->readonly) {
568
29.6k
        assert(final_size == PyUnicode_GET_LENGTH(str));
569
29.6k
        goto done;
570
29.6k
    }
571
59.4M
    assert(final_size <= PyUnicode_GET_LENGTH(str));
572
573
59.4M
    if (final_size == 1 && PyUnicode_KIND(str) == PyUnicode_1BYTE_KIND) {
574
        // Get the single character singleton
575
157k
        assert(PyUnicode_GET_LENGTH(str) >= 1);
576
157k
        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(str);
577
157k
        Py_UCS1 ch = data[0];
578
157k
        Py_DECREF(str);
579
157k
        str = _Py_LATIN1_CHR(ch);
580
157k
        goto done;
581
157k
    }
582
583
59.2M
    if (writer->recheck_maxchar) {
584
0
        Py_UCS4 maxchar = _PyUnicode_FindMaxChar(str, 0, final_size);
585
0
        if (maxchar != writer->maxchar) {
586
            // Adjust the string kind
587
0
            PyObject *str2 = PyUnicode_New(final_size, maxchar);
588
0
            if (str2 == NULL) {
589
0
                Py_DECREF(str);
590
0
                return NULL;
591
0
            }
592
0
            _PyUnicode_FastCopyCharacters(str2, 0, str, 0, final_size);
593
0
            Py_SETREF(str, str2);
594
0
            goto done;
595
0
        }
596
0
    }
597
598
59.2M
    if (PyUnicode_GET_LENGTH(str) != final_size) {
599
        // Truncate the string
600
44.8M
        PyObject *str2 = _PyUnicode_ResizeCompact(str, final_size);
601
44.8M
        if (str2 == NULL) {
602
0
            Py_DECREF(str);
603
0
            return NULL;
604
0
        }
605
44.8M
        str = str2;
606
44.8M
        goto done;
607
44.8M
    }
608
609
59.4M
done:
610
59.4M
    assert(_PyUnicode_CheckConsistency(str, 1));
611
59.4M
    return str;
612
59.2M
}
613
614
615
PyObject *
616
_PyUnicodeWriter_FinishWithSize(_PyUnicodeWriter *writer, Py_ssize_t size)
617
0
{
618
0
    assert(0 <= size);
619
0
    if (writer->buffer != NULL) {
620
0
        assert(size <= writer->pos);
621
0
        assert(size <= PyUnicode_GET_LENGTH(writer->buffer));
622
0
        if (size < writer->pos) {
623
            // Truncate the string: we may need to adjust the string kind
624
0
            writer->recheck_maxchar = 1;
625
0
        }
626
0
    }
627
0
    else {
628
0
        assert(size == 0);
629
0
    }
630
0
    writer->pos = size;
631
0
    return _PyUnicodeWriter_Finish(writer);
632
0
}
633
634
635
PyObject*
636
PyUnicodeWriter_Finish(PyUnicodeWriter *writer)
637
4.47M
{
638
4.47M
    PyObject *str = _PyUnicodeWriter_Finish((_PyUnicodeWriter*)writer);
639
4.47M
    assert(((_PyUnicodeWriter*)writer)->buffer == NULL);
640
4.47M
    _Py_FREELIST_FREE(unicode_writers, writer, PyMem_Free);
641
4.47M
    return str;
642
4.47M
}
643
644
645
void
646
_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
647
3.38M
{
648
    Py_CLEAR(writer->buffer);
649
3.38M
}