Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/_io/textio.c
Line
Count
Source
1
/*
2
    An implementation of Text I/O as defined by PEP 3116 - "New I/O"
3
4
    Classes defined here: TextIOBase, IncrementalNewlineDecoder, TextIOWrapper.
5
6
    Written by Amaury Forgeot d'Arc and Antoine Pitrou
7
*/
8
9
#include "Python.h"
10
#include "pycore_call.h"          // _PyObject_CallMethod()
11
#include "pycore_codecs.h"        // _PyCodecInfo_GetIncrementalDecoder()
12
#include "pycore_fileutils.h"     // _Py_GetLocaleEncoding()
13
#include "pycore_interp.h"        // PyInterpreterState.fs_codec
14
#include "pycore_long.h"          // _PyLong_GetZero()
15
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
16
#include "pycore_pyerrors.h"      // _PyErr_ChainExceptions1()
17
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
18
#include "pycore_unicodeobject.h" // _PyUnicode_AsASCIIString()
19
20
#include "_iomodule.h"
21
22
/*[clinic input]
23
module _io
24
class _io.IncrementalNewlineDecoder "nldecoder_object *" "clinic_state()->PyIncrementalNewlineDecoder_Type"
25
class _io.TextIOWrapper "textio *" "clinic_state()->TextIOWrapper_Type"
26
class _io._TextIOBase "PyObject *" "&PyTextIOBase_Type"
27
[clinic start generated code]*/
28
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=8b7f24fa13bfdd7f]*/
29
30
typedef struct nldecoder_object nldecoder_object;
31
typedef struct textio textio;
32
33
#define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
34
#include "clinic/textio.c.h"
35
#undef clinic_state
36
37
/* TextIOBase */
38
39
PyDoc_STRVAR(textiobase_doc,
40
    "Base class for text I/O.\n"
41
    "\n"
42
    "This class provides a character and line based interface to stream\n"
43
    "I/O. There is no readinto method because Python's character strings\n"
44
    "are immutable.\n"
45
    );
46
47
static PyObject *
48
_unsupported(_PyIO_State *state, const char *message)
49
0
{
50
0
    PyErr_SetString(state->unsupported_operation, message);
51
0
    return NULL;
52
0
}
53
54
/*[clinic input]
55
_io._TextIOBase.detach
56
    cls: defining_class
57
    /
58
59
Separate the underlying buffer from the TextIOBase and return it.
60
61
After the underlying buffer has been detached, the TextIO is in
62
an unusable state.
63
[clinic start generated code]*/
64
65
static PyObject *
66
_io__TextIOBase_detach_impl(PyObject *self, PyTypeObject *cls)
67
/*[clinic end generated code: output=50915f40c609eaa4 input=8099c088abcb87d8]*/
68
0
{
69
0
    _PyIO_State *state = get_io_state_by_cls(cls);
70
0
    return _unsupported(state, "detach");
71
0
}
72
73
/*[clinic input]
74
_io._TextIOBase.read
75
    cls: defining_class
76
    size: int(unused=True) = -1
77
    /
78
79
Read at most size characters from stream.
80
81
Read from underlying buffer until we have size characters or we hit
82
EOF.  If size is negative or omitted, read until EOF.
83
[clinic start generated code]*/
84
85
static PyObject *
86
_io__TextIOBase_read_impl(PyObject *self, PyTypeObject *cls,
87
                          int Py_UNUSED(size))
88
/*[clinic end generated code: output=51a5178a309ce647 input=c9fd4cc1cf1b4614]*/
89
0
{
90
0
    _PyIO_State *state = get_io_state_by_cls(cls);
91
0
    return _unsupported(state, "read");
92
0
}
93
94
/*[clinic input]
95
_io._TextIOBase.readline
96
    cls: defining_class
97
    size: int(unused=True) = -1
98
    /
99
100
Read until newline or EOF.
101
102
Return an empty string if EOF is hit immediately.
103
If size is specified, at most size characters will be read.
104
[clinic start generated code]*/
105
106
static PyObject *
107
_io__TextIOBase_readline_impl(PyObject *self, PyTypeObject *cls,
108
                              int Py_UNUSED(size))
109
/*[clinic end generated code: output=3f47d7966d6d074e input=42eafec94107fa27]*/
110
0
{
111
0
    _PyIO_State *state = get_io_state_by_cls(cls);
112
0
    return _unsupported(state, "readline");
113
0
}
114
115
/*[clinic input]
116
_io._TextIOBase.write
117
    cls: defining_class
118
    s: str(unused=True)
119
    /
120
121
Write string s to stream.
122
123
Return the number of characters written
124
(which is always equal to the length of the string).
125
[clinic start generated code]*/
126
127
static PyObject *
128
_io__TextIOBase_write_impl(PyObject *self, PyTypeObject *cls,
129
                           const char *Py_UNUSED(s))
130
/*[clinic end generated code: output=18b28231460275de input=e9cabaa5f6732b07]*/
131
0
{
132
0
    _PyIO_State *state = get_io_state_by_cls(cls);
133
0
    return _unsupported(state, "write");
134
0
}
135
136
/*[clinic input]
137
@getter
138
_io._TextIOBase.encoding
139
140
Encoding of the text stream.
141
142
Subclasses should override.
143
[clinic start generated code]*/
144
145
static PyObject *
146
_io__TextIOBase_encoding_get_impl(PyObject *self)
147
/*[clinic end generated code: output=e0f5d8f548b92432 input=4736d7621dd38f43]*/
148
0
{
149
0
    Py_RETURN_NONE;
150
0
}
151
152
/*[clinic input]
153
@getter
154
_io._TextIOBase.newlines
155
156
Line endings translated so far.
157
158
Only line endings translated during reading are considered.
159
160
Subclasses should override.
161
[clinic start generated code]*/
162
163
static PyObject *
164
_io__TextIOBase_newlines_get_impl(PyObject *self)
165
/*[clinic end generated code: output=46ec147fb9f00c2a input=a5b196d076af1164]*/
166
0
{
167
0
    Py_RETURN_NONE;
168
0
}
169
170
/*[clinic input]
171
@getter
172
_io._TextIOBase.errors
173
174
The error setting of the decoder or encoder.
175
176
Subclasses should override.
177
[clinic start generated code]*/
178
179
static PyObject *
180
_io__TextIOBase_errors_get_impl(PyObject *self)
181
/*[clinic end generated code: output=c6623d6addcd087d input=974aa52d1db93a82]*/
182
0
{
183
0
    Py_RETURN_NONE;
184
0
}
185
186
187
static PyMethodDef textiobase_methods[] = {
188
    _IO__TEXTIOBASE_DETACH_METHODDEF
189
    _IO__TEXTIOBASE_READ_METHODDEF
190
    _IO__TEXTIOBASE_READLINE_METHODDEF
191
    _IO__TEXTIOBASE_WRITE_METHODDEF
192
    {NULL, NULL}
193
};
194
195
static PyGetSetDef textiobase_getset[] = {
196
    _IO__TEXTIOBASE_ENCODING_GETSETDEF
197
    _IO__TEXTIOBASE_NEWLINES_GETSETDEF
198
    _IO__TEXTIOBASE_ERRORS_GETSETDEF
199
    {NULL}
200
};
201
202
static PyType_Slot textiobase_slots[] = {
203
    {Py_tp_doc, (void *)textiobase_doc},
204
    {Py_tp_methods, textiobase_methods},
205
    {Py_tp_getset, textiobase_getset},
206
    {0, NULL},
207
};
208
209
/* Do not set Py_TPFLAGS_HAVE_GC so that tp_traverse and tp_clear are inherited */
210
PyType_Spec _Py_textiobase_spec = {
211
    .name = "_io._TextIOBase",
212
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
213
              Py_TPFLAGS_IMMUTABLETYPE),
214
    .slots = textiobase_slots,
215
};
216
217
/* IncrementalNewlineDecoder */
218
219
struct nldecoder_object {
220
    PyObject_HEAD
221
    PyObject *decoder;
222
    PyObject *errors;
223
    unsigned int pendingcr: 1;
224
    unsigned int translate: 1;
225
    unsigned int seennl: 3;
226
};
227
228
107k
#define nldecoder_object_CAST(op)   ((nldecoder_object *)(op))
229
230
/*[clinic input]
231
@vectorcall
232
_io.IncrementalNewlineDecoder.__init__
233
    decoder: object
234
    translate: bool
235
    errors: object(c_default="NULL") = "strict"
236
237
Codec used when reading a file in universal newlines mode.
238
239
It wraps another incremental decoder, translating \r\n and \r into \n.
240
It also records the types of newlines encountered.  When used with
241
translate=False, it ensures that the newline sequence is returned in
242
one piece. When used with decoder=None, it expects unicode strings as
243
decode input and translates newlines without first invoking an external
244
decoder.
245
[clinic start generated code]*/
246
247
static int
248
_io_IncrementalNewlineDecoder___init___impl(nldecoder_object *self,
249
                                            PyObject *decoder, int translate,
250
                                            PyObject *errors)
251
/*[clinic end generated code: output=fbd04d443e764ec2 input=7fd0efad15bc0b69]*/
252
16.7k
{
253
254
16.7k
    if (errors == NULL) {
255
16.7k
        errors = &_Py_ID(strict);
256
16.7k
    }
257
0
    else {
258
0
        errors = Py_NewRef(errors);
259
0
    }
260
261
16.7k
    Py_XSETREF(self->errors, errors);
262
16.7k
    Py_XSETREF(self->decoder, Py_NewRef(decoder));
263
16.7k
    self->translate = translate ? 1 : 0;
264
16.7k
    self->seennl = 0;
265
16.7k
    self->pendingcr = 0;
266
267
16.7k
    return 0;
268
16.7k
}
269
270
static int
271
incrementalnewlinedecoder_traverse(PyObject *op, visitproc visit, void *arg)
272
5.94k
{
273
5.94k
    nldecoder_object *self = nldecoder_object_CAST(op);
274
5.94k
    Py_VISIT(Py_TYPE(self));
275
5.94k
    Py_VISIT(self->decoder);
276
5.94k
    Py_VISIT(self->errors);
277
5.94k
    return 0;
278
5.94k
}
279
280
static int
281
incrementalnewlinedecoder_clear(PyObject *op)
282
16.7k
{
283
16.7k
    nldecoder_object *self = nldecoder_object_CAST(op);
284
16.7k
    Py_CLEAR(self->decoder);
285
16.7k
    Py_CLEAR(self->errors);
286
16.7k
    return 0;
287
16.7k
}
288
289
static void
290
incrementalnewlinedecoder_dealloc(PyObject *op)
291
16.7k
{
292
16.7k
    nldecoder_object *self = nldecoder_object_CAST(op);
293
16.7k
    PyTypeObject *tp = Py_TYPE(self);
294
16.7k
    _PyObject_GC_UNTRACK(self);
295
16.7k
    (void)incrementalnewlinedecoder_clear(op);
296
16.7k
    tp->tp_free(self);
297
16.7k
    Py_DECREF(tp);
298
16.7k
}
299
300
static int
301
check_decoded(PyObject *decoded)
302
67.7k
{
303
67.7k
    if (decoded == NULL)
304
0
        return -1;
305
67.7k
    if (!PyUnicode_Check(decoded)) {
306
0
        PyErr_Format(PyExc_TypeError,
307
0
                     "decoder should return a string result, not '%.200s'",
308
0
                     Py_TYPE(decoded)->tp_name);
309
0
        Py_DECREF(decoded);
310
0
        return -1;
311
0
    }
312
67.7k
    return 0;
313
67.7k
}
314
315
#define CHECK_INITIALIZED_DECODER(self) \
316
67.6k
    if (self->errors == NULL) { \
317
0
        PyErr_SetString(PyExc_ValueError, \
318
0
                        "IncrementalNewlineDecoder.__init__() not called"); \
319
0
        return NULL; \
320
0
    }
321
322
38.3M
#define SEEN_CR   1
323
32.1M
#define SEEN_LF   2
324
30.4M
#define SEEN_CRLF 4
325
30.4M
#define SEEN_ALL (SEEN_CR | SEEN_LF | SEEN_CRLF)
326
327
PyObject *
328
_PyIncrementalNewlineDecoder_decode(PyObject *myself,
329
                                    PyObject *input, int final)
330
67.6k
{
331
67.6k
    PyObject *output;
332
67.6k
    Py_ssize_t output_len;
333
67.6k
    nldecoder_object *self = nldecoder_object_CAST(myself);
334
335
67.6k
    CHECK_INITIALIZED_DECODER(self);
336
337
    /* decode input (with the eventual \r from a previous pass) */
338
67.6k
    if (self->decoder != Py_None) {
339
        /* The wrapper can be reinitialized by a decoding callback. */
340
138
        PyObject *decoder = Py_NewRef(self->decoder);
341
138
        output = PyObject_CallMethodObjArgs(decoder,
342
138
            &_Py_ID(decode), input, final ? Py_True : Py_False, NULL);
343
138
        Py_DECREF(decoder);
344
138
    }
345
67.4k
    else {
346
67.4k
        output = Py_NewRef(input);
347
67.4k
    }
348
349
67.6k
    if (check_decoded(output) < 0)
350
0
        return NULL;
351
352
67.6k
    output_len = PyUnicode_GET_LENGTH(output);
353
67.6k
    if (self->pendingcr && (final || output_len > 0)) {
354
        /* Prefix output with CR */
355
0
        int kind;
356
0
        PyObject *modified;
357
0
        char *out;
358
359
0
        modified = PyUnicode_New(output_len + 1,
360
0
                                 PyUnicode_MAX_CHAR_VALUE(output));
361
0
        if (modified == NULL)
362
0
            goto error;
363
0
        kind = PyUnicode_KIND(modified);
364
0
        out = PyUnicode_DATA(modified);
365
0
        PyUnicode_WRITE(kind, out, 0, '\r');
366
0
        memcpy(out + kind, PyUnicode_DATA(output), kind * output_len);
367
0
        Py_SETREF(output, modified);
368
0
        self->pendingcr = 0;
369
0
        output_len++;
370
0
    }
371
372
    /* retain last \r even when not translating data:
373
     * then readline() is sure to get \r\n in one pass
374
     */
375
67.6k
    if (!final) {
376
120
        if (output_len > 0
377
120
            && PyUnicode_READ_CHAR(output, output_len - 1) == '\r')
378
0
        {
379
0
            PyObject *modified = PyUnicode_Substring(output, 0, output_len -1);
380
0
            if (modified == NULL)
381
0
                goto error;
382
0
            Py_SETREF(output, modified);
383
0
            self->pendingcr = 1;
384
0
        }
385
120
    }
386
387
    /* Record which newlines are read and do newline translation if desired,
388
       all in one pass. */
389
67.6k
    {
390
67.6k
        const void *in_str;
391
67.6k
        Py_ssize_t len;
392
67.6k
        int seennl = self->seennl;
393
67.6k
        int only_lf = 0;
394
67.6k
        int kind;
395
396
67.6k
        in_str = PyUnicode_DATA(output);
397
67.6k
        len = PyUnicode_GET_LENGTH(output);
398
67.6k
        kind = PyUnicode_KIND(output);
399
400
67.6k
        if (len == 0)
401
10
            return output;
402
403
        /* If, up to now, newlines are consistently \n, do a quick check
404
           for the \r *byte* with the libc's optimized memchr.
405
           */
406
67.6k
        if (seennl == SEEN_LF || seennl == 0) {
407
32.2k
            only_lf = (memchr(in_str, '\r', kind * len) == NULL);
408
32.2k
        }
409
410
67.6k
        if (only_lf) {
411
            /* If not already seen, quick scan for a possible "\n" character.
412
               (there's nothing else to be done, even when in translation mode)
413
            */
414
25.7k
            if (seennl == 0 &&
415
17.8k
                memchr(in_str, '\n', kind * len) != NULL) {
416
1.97k
                if (kind == PyUnicode_1BYTE_KIND)
417
929
                    seennl |= SEEN_LF;
418
1.04k
                else {
419
1.04k
                    Py_ssize_t i = 0;
420
195k
                    for (;;) {
421
195k
                        Py_UCS4 c;
422
                        /* Fast loop for non-control characters */
423
1.40M
                        while (PyUnicode_READ(kind, in_str, i) > '\n')
424
1.20M
                            i++;
425
195k
                        c = PyUnicode_READ(kind, in_str, i++);
426
195k
                        if (c == '\n') {
427
807
                            seennl |= SEEN_LF;
428
807
                            break;
429
807
                        }
430
194k
                        if (i >= len)
431
238
                            break;
432
194k
                    }
433
1.04k
                }
434
1.97k
            }
435
            /* Finished: we have scanned for newlines, and none of them
436
               need translating */
437
25.7k
        }
438
41.8k
        else if (!self->translate) {
439
41.8k
            Py_ssize_t i = 0;
440
            /* We have already seen all newline types, no need to scan again */
441
41.8k
            if (seennl == SEEN_ALL)
442
14.9k
                goto endscan;
443
30.4M
            for (;;) {
444
30.4M
                Py_UCS4 c;
445
                /* Fast loop for non-control characters */
446
87.0M
                while (PyUnicode_READ(kind, in_str, i) > '\r')
447
56.5M
                    i++;
448
30.4M
                c = PyUnicode_READ(kind, in_str, i++);
449
30.4M
                if (c == '\n')
450
1.49M
                    seennl |= SEEN_LF;
451
28.9M
                else if (c == '\r') {
452
7.84M
                    if (PyUnicode_READ(kind, in_str, i) == '\n') {
453
4.70k
                        seennl |= SEEN_CRLF;
454
4.70k
                        i++;
455
4.70k
                    }
456
7.83M
                    else
457
7.83M
                        seennl |= SEEN_CR;
458
7.84M
                }
459
30.4M
                if (i >= len)
460
25.5k
                    break;
461
30.4M
                if (seennl == SEEN_ALL)
462
1.34k
                    break;
463
30.4M
            }
464
41.8k
        endscan:
465
41.8k
            ;
466
41.8k
        }
467
0
        else {
468
0
            void *translated;
469
0
            int kind = PyUnicode_KIND(output);
470
0
            const void *in_str = PyUnicode_DATA(output);
471
0
            Py_ssize_t in, out;
472
            /* XXX: Previous in-place translation here is disabled as
473
               resizing is not possible anymore */
474
            /* We could try to optimize this so that we only do a copy
475
               when there is something to translate. On the other hand,
476
               we already know there is a \r byte, so chances are high
477
               that something needs to be done. */
478
0
            translated = PyMem_Malloc(kind * len);
479
0
            if (translated == NULL) {
480
0
                PyErr_NoMemory();
481
0
                goto error;
482
0
            }
483
0
            in = out = 0;
484
0
            for (;;) {
485
0
                Py_UCS4 c;
486
                /* Fast loop for non-control characters */
487
0
                while ((c = PyUnicode_READ(kind, in_str, in++)) > '\r')
488
0
                    PyUnicode_WRITE(kind, translated, out++, c);
489
0
                if (c == '\n') {
490
0
                    PyUnicode_WRITE(kind, translated, out++, c);
491
0
                    seennl |= SEEN_LF;
492
0
                    continue;
493
0
                }
494
0
                if (c == '\r') {
495
0
                    if (PyUnicode_READ(kind, in_str, in) == '\n') {
496
0
                        in++;
497
0
                        seennl |= SEEN_CRLF;
498
0
                    }
499
0
                    else
500
0
                        seennl |= SEEN_CR;
501
0
                    PyUnicode_WRITE(kind, translated, out++, '\n');
502
0
                    continue;
503
0
                }
504
0
                if (in > len)
505
0
                    break;
506
0
                PyUnicode_WRITE(kind, translated, out++, c);
507
0
            }
508
0
            Py_DECREF(output);
509
0
            output = PyUnicode_FromKindAndData(kind, translated, out);
510
0
            PyMem_Free(translated);
511
0
            if (!output)
512
0
                return NULL;
513
0
        }
514
67.6k
        self->seennl |= seennl;
515
67.6k
    }
516
517
0
    return output;
518
519
0
  error:
520
0
    Py_DECREF(output);
521
0
    return NULL;
522
67.6k
}
523
524
/*[clinic input]
525
@critical_section
526
_io.IncrementalNewlineDecoder.decode
527
    input: object
528
    final: bool = False
529
[clinic start generated code]*/
530
531
static PyObject *
532
_io_IncrementalNewlineDecoder_decode_impl(nldecoder_object *self,
533
                                          PyObject *input, int final)
