Debian Codegraph @

Modules/_io/textio.c

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