534
/*[clinic end generated code: output=0d486755bb37a66e input=9475d16a73168504]*/
535
0
{
536
0
    return _PyIncrementalNewlineDecoder_decode((PyObject *) self, input, final);
537
0
}
538
539
/*[clinic input]
540
@critical_section
541
_io.IncrementalNewlineDecoder.getstate
542
[clinic start generated code]*/
543
544
static PyObject *
545
_io_IncrementalNewlineDecoder_getstate_impl(nldecoder_object *self)
546
/*[clinic end generated code: output=f0d2c9c136f4e0d0 input=dc3e1f27aa850f12]*/
547
0
{
548
0
    PyObject *buffer;
549
0
    unsigned long long flag;
550
551
0
    CHECK_INITIALIZED_DECODER(self);
552
553
0
    if (self->decoder != Py_None) {
554
0
        PyObject *state = PyObject_CallMethodNoArgs(self->decoder,
555
0
           &_Py_ID(getstate));
556
0
        if (state == NULL)
557
0
            return NULL;
558
0
        if (!PyTuple_Check(state)) {
559
0
            PyErr_SetString(PyExc_TypeError,
560
0
                            "illegal decoder state");
561
0
            Py_DECREF(state);
562
0
            return NULL;
563
0
        }
564
0
        if (!PyArg_ParseTuple(state, "OK;illegal decoder state",
565
0
                              &buffer, &flag))
566
0
        {
567
0
            Py_DECREF(state);
568
0
            return NULL;
569
0
        }
570
0
        Py_INCREF(buffer);
571
0
        Py_DECREF(state);
572
0
    }
573
0
    else {
574
0
        buffer = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
575
0
        flag = 0;
576
0
    }
577
0
    flag <<= 1;
578
0
    if (self->pendingcr)
579
0
        flag |= 1;
580
0
    return Py_BuildValue("NK", buffer, flag);
581
0
}
582
583
/*[clinic input]
584
@critical_section
585
_io.IncrementalNewlineDecoder.setstate
586
    state: object
587
    /
588
[clinic start generated code]*/
589
590
static PyObject *
591
_io_IncrementalNewlineDecoder_setstate_impl(nldecoder_object *self,
592
                                            PyObject *state)
593
/*[clinic end generated code: output=09135cb6e78a1dc8 input=275fd3982d2b08cb]*/
594
0
{
595
0
    PyObject *buffer;
596
0
    unsigned long long flag;
597
598
0
    CHECK_INITIALIZED_DECODER(self);
599
600
0
    if (!PyTuple_Check(state)) {
601
0
        PyErr_SetString(PyExc_TypeError, "state argument must be a tuple");
602
0
        return NULL;
603
0
    }
604
0
    if (!PyArg_ParseTuple(state, "OK;setstate(): illegal state argument",
605
0
                          &buffer, &flag))
606
0
    {
607
0
        return NULL;
608
0
    }
609
610
0
    self->pendingcr = (int) (flag & 1);
611
0
    flag >>= 1;
612
613
0
    if (self->decoder != Py_None) {
614
0
        return _PyObject_CallMethod(self->decoder, &_Py_ID(setstate),
615
0
                                    "((OK))", buffer, flag);
616
0
    }
617
0
    else {
618
0
        Py_RETURN_NONE;
619
0
    }
620
0
}
621
622
/*[clinic input]
623
@critical_section
624
_io.IncrementalNewlineDecoder.reset
625
[clinic start generated code]*/
626
627
static PyObject *
628
_io_IncrementalNewlineDecoder_reset_impl(nldecoder_object *self)
629
/*[clinic end generated code: output=32fa40c7462aa8ff input=31bd8ae4e36cec83]*/
630
0
{
631
0
    CHECK_INITIALIZED_DECODER(self);
632
633
0
    self->seennl = 0;
634
0
    self->pendingcr = 0;
635
0
    if (self->decoder != Py_None)
636
0
        return PyObject_CallMethodNoArgs(self->decoder, &_Py_ID(reset));
637
0
    else
638
0
        Py_RETURN_NONE;
639
0
}
640
641
/*[clinic input]
642
@getter
643
_io.IncrementalNewlineDecoder.newlines
644
[clinic start generated code]*/
645
646
static PyObject *
647
_io_IncrementalNewlineDecoder_newlines_get_impl(nldecoder_object *self)
648
/*[clinic end generated code: output=4370cf5202a83d08 input=040f9a26aef317a8]*/
649
0
{
650
0
    CHECK_INITIALIZED_DECODER(self);
651
652
0
    switch (self->seennl) {
653
0
    case SEEN_CR:
654
0
        return PyUnicode_FromString("\r");
655
0
    case SEEN_LF:
656
0
        return PyUnicode_FromString("\n");
657
0
    case SEEN_CRLF:
658
0
        return PyUnicode_FromString("\r\n");
659
0
    case SEEN_CR | SEEN_LF:
660
0
        return Py_BuildValue("ss", "\r", "\n");
661
0
    case SEEN_CR | SEEN_CRLF:
662
0
        return Py_BuildValue("ss", "\r", "\r\n");
663
0
    case SEEN_LF | SEEN_CRLF:
664
0
        return Py_BuildValue("ss", "\n", "\r\n");
665
0
    case SEEN_CR | SEEN_LF | SEEN_CRLF:
666
0
        return Py_BuildValue("sss", "\r", "\n", "\r\n");
667
0
    default:
668
0
        Py_RETURN_NONE;
669
0
   }
670
671
0
}
672
673
/* TextIOWrapper */
674
675
typedef PyObject *(*encodefunc_t)(PyObject *, PyObject *);
676
677
struct textio
678
{
679
    PyObject_HEAD
680
    int ok; /* initialized? */
681
    int detached;
682
    Py_ssize_t chunk_size;
683
    /* Use helpers buffer_*() functions to access buffer; many operations can set it to
684
       NULL (see gh-143008, gh-142594). */
685
    PyObject *buffer;
686
    PyObject *encoding;
687
    PyObject *encoder;
688
    PyObject *decoder;
689
    PyObject *readnl;
690
    PyObject *errors;
691
    const char *writenl; /* ASCII-encoded; NULL stands for \n */
692
    char line_buffering;
693
    char write_through;
694
    char readuniversal;
695
    char readtranslate;
696
    char writetranslate;
697
    char seekable;
698
    char has_read1;
699
    char telling;
700
    char finalizing;
701
    /* Specialized encoding func (see below) */
702
    encodefunc_t encodefunc;
703
    /* Whether or not it's the start of the stream */
704
    char encoding_start_of_stream;
705
706
    /* Reads and writes are internally buffered in order to speed things up.
707
       However, any read will first flush the write buffer if itsn't empty.
708
709
       Please also note that text to be written is first encoded before being
710
       buffered. This is necessary so that encoding errors are immediately
711
       reported to the caller, but it unfortunately means that the
712
       IncrementalEncoder (whose encode() method is always written in Python)
713
       becomes a bottleneck for small writes.
714
    */
715
    PyObject *decoded_chars;       /* buffer for text returned from decoder */
716
    Py_ssize_t decoded_chars_used; /* offset into _decoded_chars for read() */
717
    PyObject *pending_bytes;       // data waiting to be written.
718
                                   // ascii unicode, bytes, or list of them.
719
    Py_ssize_t pending_bytes_count;
720
721
    /* snapshot is either NULL, or a tuple (dec_flags, next_input) where
722
     * dec_flags is the second (integer) item of the decoder state and
723
     * next_input is the chunk of input bytes that comes next after the
724
     * snapshot point.  We use this to reconstruct decoder states in tell().
725
     */
726
    PyObject *snapshot;
727
    /* Bytes-to-characters ratio for the current chunk. Serves as input for
728
       the heuristic in tell(). */
729
    double b2cratio;
730
731
    /* Cache raw object if it's a FileIO object */
732
    PyObject *raw;
733
734
735
    _PyIO_State *state;
736
};
737
738
6.18k
#define textio_CAST(op) ((textio *)(op))
739
740
/* Helpers to safely operate on self->buffer.
741
742
   self->buffer can be detached (set to NULL) by any user code that is called
743
   leading to NULL pointer dereferences (see gh-143008, gh-142594). Protect
744
   against that by using helpers to check self->buffer validity at callsites. */
745
static PyObject *
746
buffer_access_safe(textio *self)
747
352k
{
748
    /* Check self->buffer directly but match errors of CHECK_ATTACHED since this
749
       is called during construction and finalization where self->ok == 0. */
750
352k
    if (self->buffer == NULL) {
751
0
        if (self->ok <= 0) {
752
0
            PyErr_SetString(PyExc_ValueError,
753
0
                            "I/O operation on uninitialized object");
754
0
        }
755
0
        else {
756
0
            PyErr_SetString(PyExc_ValueError,
757
0
                            "underlying buffer has been detached");
758
0
        }
759
0
        return NULL;
760
0
    }
761
762
352k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
763
352k
    return Py_NewRef(self->buffer);
764
352k
}
765
766
static PyObject *
767
buffer_getattr(textio *self, PyObject *attr_name)
768
67
{
769
67
    PyObject *buffer = buffer_access_safe(self);
770
67
    if (buffer == NULL) {
771
0
        return NULL;
772
0
    }
773
774
67
    PyObject *res = PyObject_GetAttr(buffer, attr_name);
775
67
    Py_DECREF(buffer);
776
67
    return res;
777
67
}
778
779
static PyObject *
780
buffer_callmethod_noargs(textio *self, PyObject *name)
781
381
{
782
381
    PyObject *buffer = buffer_access_safe(self);
783
381
    if (buffer == NULL) {
784
0
        return NULL;
785
0
    }
786
787
381
    PyObject *res = PyObject_CallMethodNoArgs(buffer, name);
788
381
    Py_DECREF(buffer);
789
381
    return res;
790
381
}
791
792
static PyObject *
793
buffer_callmethod_onearg(textio *self, PyObject *name, PyObject *arg)
794
175k
{
795
175k
    PyObject *buffer = buffer_access_safe(self);
796
175k
    if (buffer == NULL) {
797
0
        return NULL;
798
0
    }
799
800
175k
    PyObject *res = PyObject_CallMethodOneArg(buffer, name, arg);
801
175k
    Py_DECREF(buffer);
802
175k
    return res;
803
175k
}
804
805
static void
806
textiowrapper_set_decoded_chars(textio *self, PyObject *chars);
807
808
/* A couple of specialized cases in order to bypass the slow incremental
809
   encoding methods for the most popular encodings. */
810
811
static PyObject *
812
ascii_encode(PyObject *op, PyObject *text)
813
0
{
814
0
    textio *self = textio_CAST(op);
815
0
    return _PyUnicode_AsASCIIString(text, PyUnicode_AsUTF8(self->errors));
816
0
}
817
818
static PyObject *
819
utf16be_encode(PyObject *op, PyObject *text)
820
0
{
821
0
    textio *self = textio_CAST(op);
822
0
    return _PyUnicode_EncodeUTF16(text, PyUnicode_AsUTF8(self->errors), 1);
823
0
}
824
825
static PyObject *
826
utf16le_encode(PyObject *op, PyObject *text)
827
0
{
828
0
    textio *self = textio_CAST(op);
829
0
    return _PyUnicode_EncodeUTF16(text, PyUnicode_AsUTF8(self->errors), -1);
830
0
}
831
832
static PyObject *
833
utf16_encode(PyObject *op, PyObject *text)
834
0
{
835
0
    textio *self = textio_CAST(op);
836
0
    if (!self->encoding_start_of_stream) {
837
        /* Skip the BOM and use native byte ordering */
838
#if PY_BIG_ENDIAN
839
        return utf16be_encode(op, text);
840
#else
841
0
        return utf16le_encode(op, text);
842
0
#endif
843
0
    }
844
0
    return _PyUnicode_EncodeUTF16(text, PyUnicode_AsUTF8(self->errors), 0);
845
0
}
846
847
static PyObject *
848
utf32be_encode(PyObject *op, PyObject *text)
849
0
{
850
0
    textio *self = textio_CAST(op);
851
0
    return _PyUnicode_EncodeUTF32(text, PyUnicode_AsUTF8(self->errors), 1);
852
0
}
853
854
static PyObject *
855
utf32le_encode(PyObject *op, PyObject *text)
856
0
{
857
0
    textio *self = textio_CAST(op);
858
0
    return _PyUnicode_EncodeUTF32(text, PyUnicode_AsUTF8(self->errors), -1);
859
0
}
860
861
static PyObject *
862
utf32_encode(PyObject *op, PyObject *text)
863
0
{
864
0
    textio *self = textio_CAST(op);
865
0
    if (!self->encoding_start_of_stream) {
866
        /* Skip the BOM and use native byte ordering */
867
#if PY_BIG_ENDIAN
868
        return utf32be_encode(op, text);
869
#else
870
0
        return utf32le_encode(op, text);
871
0
#endif
872
0
    }
873
0
    return _PyUnicode_EncodeUTF32(text, PyUnicode_AsUTF8(self->errors), 0);
874
0
}
875
876
static PyObject *
877
utf8_encode(PyObject *op, PyObject *text)
878
31
{
879
31
    textio *self = textio_CAST(op);
880
31
    return _PyUnicode_AsUTF8String(text, PyUnicode_AsUTF8(self->errors));
881
31
}
882
883
static PyObject *
884
latin1_encode(PyObject *op, PyObject *text)
885
0
{
886
0
    textio *self = textio_CAST(op);
887
0
    return _PyUnicode_AsLatin1String(text, PyUnicode_AsUTF8(self->errors));
888
0
}
889
890
// Return true when encoding can be skipped when text is ascii.
891
static inline int
892
is_asciicompat_encoding(encodefunc_t f)
893
175k
{
894
175k
    return f == ascii_encode || f == latin1_encode || f == utf8_encode;
895
175k
}
896
897
/* Map normalized encoding names onto the specialized encoding funcs */
898
899
typedef struct {
900
    const char *name;
901
    encodefunc_t encodefunc;
902
} encodefuncentry;
903
904
static const encodefuncentry encodefuncs[] = {
905
    {"ascii",       ascii_encode},
906
    {"iso8859-1",   latin1_encode},
907
    {"utf-8",       utf8_encode},
908
    {"utf-16-be",   utf16be_encode},
909
    {"utf-16-le",   utf16le_encode},
910
    {"utf-16",      utf16_encode},
911
    {"utf-32-be",   utf32be_encode},
912
    {"utf-32-le",   utf32le_encode},
913
    {"utf-32",      utf32_encode},
914
    {NULL, NULL}
915
};
916
917
static int
918
validate_newline(const char *newline)
919
130
{
920
130
    if (newline && newline[0] != '\0'
921
111
        && !(newline[0] == '\n' && newline[1] == '\0')
922
0
        && !(newline[0] == '\r' && newline[1] == '\0')
923
0
        && !(newline[0] == '\r' && newline[1] == '\n' && newline[2] == '\0')) {
924
0
        PyErr_Format(PyExc_ValueError,
925
0
                     "illegal newline value: %s", newline);
926
0
        return -1;
927
0
    }
928
130
    return 0;
929
130
}
930
931
static int
932
set_newline(textio *self, const char *newline)
933
130
{
934
130
    PyObject *old = self->readnl;
935
130
    if (newline == NULL) {
936
19
        self->readnl = NULL;
937
19
    }
938
111
    else {
939
111
        self->readnl = PyUnicode_FromString(newline);
940
111
        if (self->readnl == NULL) {
941
0
            self->readnl = old;
942
0
            return -1;
943
0
        }
944
111
    }
945
130
    self->readuniversal = (newline == NULL || newline[0] == '\0');
946
130
    self->readtranslate = (newline == NULL);
947
130
    self->writetranslate = (newline == NULL || newline[0] != '\0');
948
130
    if (!self->readuniversal && self->readnl != NULL) {
949
        // validate_newline() accepts only ASCII newlines.
950
111
        assert(PyUnicode_KIND(self->readnl) == PyUnicode_1BYTE_KIND);
951
111
        self->writenl = (const char *)PyUnicode_1BYTE_DATA(self->readnl);
952
111
        if (strcmp(self->writenl, "\n") == 0) {
953
111
            self->writenl = NULL;
954
111
        }
955
111
    }
956
19
    else {
957
#ifdef MS_WINDOWS
958
        self->writenl = "\r\n";
959
#else
960
19
        self->writenl = NULL;
961
19
#endif
962
19
    }
963
130
    Py_XDECREF(old);
964
130
    return 0;
965
130
}
966
967
static int
968
_textiowrapper_set_decoder(textio *self, PyObject *codec_info,
969
                           const char *errors)
970
130
{
971
130
    PyObject *res;
972
130
    int r;
973
974
130
    res = buffer_callmethod_noargs(self, &_Py_ID(readable));
975
130
    if (res == NULL)
976
0
        return -1;
977
978
130
    r = PyObject_IsTrue(res);
979
130
    Py_DECREF(res);
980
130
    if (r == -1)
981
0
        return -1;
982
983
130
    if (r != 1)
984
75
        return 0;
985
986
55
    Py_CLEAR(self->decoder);
987
55
    self->decoder = _PyCodecInfo_GetIncrementalDecoder(codec_info, errors);
988
55
    if (self->decoder == NULL)
989
0
        return -1;
990
991
55
    if (self->readuniversal) {
992
18
        _PyIO_State *state = self->state;
993
18
        PyObject *incrementalDecoder = PyObject_CallFunctionObjArgs(
994
18
            (PyObject *)state->PyIncrementalNewlineDecoder_Type,
995
18
            self->decoder, self->readtranslate ? Py_True : Py_False, NULL);
996
18
        if (incrementalDecoder == NULL)
997
0
            return -1;
998
18
        Py_XSETREF(self->decoder, incrementalDecoder);
999
18
    }
1000
1001
55
    return 0;
1002
55
}
1003
1004
static PyObject*
1005
_textiowrapper_decode(_PyIO_State *state, PyObject *decoder, PyObject *bytes,
1006
                      int eof)
1007
138
{
1008
138
    PyObject *chars;
1009
1010
138
    if (decoder == NULL) {
1011
0
        return _unsupported(state, "not readable");
1012
0
    }
1013
    /* A codec callback may replace the wrapper's decoder. */
1014
138
    Py_INCREF(decoder);
1015
138
    if (Py_IS_TYPE(decoder, state->PyIncrementalNewlineDecoder_Type))
1016
138
        chars = _PyIncrementalNewlineDecoder_decode(decoder, bytes, eof);
1017
0
    else
1018
0
        chars = PyObject_CallMethodObjArgs(decoder, &_Py_ID(decode), bytes,
1019
0
                                           eof ? Py_True : Py_False, NULL);
1020
138
    Py_DECREF(decoder);
1021
1022
138
    if (check_decoded(chars) < 0)
1023
        // check_decoded already decreases refcount
1024
0
        return NULL;
1025
1026
138
    return chars;
1027
138
}
1028
1029
static int
1030
_textiowrapper_set_encoder(textio *self, PyObject *codec_info,
1031
                           const char *errors)
1032
130
{
1033
130
    PyObject *res;
1034
130
    int r;
1035
1036
130
    res = buffer_callmethod_noargs(self, &_Py_ID(writable));
1037
130
    if (res == NULL)
1038
0
        return -1;
1039
1040
130
    r = PyObject_IsTrue(res);
1041
130
    Py_DECREF(res);
1042
130
    if (r == -1)
1043
0
        return -1;
1044
1045
130
    if (r != 1)
1046
55
        return 0;
1047
1048
75
    Py_CLEAR(self->encoder);
1049
75
    self->encodefunc = NULL;
1050
75
    self->encoder = _PyCodecInfo_GetIncrementalEncoder(codec_info, errors);
1051
75
    if (self->encoder == NULL)
1052
0
        return -1;
1053
1054
    /* Get the normalized named of the codec */
1055
75
    if (PyObject_GetOptionalAttr(codec_info, &_Py_ID(name), &res) < 0) {
1056
0
        return -1;
1057
0
    }
1058
75
    if (res != NULL && PyUnicode_Check(res)) {
1059
75
        const encodefuncentry *e = encodefuncs;
1060
225
        while (e->name != NULL) {
1061
225
            if (_PyUnicode_EqualToASCIIString(res, e->name)) {
1062
75
                self->encodefunc = e->encodefunc;
1063
75
                break;
1064
75
            }
1065
150
            e++;
1066
150
        }
1067
75
    }
1068
75
    Py_XDECREF(res);
1069
1070
75
    return 0;
1071
75
}
1072
1073
static int
1074
_textiowrapper_fix_encoder_state(textio *self)
1075
130
{
1076
130
    if (!self->seekable || !self->encoder) {
1077
55
        return 0;
1078
55
    }
1079
1080
75
    self->encoding_start_of_stream = 1;
1081
1082
75
    PyObject *cookieObj = buffer_callmethod_noargs(self, &_Py_ID(tell));
1083
75
    if (cookieObj == NULL) {
1084
0
        return -1;
1085
0
    }
1086
1087
75
    int cmp = PyObject_RichCompareBool(cookieObj, _PyLong_GetZero(), Py_EQ);
1088
75
    Py_DECREF(cookieObj);
1089
75
    if (cmp < 0) {
1090
0
        return -1;
1091
0
    }
1092
1093
75
    if (cmp == 0) {
1094
36
        self->encoding_start_of_stream = 0;
1095
36
        PyObject *res = PyObject_CallMethodOneArg(
1096
36
            self->encoder, &_Py_ID(setstate), _PyLong_GetZero());
1097
36
        if (res == NULL) {
1098
0
            return -1;
1099
0
        }
1100
36
        Py_DECREF(res);
1101
36
    }
1102
1103
75
    return 0;
1104
75
}
1105
1106
static int
1107
io_check_errors(PyObject *errors)
1108
111
{
1109
111
    assert(errors != NULL && errors != Py_None);
1110
1111
111
    PyInterpreterState *interp = _PyInterpreterState_GET();
1112
111
#ifndef Py_DEBUG
1113
    /* In release mode, only check in development mode (-X dev) */
1114
111
    if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
1115
111
        return 0;
1116
111
    }
1117
#else
1118
    /* Always check in debug mode */
1119
#endif
1120
1121
    /* Avoid calling PyCodec_LookupError() before the codec registry is ready:
1122
       before_PyUnicode_InitEncodings() is called. */
1123
0
    if (!interp->unicode.fs_codec.encoding) {
1124
0
        return 0;
1125
0
    }
1126
1127
0
    const char *name = _PyUnicode_AsUTF8NoNUL(errors);
1128
0
    if (name == NULL) {
1129
0
        return -1;
1130
0
    }
1131
0
    PyObject *handler = PyCodec_LookupError(name);
1132
0
    if (handler != NULL) {
1133
0
        Py_DECREF(handler);
1134
0
        return 0;
1135
0
    }
1136
0
    return -1;
1137
0
}
1138
1139
1140
1141
/*[clinic input]
1142
@critical_section
1143
_io.TextIOWrapper.__init__
1144
    buffer: object
1145
    encoding: str(accept={str, NoneType}) = None
1146
    errors: object = None
1147
    newline: str(accept={str, NoneType}) = None
1148
    line_buffering: bool = False
1149
    write_through: bool = False
1150
1151
Character and line based layer over a BufferedIOBase object, buffer.
1152
1153
encoding gives the name of the encoding that the stream will be
1154
decoded or encoded with. It defaults to UTF-8; if UTF-8 Mode is
1155
disabled, the encoding returned by locale.getencoding() is used
1156
instead.  See the codecs module for the list of supported
1157
encodings.
1158
1159
errors determines the strictness of encoding and decoding (see
1160
help(codecs.Codec) or the documentation for codecs.register) and
1161
defaults to "strict".
1162
1163
newline controls how line endings are handled. It can be None, '',
1164
'\n', '\r', and '\r\n'.  It works as follows:
1165
1166
* On input, if newline is None, universal newlines mode is
1167
  enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
1168
  these are translated into '\n' before being returned to the
1169
  caller. If it is '', universal newline mode is enabled, but line
1170
  endings are returned to the caller untranslated. If it has any of
1171
  the other legal values, input lines are only terminated by the given
1172
  string, and the line ending is returned to the caller untranslated.
1173
1174
* On output, if newline is None, any '\n' characters written are
1175
  translated to the system default line separator, os.linesep. If
1176
  newline is '' or '\n', no translation takes place. If newline is any
1177
  of the other legal values, any '\n' characters written are translated
1178
  to the given string.
1179
1180
If line_buffering is True, a call to flush is implied when a call to
1181
write contains a newline character.
1182
[clinic start generated code]*/
1183
1184
static int
1185
_io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
1186
                                const char *encoding, PyObject *errors,
1187
                                const char *newline, int line_buffering,
1188
                                int write_through)
1189
/*[clinic end generated code: output=72267c0c01032ed2 input=4f0bee5a0b2302fd]*/
1190
130
{
1191
130
    PyObject *raw, *codec_info = NULL;
1192
130
    PyObject *res;
1193
130
    int r;
1194
1195
130
    self->ok = 0;
1196
130
    self->detached = 0;
1197
1198
130
    if (encoding == NULL) {
1199
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
1200
0
        if (_PyInterpreterState_GetConfig(interp)->warn_default_encoding) {
1201
0
            if (PyErr_WarnEx(PyExc_EncodingWarning,
1202
0
                             "'encoding' argument not specified", 1)) {
1203
0
                return -1;
1204
0
            }
1205
0
        }
1206
0
    }
1207
1208
130
    if (errors == Py_None) {
1209
19
        errors = &_Py_ID(strict);
1210
19
    }
1211
111
    else if (!PyUnicode_Check(errors)) {
1212
        // Check 'errors' argument here because Argument Clinic doesn't support
1213
        // 'str(accept={str, NoneType})' converter.
1214
0
        PyErr_Format(
1215
0
            PyExc_TypeError,
1216
0
            "TextIOWrapper() argument 'errors' must be str or None, not %.50s",
1217
0
            Py_TYPE(errors)->tp_name);
1218
0
        return -1;
1219
0
    }
1220
111
    else if (io_check_errors(errors)) {
1221
0
        return -1;
1222
0
    }
1223
130
    const char *errors_str = _PyUnicode_AsUTF8NoNUL(errors);
1224
130
    if (errors_str == NULL) {
1225
0
        return -1;
1226
0
    }
1227
1228
130
    if (validate_newline(newline) < 0) {
1229
0
        return -1;
1230
0
    }
1231
1232
130
    Py_CLEAR(self->buffer);
1233
130
    Py_CLEAR(self->encoding);
1234
130
    Py_CLEAR(self->encoder);
1235
130
    Py_CLEAR(self->decoder);
1236
130
    Py_CLEAR(self->readnl);
1237
130
    Py_CLEAR(self->decoded_chars);
1238
130
    Py_CLEAR(self->pending_bytes);
1239
130
    Py_CLEAR(self->snapshot);
1240
130
    Py_CLEAR(self->errors);
1241
130
    Py_CLEAR(self->raw);
1242
130
    self->decoded_chars_used = 0;
1243
130
    self->pending_bytes_count = 0;
1244
130
    self->encodefunc = NULL;
1245
130
    self->b2cratio = 0.0;
1246
1247
130
    if (encoding == NULL && _PyRuntime.preconfig.utf8_mode) {
1248
0
        _Py_DECLARE_STR(utf_8, "utf-8");
1249
0
        self->encoding = &_Py_STR(utf_8);
1250
0
    }
1251
130
    else if (encoding == NULL || (strcmp(encoding, "locale") == 0)) {
1252
0
        self->encoding = _Py_GetLocaleEncodingObject();
1253
0
        if (self->encoding == NULL) {
1254
0
            goto error;
1255
0
        }
1256
0
        assert(PyUnicode_Check(self->encoding));
1257
0
    }
1258
1259
130
    if (self->encoding != NULL) {
1260
0
        encoding = PyUnicode_AsUTF8(self->encoding);
1261
0
        if (encoding == NULL)
1262
0
            goto error;
1263
0
    }
1264
130
    else if (encoding != NULL) {
1265
130
        self->encoding = PyUnicode_FromString(encoding);
1266
130
        if (self->encoding == NULL)
1267
0
            goto error;
1268
130
    }
1269
0
    else {
1270
0
        PyErr_SetString(PyExc_OSError,
1271
0
                        "could not determine default encoding");
1272
0
        goto error;
1273
0
    }
1274
1275
    /* Check we have been asked for a real text encoding */
1276
130
    codec_info = _PyCodec_LookupTextEncoding(encoding, NULL);
1277
130
    if (codec_info == NULL) {
1278
0
        Py_CLEAR(self->encoding);
1279
0
        goto error;
1280
0
    }
1281
1282
    /* XXX: Failures beyond this point have the potential to leak elements
1283
     * of the partially constructed object (like self->encoding)
1284
     */
1285
1286
130
    self->errors = Py_NewRef(errors);
1287
130
    self->chunk_size = 8192;
1288
130
    self->line_buffering = line_buffering;
1289
130
    self->write_through = write_through;
1290
130
    if (set_newline(self, newline) < 0) {
1291
0
        goto error;
1292
0
    }
1293
1294
130
    self->buffer = Py_NewRef(buffer);
1295
1296
    /* Build the decoder object */
1297
130
    _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
1298
130
    self->state = state;
1299
130
    if (_textiowrapper_set_decoder(self, codec_info, errors_str) != 0)
1300
0
        goto error;
1301
1302
    /* Build the encoder object */
1303
130
    if (_textiowrapper_set_encoder(self, codec_info, errors_str) != 0)
1304
0
        goto error;
1305
1306
    /* Finished sorting out the codec details */
1307
130
    Py_CLEAR(codec_info);
1308
1309
130
    if (Py_IS_TYPE(buffer, state->PyBufferedReader_Type) ||
1310
75
        Py_IS_TYPE(buffer, state->PyBufferedWriter_Type) ||
1311
0
        Py_IS_TYPE(buffer, state->PyBufferedRandom_Type))
1312
130
    {
1313
130
        if (PyObject_GetOptionalAttr(buffer, &_Py_ID(raw), &raw) < 0)
1314
0
            goto error;
1315
        /* Cache the raw FileIO object to speed up 'closed' checks */
1316
130
        if (raw != NULL) {
1317
130
            if (Py_IS_TYPE(raw, state->PyFileIO_Type))
1318
130
                self->raw = raw;
1319
0
            else
1320
0
                Py_DECREF(raw);
1321
130
        }
1322
130
    }
1323
1324
130
    res = PyObject_CallMethodNoArgs(buffer, &_Py_ID(seekable));
1325
130
    if (res == NULL)
1326
0
        goto error;
1327
130
    r = PyObject_IsTrue(res);
1328
130
    Py_DECREF(res);
1329
130
    if (r < 0)
1330
0
        goto error;
1331
130
    self->seekable = self->telling = r;
1332
1333
130
    r = PyObject_HasAttrWithError(buffer, &_Py_ID(read1));
1334
130
    if (r < 0) {
1335
0
        goto error;
1336
0
    }
1337
130
    self->has_read1 = r;
1338
1339
130
    self->encoding_start_of_stream = 0;
1340
130
    if (_textiowrapper_fix_encoder_state(self) < 0) {
1341
0
        goto error;
1342
0
    }
1343
1344
130
    self->ok = 1;
1345
130
    return 0;
1346
1347
0
  error:
1348
0
    Py_XDECREF(codec_info);
1349
0
    return -1;
1350
130
}
1351
1352
/* Return *default_value* if ob is None, 0 if ob is false, 1 if ob is true,
1353
 * -1 on error.
1354
 */
1355
static int
1356
convert_optional_bool(PyObject *obj, int default_value)
1357
0
{
1358
0
    long v;
1359
0
    if (obj == Py_None) {
1360
0
        v = default_value;
1361
0
    }
1362
0
    else {
1363
0
        v = PyLong_AsLong(obj);
1364
0
        if (v == -1 && PyErr_Occurred())
1365
0
            return -1;
1366
0
    }
1367
0
    return v != 0;
1368
0
}
1369
1370
static int
1371
textiowrapper_change_encoding(textio *self, PyObject *encoding,
1372
                              PyObject *errors, int newline_changed)
1373
0
{
1374
    /* Use existing settings where new settings are not specified */
1375
0
    if (encoding == Py_None && errors == Py_None && !newline_changed) {
1376
0
        return 0;  // no change
1377
0
    }
1378
1379
0
    if (encoding == Py_None) {
1380
0
        encoding = self->encoding;
1381
0
        if (errors == Py_None) {
1382
0
            errors = self->errors;
1383
0
        }
1384
0
        Py_INCREF(encoding);
1385
0
    }
1386
0
    else {
1387
0
        if (_PyUnicode_EqualToASCIIString(encoding, "locale")) {
1388
0
            encoding = _Py_GetLocaleEncodingObject();
1389
0
            if (encoding == NULL) {
1390
0
                return -1;
1391
0
            }
1392
0
        } else {
1393
0
            Py_INCREF(encoding);
1394
0
        }
1395
0
        if (errors == Py_None) {
1396
0
            errors = &_Py_ID(strict);
1397
0
        }
1398
0
    }
1399
0
    Py_INCREF(errors);
1400
1401
0
    const char *c_encoding = PyUnicode_AsUTF8(encoding);
1402
0
    if (c_encoding == NULL) {
1403
0
        Py_DECREF(encoding);
1404
0
        Py_DECREF(errors);
1405
0
        return -1;
1406
0
    }
1407
0
    const char *c_errors = PyUnicode_AsUTF8(errors);
1408
0
    if (c_errors == NULL) {
1409
0
        Py_DECREF(encoding);
1410
0
        Py_DECREF(errors);
1411
0
        return -1;
1412
0
    }
1413
1414
    // Create new encoder & decoder
1415
0
    PyObject *codec_info = _PyCodec_LookupTextEncoding(c_encoding, NULL);
1416
0
    if (codec_info == NULL) {
1417
0
        Py_DECREF(encoding);
1418
0
        Py_DECREF(errors);
1419
0
        return -1;
1420
0
    }
1421
0
    if (_textiowrapper_set_decoder(self, codec_info, c_errors) != 0 ||
1422
0
            _textiowrapper_set_encoder(self, codec_info, c_errors) != 0) {
1423
0
        Py_DECREF(codec_info);
1424
0
        Py_DECREF(encoding);
1425
0
        Py_DECREF(errors);
1426
0
        return -1;
1427
0
    }
1428
0
    Py_DECREF(codec_info);
1429
1430
0
    Py_SETREF(self->encoding, encoding);
1431
0
    Py_SETREF(self->errors, errors);
1432
1433
0
    return _textiowrapper_fix_encoder_state(self);
1434
0
}
1435
1436
/*[clinic input]
1437
@critical_section
1438
_io.TextIOWrapper.reconfigure
1439
    *
1440
    encoding: object = None
1441
    errors: object = None
1442
    newline as newline_obj: object(c_default="NULL") = None
1443
    line_buffering as line_buffering_obj: object = None
1444
    write_through as write_through_obj: object = None
1445
1446
Reconfigure the text stream with new parameters.
1447
1448
This also does an implicit stream flush.
1449
1450
[clinic start generated code]*/
1451
1452
static PyObject *
1453
_io_TextIOWrapper_reconfigure_impl(textio *self, PyObject *encoding,
1454
                                   PyObject *errors, PyObject *newline_obj,
1455
                                   PyObject *line_buffering_obj,
1456
                                   PyObject *write_through_obj)
1457
/*[clinic end generated code: output=52b812ff4b3d4b0f input=dc3bd35ebda702a7]*/
1458
0
{
1459
0
    int line_buffering;
1460
0
    int write_through;
1461
0
    const char *newline = NULL;
1462
1463
0
    if (encoding != Py_None && !PyUnicode_Check(encoding)) {
1464
0
        PyErr_Format(PyExc_TypeError,
1465
0
                "reconfigure() argument 'encoding' must be str or None, not %s",
1466
0
                Py_TYPE(encoding)->tp_name);
1467
0
        return NULL;
1468
0
    }
1469
0
    if (errors != Py_None && !PyUnicode_Check(errors)) {
1470
0
        PyErr_Format(PyExc_TypeError,
1471
0
                "reconfigure() argument 'errors' must be str or None, not %s",
1472
0
                Py_TYPE(errors)->tp_name);
1473
0
        return NULL;
1474
0
    }
1475
0
    if (newline_obj != NULL && newline_obj != Py_None &&
1476
0
        !PyUnicode_Check(newline_obj))
1477
0
    {
1478
0
        PyErr_Format(PyExc_TypeError,
1479
0
                "reconfigure() argument 'newline' must be str or None, not %s",
1480
0
                Py_TYPE(newline_obj)->tp_name);
1481
0
        return NULL;
1482
0
    }
1483
    /* Check if something is in the read buffer */
1484
0
    if (self->decoded_chars != NULL) {
1485
0
        if (encoding != Py_None || errors != Py_None || newline_obj != NULL) {
1486
0
            _unsupported(self->state,
1487
0
                         "It is not possible to set the encoding or newline "
1488
0
                         "of stream after the first read");
1489
0
            return NULL;
1490
0
        }
1491
0
    }
1492
1493
0
    if (newline_obj != NULL && newline_obj != Py_None) {
1494
0
        newline = PyUnicode_AsUTF8(newline_obj);
1495
0
        if (newline == NULL || validate_newline(newline) < 0) {
1496
0
            return NULL;
1497
0
        }
1498
0
    }
1499
1500
0
    line_buffering = convert_optional_bool(line_buffering_obj,
1501
0
                                           self->line_buffering);
1502
0
    if (line_buffering < 0) {
1503
0
        return NULL;
1504
0
    }
1505
0
    write_through = convert_optional_bool(write_through_obj,
1506
0
                                          self->write_through);
1507
0
    if (write_through < 0) {
1508
0
        return NULL;
1509
0
    }
1510
1511
0
    if (_PyFile_Flush((PyObject *)self) < 0) {
1512
0
        return NULL;
1513
0
    }
1514
0
    self->b2cratio = 0;
1515
1516
0
    if (newline_obj != NULL && set_newline(self, newline) < 0) {
1517
0
        return NULL;
1518
0
    }
1519
1520
0
    if (textiowrapper_change_encoding(
1521
0
            self, encoding, errors, newline_obj != NULL) < 0) {
1522
0
        return NULL;
1523
0
    }
1524
1525
0
    self->line_buffering = line_buffering;
1526
0
    self->write_through = write_through;
1527
0
    Py_RETURN_NONE;
1528
0
}
1529
1530
static int
1531
textiowrapper_clear(PyObject *op)
1532
19
{
1533
19
    textio *self = textio_CAST(op);
1534
19
    self->ok = 0;
1535
19
    Py_CLEAR(self->buffer);
1536
19
    Py_CLEAR(self->encoding);
1537
19
    Py_CLEAR(self->encoder);
1538
19
    Py_CLEAR(self->decoder);
1539
19
    Py_CLEAR(self->readnl);
1540
19
    Py_CLEAR(self->decoded_chars);
1541
19
    Py_CLEAR(self->pending_bytes);
1542
19
    Py_CLEAR(self->snapshot);
1543
19
    Py_CLEAR(self->errors);
1544
19
    Py_CLEAR(self->raw);
1545
1546
19
    PyObject_ClearManagedDict(op);
1547
19
    return 0;
1548
19
}
1549
1550
static void
1551
textiowrapper_dealloc(PyObject *op)
1552
19
{
1553
19
    textio *self = textio_CAST(op);
1554
19
    PyTypeObject *tp = Py_TYPE(self);
1555
19
    self->finalizing = 1;
1556
19
    if (_PyIOBase_finalize(op) < 0)
1557
0
        return;
1558
19
    self->ok = 0;
1559
19
    _PyObject_GC_UNTRACK(self);
1560
19
    PyObject_ClearWeakRefs(op);
1561
19
    (void)textiowrapper_clear(op);
1562
19
    tp->tp_free(self);
1563
19
    Py_DECREF(tp);
1564
19
}
1565
1566
static int
1567
textiowrapper_traverse(PyObject *op, visitproc visit, void *arg)
1568
6.11k
{
1569
6.11k
    textio *self = textio_CAST(op);
1570
6.11k
    Py_VISIT(Py_TYPE(self));
1571
6.11k
    Py_VISIT(self->buffer);
1572
6.11k
    Py_VISIT(self->encoding);
1573
6.11k
    Py_VISIT(self->encoder);
1574
6.11k
    Py_VISIT(self->decoder);
1575
6.11k
    Py_VISIT(self->readnl);
1576
6.11k
    Py_VISIT(self->decoded_chars);
1577
6.11k
    Py_VISIT(self->pending_bytes);
1578
6.11k
    Py_VISIT(self->snapshot);
1579
6.11k
    Py_VISIT(self->errors);
1580
6.11k
    Py_VISIT(self->raw);
1581
1582
6.11k
    return PyObject_VisitManagedDict(op, visit, arg);
1583
6.11k
}
1584
1585
static PyObject *
1586
_io_TextIOWrapper_closed_get_impl(textio *self);
1587
1588
/* This macro takes some shortcuts to make the common case faster. */
1589
#define CHECK_CLOSED(self) \
1590
199k
    do { \
1591
199k
        int r; \
1592
199k
        PyObject *_res; \
1593
199k
        if (Py_IS_TYPE(self, self->state->PyTextIOWrapper_Type)) { \
1594
199k
            if (self->raw != NULL) \
1595
199k
                r = _PyFileIO_closed(self->raw); \
1596
199k
            else { \
1597
0
                _res = _io_TextIOWrapper_closed_get_impl(self); \
1598
0
                if (_res == NULL) \
1599
0
                    return NULL; \
1600
0
                r = PyObject_IsTrue(_res); \
1601
0
                Py_DECREF(_res); \
1602
0
                if (r < 0) \
1603
0
                    return NULL; \
1604
0
            } \
1605
199k
            if (r > 0) { \
1606
0
                PyErr_SetString(PyExc_ValueError, \
1607
0
                                "I/O operation on closed file."); \
1608
0
                return NULL; \
1609
0
            } \
1610
199k
        } \
1611
199k
        else if (_PyIOBase_check_closed((PyObject *)self, Py_True) == NULL) \
1612
0
            return NULL; \
1613
199k
    } while (0)
1614
1615
#define CHECK_INITIALIZED(self) \
1616
199k
    if (self->ok <= 0) { \
1617
0
        PyErr_SetString(PyExc_ValueError, \
1618
0
            "I/O operation on uninitialized object"); \
1619
0
        return NULL; \
1620
0
    }
1621
1622
#define CHECK_ATTACHED(self) \
1623
199k
    CHECK_INITIALIZED(self); \
1624
199k
    if (self->detached) { \
1625
0
        PyErr_SetString(PyExc_ValueError, \
1626
0
             "underlying buffer has been detached"); \
1627
0
        return NULL; \
1628
0
    }
1629
1630
#define CHECK_ATTACHED_INT(self) \
1631
0
    if (self->ok <= 0) { \
1632
0
        PyErr_SetString(PyExc_ValueError, \
1633
0
            "I/O operation on uninitialized object"); \
1634
0
        return -1; \
1635
0
    } else if (self->detached) { \
1636
0
        PyErr_SetString(PyExc_ValueError, \
1637
0
             "underlying buffer has been detached"); \
1638
0
        return -1; \
1639
0
    }
1640
1641
1642
/*[clinic input]
1643
@critical_section
1644
_io.TextIOWrapper.detach
1645
[clinic start generated code]*/
1646
1647
static PyObject *
1648
_io_TextIOWrapper_detach_impl(textio *self)
1649
/*[clinic end generated code: output=7ba3715cd032d5f2 input=c908a3b4ef203b0f]*/
1650
0
{
1651
0
    PyObject *buffer;
1652
0
    if (_PyFile_Flush((PyObject *)self) < 0) {
1653
0
        return NULL;
1654
0
    }
1655
    /* _PyFile_Flush could detach before returning; raise an exception. */
1656
0
    buffer = buffer_access_safe(self);
1657
0
    if (buffer == NULL) {
1658
0
        return NULL;
1659
0
    }
1660
0
    Py_CLEAR(self->buffer);
1661
0
    self->detached = 1;
1662
0
    return buffer;
1663
0
}
1664
1665
/* Flush the internal write buffer. This doesn't explicitly flush the
1666
   underlying buffered object, though. */
1667
static int
1668
_textiowrapper_writeflush(textio *self)
1669
199k
{
1670
199k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
1671
1672
199k
    if (self->pending_bytes == NULL)
1673
23.6k
        return 0;
1674
1675
175k
    PyObject *pending = self->pending_bytes;
1676
175k
    PyObject *b;
1677
1678
175k
    if (PyBytes_Check(pending)) {
1679
31
        b = Py_NewRef(pending);
1680
31
    }
1681
175k
    else if (PyUnicode_Check(pending)) {
1682
175k
        assert(PyUnicode_IS_ASCII(pending));
1683
175k
        assert(PyUnicode_GET_LENGTH(pending) == self->pending_bytes_count);
1684
175k
        b = PyBytes_FromStringAndSize(
1685
175k
                PyUnicode_DATA(pending), PyUnicode_GET_LENGTH(pending));
1686
175k
        if (b == NULL) {
1687
0
            return -1;
1688
0
        }
1689
175k
    }
1690
0
    else {
1691
0
        assert(PyList_Check(pending));
1692
0
        PyBytesWriter *writer = PyBytesWriter_Create(self->pending_bytes_count);
1693
0
        if (writer == NULL) {
1694
0
            return -1;
1695
0
        }
1696
1697
0
        char *buf = PyBytesWriter_GetData(writer);
1698
0
        Py_ssize_t pos = 0;
1699
1700
0
        for (Py_ssize_t i = 0; i < PyList_GET_SIZE(pending); i++) {
1701
0
            PyObject *obj = PyList_GET_ITEM(pending, i);
1702
0
            const char *src;
1703
0
            Py_ssize_t len;
1704
0
            if (PyUnicode_Check(obj)) {
1705
0
                assert(PyUnicode_IS_ASCII(obj));
1706
0
                src = PyUnicode_DATA(obj);
1707
0
                len = PyUnicode_GET_LENGTH(obj);
1708
0
            }
1709
0
            else {
1710
0
                assert(PyBytes_Check(obj));
1711
0
                src = PyBytes_AS_STRING(obj);
1712
0
                len = PyBytes_GET_SIZE(obj);
1713
0
            }
1714
0
            memcpy(buf + pos, src, len);
1715
0
            pos += len;
1716
0
        }
1717
0
        assert(pos == self->pending_bytes_count);
1718
1719
0
        b = PyBytesWriter_Finish(writer);
1720
0
        if (b == NULL) {
1721
0
            return -1;
1722
0
        }
1723
0
    }
1724
1725
175k
    self->pending_bytes_count = 0;
1726
175k
    self->pending_bytes = NULL;
1727
175k
    Py_DECREF(pending);
1728
1729
175k
    PyObject *ret;
1730
175k
    do {
1731
175k
        ret = buffer_callmethod_onearg(self, &_Py_ID(write), b);
1732
175k
    } while (ret == NULL && _PyIO_trap_eintr());
1733
175k
    Py_DECREF(b);
1734
    // NOTE: We cleared buffer but we don't know how many bytes are actually written
1735
    // when an error occurred.
1736
175k
    if (ret == NULL)
1737
0
        return -1;
1738
175k
    Py_DECREF(ret);
1739
175k
    return 0;
1740
175k
}
1741
1742
/* Return borrowed Py_None on success, or NULL on error. */
1743
static PyObject *
1744
textiowrapper_check_write(textio *self)
1745
175k
{
1746
175k
    CHECK_ATTACHED(self);
1747
175k
    CHECK_CLOSED(self);
1748
1749
175k
    if (self->encoder == NULL) {
1750
0
        return _unsupported(self->state, "not writable");
1751
0
    }
1752
175k
    return Py_None;
1753
175k
}
1754
1755
/* Consume b, which is either bytes or an ASCII string. */
1756
static int
1757
textiowrapper_write_bytes(textio *self, PyObject *b,
1758
                          int needflush, int text_needflush)
1759
175k
{
1760
175k
    Py_ssize_t bytes_len;
1761
175k
    if (PyUnicode_Check(b)) {
1762
175k
        assert(PyUnicode_IS_ASCII(b));
1763
175k
        bytes_len = PyUnicode_GET_LENGTH(b);
1764
175k
    }
1765
31
    else {
1766
31
        bytes_len = PyBytes_GET_SIZE(b);
1767
31
    }
1768
1769
    // We should avoid concatenating huge data.
1770
    // Flush the buffer before adding b to the buffer if b is not small.
1771
    // https://github.com/python/cpython/issues/87426
1772
175k
    if (bytes_len >= self->chunk_size) {
1773
        // _textiowrapper_writeflush() calls buffer.write().
1774
        // self->pending_bytes can be appended during buffer->write()
1775
        // or other thread.
1776
        // We need to loop until buffer becomes empty.
1777
        // https://github.com/python/cpython/issues/118138
1778
        // https://github.com/python/cpython/issues/119506
1779
0
        while (self->pending_bytes != NULL) {
1780
0
            if (_textiowrapper_writeflush(self) < 0) {
1781
0
                Py_DECREF(b);
1782
0
                return -1;
1783
0
            }
1784
0
        }
1785
0
    }
1786
1787
175k
    if (bytes_len > 0) {
1788
175k
        if (self->pending_bytes == NULL) {
1789
175k
            assert(self->pending_bytes_count == 0);
1790
175k
            self->pending_bytes = b;
1791
175k
        }
1792
0
        else if (!PyList_CheckExact(self->pending_bytes)) {
1793
0
            PyObject *list = PyList_New(2);
1794
0
            if (list == NULL) {
1795
0
                Py_DECREF(b);
1796
0
                return -1;
1797
0
            }
1798
            // Since Python 3.12, allocating GC object won't trigger GC and release
1799
            // GIL. See https://github.com/python/cpython/issues/97922
1800
0
            assert(!PyList_CheckExact(self->pending_bytes));
1801
0
            PyList_SET_ITEM(list, 0, self->pending_bytes);
1802
0
            PyList_SET_ITEM(list, 1, b);
1803
0
            self->pending_bytes = list;
1804
0
        }
1805
0
        else {
1806
0
            if (PyList_Append(self->pending_bytes, b) < 0) {
1807
0
                Py_DECREF(b);
1808
0
                return -1;
1809
0
            }
1810
0
            Py_DECREF(b);
1811
0
        }
1812
1813
175k
        self->pending_bytes_count += bytes_len;
1814
175k
    }
1815
0
    else {
1816
0
        Py_DECREF(b);
1817
0
    }
1818
1819
175k
    if (self->pending_bytes_count >= self->chunk_size || needflush ||
1820
175k
        text_needflush) {
1821
175k
        if (_textiowrapper_writeflush(self) < 0)
1822
0
            return -1;
1823
175k
    }
1824
1825
175k
    if (needflush) {
1826
175k
        PyObject *buffer = buffer_access_safe(self);
1827
175k
        if (buffer == NULL) {
1828
0
            return -1;
1829
0
        }
1830
175k
        int res = _PyFile_Flush(buffer);
1831
175k
        Py_DECREF(buffer);
1832
175k
        if (res < 0) {
1833
0
            return -1;
1834
0
        }
1835
175k
    }
1836
1837
175k
    if (self->snapshot != NULL) {
1838
0
        textiowrapper_set_decoded_chars(self, NULL);
1839
0
        Py_CLEAR(self->snapshot);
1840
0
    }
1841
1842
175k
    if (self->decoder) {
1843
0
        PyObject *ret = PyObject_CallMethodNoArgs(self->decoder, &_Py_ID(reset));
1844
0
        if (ret == NULL)
1845
0
            return -1;
1846
0
        Py_DECREF(ret);
1847
0
    }
1848
1849
175k
    return 0;
1850
175k
}
1851
1852
static PyObject *
1853
textiowrapper_write_text(textio *self, PyObject *text)
1854
175k
{
1855
175k
    PyObject *b;
1856
175k
    Py_ssize_t textlen;
1857
175k
    int haslf = 0;
1858
175k
    int needflush = 0, text_needflush = 0;
1859
1860
175k
    Py_INCREF(text);
1861
1862
175k
    textlen = PyUnicode_GET_LENGTH(text);
1863
1864
175k
    if ((self->writetranslate && self->writenl != NULL) || self->line_buffering)
1865
175k
        if (PyUnicode_FindChar(text, '\n', 0, PyUnicode_GET_LENGTH(text), 1) != -1)
1866
175k
            haslf = 1;
1867
1868
175k
    if (haslf && self->writetranslate && self->writenl != NULL) {
1869
0
        PyObject *newtext = _PyObject_CallMethod(text, &_Py_ID(replace),
1870
0
                                                 "ss", "\n", self->writenl);
1871
0
        Py_DECREF(text);
1872
0
        if (newtext == NULL)
1873
0
            return NULL;
1874
0
        if (!PyUnicode_Check(newtext)) {
1875
0
            PyErr_Format(PyExc_TypeError,
1876
0
                         "replace() should return a str, not %T", newtext);
1877
0
            Py_DECREF(newtext);
1878
0
            return NULL;
1879
0
        }
1880
        /* replace() may have closed, detached or reinitialized the stream. */
1881
0
        if (textiowrapper_check_write(self) == NULL) {
1882
0
            Py_DECREF(newtext);
1883
0
            return NULL;
1884
0
        }
1885
0
        text = newtext;
1886
0
    }
1887
1888
175k
    if (self->write_through)
1889
0
        text_needflush = 1;
1890
175k
    if (self->line_buffering &&
1891
175k
        (haslf ||
1892
0
         PyUnicode_FindChar(text, '\r', 0, PyUnicode_GET_LENGTH(text), 1) != -1))
1893
175k
        needflush = 1;
1894
1895
    /* XXX What if we were just reading? */
1896
175k
    if (self->encodefunc != NULL) {
1897
175k
        if (PyUnicode_IS_ASCII(text) &&
1898
                // See bpo-43260
1899
175k
                PyUnicode_GET_LENGTH(text) <= self->chunk_size &&
1900
175k
                is_asciicompat_encoding(self->encodefunc)) {
1901
175k
            b = Py_NewRef(text);
1902
175k
        }
1903
31
        else {
1904
31
            b = (*self->encodefunc)((PyObject *) self, text);
1905
31
        }
1906
175k
        self->encoding_start_of_stream = 0;
1907
175k
    }
1908
0
    else {
1909
        /* A codec callback may reconfigure the stream. */
1910
0
        PyObject *encoder = Py_NewRef(self->encoder);
1911
0
        b = PyObject_CallMethodOneArg(encoder, &_Py_ID(encode), text);
1912
0
        Py_DECREF(encoder);
1913
0
    }
1914
1915
175k
    Py_DECREF(text);
1916
175k
    if (b == NULL)
1917
0
        return NULL;
1918
175k
    if (b != text && !PyBytes_Check(b)) {
1919
0
        PyErr_Format(PyExc_TypeError,
1920
0
                     "encoder should return a bytes object, not '%.200s'",
1921
0
                     Py_TYPE(b)->tp_name);
1922
0
        Py_DECREF(b);
1923
0
        return NULL;
1924
0
    }
1925
1926
175k
    if (textiowrapper_write_bytes(self, b, needflush, text_needflush) < 0) {
1927
0
        return NULL;
1928
0
    }
1929
175k
    return PyLong_FromSsize_t(textlen);
1930
175k
}
1931
1932
/*[clinic input]
1933
@critical_section
1934
_io.TextIOWrapper.write
1935
    text: unicode
1936
    /
1937
[clinic start generated code]*/
1938
1939
static PyObject *
1940
_io_TextIOWrapper_write_impl(textio *self, PyObject *text)
1941
/*[clinic end generated code: output=d2deb0d50771fcec input=73ec95c5c4a3489c]*/
1942
175k
{
1943
175k
    if (textiowrapper_check_write(self) == NULL) {
1944
0
        return NULL;
1945
0
    }
1946
175k
    return textiowrapper_write_text(self, text);
1947
175k
}
1948
1949
/* Steal a reference to chars and store it in the decoded_char buffer;
1950
 */
1951
static void
1952
textiowrapper_set_decoded_chars(textio *self, PyObject *chars)
1953
260
{
1954
260
    Py_XSETREF(self->decoded_chars, chars);
1955
260
    self->decoded_chars_used = 0;
1956
260
}
1957
1958
static PyObject *
1959
textiowrapper_get_decoded_chars(textio *self, Py_ssize_t n)
1960
8
{
1961
8
    PyObject *chars;
1962
8
    Py_ssize_t avail;
1963
1964
8
    if (self->decoded_chars == NULL)
1965
8
        return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
1966
1967
0
    avail = (PyUnicode_GET_LENGTH(self->decoded_chars)
1968
0
             - self->decoded_chars_used);
1969
1970
0
    assert(avail >= 0);
1971
1972
0
    if (n < 0 || n > avail)
1973
0
        n = avail;
1974
1975
0
    if (self->decoded_chars_used > 0 || n < avail) {
1976
0
        chars = PyUnicode_Substring(self->decoded_chars,
1977
0
                                    self->decoded_chars_used,
1978
0
                                    self->decoded_chars_used + n);
1979
0
        if (chars == NULL)
1980
0
            return NULL;
1981
0
    }
1982
0
    else {
1983
0
        chars = Py_NewRef(self->decoded_chars);
1984
0
    }
1985
1986
0
    self->decoded_chars_used += n;
1987
0
    return chars;
1988
0
}
1989
1990
/* Read and decode the next chunk of data from the BufferedReader.
1991
 */
1992
static int
1993
textiowrapper_read_chunk(textio *self, Py_ssize_t size_hint)
1994
130
{
1995
130
    PyObject *dec_buffer = NULL;
1996
130
    PyObject *dec_flags = NULL;
1997
130
    PyObject *input_chunk = NULL;
1998
130
    Py_buffer input_chunk_buf;
1999
130
    PyObject *decoded_chars, *chunk_size;
2000
130
    Py_ssize_t nbytes, nchars;
2001
130
    int eof;
2002
2003
    /* The return value is True unless EOF was reached.  The decoded string is
2004
     * placed in self._decoded_chars (replacing its previous value).  The
2005
     * entire input chunk is sent to the decoder, though some of it may remain
2006
     * buffered in the decoder, yet to be converted.
2007
     */
2008
2009
130
    if (self->decoder == NULL) {
2010
0
        _unsupported(self->state, "not readable");
2011
0
        return -1;
2012
0
    }
2013
2014
130
    if (self->telling) {
2015
        /* To prepare for tell(), we need to snapshot a point in the file
2016
         * where the decoder's input buffer is empty.
2017
         */
2018
0
        PyObject *state = PyObject_CallMethodNoArgs(self->decoder,
2019
0
                                                     &_Py_ID(getstate));
2020
0
        if (state == NULL)
2021
0
            return -1;
2022
        /* Given this, we know there was a valid snapshot point
2023
         * len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
2024
         */
2025
0
        if (!PyTuple_Check(state)) {
2026
0
            PyErr_SetString(PyExc_TypeError,
2027
0
                            "illegal decoder state");
2028
0
            Py_DECREF(state);
2029
0
            return -1;
2030
0
        }
2031
0
        if (!PyArg_ParseTuple(state,
2032
0
                              "OO;illegal decoder state", &dec_buffer, &dec_flags))
2033
0
        {
2034
0
            Py_DECREF(state);
2035
0
            return -1;
2036
0
        }
2037
2038
0
        if (!PyBytes_Check(dec_buffer)) {
2039
0
            PyErr_Format(PyExc_TypeError,
2040
0
                         "illegal decoder state: the first item should be a "
2041
0
                         "bytes object, not '%.200s'",
2042
0
                         Py_TYPE(dec_buffer)->tp_name);
2043
0
            Py_DECREF(state);
2044
0
            return -1;
2045
0
        }
2046
0
        Py_INCREF(dec_buffer);
2047
0
        Py_INCREF(dec_flags);
2048
0
        Py_DECREF(state);
2049
0
    }
2050
2051
    /* Read a chunk, decode it, and put the result in self._decoded_chars. */
2052
130
    if (size_hint > 0) {
2053
0
        size_hint = (Py_ssize_t)(Py_MAX(self->b2cratio, 1.0) * size_hint);
2054
0
    }
2055
130
    chunk_size = PyLong_FromSsize_t(Py_MAX(self->chunk_size, size_hint));
2056
130
    if (chunk_size == NULL)
2057
0
        goto fail;
2058
2059
130
    input_chunk = buffer_callmethod_onearg(self,
2060
130
                                           (self->has_read1 ? &_Py_ID(read1) :
2061
130
                                                              &_Py_ID(read)),
2062
130
                                           chunk_size);
2063
130
    Py_DECREF(chunk_size);
2064
130
    if (input_chunk == NULL)
2065
0
        goto fail;
2066
2067
130
    if (PyObject_GetBuffer(input_chunk, &input_chunk_buf, 0) != 0) {
2068
0
        PyErr_Format(PyExc_TypeError,
2069
0
                     "underlying %s() should have returned a bytes-like object, "
2070
0
                     "not '%.200s'", (self->has_read1 ? "read1": "read"),
2071
0
                     Py_TYPE(input_chunk)->tp_name);
2072
0
        goto fail;
2073
0
    }
2074
2075
130
    nbytes = input_chunk_buf.len;
2076
130
    eof = (nbytes == 0);
2077
2078
130
    decoded_chars = _textiowrapper_decode(self->state, self->decoder,
2079
130
                                          input_chunk, eof);
2080
130
    PyBuffer_Release(&input_chunk_buf);
2081
130
    if (decoded_chars == NULL)
2082
0
        goto fail;
2083
2084
    /* The old chunk's finalizer can clear the new chunk. */
2085
130
    nchars = PyUnicode_GET_LENGTH(decoded_chars);
2086
130
    textiowrapper_set_decoded_chars(self, decoded_chars);
2087
130
    if (nchars > 0)
2088
120
        self->b2cratio = (double) nbytes / nchars;
2089
10
    else
2090
10
        self->b2cratio = 0.0;
2091
130
    if (nchars > 0)
2092
120
        eof = 0;
2093
2094
130
    if (self->telling) {
2095
        /* At the snapshot point, len(dec_buffer) bytes before the read, the
2096
         * next input to be decoded is dec_buffer + input_chunk.
2097
         */
2098
0
        PyObject *next_input = dec_buffer;
2099
0
        PyBytes_Concat(&next_input, input_chunk);
2100
0
        dec_buffer = NULL; /* Reference lost to PyBytes_Concat */
2101
0
        if (next_input == NULL) {
2102
0
            goto fail;
2103
0
        }
2104
0
        PyObject *snapshot = Py_BuildValue("NN", dec_flags, next_input);
2105
0
        if (snapshot == NULL) {
2106
0
            dec_flags = NULL;
2107
0
            goto fail;
2108
0
        }
2109
0
        Py_XSETREF(self->snapshot, snapshot);
2110
0
    }
2111
130
    Py_DECREF(input_chunk);
2112
2113
130
    return (eof == 0);
2114
2115
0
  fail:
2116
0
    Py_XDECREF(dec_buffer);
2117
0
    Py_XDECREF(dec_flags);
2118
0
    Py_XDECREF(input_chunk);
2119
0
    return -1;
2120
130
}
2121
2122
/*[clinic input]
2123
@critical_section
2124
_io.TextIOWrapper.read
2125
    size as n: Py_ssize_t(accept={int, NoneType}) = -1
2126
    /
2127
[clinic start generated code]*/
2128
2129
static PyObject *
2130
_io_TextIOWrapper_read_impl(textio *self, Py_ssize_t n)
2131
/*[clinic end generated code: output=7e651ce6cc6a25a6 input=67d14c5661121377]*/
2132
8
{
2133
8
    PyObject *result = NULL, *chunks = NULL;
2134
2135
8
    CHECK_ATTACHED(self);
2136
8
    CHECK_CLOSED(self);
2137
2138
8
    if (self->decoder == NULL) {
2139
0
        return _unsupported(self->state, "not readable");
2140
0
    }
2141
2142
8
    if (_textiowrapper_writeflush(self) < 0)
2143
0
        return NULL;
2144
2145
8
    if (n < 0) {
2146
        /* Read everything */
2147
8
        PyObject *bytes = buffer_callmethod_noargs(self, &_Py_ID(read));
2148
8
        PyObject *decoded;
2149
8
        if (bytes == NULL)
2150
0
            goto fail;
2151
2152
8
        if (bytes == Py_None){
2153
0
            Py_DECREF(bytes);
2154
0
            PyErr_SetString(PyExc_BlockingIOError, "Read returned None.");
2155
0
            return NULL;
2156
0
        }
2157
2158
8
        decoded = _textiowrapper_decode(self->state, self->decoder, bytes, 1);
2159
8
        Py_DECREF(bytes);
2160
8
        if (decoded == NULL)
2161
0
            goto fail;
2162
2163
8
        result = textiowrapper_get_decoded_chars(self, -1);
2164
2165
8
        if (result == NULL) {
2166
0
            Py_DECREF(decoded);
2167
0
            return NULL;
2168
0
        }
2169
2170
8
        PyUnicode_AppendAndDel(&result, decoded);
2171
8
        if (result == NULL)
2172
0
            goto fail;
2173
2174
8
        if (self->snapshot != NULL) {
2175
0
            textiowrapper_set_decoded_chars(self, NULL);
2176
0
            Py_CLEAR(self->snapshot);
2177
0
        }
2178
8
        return result;
2179
8
    }
2180
0
    else {
2181
0
        int res = 1;
2182
0
        Py_ssize_t remaining = n;
2183
2184
0
        result = textiowrapper_get_decoded_chars(self, n);
2185
0
        if (result == NULL)
2186
0
            goto fail;
2187
0
        remaining -= PyUnicode_GET_LENGTH(result);
2188
2189
        /* Keep reading chunks until we have n characters to return */
2190
0
        while (remaining > 0) {
2191
0
            res = textiowrapper_read_chunk(self, remaining);
2192
0
            if (res < 0) {
2193
                /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
2194
                   when EINTR occurs so we needn't do it ourselves. */
2195
0
                if (_PyIO_trap_eintr()) {
2196
0
                    continue;
2197
0
                }
2198
0
                goto fail;
2199
0
            }
2200
0
            if (res == 0)  /* EOF */
2201
0
                break;
2202
0
            if (chunks == NULL) {
2203
0
                chunks = PyList_New(0);
2204
0
                if (chunks == NULL)
2205
0
                    goto fail;
2206
0
            }
2207
0
            if (PyUnicode_GET_LENGTH(result) > 0 &&
2208
0
                PyList_Append(chunks, result) < 0)
2209
0
                goto fail;
2210
0
            Py_DECREF(result);
2211
0
            result = textiowrapper_get_decoded_chars(self, remaining);
2212
0
            if (result == NULL)
2213
0
                goto fail;
2214
0
            remaining -= PyUnicode_GET_LENGTH(result);
2215
0
        }
2216
0
        if (chunks != NULL) {
2217
0
            if (result != NULL && PyList_Append(chunks, result) < 0)
2218
0
                goto fail;
2219
0
            _Py_DECLARE_STR(empty, "");
2220
0
            Py_XSETREF(result, PyUnicode_Join(&_Py_STR(empty), chunks));
2221
0
            if (result == NULL)
2222
0
                goto fail;
2223
0
            Py_CLEAR(chunks);
2224
0
        }
2225
0
        return result;
2226
0
    }
2227
0
  fail:
2228
0
    Py_XDECREF(result);
2229
0
    Py_XDECREF(chunks);
2230
0
    return NULL;
2231
8
}
2232
2233
2234
/* NOTE: `end` must point to the real end of the Py_UCS4 storage,
2235
   that is to the NUL character. Otherwise the function will produce
2236
   incorrect results. */
2237
static const char *
2238
find_control_char(int kind, const char *s, const char *end, Py_UCS4 ch)
2239
12.2M
{
2240
12.2M
    if (kind == PyUnicode_1BYTE_KIND) {
2241
22.9k
        assert(ch < 256);
2242
22.9k
        return (char *) memchr((const void *) s, (char) ch, end - s);
2243
22.9k
    }
2244
138M
    for (;;) {
2245
242M
        while (PyUnicode_READ(kind, s, 0) > ch)
2246
104M
            s += kind;
2247
138M
        if (PyUnicode_READ(kind, s, 0) == ch)
2248
12.2M
            return s;
2249
126M
        if (s == end)
2250
5.37k
            return NULL;
2251
126M
        s += kind;
2252
126M
    }
2253
12.2M
}
2254
2255
Py_ssize_t
2256
_PyIO_find_line_ending(
2257
    int translated, int universal, PyObject *readnl,
2258
    int kind, const char *start, const char *end, Py_ssize_t *consumed)
2259
30.6M
{
2260
30.6M
    Py_ssize_t len = (end - start)/kind;
2261
2262
30.6M
    if (translated) {
2263
        /* Newlines are already translated, only search for \n */
2264
23.7k
        const char *pos = find_control_char(kind, start, end, '\n');
2265
23.7k
        if (pos != NULL)
2266
23.6k
            return (pos - start)/kind + 1;
2267
120
        else {
2268
120
            *consumed = len;
2269
120
            return -1;
2270
120
        }
2271
23.7k
    }
2272
30.6M
    else if (universal) {
2273
        /* Universal newline search. Find any of \r, \r\n, \n
2274
         * The decoder ensures that \r\n are not split in two pieces
2275
         */
2276
18.4M
        const char *s = start;
2277
90.3M
        for (;;) {
2278
90.3M
            Py_UCS4 ch;
2279
            /* Fast path for non-control chars. The loop always ends
2280
               since the Unicode string is NUL-terminated. */
2281
266M
            while (PyUnicode_READ(kind, s, 0) > '\r')
2282
175M
                s += kind;
2283
90.3M
            if (s >= end) {
2284
33.7k
                *consumed = len;
2285
33.7k
                return -1;
2286
33.7k
            }
2287
90.3M
            ch = PyUnicode_READ(kind, s, 0);
2288
90.3M
            s += kind;
2289
90.3M
            if (ch == '\n')
2290
3.79M
                return (s - start)/kind;
2291
86.5M
            if (ch == '\r') {
2292
14.5M
                if (PyUnicode_READ(kind, s, 0) == '\n')
2293
443k
                    return (s - start)/kind + 1;
2294
14.1M
                else
2295
14.1M
                    return (s - start)/kind;
2296
14.5M
            }
2297
86.5M
        }
2298
18.4M
    }
2299
12.2M
    else {
2300
        /* Non-universal mode. */
2301
12.2M
        Py_ssize_t readnl_len = PyUnicode_GET_LENGTH(readnl);
2302
12.2M
        const Py_UCS1 *nl = PyUnicode_1BYTE_DATA(readnl);
2303
        /* Assume that readnl is an ASCII character. */
2304
12.2M
        assert(PyUnicode_KIND(readnl) == PyUnicode_1BYTE_KIND);
2305
12.2M
        if (readnl_len == 1) {
2306
12.2M
            const char *pos = find_control_char(kind, start, end, nl[0]);
2307
12.2M
            if (pos != NULL)
2308
12.2M
                return (pos - start)/kind + 1;
2309
5.37k
            *consumed = len;
2310
5.37k
            return -1;
2311
12.2M
        }
2312
0
        else {
2313
0
            const char *s = start;
2314
0
            const char *e = end - (readnl_len - 1)*kind;
2315
0
            const char *pos;
2316
0
            if (e < s)
2317
0
                e = s;
2318
0
            while (s < e) {
2319
0
                Py_ssize_t i;
2320
0
                const char *pos = find_control_char(kind, s, end, nl[0]);
2321
0
                if (pos == NULL || pos >= e)
2322
0
                    break;
2323
0
                for (i = 1; i < readnl_len; i++) {
2324
0
                    if (PyUnicode_READ(kind, pos, i) != nl[i])
2325
0
                        break;
2326
0
                }
2327
0
                if (i == readnl_len)
2328
0
                    return (pos - start)/kind + readnl_len;
2329
0
                s = pos + kind;
2330
0
            }
2331
0
            pos = find_control_char(kind, e, end, nl[0]);
2332
0
            if (pos == NULL)
2333
0
                *consumed = len;
2334
0
            else
2335
0
                *consumed = (pos - start)/kind;
2336
0
            return -1;
2337
0
        }
2338
12.2M
    }
2339
30.6M
}
2340
2341
static PyObject *
2342
_textiowrapper_readline(textio *self, Py_ssize_t limit)
2343
23.6k
{
2344
23.6k
    PyObject *line = NULL, *chunks = NULL, *remaining = NULL;
2345
23.6k
    Py_ssize_t start, endpos, chunked, offset_to_buffer;
2346
23.6k
    int res;
2347
2348
23.6k
    CHECK_CLOSED(self);
2349
2350
23.6k
    if (_textiowrapper_writeflush(self) < 0)
2351
0
        return NULL;
2352
2353
23.6k
    chunked = 0;
2354
2355
23.7k
    while (1) {
2356
23.7k
        const char *ptr;
2357
23.7k
        Py_ssize_t line_len;
2358
23.7k
        int kind;
2359
23.7k
        Py_ssize_t consumed = 0;
2360
2361
        /* First, get some data if necessary */
2362
23.7k
        res = 1;
2363
23.9k
        while (!self->decoded_chars ||
2364
23.7k
               !PyUnicode_GET_LENGTH(self->decoded_chars)) {
2365
130
            res = textiowrapper_read_chunk(self, 0);
2366
130
            if (res < 0) {
2367
                /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
2368
                   when EINTR occurs so we needn't do it ourselves. */
2369
0
                if (_PyIO_trap_eintr()) {
2370
0
                    continue;
2371
0
                }
2372
0
                goto error;
2373
0
            }
2374
130
            if (res == 0)
2375
10
                break;
2376
130
        }
2377
23.7k
        if (res == 0) {
2378
            /* end of file */
2379
10
            textiowrapper_set_decoded_chars(self, NULL);
2380
10
            Py_CLEAR(self->snapshot);
2381
10
            start = endpos = offset_to_buffer = 0;
2382
10
            break;
2383
10
        }
2384
2385
23.7k
        if (remaining == NULL) {
2386
23.7k
            line = Py_NewRef(self->decoded_chars);
2387
23.7k
            start = self->decoded_chars_used;
2388
23.7k
            offset_to_buffer = 0;
2389
23.7k
        }
2390
0
        else {
2391
0
            assert(self->decoded_chars_used == 0);
2392
0
            line = PyUnicode_Concat(remaining, self->decoded_chars);
2393
0
            start = 0;
2394
0
            offset_to_buffer = PyUnicode_GET_LENGTH(remaining);
2395
0
            Py_CLEAR(remaining);
2396
0
            if (line == NULL)
2397
0
                goto error;
2398
0
        }
2399
2400
23.7k
        ptr = PyUnicode_DATA(line);
2401
23.7k
        line_len = PyUnicode_GET_LENGTH(line);
2402
23.7k
        kind = PyUnicode_KIND(line);
2403
2404
23.7k
        endpos = _PyIO_find_line_ending(
2405
23.7k
            self->readtranslate, self->readuniversal, self->readnl,
2406
23.7k
            kind,
2407
23.7k
            ptr + kind * start,
2408
23.7k
            ptr + kind * line_len,
2409
23.7k
            &consumed);
2410
23.7k
        if (endpos >= 0) {
2411
23.6k
            endpos += start;
2412
23.6k
            if (limit >= 0 && (endpos - start) + chunked >= limit)
2413
0
                endpos = start + limit - chunked;
2414
23.6k
            break;
2415
23.6k
        }
2416
2417
        /* We can put aside up to `endpos` */
2418
120
        endpos = consumed + start;
2419
120
        if (limit >= 0 && (endpos - start) + chunked >= limit) {
2420
            /* Didn't find line ending, but reached length limit */
2421
0
            endpos = start + limit - chunked;
2422
0
            break;
2423
0
        }
2424
2425
120
        if (endpos > start) {
2426
            /* No line ending seen yet - put aside current data */
2427
104
            PyObject *s;
2428
104
            if (chunks == NULL) {
2429
104
                chunks = PyList_New(0);
2430
104
                if (chunks == NULL)
2431
0
                    goto error;
2432
104
            }
2433
104
            s = PyUnicode_Substring(line, start, endpos);
2434
104
            if (s == NULL)
2435
0
                goto error;
2436
104
            if (PyList_Append(chunks, s) < 0) {
2437
0
                Py_DECREF(s);
2438
0
                goto error;
2439
0
            }
2440
104
            chunked += PyUnicode_GET_LENGTH(s);
2441
104
            Py_DECREF(s);
2442
104
        }
2443
        /* There may be some remaining bytes we'll have to prepend to the
2444
           next chunk of data */
2445
120
        if (endpos < line_len) {
2446
0
            remaining = PyUnicode_Substring(line, endpos, line_len);
2447
0
            if (remaining == NULL)
2448
0
                goto error;
2449
0
        }
2450
120
        Py_CLEAR(line);
2451
        /* We have consumed the buffer */
2452
120
        textiowrapper_set_decoded_chars(self, NULL);
2453
120
    }
2454
2455
23.6k
    if (line != NULL) {
2456
        /* Our line ends in the current buffer */
2457
23.6k
        self->decoded_chars_used = endpos - offset_to_buffer;
2458
23.6k
        if (start > 0 || endpos < PyUnicode_GET_LENGTH(line)) {
2459
23.6k
            PyObject *s = PyUnicode_Substring(line, start, endpos);
2460
23.6k
            Py_CLEAR(line);
2461
23.6k
            if (s == NULL)
2462
0
                goto error;
2463
23.6k
            line = s;
2464
23.6k
        }
2465
23.6k
    }
2466
23.6k
    if (remaining != NULL) {
2467
0
        if (chunks == NULL) {
2468
0
            chunks = PyList_New(0);
2469
0
            if (chunks == NULL)
2470
0
                goto error;
2471
0
        }
2472
0
        if (PyList_Append(chunks, remaining) < 0)
2473
0
            goto error;
2474
0
        Py_CLEAR(remaining);
2475
0
    }
2476
23.6k
    if (chunks != NULL) {
2477
104
        if (line != NULL) {
2478
104
            if (PyList_Append(chunks, line) < 0)
2479
0
                goto error;
2480
104
            Py_DECREF(line);
2481
104
        }
2482
104
        line = PyUnicode_Join(&_Py_STR(empty), chunks);
2483
104
        if (line == NULL)
2484
0
            goto error;
2485
104
        Py_CLEAR(chunks);
2486
104
    }
2487
23.6k
    if (line == NULL) {
2488
10
        line = &_Py_STR(empty);
2489
10
    }
2490
2491
23.6k
    return line;
2492
2493
0
  error:
2494
0
    Py_XDECREF(chunks);
2495
0
    Py_XDECREF(remaining);
2496
0
    Py_XDECREF(line);
2497
0
    return NULL;
2498
23.6k
}
2499
2500
/*[clinic input]
2501
@critical_section
2502
_io.TextIOWrapper.readline
2503
    size: Py_ssize_t = -1
2504
    /
2505
[clinic start generated code]*/
2506
2507
static PyObject *
2508
_io_TextIOWrapper_readline_impl(textio *self, Py_ssize_t size)
2509
/*[clinic end generated code: output=344afa98804e8b25 input=b65bab871dc3ddba]*/
2510
0
{
2511
0
    CHECK_ATTACHED(self);
2512
0
    return _textiowrapper_readline(self, size);
2513
0
}
2514
2515
/* Seek and Tell */
2516
2517
typedef struct {
2518
    Py_off_t start_pos;
2519
    int dec_flags;
2520
    int bytes_to_feed;
2521
    int chars_to_skip;
2522
    char need_eof;
2523
} cookie_type;
2524
2525
/*
2526
   To speed up cookie packing/unpacking, we store the fields in a temporary
2527
   string and call _PyLong_FromByteArray() or _PyLong_AsByteArray (resp.).
2528
   The following macros define at which offsets in the intermediary byte
2529
   string the various CookieStruct fields will be stored.
2530
 */
2531
2532
#define COOKIE_BUF_LEN      (sizeof(Py_off_t) + 3 * sizeof(int) + sizeof(char))
2533
2534
#if PY_BIG_ENDIAN
2535
/* We want the least significant byte of start_pos to also be the least
2536
   significant byte of the cookie, which means that in big-endian mode we
2537
   must copy the fields in reverse order. */
2538
2539
# define OFF_START_POS      (sizeof(char) + 3 * sizeof(int))
2540
# define OFF_DEC_FLAGS      (sizeof(char) + 2 * sizeof(int))
2541
# define OFF_BYTES_TO_FEED  (sizeof(char) + sizeof(int))
2542
# define OFF_CHARS_TO_SKIP  (sizeof(char))
2543
# define OFF_NEED_EOF       0
2544
2545
#else
2546
/* Little-endian mode: the least significant byte of start_pos will
2547
   naturally end up the least significant byte of the cookie. */
2548
2549
0
# define OFF_START_POS      0
2550
0
# define OFF_DEC_FLAGS      (sizeof(Py_off_t))
2551
0
# define OFF_BYTES_TO_FEED  (sizeof(Py_off_t) + sizeof(int))
2552
0
# define OFF_CHARS_TO_SKIP  (sizeof(Py_off_t) + 2 * sizeof(int))
2553
0
# define OFF_NEED_EOF       (sizeof(Py_off_t) + 3 * sizeof(int))
2554
2555
#endif
2556
2557
static int
2558
textiowrapper_parse_cookie(cookie_type *cookie, PyObject *cookieObj)
2559
0
{
2560
0
    unsigned char buffer[COOKIE_BUF_LEN];
2561
0
    PyLongObject *cookieLong = (PyLongObject *)PyNumber_Long(cookieObj);
2562
0
    if (cookieLong == NULL)
2563
0
        return -1;
2564
2565
0
    if (_PyLong_AsByteArray(cookieLong, buffer, sizeof(buffer),
2566
0
                            PY_LITTLE_ENDIAN, 0, 1) < 0) {
2567
0
        Py_DECREF(cookieLong);
2568
0
        return -1;
2569
0
    }
2570
0
    Py_DECREF(cookieLong);
2571
2572
0
    memcpy(&cookie->start_pos, buffer + OFF_START_POS, sizeof(cookie->start_pos));
2573
0
    memcpy(&cookie->dec_flags, buffer + OFF_DEC_FLAGS, sizeof(cookie->dec_flags));
2574
0
    memcpy(&cookie->bytes_to_feed, buffer + OFF_BYTES_TO_FEED, sizeof(cookie->bytes_to_feed));
2575
0
    memcpy(&cookie->chars_to_skip, buffer + OFF_CHARS_TO_SKIP, sizeof(cookie->chars_to_skip));
2576
0
    memcpy(&cookie->need_eof, buffer + OFF_NEED_EOF, sizeof(cookie->need_eof));
2577
2578
0
    return 0;
2579
0
}
2580
2581
static PyObject *
2582
textiowrapper_build_cookie(cookie_type *cookie)
2583
0
{
2584
0
    unsigned char buffer[COOKIE_BUF_LEN];
2585
2586
0
    memcpy(buffer + OFF_START_POS, &cookie->start_pos, sizeof(cookie->start_pos));
2587
0
    memcpy(buffer + OFF_DEC_FLAGS, &cookie->dec_flags, sizeof(cookie->dec_flags));
2588
0
    memcpy(buffer + OFF_BYTES_TO_FEED, &cookie->bytes_to_feed, sizeof(cookie->bytes_to_feed));
2589
0
    memcpy(buffer + OFF_CHARS_TO_SKIP, &cookie->chars_to_skip, sizeof(cookie->chars_to_skip));
2590
0
    memcpy(buffer + OFF_NEED_EOF, &cookie->need_eof, sizeof(cookie->need_eof));
2591
2592
0
    return _PyLong_FromByteArray(buffer, sizeof(buffer),
2593
0
                                 PY_LITTLE_ENDIAN, 0);
2594
0
}
2595
2596
static int
2597
_textiowrapper_decoder_setstate(textio *self, cookie_type *cookie)
2598
0
{
2599
0
    PyObject *res;
2600
    /* When seeking to the start of the stream, we call decoder.reset()
2601
       rather than decoder.getstate().
2602
       This is for a few decoders such as utf-16 for which the state value
2603
       at start is not (b"", 0) but e.g. (b"", 2) (meaning, in the case of
2604
       utf-16, that we are expecting a BOM).
2605
    */
2606
0
    if (cookie->start_pos == 0 && cookie->dec_flags == 0) {
2607
0
        res = PyObject_CallMethodNoArgs(self->decoder, &_Py_ID(reset));
2608
0
    }
2609
0
    else {
2610
0
        res = _PyObject_CallMethod(self->decoder, &_Py_ID(setstate),
2611
0
                                   "((yi))", "", cookie->dec_flags);
2612
0
    }
2613
0
    if (res == NULL) {
2614
0
        return -1;
2615
0
    }
2616
0
    Py_DECREF(res);
2617
0
    return 0;
2618
0
}
2619
2620
static int
2621
_textiowrapper_encoder_reset(textio *self, int start_of_stream)
2622
0
{
2623
0
    PyObject *res;
2624
0
    if (start_of_stream) {
2625
0
        res = PyObject_CallMethodNoArgs(self->encoder, &_Py_ID(reset));
2626
0
        self->encoding_start_of_stream = 1;
2627
0
    }
2628
0
    else {
2629
0
        res = PyObject_CallMethodOneArg(self->encoder, &_Py_ID(setstate),
2630
0
                                        _PyLong_GetZero());
2631
0
        self->encoding_start_of_stream = 0;
2632
0
    }
2633
0
    if (res == NULL)
2634
0
        return -1;
2635
0
    Py_DECREF(res);
2636
0
    return 0;
2637
0
}
2638
2639
static int
2640
_textiowrapper_encoder_setstate(textio *self, cookie_type *cookie)
2641
0
{
2642
    /* Same as _textiowrapper_decoder_setstate() above. */
2643
0
    return _textiowrapper_encoder_reset(
2644
0
        self, cookie->start_pos == 0 && cookie->dec_flags == 0);
2645
0
}
2646
2647
/*[clinic input]
2648
@critical_section
2649
_io.TextIOWrapper.seek
2650
    cookie as cookieObj: object
2651
      Zero or an opaque number returned by tell().
2652
    whence: int(c_default='0') = os.SEEK_SET
2653
      The relative position to seek from.
2654
    /
2655
2656
Set the stream position, and return the new stream position.
2657
2658
Four operations are supported, given by the following argument
2659
combinations:
2660
2661
- seek(0, SEEK_SET): Rewind to the start of the stream.
2662
- seek(cookie, SEEK_SET): Restore a previous position;
2663
  'cookie' must be a number returned by tell().
2664
- seek(0, SEEK_END): Fast-forward to the end of the stream.
2665
- seek(0, SEEK_CUR): Leave the current stream position unchanged.
2666
2667
Any other argument combinations are invalid,
2668
and may raise exceptions.
2669
[clinic start generated code]*/
2670
2671
static PyObject *
2672
_io_TextIOWrapper_seek_impl(textio *self, PyObject *cookieObj, int whence)
2673
/*[clinic end generated code: output=0a15679764e2d04d input=4bea78698be23d7e]*/
2674
0
{
2675
0
    PyObject *posobj;
2676
0
    cookie_type cookie;
2677
0
    PyObject *res;
2678
0
    int cmp;
2679
0
    PyObject *snapshot;
2680
2681
0
    CHECK_ATTACHED(self);
2682
0
    CHECK_CLOSED(self);
2683
2684
0
    Py_INCREF(cookieObj);
2685
2686
0
    if (!self->seekable) {
2687
0
        _unsupported(self->state, "underlying stream is not seekable");
2688
0
        goto fail;
2689
0
    }
2690
2691
0
    PyObject *zero = _PyLong_GetZero();  // borrowed reference
2692
2693
0
    switch (whence) {
2694
0
    case SEEK_CUR:
2695
        /* seek relative to current position */
2696
0
        cmp = PyObject_RichCompareBool(cookieObj, zero, Py_EQ);
2697
0
        if (cmp < 0)
2698
0
            goto fail;
2699
2700
0
        if (cmp == 0) {
2701
0
            _unsupported(self->state, "can't do nonzero cur-relative seeks");
2702
0
            goto fail;
2703
0
        }
2704
2705
        /* Seeking to the current position should attempt to
2706
         * sync the underlying buffer with the current position.
2707
         */
2708
0
        Py_DECREF(cookieObj);
2709
0
        cookieObj = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(tell));
2710
0
        if (cookieObj == NULL)
2711
0
            goto fail;
2712
0
        break;
2713
2714
0
    case SEEK_END:
2715
        /* seek relative to end of file */
2716
0
        cmp = PyObject_RichCompareBool(cookieObj, zero, Py_EQ);
2717
0
        if (cmp < 0)
2718
0
            goto fail;
2719
2720
0
        if (cmp == 0) {
2721
0
            _unsupported(self->state, "can't do nonzero end-relative seeks");
2722
0
            goto fail;
2723
0
        }
2724
2725
0
        if (_PyFile_Flush((PyObject *)self) < 0) {
2726
0
            goto fail;
2727
0
        }
2728
2729
0
        textiowrapper_set_decoded_chars(self, NULL);
2730
0
        Py_CLEAR(self->snapshot);
2731
0
        if (self->decoder) {
2732
0
            res = PyObject_CallMethodNoArgs(self->decoder, &_Py_ID(reset));
2733
0
            if (res == NULL)
2734
0
                goto fail;
2735
0
            Py_DECREF(res);
2736
0
        }
2737
2738
0
        PyObject *buf = buffer_access_safe(self);
2739
0
        if (buf == NULL) {
2740
0
            goto fail;
2741
0
        }
2742
0
        res = _PyObject_CallMethod(buf, &_Py_ID(seek), "ii", 0, 2);
2743
0
        Py_DECREF(buf);
2744
0
        Py_CLEAR(cookieObj);
2745
0
        if (res == NULL)
2746
0
            goto fail;
2747
0
        if (self->encoder) {
2748
            /* If seek() == 0, we are at the start of stream, otherwise not */
2749
0
            cmp = PyObject_RichCompareBool(res, zero, Py_EQ);
2750
0
            if (cmp < 0 || _textiowrapper_encoder_reset(self, cmp)) {
2751
0
                Py_DECREF(res);
2752
0
                goto fail;
2753
0
            }
2754
0
        }
2755
0
        return res;
2756
2757
0
    case SEEK_SET:
2758
0
        break;
2759
2760
0
    default:
2761
0
        PyErr_Format(PyExc_ValueError,
2762
0
                     "invalid whence (%d, should be %d, %d or %d)", whence,
2763
0
                     SEEK_SET, SEEK_CUR, SEEK_END);
2764
0
        goto fail;
2765
0
    }
2766
2767
0
    cmp = PyObject_RichCompareBool(cookieObj, zero, Py_LT);
2768
0
    if (cmp < 0)
2769
0
        goto fail;
2770
2771
0
    if (cmp == 1) {
2772
0
        PyErr_Format(PyExc_ValueError,
2773
0
                     "negative seek position %R", cookieObj);
2774
0
        goto fail;
2775
0
    }
2776
2777
0
    if (_PyFile_Flush((PyObject *)self) < 0) {
2778
0
        goto fail;
2779
0
    }
2780
2781
    /* The strategy of seek() is to go back to the safe start point
2782
     * and replay the effect of read(chars_to_skip) from there.
2783
     */
2784
0
    if (textiowrapper_parse_cookie(&cookie, cookieObj) < 0)
2785
0
        goto fail;
2786
2787
    /* Seek back to the safe start point. */
2788
0
    posobj = PyLong_FromOff_t(cookie.start_pos);
2789
0
    if (posobj == NULL)
2790
0
        goto fail;
2791
0
    res = buffer_callmethod_onearg(self, &_Py_ID(seek), posobj);
2792
0
    Py_DECREF(posobj);
2793
0
    if (res == NULL)
2794
0
        goto fail;
2795
0
    Py_DECREF(res);
2796
2797
0
    textiowrapper_set_decoded_chars(self, NULL);
2798
0
    Py_CLEAR(self->snapshot);
2799
2800
    /* Restore the decoder to its state from the safe start point. */
2801
0
    if (self->decoder) {
2802
0
        if (_textiowrapper_decoder_setstate(self, &cookie) < 0)
2803
0
            goto fail;
2804
0
    }
2805
2806
0
    if (cookie.chars_to_skip) {
2807
        /* Just like _read_chunk, feed the decoder and save a snapshot. */
2808
0
        PyObject *bytes_to_feed = PyLong_FromLong(cookie.bytes_to_feed);
2809
0
        if (bytes_to_feed == NULL) {
2810
0
            goto fail;
2811
0
        }
2812
0
        PyObject *input_chunk = buffer_callmethod_onearg(self,
2813
0
                                                         &_Py_ID(read),
2814
0
                                                         bytes_to_feed);
2815
0
        Py_DECREF(bytes_to_feed);
2816
2817
0
        PyObject *decoded;
2818
2819
0
        if (input_chunk == NULL)
2820
0
            goto fail;
2821
2822
0
        if (!PyBytes_Check(input_chunk)) {
2823
0
            PyErr_Format(PyExc_TypeError,
2824
0
                         "underlying read() should have returned a bytes "
2825
0
                         "object, not '%.200s'",
2826
0
                         Py_TYPE(input_chunk)->tp_name);
2827
0
            Py_DECREF(input_chunk);
2828
0
            goto fail;
2829
0
        }
2830
2831
0
        snapshot = Py_BuildValue("iN", cookie.dec_flags, input_chunk);
2832
0
        if (snapshot == NULL) {
2833
0
            goto fail;
2834
0
        }
2835
0
        Py_XSETREF(self->snapshot, snapshot);
2836
2837
0
        decoded = PyObject_CallMethodObjArgs(self->decoder, &_Py_ID(decode),
2838
0
            input_chunk, cookie.need_eof ? Py_True : Py_False, NULL);
2839
2840
0
        if (check_decoded(decoded) < 0)
2841
0
            goto fail;
2842
2843
0
        textiowrapper_set_decoded_chars(self, decoded);
2844
2845
        /* Skip chars_to_skip of the decoded characters. */
2846
0
        if (PyUnicode_GetLength(self->decoded_chars) < cookie.chars_to_skip) {
2847
0
            PyErr_SetString(PyExc_OSError, "can't restore logical file position");
2848
0
            goto fail;
2849
0
        }
2850
0
        self->decoded_chars_used = cookie.chars_to_skip;
2851
0
    }
2852
0
    else {
2853
0
        snapshot = Py_BuildValue("iy", cookie.dec_flags, "");
2854
0
        if (snapshot == NULL)
2855
0
            goto fail;
2856
0
        Py_XSETREF(self->snapshot, snapshot);
2857
0
    }
2858
2859
    /* Finally, reset the encoder (merely useful for proper BOM handling) */
2860
0
    if (self->encoder) {
2861
0
        if (_textiowrapper_encoder_setstate(self, &cookie) < 0)
2862
0
            goto fail;
2863
0
    }
2864
0
    return cookieObj;
2865
0
  fail:
2866
0
    Py_XDECREF(cookieObj);
2867
0
    return NULL;
2868
2869
0
}
2870
2871
/*[clinic input]
2872
@critical_section
2873
_io.TextIOWrapper.tell
2874
2875
Return the stream position as an opaque number.
2876
2877
The return value of tell() can be given as input to seek(), to
2878
restore a previous stream position.
2879
[clinic start generated code]*/
2880
2881
static PyObject *
2882
_io_TextIOWrapper_tell_impl(textio *self)
2883
/*[clinic end generated code: output=4f168c08bf34ad5f input=aeece020f747fd92]*/
2884
0
{
2885
0
    PyObject *res;
2886
0
    PyObject *posobj = NULL;
2887
0
    cookie_type cookie = {0,0,0,0,0};
2888
0
    PyObject *next_input = NULL;
2889
0
    Py_ssize_t chars_to_skip, chars_decoded;
2890
0
    Py_ssize_t skip_bytes, skip_back;
2891
0
    PyObject *saved_state = NULL;
2892
0
    const char *input, *input_end;
2893
0
    Py_ssize_t dec_buffer_len;
2894
0
    int dec_flags;
2895
2896
0
    CHECK_ATTACHED(self);
2897
0
    CHECK_CLOSED(self);
2898
2899
0
    if (!self->seekable) {
2900
0
        _unsupported(self->state, "underlying stream is not seekable");
2901
0
        goto fail;
2902
0
    }
2903
0
    if (!self->telling) {
2904
0
        PyErr_SetString(PyExc_OSError,
2905
0
                        "telling position disabled by next() call");
2906
0
        goto fail;
2907
0
    }
2908
2909
0
    if (_textiowrapper_writeflush(self) < 0)
2910
0
        return NULL;
2911
0
    if (_PyFile_Flush((PyObject *)self) < 0) {
2912
0
        goto fail;
2913
0
    }
2914
2915
0
    posobj = buffer_callmethod_noargs(self, &_Py_ID(tell));
2916
0
    if (posobj == NULL)
2917
0
        goto fail;
2918
2919
0
    if (self->decoder == NULL || self->snapshot == NULL) {
2920
0
        assert (self->decoded_chars == NULL || PyUnicode_GetLength(self->decoded_chars) == 0);
2921
0
        return posobj;
2922
0
    }
2923
2924
#if defined(HAVE_LARGEFILE_SUPPORT)
2925
    cookie.start_pos = PyLong_AsLongLong(posobj);
2926
#else
2927
0
    cookie.start_pos = PyLong_AsLong(posobj);
2928
0
#endif
2929
0
    Py_DECREF(posobj);
2930
0
    if (PyErr_Occurred())
2931
0
        goto fail;
2932
2933
    /* Skip backward to the snapshot point (see _read_chunk). */
2934
0
    assert(PyTuple_Check(self->snapshot));
2935
0
    if (!PyArg_ParseTuple(self->snapshot, "iO", &cookie.dec_flags, &next_input))
2936
0
        goto fail;
2937
2938
0
    assert (PyBytes_Check(next_input));
2939
2940
    /* Own next_input: a reentrant or concurrent seek can drop the snapshot. */
2941
0
    Py_INCREF(next_input);
2942
2943
0
    cookie.start_pos -= PyBytes_GET_SIZE(next_input);
2944
2945
    /* How many decoded characters have been used up since the snapshot? */
2946
0
    if (self->decoded_chars_used == 0)  {
2947
        /* We haven't moved from the snapshot point. */
2948
0
        Py_DECREF(next_input);
2949
0
        return textiowrapper_build_cookie(&cookie);
2950
0
    }
2951
2952
0
    chars_to_skip = self->decoded_chars_used;
2953
2954
    /* Decoder state will be restored at the end */
2955
0
    saved_state = PyObject_CallMethodNoArgs(self->decoder,
2956
0
                                             &_Py_ID(getstate));
2957
0
    if (saved_state == NULL)
2958
0
        goto fail;
2959
2960
0
#define DECODER_GETSTATE() do { \
2961
0
        PyObject *dec_buffer; \
2962
0
        PyObject *_state = PyObject_CallMethodNoArgs(self->decoder, \
2963
0
            &_Py_ID(getstate)); \
2964
0
        if (_state == NULL) \
2965
0
            goto fail; \
2966
0
        if (!PyTuple_Check(_state)) { \
2967
0
            PyErr_SetString(PyExc_TypeError, \
2968
0
                            "illegal decoder state"); \
2969
0
            Py_DECREF(_state); \
2970
0
            goto fail; \
2971
0
        } \
2972
0
        if (!PyArg_ParseTuple(_state, "Oi;illegal decoder state", \
2973
0
                              &dec_buffer, &dec_flags)) \
2974
0
        { \
2975
0
            Py_DECREF(_state); \
2976
0
            goto fail; \
2977
0
        } \
2978
0
        if (!PyBytes_Check(dec_buffer)) { \
2979
0
            PyErr_Format(PyExc_TypeError, \
2980
0
                         "illegal decoder state: the first item should be a " \
2981
0
                         "bytes object, not '%.200s'", \
2982
0
                         Py_TYPE(dec_buffer)->tp_name); \
2983
0
            Py_DECREF(_state); \
2984
0
            goto fail; \
2985
0
        } \
2986
0
        dec_buffer_len = PyBytes_GET_SIZE(dec_buffer); \
2987
0
        Py_DECREF(_state); \
2988
0
    } while (0)
2989
2990
0
#define DECODER_DECODE(start, len, res) do { \
2991
0
        PyObject *_decoded = _PyObject_CallMethod( \
2992
0
            self->decoder, &_Py_ID(decode), "y#", start, len); \
2993
0
        if (check_decoded(_decoded) < 0) \
2994
0
            goto fail; \
2995
0
        res = PyUnicode_GET_LENGTH(_decoded); \
2996
0
        Py_DECREF(_decoded); \
2997
0
    } while (0)
2998
2999
    /* Fast search for an acceptable start point, close to our
3000
       current pos */
3001
0
    double skip_estimate = self->b2cratio * chars_to_skip;
3002
0
    if (skip_estimate >= 0 &&
3003
0
        skip_estimate <= PyBytes_GET_SIZE(next_input))
3004
0
    {
3005
0
        skip_bytes = (Py_ssize_t)skip_estimate;
3006
0
    }
3007
0
    else {
3008
0
        skip_bytes = 0;
3009
0
    }
3010
0
    skip_back = 1;
3011
0
    input = PyBytes_AS_STRING(next_input);
3012
0
    while (skip_bytes > 0) {
3013
        /* Decode up to temptative start point */
3014
0
        if (_textiowrapper_decoder_setstate(self, &cookie) < 0)
3015
0
            goto fail;
3016
0
        DECODER_DECODE(input, skip_bytes, chars_decoded);
3017
0
        if (chars_decoded <= chars_to_skip) {
3018
0
            DECODER_GETSTATE();
3019
0
            if (dec_buffer_len == 0) {
3020
                /* Before pos and no bytes buffered in decoder => OK */
3021
0
                cookie.dec_flags = dec_flags;
3022
0
                chars_to_skip -= chars_decoded;
3023
0
                break;
3024
0
            }
3025
            /* Skip back by buffered amount and reset heuristic */
3026
0
            skip_bytes -= dec_buffer_len;
3027
0
            skip_back = 1;
3028
0
        }
3029
0
        else {
3030
            /* We're too far ahead, skip back a bit */
3031
0
            skip_bytes -= skip_back;
3032
0
            skip_back *= 2;
3033
0
        }
3034
0
    }
3035
0
    if (skip_bytes <= 0) {
3036
0
        skip_bytes = 0;
3037
0
        if (_textiowrapper_decoder_setstate(self, &cookie) < 0)
3038
0
            goto fail;
3039
0
    }
3040
3041
    /* Note our initial start point. */
3042
0
    cookie.start_pos += skip_bytes;
3043
0
    cookie.chars_to_skip = Py_SAFE_DOWNCAST(chars_to_skip, Py_ssize_t, int);
3044
0
    if (chars_to_skip == 0)
3045
0
        goto finally;
3046
3047
    /* We should be close to the desired position.  Now feed the decoder one
3048
     * byte at a time until we reach the `chars_to_skip` target.
3049
     * As we go, note the nearest "safe start point" before the current
3050
     * location (a point where the decoder has nothing buffered, so seek()
3051
     * can safely start from there and advance to this location).
3052
     */
3053
0
    chars_decoded = 0;
3054
0
    input = PyBytes_AS_STRING(next_input);
3055
0
    input_end = input + PyBytes_GET_SIZE(next_input);
3056
0
    input += skip_bytes;
3057
0
    while (input < input_end) {
3058
0
        Py_ssize_t n;
3059
3060
0
        DECODER_DECODE(input, (Py_ssize_t)1, n);
3061
        /* We got n chars for 1 byte */
3062
0
        chars_decoded += n;
3063
0
        cookie.bytes_to_feed += 1;
3064
0
        DECODER_GETSTATE();
3065
3066
0
        if (dec_buffer_len == 0 && chars_decoded <= chars_to_skip) {
3067
            /* Decoder buffer is empty, so this is a safe start point. */
3068
0
            cookie.start_pos += cookie.bytes_to_feed;
3069
0
            chars_to_skip -= chars_decoded;
3070
0
            cookie.dec_flags = dec_flags;
3071
0
            cookie.bytes_to_feed = 0;
3072
0
            chars_decoded = 0;
3073
0
        }
3074
0
        if (chars_decoded >= chars_to_skip)
3075
0
            break;
3076
0
        input++;
3077
0
    }
3078
0
    if (input == input_end) {
3079
        /* We didn't get enough decoded data; signal EOF to get more. */
3080
0
        PyObject *decoded = _PyObject_CallMethod(
3081
0
            self->decoder, &_Py_ID(decode), "yO", "", /* final = */ Py_True);
3082
0
        if (check_decoded(decoded) < 0)
3083
0
            goto fail;
3084
0
        chars_decoded += PyUnicode_GET_LENGTH(decoded);
3085
0
        Py_DECREF(decoded);
3086
0
        cookie.need_eof = 1;
3087
3088
0
        if (chars_decoded < chars_to_skip) {
3089
0
            PyErr_SetString(PyExc_OSError,
3090
0
                            "can't reconstruct logical file position");
3091
0
            goto fail;
3092
0
        }
3093
0
    }
3094
3095
0
finally:
3096
0
    Py_XDECREF(next_input);
3097
0
    res = PyObject_CallMethodOneArg(
3098
0
            self->decoder, &_Py_ID(setstate), saved_state);
3099
0
    Py_DECREF(saved_state);
3100
0
    if (res == NULL)
3101
0
        return NULL;
3102
0
    Py_DECREF(res);
3103
3104
    /* The returned cookie corresponds to the last safe start point. */
3105
0
    cookie.chars_to_skip = Py_SAFE_DOWNCAST(chars_to_skip, Py_ssize_t, int);
3106
0
    return textiowrapper_build_cookie(&cookie);
3107
3108
0
fail:
3109
0
    Py_XDECREF(next_input);
3110
0
    if (saved_state) {
3111
0
        PyObject *exc = PyErr_GetRaisedException();
3112
0
        res = PyObject_CallMethodOneArg(
3113
0
                self->decoder, &_Py_ID(setstate), saved_state);
3114
0
        _PyErr_ChainExceptions1(exc);
3115
0
        Py_DECREF(saved_state);
3116
0
        Py_XDECREF(res);
3117
0
    }
3118
0
    return NULL;
3119
0
}
3120
3121
/*[clinic input]
3122
@critical_section
3123
_io.TextIOWrapper.truncate
3124
    pos: object = None
3125
    /
3126
[clinic start generated code]*/
3127
3128
static PyObject *
3129
_io_TextIOWrapper_truncate_impl(textio *self, PyObject *pos)
3130
/*[clinic end generated code: output=90ec2afb9bb7745f input=8bddb320834c93ee]*/
3131
0
{
3132
0
    CHECK_ATTACHED(self)
3133
3134
0
    if (_PyFile_Flush((PyObject *)self) < 0) {
3135
0
        return NULL;
3136
0
    }
3137
3138
0
    return buffer_callmethod_onearg(self, &_Py_ID(truncate), pos);
3139
0
}
3140
3141
static PyObject *
3142
textiowrapper_repr(PyObject *op)
3143
0
{
3144
0
    PyObject *nameobj, *modeobj, *res, *s;
3145
0
    int status;
3146
0
    textio *self = textio_CAST(op);
3147
0
    const char *type_name = Py_TYPE(self)->tp_name;
3148
3149
0
    CHECK_INITIALIZED(self);
3150
3151
0
    res = PyUnicode_FromFormat("<%.100s", type_name);
3152
0
    if (res == NULL)
3153
0
        return NULL;
3154
3155
0
    status = Py_ReprEnter(op);
3156
0
    if (status != 0) {
3157
0
        if (status > 0) {
3158
0
            PyErr_Format(PyExc_RuntimeError,
3159
0
                         "reentrant call inside %.100s.__repr__",
3160
0
                         type_name);
3161
0
        }
3162
0
        goto error;
3163
0
    }
3164
0
    if (PyObject_GetOptionalAttr(op, &_Py_ID(name), &nameobj) < 0) {
3165
0
        if (!PyErr_ExceptionMatches(PyExc_ValueError)) {
3166
0
            goto error;
3167
0
        }
3168
        /* Ignore ValueError raised if the underlying stream was detached */
3169
0
        PyErr_Clear();
3170
0
    }
3171
0
    if (nameobj != NULL) {
3172
0
        s = PyUnicode_FromFormat(" name=%R", nameobj);
3173
0
        Py_DECREF(nameobj);
3174
0
        if (s == NULL)
3175
0
            goto error;
3176
0
        PyUnicode_AppendAndDel(&res, s);
3177
0
        if (res == NULL)
3178
0
            goto error;
3179
0
    }
3180
0
    if (PyObject_GetOptionalAttr(op, &_Py_ID(mode), &modeobj) < 0) {
3181
0
        goto error;
3182
0
    }
3183
0
    if (modeobj != NULL) {
3184
0
        s = PyUnicode_FromFormat(" mode=%R", modeobj);
3185
0
        Py_DECREF(modeobj);
3186
0
        if (s == NULL)
3187
0
            goto error;
3188
0
        PyUnicode_AppendAndDel(&res, s);
3189
0
        if (res == NULL)
3190
0
            goto error;
3191
0
    }
3192
0
    s = PyUnicode_FromFormat("%U encoding=%R>",
3193
0
                             res, self->encoding);
3194
0
    Py_DECREF(res);
3195
0
    if (status == 0) {
3196
0
        Py_ReprLeave(op);
3197
0
    }
3198
0
    return s;
3199
3200
0
  error:
3201
0
    Py_XDECREF(res);
3202
0
    if (status == 0) {
3203
0
        Py_ReprLeave(op);
3204
0
    }
3205
0
    return NULL;
3206
0
}
3207
3208
3209
/* Inquiries */
3210
3211
/*[clinic input]
3212
@critical_section
3213
_io.TextIOWrapper.fileno
3214
[clinic start generated code]*/
3215
3216
static PyObject *
3217
_io_TextIOWrapper_fileno_impl(textio *self)
3218
/*[clinic end generated code: output=21490a4c3da13e6c input=515e1196aceb97ab]*/
3219
0
{
3220
0
    return buffer_callmethod_noargs(self, &_Py_ID(fileno));
3221
0
}
3222
3223
/*[clinic input]
3224
@critical_section
3225
_io.TextIOWrapper.seekable
3226
[clinic start generated code]*/
3227
3228
static PyObject *
3229
_io_TextIOWrapper_seekable_impl(textio *self)
3230
/*[clinic end generated code: output=ab223dbbcffc0f00 input=71c4c092736c549b]*/
3231
0
{
3232
0
    return buffer_callmethod_noargs(self, &_Py_ID(seekable));
3233
0
}
3234
3235
/*[clinic input]
3236
@critical_section
3237
_io.TextIOWrapper.readable
3238
[clinic start generated code]*/
3239
3240
static PyObject *
3241
_io_TextIOWrapper_readable_impl(textio *self)
3242
/*[clinic end generated code: output=72ff7ba289a8a91b input=80438d1f01b0a89b]*/
3243
0
{
3244
0
    return buffer_callmethod_noargs(self, &_Py_ID(readable));
3245
0
}
3246
3247
/*[clinic input]
3248
@critical_section
3249
_io.TextIOWrapper.writable
3250
[clinic start generated code]*/
3251
3252
static PyObject *
3253
_io_TextIOWrapper_writable_impl(textio *self)
3254
/*[clinic end generated code: output=a728c71790d03200 input=9d6c22befb0c340a]*/
3255
0
{
3256
0
    return buffer_callmethod_noargs(self, &_Py_ID(writable));
3257
0
}
3258
3259
/*[clinic input]
3260
@critical_section
3261
_io.TextIOWrapper.isatty
3262
[clinic start generated code]*/
3263
3264
static PyObject *
3265
_io_TextIOWrapper_isatty_impl(textio *self)
3266
/*[clinic end generated code: output=12be1a35bace882e input=7f83ff04d4d1733d]*/
3267
0
{
3268
0
    return buffer_callmethod_noargs(self, &_Py_ID(isatty));
3269
0
}
3270
3271
/*[clinic input]
3272
@critical_section
3273
_io.TextIOWrapper.flush
3274
[clinic start generated code]*/
3275
3276
static PyObject *
3277
_io_TextIOWrapper_flush_impl(textio *self)
3278
/*[clinic end generated code: output=59de9165f9c2e4d2 input=3ac3bf521bfed59d]*/
3279
19
{
3280
19
    CHECK_ATTACHED(self);
3281
19
    CHECK_CLOSED(self);
3282
19
    self->telling = self->seekable;
3283
19
    if (_textiowrapper_writeflush(self) < 0)
3284
0
        return NULL;
3285
19
    return buffer_callmethod_noargs(self, &_Py_ID(flush));
3286
19
}
3287
3288
/*[clinic input]
3289
@critical_section
3290
_io.TextIOWrapper.close
3291
[clinic start generated code]*/
3292
3293
static PyObject *
3294
_io_TextIOWrapper_close_impl(textio *self)
3295
/*[clinic end generated code: output=056ccf8b4876e4f4 input=8e12d7079d5ac5c1]*/
3296
19
{
3297
19
    PyObject *res;
3298
19
    int r;
3299
19
    CHECK_ATTACHED(self);
3300
3301
19
    res = _io_TextIOWrapper_closed_get_impl(self);
3302
19
    if (res == NULL)
3303
0
        return NULL;
3304
19
    r = PyObject_IsTrue(res);
3305
19
    Py_DECREF(res);
3306
19
    if (r < 0)
3307
0
        return NULL;
3308
3309
19
    if (r > 0) {
3310
0
        Py_RETURN_NONE; /* stream already closed */
3311
0
    }
3312
19
    if (self->detached) {
3313
0
        Py_RETURN_NONE; /* gh-142594 null pointer issue */
3314
0
    }
3315
19
    else {
3316
19
        PyObject *exc = NULL;
3317
19
        if (self->finalizing) {
3318
0
            res = buffer_callmethod_onearg(self,
3319
0
                                           &_Py_ID(_dealloc_warn),
3320
0
                                           (PyObject *)self);
3321
0
            if (res) {
3322
0
                Py_DECREF(res);
3323
0
            }
3324
0
            else {
3325
0
                PyErr_Clear();
3326
0
            }
3327
0
        }
3328
19
        if (_PyFile_Flush((PyObject *)self) < 0) {
3329
0
            exc = PyErr_GetRaisedException();
3330
0
        }
3331
3332
19
        res = buffer_callmethod_noargs(self, &_Py_ID(close));
3333
19
        if (exc != NULL) {
3334
0
            _PyErr_ChainExceptions1(exc);
3335
0
            Py_CLEAR(res);
3336
0
        }
3337
19
        return res;
3338
19
    }
3339
19
}
3340
3341
/*[clinic input]
3342
@critical_section
3343
_io.TextIOWrapper.__next__ as textiowrapper_iternext
3344
[clinic start generated code]*/
3345
3346
static PyObject *
3347
textiowrapper_iternext_impl(textio *self)
3348
/*[clinic end generated code: output=f365c4287cd43a1f input=c5b4c79faf0c98cb]*/
3349
23.6k
{
3350
23.6k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
3351
23.6k
    PyObject *line;
3352
3353
23.6k
    CHECK_ATTACHED(self);
3354
3355
23.6k
    self->telling = 0;
3356
23.6k
    if (Py_IS_TYPE(self, self->state->PyTextIOWrapper_Type)) {
3357
        /* Skip method call overhead for speed */
3358
23.6k
        line = _textiowrapper_readline(self, -1);
3359
23.6k
    }
3360
0
    else {
3361
0
        line = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(readline));
3362
0
        if (line && !PyUnicode_Check(line)) {
3363
0
            PyErr_Format(PyExc_OSError,
3364
0
                         "readline() should have returned a str object, "
3365
0
                         "not '%.200s'", Py_TYPE(line)->tp_name);
3366
0
            Py_DECREF(line);
3367
0
            return NULL;
3368
0
        }
3369
0
    }
3370
3371
23.6k
    if (line == NULL)
3372
0
        return NULL;
3373
3374
23.6k
    if (PyUnicode_GET_LENGTH(line) == 0) {
3375
        /* Reached EOF or would have blocked */
3376
10
        Py_DECREF(line);
3377
10
        Py_CLEAR(self->snapshot);
3378
10
        self->telling = self->seekable;
3379
10
        return NULL;
3380
10
    }
3381
3382
23.6k
    return line;
3383
23.6k
}
3384
3385
/*[clinic input]
3386
@critical_section
3387
@getter
3388
_io.TextIOWrapper.name
3389
[clinic start generated code]*/
3390
3391
static PyObject *
3392
_io_TextIOWrapper_name_get_impl(textio *self)
3393
/*[clinic end generated code: output=8c2f1d6d8756af40 input=26ecec9b39e30e07]*/
3394
0
{
3395
0
    return buffer_getattr(self, &_Py_ID(name));
3396
0
}
3397
3398
/*[clinic input]
3399
@critical_section
3400
@getter
3401
_io.TextIOWrapper.closed
3402
[clinic start generated code]*/
3403
3404
static PyObject *
3405
_io_TextIOWrapper_closed_get_impl(textio *self)
3406
/*[clinic end generated code: output=b49b68f443a85e3c input=7dfcf43f63c7003d]*/
3407
67
{
3408
    /* If partially constructed or deconstructed, return that the underlying
3409
       buffer is closed.
3410
3411
       The code managing the transition is responsible for closing. The closed
3412
       attribute is often called in re-initalization, as part of repr in error
3413
       cases, and when the I/O stack is garbage collected. */
3414
67
    if (self->ok <= 0) {
3415
0
        Py_RETURN_TRUE;
3416
0
    }
3417
3418
67
    return buffer_getattr(self, &_Py_ID(closed));
3419
67
}
3420
3421
/*[clinic input]
3422
@critical_section
3423
@getter
3424
_io.TextIOWrapper.newlines
3425
[clinic start generated code]*/
3426
3427
static PyObject *
3428
_io_TextIOWrapper_newlines_get_impl(textio *self)
3429
/*[clinic end generated code: output=53aa03ac35573180 input=610df647e514b3e8]*/
3430
0
{
3431
0
    PyObject *res;
3432
0
    CHECK_ATTACHED(self);
3433
0
    if (self->decoder == NULL ||
3434
0
        PyObject_GetOptionalAttr(self->decoder, &_Py_ID(newlines), &res) == 0)
3435
0
    {
3436
0
        Py_RETURN_NONE;
3437
0
    }
3438
0
    return res;
3439
0
}
3440
3441
/*[clinic input]
3442
@critical_section
3443
@getter
3444
_io.TextIOWrapper.errors
3445
[clinic start generated code]*/
3446
3447
static PyObject *
3448
_io_TextIOWrapper_errors_get_impl(textio *self)
3449
/*[clinic end generated code: output=dca3a3ef21b09484 input=b45f983e6d43c4d8]*/
3450
0
{
3451
0
    CHECK_INITIALIZED(self);
3452
0
    return Py_NewRef(self->errors);
3453
0
}
3454
3455
/*[clinic input]
3456
@critical_section
3457
@getter
3458
_io.TextIOWrapper._CHUNK_SIZE -> Py_ssize_t
3459
[clinic start generated code]*/
3460
3461
static Py_ssize_t
3462
_io_TextIOWrapper__CHUNK_SIZE_get_impl(textio *self)
3463
/*[clinic end generated code: output=3fe34b873b6b2c8c input=cae767b74b6b46bd]*/
3464
0
{
3465
0
    CHECK_ATTACHED_INT(self);
3466
0
    return self->chunk_size;
3467
0
}
3468
3469
/*[clinic input]
3470
@critical_section
3471
@setter
3472
_io.TextIOWrapper._CHUNK_SIZE
3473
    value: Py_ssize_t
3474
[clinic start generated code]*/
3475
3476
static int
3477
_io_TextIOWrapper__CHUNK_SIZE_set_impl(textio *self, Py_ssize_t value)
3478
/*[clinic end generated code: output=5170a93dd4d74917 input=ede7bae6145f941b]*/
3479
0
{
3480
0
    CHECK_ATTACHED_INT(self);
3481
0
    if (value <= 0) {
3482
0
        PyErr_SetString(PyExc_ValueError,
3483
0
                        "a strictly positive integer is required");
3484
0
        return -1;
3485
0
    }
3486
0
    self->chunk_size = value;
3487
0
    return 0;
3488
0
}
3489
3490
/*[clinic input]
3491
@critical_section
3492
@getter
3493
_io.TextIOWrapper.buffer
3494
[clinic start generated code]*/
3495
3496
static PyObject *
3497
_io_TextIOWrapper_buffer_get_impl(textio *self)
3498
/*[clinic end generated code: output=d265a34555aa5d4b input=5951cfa148f7350a]*/
3499
0
{
3500
    /* gh-160427: None once detached, matching the former member descriptor. */
3501
0
    if (self->buffer == NULL) {
3502
0
        Py_RETURN_NONE;
3503
0
    }
3504
0
    return Py_NewRef(self->buffer);
3505
0
}
3506
3507
static PyMethodDef incrementalnewlinedecoder_methods[] = {
3508
    _IO_INCREMENTALNEWLINEDECODER_DECODE_METHODDEF
3509
    _IO_INCREMENTALNEWLINEDECODER_GETSTATE_METHODDEF
3510
    _IO_INCREMENTALNEWLINEDECODER_SETSTATE_METHODDEF
3511
    _IO_INCREMENTALNEWLINEDECODER_RESET_METHODDEF
3512
    {NULL}
3513
};
3514
3515
static PyGetSetDef incrementalnewlinedecoder_getset[] = {
3516
    _IO_INCREMENTALNEWLINEDECODER_NEWLINES_GETSETDEF
3517
    {NULL}
3518
};
3519
3520
static PyType_Slot nldecoder_slots[] = {
3521
    {Py_tp_dealloc, incrementalnewlinedecoder_dealloc},
3522
    {Py_tp_doc, (void *)_io_IncrementalNewlineDecoder___init____doc__},
3523
    {Py_tp_methods, incrementalnewlinedecoder_methods},
3524
    {Py_tp_getset, incrementalnewlinedecoder_getset},
3525
    {Py_tp_traverse, incrementalnewlinedecoder_traverse},
3526
    {Py_tp_clear, incrementalnewlinedecoder_clear},
3527
    {Py_tp_init, _io_IncrementalNewlineDecoder___init__},
3528
    {Py_tp_vectorcall, _io_IncrementalNewlineDecoder_vectorcall},
3529
    {0, NULL},
3530
};
3531
3532
PyType_Spec _Py_nldecoder_spec = {
3533
    .name = "_io.IncrementalNewlineDecoder",
3534
    .basicsize = sizeof(nldecoder_object),
3535
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
3536
              Py_TPFLAGS_IMMUTABLETYPE),
3537
    .slots = nldecoder_slots,
3538
};
3539
3540
3541
static PyMethodDef textiowrapper_methods[] = {
3542
    _IO_TEXTIOWRAPPER_DETACH_METHODDEF
3543
    _IO_TEXTIOWRAPPER_RECONFIGURE_METHODDEF
3544
    _IO_TEXTIOWRAPPER_WRITE_METHODDEF
3545
    _IO_TEXTIOWRAPPER_READ_METHODDEF
3546
    _IO_TEXTIOWRAPPER_READLINE_METHODDEF
3547
    _IO_TEXTIOWRAPPER_FLUSH_METHODDEF
3548
    _IO_TEXTIOWRAPPER_CLOSE_METHODDEF
3549
3550
    _IO_TEXTIOWRAPPER_FILENO_METHODDEF
3551
    _IO_TEXTIOWRAPPER_SEEKABLE_METHODDEF
3552
    _IO_TEXTIOWRAPPER_READABLE_METHODDEF
3553
    _IO_TEXTIOWRAPPER_WRITABLE_METHODDEF
3554
    _IO_TEXTIOWRAPPER_ISATTY_METHODDEF
3555
3556
    _IO_TEXTIOWRAPPER_SEEK_METHODDEF
3557
    _IO_TEXTIOWRAPPER_TELL_METHODDEF
3558
    _IO_TEXTIOWRAPPER_TRUNCATE_METHODDEF
3559
3560
    {"__getstate__", _PyIOBase_cannot_pickle, METH_NOARGS},
3561
    {NULL, NULL}
3562
};
3563
3564
static PyMemberDef textiowrapper_members[] = {
3565
    {"encoding", _Py_T_OBJECT, offsetof(textio, encoding), Py_READONLY},
3566
    {"line_buffering", Py_T_BOOL, offsetof(textio, line_buffering), Py_READONLY},
3567
    {"write_through", Py_T_BOOL, offsetof(textio, write_through), Py_READONLY},
3568
    {"_finalizing", Py_T_BOOL, offsetof(textio, finalizing), 0},
3569
    {NULL}
3570
};
3571
3572
static PyGetSetDef textiowrapper_getset[] = {
3573
    _IO_TEXTIOWRAPPER_NAME_GETSETDEF
3574
    _IO_TEXTIOWRAPPER_CLOSED_GETSETDEF
3575
    _IO_TEXTIOWRAPPER_NEWLINES_GETSETDEF
3576
    _IO_TEXTIOWRAPPER_ERRORS_GETSETDEF
3577
    _IO_TEXTIOWRAPPER__CHUNK_SIZE_GETSETDEF
3578
    _IO_TEXTIOWRAPPER_BUFFER_GETSETDEF
3579
    {NULL}
3580
};
3581
3582
static PyType_Slot textiowrapper_slots[] = {
3583
    {Py_tp_dealloc, textiowrapper_dealloc},
3584
    {Py_tp_repr, textiowrapper_repr},
3585
    {Py_tp_doc, (void *)_io_TextIOWrapper___init____doc__},
3586
    {Py_tp_traverse, textiowrapper_traverse},
3587
    {Py_tp_clear, textiowrapper_clear},
3588
    {Py_tp_iternext, textiowrapper_iternext},
3589
    {Py_tp_methods, textiowrapper_methods},
3590
    {Py_tp_members, textiowrapper_members},
3591
    {Py_tp_getset, textiowrapper_getset},
3592
    {Py_tp_init, _io_TextIOWrapper___init__},
3593
    {0, NULL},
3594
};
3595
3596
PyType_Spec _Py_textiowrapper_spec = {
3597
    .name = "_io.TextIOWrapper",
3598
    .basicsize = sizeof(textio),
3599
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
3600
              Py_TPFLAGS_IMMUTABLETYPE),
3601
    .slots = textiowrapper_slots,
3602
};