2 An implementation of Text I/O as defined by PEP 3116 - "New I/O"
4 Classes defined here: TextIOBase, IncrementalNewlineDecoder, TextIOWrapper.
6 Written by Amaury Forgeot d'Arc and Antoine Pitrou
9 #define PY_SSIZE_T_CLEAN
11 #include "structmember.h"
12 #include "_iomodule.h"
16 PyDoc_STRVAR(textiobase_doc
,
17 "Base class for text I/O.\n"
19 "This class provides a character and line based interface to stream\n"
20 "I/O. There is no readinto method because Python's character strings\n"
21 "are immutable. There is no public constructor.\n"
25 _unsupported(const char *message
)
27 PyErr_SetString(_PyIO_unsupported_operation
, message
);
31 PyDoc_STRVAR(textiobase_detach_doc
,
32 "Separate the underlying buffer from the TextIOBase and return it.\n"
34 "After the underlying buffer has been detached, the TextIO is in an\n"
39 textiobase_detach(PyObject
*self
)
41 return _unsupported("detach");
44 PyDoc_STRVAR(textiobase_read_doc
,
45 "Read at most n characters from stream.\n"
47 "Read from underlying buffer until we have n characters or we hit EOF.\n"
48 "If n is negative or omitted, read until EOF.\n"
52 textiobase_read(PyObject
*self
, PyObject
*args
)
54 return _unsupported("read");
57 PyDoc_STRVAR(textiobase_readline_doc
,
58 "Read until newline or EOF.\n"
60 "Returns an empty string if EOF is hit immediately.\n"
64 textiobase_readline(PyObject
*self
, PyObject
*args
)
66 return _unsupported("readline");
69 PyDoc_STRVAR(textiobase_write_doc
,
70 "Write string to stream.\n"
71 "Returns the number of characters written (which is always equal to\n"
72 "the length of the string).\n"
76 textiobase_write(PyObject
*self
, PyObject
*args
)
78 return _unsupported("write");
81 PyDoc_STRVAR(textiobase_encoding_doc
,
82 "Encoding of the text stream.\n"
84 "Subclasses should override.\n"
88 textiobase_encoding_get(PyObject
*self
, void *context
)
93 PyDoc_STRVAR(textiobase_newlines_doc
,
94 "Line endings translated so far.\n"
96 "Only line endings translated during reading are considered.\n"
98 "Subclasses should override.\n"
102 textiobase_newlines_get(PyObject
*self
, void *context
)
107 PyDoc_STRVAR(textiobase_errors_doc
,
108 "The error setting of the decoder or encoder.\n"
110 "Subclasses should override.\n"
114 textiobase_errors_get(PyObject
*self
, void *context
)
120 static PyMethodDef textiobase_methods
[] = {
121 {"detach", (PyCFunction
)textiobase_detach
, METH_NOARGS
, textiobase_detach_doc
},
122 {"read", textiobase_read
, METH_VARARGS
, textiobase_read_doc
},
123 {"readline", textiobase_readline
, METH_VARARGS
, textiobase_readline_doc
},
124 {"write", textiobase_write
, METH_VARARGS
, textiobase_write_doc
},
128 static PyGetSetDef textiobase_getset
[] = {
129 {"encoding", (getter
)textiobase_encoding_get
, NULL
, textiobase_encoding_doc
},
130 {"newlines", (getter
)textiobase_newlines_get
, NULL
, textiobase_newlines_doc
},
131 {"errors", (getter
)textiobase_errors_get
, NULL
, textiobase_errors_doc
},
135 PyTypeObject PyTextIOBase_Type
= {
136 PyVarObject_HEAD_INIT(NULL
, 0)
137 "_io._TextIOBase", /*tp_name*/
147 0, /*tp_as_sequence*/
155 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
156 textiobase_doc
, /* tp_doc */
159 0, /* tp_richcompare */
160 0, /* tp_weaklistoffset */
163 textiobase_methods
, /* tp_methods */
165 textiobase_getset
, /* tp_getset */
166 &PyIOBase_Type
, /* tp_base */
168 0, /* tp_descr_get */
169 0, /* tp_descr_set */
170 0, /* tp_dictoffset */
177 /* IncrementalNewlineDecoder */
179 PyDoc_STRVAR(incrementalnewlinedecoder_doc
,
180 "Codec used when reading a file in universal newlines mode. It wraps\n"
181 "another incremental decoder, translating \\r\\n and \\r into \\n. It also\n"
182 "records the types of newlines encountered. When used with\n"
183 "translate=False, it ensures that the newline sequence is returned in\n"
184 "one piece. When used with decoder=None, it expects unicode strings as\n"
185 "decode input and translates newlines without first invoking an external\n"
193 signed int pendingcr
: 1;
194 signed int translate
: 1;
195 unsigned int seennl
: 3;
199 incrementalnewlinedecoder_init(nldecoder_object
*self
,
200 PyObject
*args
, PyObject
*kwds
)
204 PyObject
*errors
= NULL
;
205 char *kwlist
[] = {"decoder", "translate", "errors", NULL
};
207 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "Oi|O:IncrementalNewlineDecoder",
208 kwlist
, &decoder
, &translate
, &errors
))
211 self
->decoder
= decoder
;
214 if (errors
== NULL
) {
215 self
->errors
= PyUnicode_FromString("strict");
216 if (self
->errors
== NULL
)
221 self
->errors
= errors
;
224 self
->translate
= translate
;
232 incrementalnewlinedecoder_dealloc(nldecoder_object
*self
)
234 Py_CLEAR(self
->decoder
);
235 Py_CLEAR(self
->errors
);
236 Py_TYPE(self
)->tp_free((PyObject
*)self
);
242 #define SEEN_ALL (SEEN_CR | SEEN_LF | SEEN_CRLF)
245 _PyIncrementalNewlineDecoder_decode(PyObject
*_self
,
246 PyObject
*input
, int final
)
249 Py_ssize_t output_len
;
250 nldecoder_object
*self
= (nldecoder_object
*) _self
;
252 if (self
->decoder
== NULL
) {
253 PyErr_SetString(PyExc_ValueError
,
254 "IncrementalNewlineDecoder.__init__ not called");
258 /* decode input (with the eventual \r from a previous pass) */
259 if (self
->decoder
!= Py_None
) {
260 output
= PyObject_CallMethodObjArgs(self
->decoder
,
261 _PyIO_str_decode
, input
, final
? Py_True
: Py_False
, NULL
);
271 if (!PyUnicode_Check(output
)) {
272 PyErr_SetString(PyExc_TypeError
,
273 "decoder should return a string result");
277 output_len
= PyUnicode_GET_SIZE(output
);
278 if (self
->pendingcr
&& (final
|| output_len
> 0)) {
280 PyObject
*modified
= PyUnicode_FromUnicode(NULL
, output_len
+ 1);
281 if (modified
== NULL
)
283 out
= PyUnicode_AS_UNICODE(modified
);
285 memcpy(out
+ 1, PyUnicode_AS_UNICODE(output
),
286 output_len
* sizeof(Py_UNICODE
));
293 /* retain last \r even when not translating data:
294 * then readline() is sure to get \r\n in one pass
298 && PyUnicode_AS_UNICODE(output
)[output_len
- 1] == '\r') {
300 if (Py_REFCNT(output
) == 1) {
301 if (PyUnicode_Resize(&output
, output_len
- 1) < 0)
305 PyObject
*modified
= PyUnicode_FromUnicode(
306 PyUnicode_AS_UNICODE(output
),
308 if (modified
== NULL
)
317 /* Record which newlines are read and do newline translation if desired,
322 int seennl
= self
->seennl
;
325 in_str
= PyUnicode_AS_UNICODE(output
);
326 len
= PyUnicode_GET_SIZE(output
);
331 /* If, up to now, newlines are consistently \n, do a quick check
332 for the \r *byte* with the libc's optimized memchr.
334 if (seennl
== SEEN_LF
|| seennl
== 0) {
335 only_lf
= (memchr(in_str
, '\r', len
* sizeof(Py_UNICODE
)) == NULL
);
339 /* If not already seen, quick scan for a possible "\n" character.
340 (there's nothing else to be done, even when in translation mode)
343 memchr(in_str
, '\n', len
* sizeof(Py_UNICODE
)) != NULL
) {
349 /* Fast loop for non-control characters */
361 /* Finished: we have scanned for newlines, and none of them
364 else if (!self
->translate
) {
366 /* We have already seen all newline types, no need to scan again */
367 if (seennl
== SEEN_ALL
)
373 /* Fast loop for non-control characters */
379 else if (c
== '\r') {
389 if (seennl
== SEEN_ALL
)
396 PyObject
*translated
= NULL
;
398 Py_UNICODE
*in
, *out
, *end
;
399 if (Py_REFCNT(output
) != 1) {
400 /* We could try to optimize this so that we only do a copy
401 when there is something to translate. On the other hand,
402 most decoders should only output non-shared strings, i.e.
403 translation is done in place. */
404 translated
= PyUnicode_FromUnicode(NULL
, len
);
405 if (translated
== NULL
)
407 assert(Py_REFCNT(translated
) == 1);
408 memcpy(PyUnicode_AS_UNICODE(translated
),
409 PyUnicode_AS_UNICODE(output
),
410 len
* sizeof(Py_UNICODE
));
415 out_str
= PyUnicode_AS_UNICODE(translated
);
421 /* Fast loop for non-control characters */
422 while ((c
= *in
++) > '\r')
443 if (translated
!= output
) {
447 if (out
- out_str
!= len
) {
448 if (PyUnicode_Resize(&output
, out
- out_str
) < 0)
452 self
->seennl
|= seennl
;
463 incrementalnewlinedecoder_decode(nldecoder_object
*self
,
464 PyObject
*args
, PyObject
*kwds
)
466 char *kwlist
[] = {"input", "final", NULL
};
470 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|i:IncrementalNewlineDecoder",
471 kwlist
, &input
, &final
))
473 return _PyIncrementalNewlineDecoder_decode((PyObject
*) self
, input
, final
);
477 incrementalnewlinedecoder_getstate(nldecoder_object
*self
, PyObject
*args
)
480 unsigned PY_LONG_LONG flag
;
482 if (self
->decoder
!= Py_None
) {
483 PyObject
*state
= PyObject_CallMethodObjArgs(self
->decoder
,
484 _PyIO_str_getstate
, NULL
);
487 if (!PyArg_Parse(state
, "(OK)", &buffer
, &flag
)) {
495 buffer
= PyBytes_FromString("");
501 return Py_BuildValue("NK", buffer
, flag
);
505 incrementalnewlinedecoder_setstate(nldecoder_object
*self
, PyObject
*state
)
508 unsigned PY_LONG_LONG flag
;
510 if (!PyArg_Parse(state
, "(OK)", &buffer
, &flag
))
513 self
->pendingcr
= (int) flag
& 1;
516 if (self
->decoder
!= Py_None
)
517 return PyObject_CallMethod(self
->decoder
,
518 "setstate", "((OK))", buffer
, flag
);
524 incrementalnewlinedecoder_reset(nldecoder_object
*self
, PyObject
*args
)
528 if (self
->decoder
!= Py_None
)
529 return PyObject_CallMethodObjArgs(self
->decoder
, _PyIO_str_reset
, NULL
);
535 incrementalnewlinedecoder_newlines_get(nldecoder_object
*self
, void *context
)
537 switch (self
->seennl
) {
539 return PyUnicode_FromString("\r");
541 return PyUnicode_FromString("\n");
543 return PyUnicode_FromString("\r\n");
544 case SEEN_CR
| SEEN_LF
:
545 return Py_BuildValue("ss", "\r", "\n");
546 case SEEN_CR
| SEEN_CRLF
:
547 return Py_BuildValue("ss", "\r", "\r\n");
548 case SEEN_LF
| SEEN_CRLF
:
549 return Py_BuildValue("ss", "\n", "\r\n");
550 case SEEN_CR
| SEEN_LF
| SEEN_CRLF
:
551 return Py_BuildValue("sss", "\r", "\n", "\r\n");
559 static PyMethodDef incrementalnewlinedecoder_methods
[] = {
560 {"decode", (PyCFunction
)incrementalnewlinedecoder_decode
, METH_VARARGS
|METH_KEYWORDS
},
561 {"getstate", (PyCFunction
)incrementalnewlinedecoder_getstate
, METH_NOARGS
},
562 {"setstate", (PyCFunction
)incrementalnewlinedecoder_setstate
, METH_O
},
563 {"reset", (PyCFunction
)incrementalnewlinedecoder_reset
, METH_NOARGS
},
567 static PyGetSetDef incrementalnewlinedecoder_getset
[] = {
568 {"newlines", (getter
)incrementalnewlinedecoder_newlines_get
, NULL
, NULL
},
572 PyTypeObject PyIncrementalNewlineDecoder_Type
= {
573 PyVarObject_HEAD_INIT(NULL
, 0)
574 "_io.IncrementalNewlineDecoder", /*tp_name*/
575 sizeof(nldecoder_object
), /*tp_basicsize*/
577 (destructor
)incrementalnewlinedecoder_dealloc
, /*tp_dealloc*/
584 0, /*tp_as_sequence*/
592 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
593 incrementalnewlinedecoder_doc
, /* tp_doc */
596 0, /* tp_richcompare */
597 0, /*tp_weaklistoffset*/
600 incrementalnewlinedecoder_methods
, /* tp_methods */
602 incrementalnewlinedecoder_getset
, /* tp_getset */
605 0, /* tp_descr_get */
606 0, /* tp_descr_set */
607 0, /* tp_dictoffset */
608 (initproc
)incrementalnewlinedecoder_init
, /* tp_init */
610 PyType_GenericNew
, /* tp_new */
616 PyDoc_STRVAR(textiowrapper_doc
,
617 "Character and line based layer over a BufferedIOBase object, buffer.\n"
619 "encoding gives the name of the encoding that the stream will be\n"
620 "decoded or encoded with. It defaults to locale.getpreferredencoding.\n"
622 "errors determines the strictness of encoding and decoding (see the\n"
623 "codecs.register) and defaults to \"strict\".\n"
625 "newline can be None, '', '\\n', '\\r', or '\\r\\n'. It controls the\n"
626 "handling of line endings. If it is None, universal newlines is\n"
627 "enabled. With this enabled, on input, the lines endings '\\n', '\\r',\n"
628 "or '\\r\\n' are translated to '\\n' before being returned to the\n"
629 "caller. Conversely, on output, '\\n' is translated to the system\n"
630 "default line seperator, os.linesep. If newline is any other of its\n"
631 "legal values, that newline becomes the newline when the file is read\n"
632 "and it is returned untranslated. On output, '\\n' is converted to the\n"
635 "If line_buffering is True, a call to flush is implied when a call to\n"
636 "write contains a newline character."
640 (*encodefunc_t
)(PyObject
*, PyObject
*);
645 int ok
; /* initialized? */
647 Py_ssize_t chunk_size
;
654 const char *writenl
; /* utf-8 encoded, NULL stands for \n */
661 /* Specialized encoding func (see below) */
662 encodefunc_t encodefunc
;
663 /* Whether or not it's the start of the stream */
664 char encoding_start_of_stream
;
666 /* Reads and writes are internally buffered in order to speed things up.
667 However, any read will first flush the write buffer if itsn't empty.
669 Please also note that text to be written is first encoded before being
670 buffered. This is necessary so that encoding errors are immediately
671 reported to the caller, but it unfortunately means that the
672 IncrementalEncoder (whose encode() method is always written in Python)
673 becomes a bottleneck for small writes.
675 PyObject
*decoded_chars
; /* buffer for text returned from decoder */
676 Py_ssize_t decoded_chars_used
; /* offset into _decoded_chars for read() */
677 PyObject
*pending_bytes
; /* list of bytes objects waiting to be
679 Py_ssize_t pending_bytes_count
;
681 /* snapshot is either None, or a tuple (dec_flags, next_input) where
682 * dec_flags is the second (integer) item of the decoder state and
683 * next_input is the chunk of input bytes that comes next after the
684 * snapshot point. We use this to reconstruct decoder states in tell().
687 /* Cache raw object if it's a FileIO object */
690 PyObject
*weakreflist
;
695 /* A couple of specialized cases in order to bypass the slow incremental
696 encoding methods for the most popular encodings. */
699 ascii_encode(textio
*self
, PyObject
*text
)
701 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(text
),
702 PyUnicode_GET_SIZE(text
),
703 PyBytes_AS_STRING(self
->errors
));
707 utf16be_encode(textio
*self
, PyObject
*text
)
709 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(text
),
710 PyUnicode_GET_SIZE(text
),
711 PyBytes_AS_STRING(self
->errors
), 1);
715 utf16le_encode(textio
*self
, PyObject
*text
)
717 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(text
),
718 PyUnicode_GET_SIZE(text
),
719 PyBytes_AS_STRING(self
->errors
), -1);
723 utf16_encode(textio
*self
, PyObject
*text
)
725 if (!self
->encoding_start_of_stream
) {
726 /* Skip the BOM and use native byte ordering */
727 #if defined(WORDS_BIGENDIAN)
728 return utf16be_encode(self
, text
);
730 return utf16le_encode(self
, text
);
733 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(text
),
734 PyUnicode_GET_SIZE(text
),
735 PyBytes_AS_STRING(self
->errors
), 0);
739 utf32be_encode(textio
*self
, PyObject
*text
)
741 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(text
),
742 PyUnicode_GET_SIZE(text
),
743 PyBytes_AS_STRING(self
->errors
), 1);
747 utf32le_encode(textio
*self
, PyObject
*text
)
749 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(text
),
750 PyUnicode_GET_SIZE(text
),
751 PyBytes_AS_STRING(self
->errors
), -1);
755 utf32_encode(textio
*self
, PyObject
*text
)
757 if (!self
->encoding_start_of_stream
) {
758 /* Skip the BOM and use native byte ordering */
759 #if defined(WORDS_BIGENDIAN)
760 return utf32be_encode(self
, text
);
762 return utf32le_encode(self
, text
);
765 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(text
),
766 PyUnicode_GET_SIZE(text
),
767 PyBytes_AS_STRING(self
->errors
), 0);
771 utf8_encode(textio
*self
, PyObject
*text
)
773 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(text
),
774 PyUnicode_GET_SIZE(text
),
775 PyBytes_AS_STRING(self
->errors
));
779 latin1_encode(textio
*self
, PyObject
*text
)
781 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(text
),
782 PyUnicode_GET_SIZE(text
),
783 PyBytes_AS_STRING(self
->errors
));
786 /* Map normalized encoding names onto the specialized encoding funcs */
790 encodefunc_t encodefunc
;
793 static encodefuncentry encodefuncs
[] = {
794 {"ascii", (encodefunc_t
) ascii_encode
},
795 {"iso8859-1", (encodefunc_t
) latin1_encode
},
796 {"utf-8", (encodefunc_t
) utf8_encode
},
797 {"utf-16-be", (encodefunc_t
) utf16be_encode
},
798 {"utf-16-le", (encodefunc_t
) utf16le_encode
},
799 {"utf-16", (encodefunc_t
) utf16_encode
},
800 {"utf-32-be", (encodefunc_t
) utf32be_encode
},
801 {"utf-32-le", (encodefunc_t
) utf32le_encode
},
802 {"utf-32", (encodefunc_t
) utf32_encode
},
808 textiowrapper_init(textio
*self
, PyObject
*args
, PyObject
*kwds
)
810 char *kwlist
[] = {"buffer", "encoding", "errors",
811 "newline", "line_buffering",
813 PyObject
*buffer
, *raw
;
814 char *encoding
= NULL
;
816 char *newline
= NULL
;
817 int line_buffering
= 0;
824 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|zzzi:fileio",
825 kwlist
, &buffer
, &encoding
, &errors
,
826 &newline
, &line_buffering
))
829 if (newline
&& newline
[0] != '\0'
830 && !(newline
[0] == '\n' && newline
[1] == '\0')
831 && !(newline
[0] == '\r' && newline
[1] == '\0')
832 && !(newline
[0] == '\r' && newline
[1] == '\n' && newline
[2] == '\0')) {
833 PyErr_Format(PyExc_ValueError
,
834 "illegal newline value: %s", newline
);
838 Py_CLEAR(self
->buffer
);
839 Py_CLEAR(self
->encoding
);
840 Py_CLEAR(self
->encoder
);
841 Py_CLEAR(self
->decoder
);
842 Py_CLEAR(self
->readnl
);
843 Py_CLEAR(self
->decoded_chars
);
844 Py_CLEAR(self
->pending_bytes
);
845 Py_CLEAR(self
->snapshot
);
846 Py_CLEAR(self
->errors
);
848 self
->decoded_chars_used
= 0;
849 self
->pending_bytes_count
= 0;
850 self
->encodefunc
= NULL
;
851 self
->writenl
= NULL
;
853 if (encoding
== NULL
&& self
->encoding
== NULL
) {
854 if (_PyIO_locale_module
== NULL
) {
855 _PyIO_locale_module
= PyImport_ImportModule("locale");
856 if (_PyIO_locale_module
== NULL
)
857 goto catch_ImportError
;
863 self
->encoding
= PyObject_CallMethod(
864 _PyIO_locale_module
, "getpreferredencoding", NULL
);
865 if (self
->encoding
== NULL
) {
868 Importing locale can raise a ImportError because of
869 _functools, and locale.getpreferredencoding can raise a
870 ImportError if _locale is not available. These will happen
871 during module building.
873 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
875 self
->encoding
= PyString_FromString("ascii");
880 else if (!PyString_Check(self
->encoding
))
881 Py_CLEAR(self
->encoding
);
884 if (self
->encoding
!= NULL
)
885 encoding
= PyString_AsString(self
->encoding
);
886 else if (encoding
!= NULL
) {
887 self
->encoding
= PyString_FromString(encoding
);
888 if (self
->encoding
== NULL
)
892 PyErr_SetString(PyExc_IOError
,
893 "could not determine default encoding");
898 self
->errors
= PyBytes_FromString(errors
);
899 if (self
->errors
== NULL
)
902 self
->chunk_size
= 8192;
903 self
->readuniversal
= (newline
== NULL
|| newline
[0] == '\0');
904 self
->line_buffering
= line_buffering
;
905 self
->readtranslate
= (newline
== NULL
);
907 self
->readnl
= PyString_FromString(newline
);
908 if (self
->readnl
== NULL
)
911 self
->writetranslate
= (newline
== NULL
|| newline
[0] != '\0');
912 if (!self
->readuniversal
&& self
->writetranslate
) {
913 self
->writenl
= PyString_AsString(self
->readnl
);
914 if (!strcmp(self
->writenl
, "\n"))
915 self
->writenl
= NULL
;
919 self
->writenl
= "\r\n";
922 /* Build the decoder object */
923 res
= PyObject_CallMethod(buffer
, "readable", NULL
);
926 r
= PyObject_IsTrue(res
);
931 self
->decoder
= PyCodec_IncrementalDecoder(
933 if (self
->decoder
== NULL
)
936 if (self
->readuniversal
) {
937 PyObject
*incrementalDecoder
= PyObject_CallFunction(
938 (PyObject
*)&PyIncrementalNewlineDecoder_Type
,
939 "Oi", self
->decoder
, (int)self
->readtranslate
);
940 if (incrementalDecoder
== NULL
)
942 Py_CLEAR(self
->decoder
);
943 self
->decoder
= incrementalDecoder
;
947 /* Build the encoder object */
948 res
= PyObject_CallMethod(buffer
, "writable", NULL
);
951 r
= PyObject_IsTrue(res
);
957 self
->encoder
= PyCodec_IncrementalEncoder(
959 if (self
->encoder
== NULL
)
961 /* Get the normalized named of the codec */
962 ci
= _PyCodec_Lookup(encoding
);
965 res
= PyObject_GetAttrString(ci
, "name");
968 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
973 else if (PyString_Check(res
)) {
974 encodefuncentry
*e
= encodefuncs
;
975 while (e
->name
!= NULL
) {
976 if (!strcmp(PyString_AS_STRING(res
), e
->name
)) {
977 self
->encodefunc
= e
->encodefunc
;
986 self
->buffer
= buffer
;
989 if (Py_TYPE(buffer
) == &PyBufferedReader_Type
||
990 Py_TYPE(buffer
) == &PyBufferedWriter_Type
||
991 Py_TYPE(buffer
) == &PyBufferedRandom_Type
) {
992 raw
= PyObject_GetAttrString(buffer
, "raw");
993 /* Cache the raw FileIO object to speed up 'closed' checks */
995 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1000 else if (Py_TYPE(raw
) == &PyFileIO_Type
)
1006 res
= PyObject_CallMethod(buffer
, "seekable", NULL
);
1009 self
->seekable
= self
->telling
= PyObject_IsTrue(res
);
1012 self
->encoding_start_of_stream
= 0;
1013 if (self
->seekable
&& self
->encoder
) {
1014 PyObject
*cookieObj
;
1017 self
->encoding_start_of_stream
= 1;
1019 cookieObj
= PyObject_CallMethodObjArgs(buffer
, _PyIO_str_tell
, NULL
);
1020 if (cookieObj
== NULL
)
1023 cmp
= PyObject_RichCompareBool(cookieObj
, _PyIO_zero
, Py_EQ
);
1024 Py_DECREF(cookieObj
);
1030 self
->encoding_start_of_stream
= 0;
1031 res
= PyObject_CallMethodObjArgs(self
->encoder
, _PyIO_str_setstate
,
1047 _textiowrapper_clear(textio
*self
)
1049 if (self
->ok
&& _PyIOBase_finalize((PyObject
*) self
) < 0)
1052 Py_CLEAR(self
->buffer
);
1053 Py_CLEAR(self
->encoding
);
1054 Py_CLEAR(self
->encoder
);
1055 Py_CLEAR(self
->decoder
);
1056 Py_CLEAR(self
->readnl
);
1057 Py_CLEAR(self
->decoded_chars
);
1058 Py_CLEAR(self
->pending_bytes
);
1059 Py_CLEAR(self
->snapshot
);
1060 Py_CLEAR(self
->errors
);
1061 Py_CLEAR(self
->raw
);
1066 textiowrapper_dealloc(textio
*self
)
1068 if (_textiowrapper_clear(self
) < 0)
1070 _PyObject_GC_UNTRACK(self
);
1071 if (self
->weakreflist
!= NULL
)
1072 PyObject_ClearWeakRefs((PyObject
*)self
);
1073 Py_CLEAR(self
->dict
);
1074 Py_TYPE(self
)->tp_free((PyObject
*)self
);
1078 textiowrapper_traverse(textio
*self
, visitproc visit
, void *arg
)
1080 Py_VISIT(self
->buffer
);
1081 Py_VISIT(self
->encoding
);
1082 Py_VISIT(self
->encoder
);
1083 Py_VISIT(self
->decoder
);
1084 Py_VISIT(self
->readnl
);
1085 Py_VISIT(self
->decoded_chars
);
1086 Py_VISIT(self
->pending_bytes
);
1087 Py_VISIT(self
->snapshot
);
1088 Py_VISIT(self
->errors
);
1089 Py_VISIT(self
->raw
);
1091 Py_VISIT(self
->dict
);
1096 textiowrapper_clear(textio
*self
)
1098 if (_textiowrapper_clear(self
) < 0)
1100 Py_CLEAR(self
->dict
);
1105 textiowrapper_closed_get(textio
*self
, void *context
);
1107 /* This macro takes some shortcuts to make the common case faster. */
1108 #define CHECK_CLOSED(self) \
1112 if (Py_TYPE(self) == &PyTextIOWrapper_Type) { \
1113 if (self->raw != NULL) \
1114 r = _PyFileIO_closed(self->raw); \
1116 _res = textiowrapper_closed_get(self, NULL); \
1119 r = PyObject_IsTrue(_res); \
1125 PyErr_SetString(PyExc_ValueError, \
1126 "I/O operation on closed file."); \
1130 else if (_PyIOBase_check_closed((PyObject *)self, Py_True) == NULL) \
1134 #define CHECK_INITIALIZED(self) \
1135 if (self->ok <= 0) { \
1136 if (self->detached) { \
1137 PyErr_SetString(PyExc_ValueError, \
1138 "underlying buffer has been detached"); \
1140 PyErr_SetString(PyExc_ValueError, \
1141 "I/O operation on uninitialized object"); \
1146 #define CHECK_INITIALIZED_INT(self) \
1147 if (self->ok <= 0) { \
1148 if (self->detached) { \
1149 PyErr_SetString(PyExc_ValueError, \
1150 "underlying buffer has been detached"); \
1152 PyErr_SetString(PyExc_ValueError, \
1153 "I/O operation on uninitialized object"); \
1160 textiowrapper_detach(textio
*self
)
1162 PyObject
*buffer
, *res
;
1163 CHECK_INITIALIZED(self
);
1164 res
= PyObject_CallMethodObjArgs((PyObject
*)self
, _PyIO_str_flush
, NULL
);
1168 buffer
= self
->buffer
;
1169 self
->buffer
= NULL
;
1175 Py_LOCAL_INLINE(const Py_UNICODE
*)
1176 findchar(const Py_UNICODE
*s
, Py_ssize_t size
, Py_UNICODE ch
)
1178 /* like wcschr, but doesn't stop at NULL characters */
1179 while (size
-- > 0) {
1187 /* Flush the internal write buffer. This doesn't explicitly flush the
1188 underlying buffered object, though. */
1190 _textiowrapper_writeflush(textio
*self
)
1192 PyObject
*pending
, *b
, *ret
;
1194 if (self
->pending_bytes
== NULL
)
1197 pending
= self
->pending_bytes
;
1199 self
->pending_bytes_count
= 0;
1200 Py_CLEAR(self
->pending_bytes
);
1202 b
= _PyBytes_Join(_PyIO_empty_bytes
, pending
);
1206 ret
= PyObject_CallMethodObjArgs(self
->buffer
,
1207 _PyIO_str_write
, b
, NULL
);
1216 textiowrapper_write(textio
*self
, PyObject
*args
)
1219 PyObject
*text
; /* owned reference */
1225 CHECK_INITIALIZED(self
);
1227 if (!PyArg_ParseTuple(args
, "U:write", &text
)) {
1233 if (self
->encoder
== NULL
) {
1234 PyErr_SetString(PyExc_IOError
, "not writable");
1240 textlen
= PyUnicode_GetSize(text
);
1242 if ((self
->writetranslate
&& self
->writenl
!= NULL
) || self
->line_buffering
)
1243 if (findchar(PyUnicode_AS_UNICODE(text
),
1244 PyUnicode_GET_SIZE(text
), '\n'))
1247 if (haslf
&& self
->writetranslate
&& self
->writenl
!= NULL
) {
1248 PyObject
*newtext
= PyObject_CallMethod(
1249 text
, "replace", "ss", "\n", self
->writenl
);
1251 if (newtext
== NULL
)
1256 if (self
->line_buffering
&&
1258 findchar(PyUnicode_AS_UNICODE(text
),
1259 PyUnicode_GET_SIZE(text
), '\r')))
1262 /* XXX What if we were just reading? */
1263 if (self
->encodefunc
!= NULL
) {
1264 b
= (*self
->encodefunc
)((PyObject
*) self
, text
);
1265 self
->encoding_start_of_stream
= 0;
1268 b
= PyObject_CallMethodObjArgs(self
->encoder
,
1269 _PyIO_str_encode
, text
, NULL
);
1274 if (self
->pending_bytes
== NULL
) {
1275 self
->pending_bytes
= PyList_New(0);
1276 if (self
->pending_bytes
== NULL
) {
1280 self
->pending_bytes_count
= 0;
1282 if (PyList_Append(self
->pending_bytes
, b
) < 0) {
1286 self
->pending_bytes_count
+= PyBytes_GET_SIZE(b
);
1288 if (self
->pending_bytes_count
> self
->chunk_size
|| needflush
) {
1289 if (_textiowrapper_writeflush(self
) < 0)
1294 ret
= PyObject_CallMethodObjArgs(self
->buffer
, _PyIO_str_flush
, NULL
);
1300 Py_CLEAR(self
->snapshot
);
1302 if (self
->decoder
) {
1303 ret
= PyObject_CallMethod(self
->decoder
, "reset", NULL
);
1309 return PyLong_FromSsize_t(textlen
);
1312 /* Steal a reference to chars and store it in the decoded_char buffer;
1315 textiowrapper_set_decoded_chars(textio
*self
, PyObject
*chars
)
1317 Py_CLEAR(self
->decoded_chars
);
1318 self
->decoded_chars
= chars
;
1319 self
->decoded_chars_used
= 0;
1323 textiowrapper_get_decoded_chars(textio
*self
, Py_ssize_t n
)
1328 if (self
->decoded_chars
== NULL
)
1329 return PyUnicode_FromStringAndSize(NULL
, 0);
1331 avail
= (PyUnicode_GET_SIZE(self
->decoded_chars
)
1332 - self
->decoded_chars_used
);
1336 if (n
< 0 || n
> avail
)
1339 if (self
->decoded_chars_used
> 0 || n
< avail
) {
1340 chars
= PyUnicode_FromUnicode(
1341 PyUnicode_AS_UNICODE(self
->decoded_chars
)
1342 + self
->decoded_chars_used
, n
);
1347 chars
= self
->decoded_chars
;
1351 self
->decoded_chars_used
+= n
;
1355 /* Read and decode the next chunk of data from the BufferedReader.
1358 textiowrapper_read_chunk(textio
*self
)
1360 PyObject
*dec_buffer
= NULL
;
1361 PyObject
*dec_flags
= NULL
;
1362 PyObject
*input_chunk
= NULL
;
1363 PyObject
*decoded_chars
, *chunk_size
;
1366 /* The return value is True unless EOF was reached. The decoded string is
1367 * placed in self._decoded_chars (replacing its previous value). The
1368 * entire input chunk is sent to the decoder, though some of it may remain
1369 * buffered in the decoder, yet to be converted.
1372 if (self
->decoder
== NULL
) {
1373 PyErr_SetString(PyExc_IOError
, "not readable");
1377 if (self
->telling
) {
1378 /* To prepare for tell(), we need to snapshot a point in the file
1379 * where the decoder's input buffer is empty.
1382 PyObject
*state
= PyObject_CallMethodObjArgs(self
->decoder
,
1383 _PyIO_str_getstate
, NULL
);
1386 /* Given this, we know there was a valid snapshot point
1387 * len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1389 if (PyArg_Parse(state
, "(OO)", &dec_buffer
, &dec_flags
) < 0) {
1393 Py_INCREF(dec_buffer
);
1394 Py_INCREF(dec_flags
);
1398 /* Read a chunk, decode it, and put the result in self._decoded_chars. */
1399 chunk_size
= PyLong_FromSsize_t(self
->chunk_size
);
1400 if (chunk_size
== NULL
)
1402 input_chunk
= PyObject_CallMethodObjArgs(self
->buffer
,
1403 _PyIO_str_read1
, chunk_size
, NULL
);
1404 Py_DECREF(chunk_size
);
1405 if (input_chunk
== NULL
)
1407 assert(PyBytes_Check(input_chunk
));
1409 eof
= (PyBytes_Size(input_chunk
) == 0);
1411 if (Py_TYPE(self
->decoder
) == &PyIncrementalNewlineDecoder_Type
) {
1412 decoded_chars
= _PyIncrementalNewlineDecoder_decode(
1413 self
->decoder
, input_chunk
, eof
);
1416 decoded_chars
= PyObject_CallMethodObjArgs(self
->decoder
,
1417 _PyIO_str_decode
, input_chunk
, eof
? Py_True
: Py_False
, NULL
);
1420 /* TODO sanity check: isinstance(decoded_chars, unicode) */
1421 if (decoded_chars
== NULL
)
1423 textiowrapper_set_decoded_chars(self
, decoded_chars
);
1424 if (PyUnicode_GET_SIZE(decoded_chars
) > 0)
1427 if (self
->telling
) {
1428 /* At the snapshot point, len(dec_buffer) bytes before the read, the
1429 * next input to be decoded is dec_buffer + input_chunk.
1431 PyObject
*next_input
= PyNumber_Add(dec_buffer
, input_chunk
);
1432 if (next_input
== NULL
)
1434 assert (PyBytes_Check(next_input
));
1435 Py_DECREF(dec_buffer
);
1436 Py_CLEAR(self
->snapshot
);
1437 self
->snapshot
= Py_BuildValue("NN", dec_flags
, next_input
);
1439 Py_DECREF(input_chunk
);
1444 Py_XDECREF(dec_buffer
);
1445 Py_XDECREF(dec_flags
);
1446 Py_XDECREF(input_chunk
);
1451 textiowrapper_read(textio
*self
, PyObject
*args
)
1454 PyObject
*result
= NULL
, *chunks
= NULL
;
1456 CHECK_INITIALIZED(self
);
1458 if (!PyArg_ParseTuple(args
, "|n:read", &n
))
1463 if (self
->decoder
== NULL
) {
1464 PyErr_SetString(PyExc_IOError
, "not readable");
1468 if (_textiowrapper_writeflush(self
) < 0)
1472 /* Read everything */
1473 PyObject
*bytes
= PyObject_CallMethod(self
->buffer
, "read", NULL
);
1474 PyObject
*decoded
, *final
;
1477 decoded
= PyObject_CallMethodObjArgs(self
->decoder
, _PyIO_str_decode
,
1478 bytes
, Py_True
, NULL
);
1480 if (decoded
== NULL
)
1483 result
= textiowrapper_get_decoded_chars(self
, -1);
1485 if (result
== NULL
) {
1490 final
= PyUnicode_Concat(result
, decoded
);
1496 Py_CLEAR(self
->snapshot
);
1501 Py_ssize_t remaining
= n
;
1503 result
= textiowrapper_get_decoded_chars(self
, n
);
1506 remaining
-= PyUnicode_GET_SIZE(result
);
1508 /* Keep reading chunks until we have n characters to return */
1509 while (remaining
> 0) {
1510 res
= textiowrapper_read_chunk(self
);
1513 if (res
== 0) /* EOF */
1515 if (chunks
== NULL
) {
1516 chunks
= PyList_New(0);
1520 if (PyList_Append(chunks
, result
) < 0)
1523 result
= textiowrapper_get_decoded_chars(self
, remaining
);
1526 remaining
-= PyUnicode_GET_SIZE(result
);
1528 if (chunks
!= NULL
) {
1529 if (result
!= NULL
&& PyList_Append(chunks
, result
) < 0)
1532 result
= PyUnicode_Join(_PyIO_empty_str
, chunks
);
1546 /* NOTE: `end` must point to the real end of the Py_UNICODE storage,
1547 that is to the NUL character. Otherwise the function will produce
1548 incorrect results. */
1550 find_control_char(Py_UNICODE
*start
, Py_UNICODE
*end
, Py_UNICODE ch
)
1552 Py_UNICODE
*s
= start
;
1565 _PyIO_find_line_ending(
1566 int translated
, int universal
, PyObject
*readnl
,
1567 Py_UNICODE
*start
, Py_UNICODE
*end
, Py_ssize_t
*consumed
)
1569 Py_ssize_t len
= end
- start
;
1572 /* Newlines are already translated, only search for \n */
1573 Py_UNICODE
*pos
= find_control_char(start
, end
, '\n');
1575 return pos
- start
+ 1;
1581 else if (universal
) {
1582 /* Universal newline search. Find any of \r, \r\n, \n
1583 * The decoder ensures that \r\n are not split in two pieces
1585 Py_UNICODE
*s
= start
;
1588 /* Fast path for non-control chars. The loop always ends
1589 since the Py_UNICODE storage is NUL-terminated. */
1601 return s
- start
+ 1;
1608 /* Non-universal mode. */
1609 Py_ssize_t readnl_len
= PyString_GET_SIZE(readnl
);
1610 unsigned char *nl
= (unsigned char *) PyString_AS_STRING(readnl
);
1611 if (readnl_len
== 1) {
1612 Py_UNICODE
*pos
= find_control_char(start
, end
, nl
[0]);
1614 return pos
- start
+ 1;
1619 Py_UNICODE
*s
= start
;
1620 Py_UNICODE
*e
= end
- readnl_len
+ 1;
1626 Py_UNICODE
*pos
= find_control_char(s
, end
, nl
[0]);
1627 if (pos
== NULL
|| pos
>= e
)
1629 for (i
= 1; i
< readnl_len
; i
++) {
1630 if (pos
[i
] != nl
[i
])
1633 if (i
== readnl_len
)
1634 return pos
- start
+ readnl_len
;
1637 pos
= find_control_char(e
, end
, nl
[0]);
1641 *consumed
= pos
- start
;
1648 _textiowrapper_readline(textio
*self
, Py_ssize_t limit
)
1650 PyObject
*line
= NULL
, *chunks
= NULL
, *remaining
= NULL
;
1651 Py_ssize_t start
, endpos
, chunked
, offset_to_buffer
;
1656 if (_textiowrapper_writeflush(self
) < 0)
1663 Py_ssize_t line_len
;
1664 Py_ssize_t consumed
= 0;
1666 /* First, get some data if necessary */
1668 while (!self
->decoded_chars
||
1669 !PyUnicode_GET_SIZE(self
->decoded_chars
)) {
1670 res
= textiowrapper_read_chunk(self
);
1678 textiowrapper_set_decoded_chars(self
, NULL
);
1679 Py_CLEAR(self
->snapshot
);
1680 start
= endpos
= offset_to_buffer
= 0;
1684 if (remaining
== NULL
) {
1685 line
= self
->decoded_chars
;
1686 start
= self
->decoded_chars_used
;
1687 offset_to_buffer
= 0;
1691 assert(self
->decoded_chars_used
== 0);
1692 line
= PyUnicode_Concat(remaining
, self
->decoded_chars
);
1694 offset_to_buffer
= PyUnicode_GET_SIZE(remaining
);
1695 Py_CLEAR(remaining
);
1700 ptr
= PyUnicode_AS_UNICODE(line
);
1701 line_len
= PyUnicode_GET_SIZE(line
);
1703 endpos
= _PyIO_find_line_ending(
1704 self
->readtranslate
, self
->readuniversal
, self
->readnl
,
1705 ptr
+ start
, ptr
+ line_len
, &consumed
);
1708 if (limit
>= 0 && (endpos
- start
) + chunked
>= limit
)
1709 endpos
= start
+ limit
- chunked
;
1713 /* We can put aside up to `endpos` */
1714 endpos
= consumed
+ start
;
1715 if (limit
>= 0 && (endpos
- start
) + chunked
>= limit
) {
1716 /* Didn't find line ending, but reached length limit */
1717 endpos
= start
+ limit
- chunked
;
1721 if (endpos
> start
) {
1722 /* No line ending seen yet - put aside current data */
1724 if (chunks
== NULL
) {
1725 chunks
= PyList_New(0);
1729 s
= PyUnicode_FromUnicode(ptr
+ start
, endpos
- start
);
1732 if (PyList_Append(chunks
, s
) < 0) {
1736 chunked
+= PyUnicode_GET_SIZE(s
);
1739 /* There may be some remaining bytes we'll have to prepend to the
1740 next chunk of data */
1741 if (endpos
< line_len
) {
1742 remaining
= PyUnicode_FromUnicode(
1743 ptr
+ endpos
, line_len
- endpos
);
1744 if (remaining
== NULL
)
1748 /* We have consumed the buffer */
1749 textiowrapper_set_decoded_chars(self
, NULL
);
1753 /* Our line ends in the current buffer */
1754 self
->decoded_chars_used
= endpos
- offset_to_buffer
;
1755 if (start
> 0 || endpos
< PyUnicode_GET_SIZE(line
)) {
1756 if (start
== 0 && Py_REFCNT(line
) == 1) {
1757 if (PyUnicode_Resize(&line
, endpos
) < 0)
1761 PyObject
*s
= PyUnicode_FromUnicode(
1762 PyUnicode_AS_UNICODE(line
) + start
, endpos
- start
);
1770 if (remaining
!= NULL
) {
1771 if (chunks
== NULL
) {
1772 chunks
= PyList_New(0);
1776 if (PyList_Append(chunks
, remaining
) < 0)
1778 Py_CLEAR(remaining
);
1780 if (chunks
!= NULL
) {
1781 if (line
!= NULL
&& PyList_Append(chunks
, line
) < 0)
1784 line
= PyUnicode_Join(_PyIO_empty_str
, chunks
);
1790 line
= PyUnicode_FromStringAndSize(NULL
, 0);
1796 Py_XDECREF(remaining
);
1802 textiowrapper_readline(textio
*self
, PyObject
*args
)
1804 PyObject
*limitobj
= NULL
;
1805 Py_ssize_t limit
= -1;
1807 CHECK_INITIALIZED(self
);
1808 if (!PyArg_ParseTuple(args
, "|O:readline", &limitobj
)) {
1812 if (!PyNumber_Check(limitobj
)) {
1813 PyErr_Format(PyExc_TypeError
,
1814 "integer argument expected, got '%.200s'",
1815 Py_TYPE(limitobj
)->tp_name
);
1818 limit
= PyNumber_AsSsize_t(limitobj
, PyExc_OverflowError
);
1819 if (limit
== -1 && PyErr_Occurred())
1822 return _textiowrapper_readline(self
, limit
);
1836 To speed up cookie packing/unpacking, we store the fields in a temporary
1837 string and call _PyLong_FromByteArray() or _PyLong_AsByteArray (resp.).
1838 The following macros define at which offsets in the intermediary byte
1839 string the various CookieStruct fields will be stored.
1842 #define COOKIE_BUF_LEN (sizeof(Py_off_t) + 3 * sizeof(int) + sizeof(char))
1844 #if defined(WORDS_BIGENDIAN)
1846 # define IS_LITTLE_ENDIAN 0
1848 /* We want the least significant byte of start_pos to also be the least
1849 significant byte of the cookie, which means that in big-endian mode we
1850 must copy the fields in reverse order. */
1852 # define OFF_START_POS (sizeof(char) + 3 * sizeof(int))
1853 # define OFF_DEC_FLAGS (sizeof(char) + 2 * sizeof(int))
1854 # define OFF_BYTES_TO_FEED (sizeof(char) + sizeof(int))
1855 # define OFF_CHARS_TO_SKIP (sizeof(char))
1856 # define OFF_NEED_EOF 0
1860 # define IS_LITTLE_ENDIAN 1
1862 /* Little-endian mode: the least significant byte of start_pos will
1863 naturally end up the least significant byte of the cookie. */
1865 # define OFF_START_POS 0
1866 # define OFF_DEC_FLAGS (sizeof(Py_off_t))
1867 # define OFF_BYTES_TO_FEED (sizeof(Py_off_t) + sizeof(int))
1868 # define OFF_CHARS_TO_SKIP (sizeof(Py_off_t) + 2 * sizeof(int))
1869 # define OFF_NEED_EOF (sizeof(Py_off_t) + 3 * sizeof(int))
1874 textiowrapper_parse_cookie(cookie_type
*cookie
, PyObject
*cookieObj
)
1876 unsigned char buffer
[COOKIE_BUF_LEN
];
1877 PyLongObject
*cookieLong
= (PyLongObject
*)PyNumber_Long(cookieObj
);
1878 if (cookieLong
== NULL
)
1881 if (_PyLong_AsByteArray(cookieLong
, buffer
, sizeof(buffer
),
1882 IS_LITTLE_ENDIAN
, 0) < 0) {
1883 Py_DECREF(cookieLong
);
1886 Py_DECREF(cookieLong
);
1888 memcpy(&cookie
->start_pos
, buffer
+ OFF_START_POS
, sizeof(cookie
->start_pos
));
1889 memcpy(&cookie
->dec_flags
, buffer
+ OFF_DEC_FLAGS
, sizeof(cookie
->dec_flags
));
1890 memcpy(&cookie
->bytes_to_feed
, buffer
+ OFF_BYTES_TO_FEED
, sizeof(cookie
->bytes_to_feed
));
1891 memcpy(&cookie
->chars_to_skip
, buffer
+ OFF_CHARS_TO_SKIP
, sizeof(cookie
->chars_to_skip
));
1892 memcpy(&cookie
->need_eof
, buffer
+ OFF_NEED_EOF
, sizeof(cookie
->need_eof
));
1898 textiowrapper_build_cookie(cookie_type
*cookie
)
1900 unsigned char buffer
[COOKIE_BUF_LEN
];
1902 memcpy(buffer
+ OFF_START_POS
, &cookie
->start_pos
, sizeof(cookie
->start_pos
));
1903 memcpy(buffer
+ OFF_DEC_FLAGS
, &cookie
->dec_flags
, sizeof(cookie
->dec_flags
));
1904 memcpy(buffer
+ OFF_BYTES_TO_FEED
, &cookie
->bytes_to_feed
, sizeof(cookie
->bytes_to_feed
));
1905 memcpy(buffer
+ OFF_CHARS_TO_SKIP
, &cookie
->chars_to_skip
, sizeof(cookie
->chars_to_skip
));
1906 memcpy(buffer
+ OFF_NEED_EOF
, &cookie
->need_eof
, sizeof(cookie
->need_eof
));
1908 return _PyLong_FromByteArray(buffer
, sizeof(buffer
), IS_LITTLE_ENDIAN
, 0);
1910 #undef IS_LITTLE_ENDIAN
1913 _textiowrapper_decoder_setstate(textio
*self
, cookie_type
*cookie
)
1916 /* When seeking to the start of the stream, we call decoder.reset()
1917 rather than decoder.getstate().
1918 This is for a few decoders such as utf-16 for which the state value
1919 at start is not (b"", 0) but e.g. (b"", 2) (meaning, in the case of
1920 utf-16, that we are expecting a BOM).
1922 if (cookie
->start_pos
== 0 && cookie
->dec_flags
== 0)
1923 res
= PyObject_CallMethodObjArgs(self
->decoder
, _PyIO_str_reset
, NULL
);
1925 res
= PyObject_CallMethod(self
->decoder
, "setstate",
1926 "((si))", "", cookie
->dec_flags
);
1934 _textiowrapper_encoder_setstate(textio
*self
, cookie_type
*cookie
)
1937 /* Same as _textiowrapper_decoder_setstate() above. */
1938 if (cookie
->start_pos
== 0 && cookie
->dec_flags
== 0) {
1939 res
= PyObject_CallMethodObjArgs(self
->encoder
, _PyIO_str_reset
, NULL
);
1940 self
->encoding_start_of_stream
= 1;
1943 res
= PyObject_CallMethodObjArgs(self
->encoder
, _PyIO_str_setstate
,
1945 self
->encoding_start_of_stream
= 0;
1954 textiowrapper_seek(textio
*self
, PyObject
*args
)
1956 PyObject
*cookieObj
, *posobj
;
1962 CHECK_INITIALIZED(self
);
1964 if (!PyArg_ParseTuple(args
, "O|i:seek", &cookieObj
, &whence
))
1968 Py_INCREF(cookieObj
);
1970 if (!self
->seekable
) {
1971 PyErr_SetString(PyExc_IOError
,
1972 "underlying stream is not seekable");
1977 /* seek relative to current position */
1978 cmp
= PyObject_RichCompareBool(cookieObj
, _PyIO_zero
, Py_EQ
);
1983 PyErr_SetString(PyExc_IOError
,
1984 "can't do nonzero cur-relative seeks");
1988 /* Seeking to the current position should attempt to
1989 * sync the underlying buffer with the current position.
1991 Py_DECREF(cookieObj
);
1992 cookieObj
= PyObject_CallMethod((PyObject
*)self
, "tell", NULL
);
1993 if (cookieObj
== NULL
)
1996 else if (whence
== 2) {
1997 /* seek relative to end of file */
1999 cmp
= PyObject_RichCompareBool(cookieObj
, _PyIO_zero
, Py_EQ
);
2004 PyErr_SetString(PyExc_IOError
,
2005 "can't do nonzero end-relative seeks");
2009 res
= PyObject_CallMethod((PyObject
*)self
, "flush", NULL
);
2014 textiowrapper_set_decoded_chars(self
, NULL
);
2015 Py_CLEAR(self
->snapshot
);
2016 if (self
->decoder
) {
2017 res
= PyObject_CallMethod(self
->decoder
, "reset", NULL
);
2023 res
= PyObject_CallMethod(self
->buffer
, "seek", "ii", 0, 2);
2024 Py_XDECREF(cookieObj
);
2027 else if (whence
!= 0) {
2028 PyErr_Format(PyExc_ValueError
,
2029 "invalid whence (%d, should be 0, 1 or 2)", whence
);
2033 cmp
= PyObject_RichCompareBool(cookieObj
, _PyIO_zero
, Py_LT
);
2038 PyObject
*repr
= PyObject_Repr(cookieObj
);
2040 PyErr_Format(PyExc_ValueError
,
2041 "negative seek position %s",
2042 PyString_AS_STRING(repr
));
2048 res
= PyObject_CallMethodObjArgs((PyObject
*)self
, _PyIO_str_flush
, NULL
);
2053 /* The strategy of seek() is to go back to the safe start point
2054 * and replay the effect of read(chars_to_skip) from there.
2056 if (textiowrapper_parse_cookie(&cookie
, cookieObj
) < 0)
2059 /* Seek back to the safe start point. */
2060 posobj
= PyLong_FromOff_t(cookie
.start_pos
);
2063 res
= PyObject_CallMethodObjArgs(self
->buffer
,
2064 _PyIO_str_seek
, posobj
, NULL
);
2070 textiowrapper_set_decoded_chars(self
, NULL
);
2071 Py_CLEAR(self
->snapshot
);
2073 /* Restore the decoder to its state from the safe start point. */
2074 if (self
->decoder
) {
2075 if (_textiowrapper_decoder_setstate(self
, &cookie
) < 0)
2079 if (cookie
.chars_to_skip
) {
2080 /* Just like _read_chunk, feed the decoder and save a snapshot. */
2081 PyObject
*input_chunk
= PyObject_CallMethod(
2082 self
->buffer
, "read", "i", cookie
.bytes_to_feed
);
2085 if (input_chunk
== NULL
)
2088 assert (PyBytes_Check(input_chunk
));
2090 self
->snapshot
= Py_BuildValue("iN", cookie
.dec_flags
, input_chunk
);
2091 if (self
->snapshot
== NULL
) {
2092 Py_DECREF(input_chunk
);
2096 decoded
= PyObject_CallMethod(self
->decoder
, "decode",
2097 "Oi", input_chunk
, (int)cookie
.need_eof
);
2099 if (decoded
== NULL
)
2102 textiowrapper_set_decoded_chars(self
, decoded
);
2104 /* Skip chars_to_skip of the decoded characters. */
2105 if (PyUnicode_GetSize(self
->decoded_chars
) < cookie
.chars_to_skip
) {
2106 PyErr_SetString(PyExc_IOError
, "can't restore logical file position");
2109 self
->decoded_chars_used
= cookie
.chars_to_skip
;
2112 self
->snapshot
= Py_BuildValue("is", cookie
.dec_flags
, "");
2113 if (self
->snapshot
== NULL
)
2117 /* Finally, reset the encoder (merely useful for proper BOM handling) */
2118 if (self
->encoder
) {
2119 if (_textiowrapper_encoder_setstate(self
, &cookie
) < 0)
2124 Py_XDECREF(cookieObj
);
2130 textiowrapper_tell(textio
*self
, PyObject
*args
)
2133 PyObject
*posobj
= NULL
;
2134 cookie_type cookie
= {0,0,0,0,0};
2135 PyObject
*next_input
;
2136 Py_ssize_t chars_to_skip
, chars_decoded
;
2137 PyObject
*saved_state
= NULL
;
2138 char *input
, *input_end
;
2140 CHECK_INITIALIZED(self
);
2143 if (!self
->seekable
) {
2144 PyErr_SetString(PyExc_IOError
,
2145 "underlying stream is not seekable");
2148 if (!self
->telling
) {
2149 PyErr_SetString(PyExc_IOError
,
2150 "telling position disabled by next() call");
2154 if (_textiowrapper_writeflush(self
) < 0)
2156 res
= PyObject_CallMethod((PyObject
*)self
, "flush", NULL
);
2161 posobj
= PyObject_CallMethod(self
->buffer
, "tell", NULL
);
2165 if (self
->decoder
== NULL
|| self
->snapshot
== NULL
) {
2166 assert (self
->decoded_chars
== NULL
|| PyUnicode_GetSize(self
->decoded_chars
) == 0);
2170 #if defined(HAVE_LARGEFILE_SUPPORT)
2171 cookie
.start_pos
= PyLong_AsLongLong(posobj
);
2173 cookie
.start_pos
= PyLong_AsLong(posobj
);
2175 if (PyErr_Occurred())
2178 /* Skip backward to the snapshot point (see _read_chunk). */
2179 if (!PyArg_Parse(self
->snapshot
, "(iO)", &cookie
.dec_flags
, &next_input
))
2182 assert (PyBytes_Check(next_input
));
2184 cookie
.start_pos
-= PyBytes_GET_SIZE(next_input
);
2186 /* How many decoded characters have been used up since the snapshot? */
2187 if (self
->decoded_chars_used
== 0) {
2188 /* We haven't moved from the snapshot point. */
2190 return textiowrapper_build_cookie(&cookie
);
2193 chars_to_skip
= self
->decoded_chars_used
;
2195 /* Starting from the snapshot position, we will walk the decoder
2196 * forward until it gives us enough decoded characters.
2198 saved_state
= PyObject_CallMethodObjArgs(self
->decoder
,
2199 _PyIO_str_getstate
, NULL
);
2200 if (saved_state
== NULL
)
2203 /* Note our initial start point. */
2204 if (_textiowrapper_decoder_setstate(self
, &cookie
) < 0)
2207 /* Feed the decoder one byte at a time. As we go, note the
2208 * nearest "safe start point" before the current location
2209 * (a point where the decoder has nothing buffered, so seek()
2210 * can safely start from there and advance to this location).
2213 input
= PyBytes_AS_STRING(next_input
);
2214 input_end
= input
+ PyBytes_GET_SIZE(next_input
);
2215 while (input
< input_end
) {
2218 Py_ssize_t dec_buffer_len
;
2221 PyObject
*decoded
= PyObject_CallMethod(
2222 self
->decoder
, "decode", "s#", input
, 1);
2223 if (decoded
== NULL
)
2225 assert (PyUnicode_Check(decoded
));
2226 chars_decoded
+= PyUnicode_GET_SIZE(decoded
);
2229 cookie
.bytes_to_feed
+= 1;
2231 state
= PyObject_CallMethodObjArgs(self
->decoder
,
2232 _PyIO_str_getstate
, NULL
);
2235 if (!PyArg_Parse(state
, "(s#i)", &dec_buffer
, &dec_buffer_len
, &dec_flags
)) {
2241 if (dec_buffer_len
== 0 && chars_decoded
<= chars_to_skip
) {
2242 /* Decoder buffer is empty, so this is a safe start point. */
2243 cookie
.start_pos
+= cookie
.bytes_to_feed
;
2244 chars_to_skip
-= chars_decoded
;
2245 cookie
.dec_flags
= dec_flags
;
2246 cookie
.bytes_to_feed
= 0;
2249 if (chars_decoded
>= chars_to_skip
)
2253 if (input
== input_end
) {
2254 /* We didn't get enough decoded data; signal EOF to get more. */
2255 PyObject
*decoded
= PyObject_CallMethod(
2256 self
->decoder
, "decode", "si", "", /* final = */ 1);
2257 if (decoded
== NULL
)
2259 assert (PyUnicode_Check(decoded
));
2260 chars_decoded
+= PyUnicode_GET_SIZE(decoded
);
2262 cookie
.need_eof
= 1;
2264 if (chars_decoded
< chars_to_skip
) {
2265 PyErr_SetString(PyExc_IOError
,
2266 "can't reconstruct logical file position");
2273 res
= PyObject_CallMethod(self
->decoder
, "setstate", "(O)", saved_state
);
2274 Py_DECREF(saved_state
);
2279 /* The returned cookie corresponds to the last safe start point. */
2280 cookie
.chars_to_skip
= Py_SAFE_DOWNCAST(chars_to_skip
, Py_ssize_t
, int);
2281 return textiowrapper_build_cookie(&cookie
);
2286 PyObject
*type
, *value
, *traceback
;
2287 PyErr_Fetch(&type
, &value
, &traceback
);
2289 res
= PyObject_CallMethod(self
->decoder
, "setstate", "(O)", saved_state
);
2290 Py_DECREF(saved_state
);
2295 PyErr_Restore(type
, value
, traceback
);
2301 textiowrapper_truncate(textio
*self
, PyObject
*args
)
2303 PyObject
*pos
= Py_None
;
2306 CHECK_INITIALIZED(self
)
2307 if (!PyArg_ParseTuple(args
, "|O:truncate", &pos
)) {
2311 res
= PyObject_CallMethodObjArgs((PyObject
*) self
, _PyIO_str_flush
, NULL
);
2316 if (pos
!= Py_None
) {
2317 res
= PyObject_CallMethodObjArgs((PyObject
*) self
,
2318 _PyIO_str_seek
, pos
, NULL
);
2324 return PyObject_CallMethodObjArgs(self
->buffer
, _PyIO_str_truncate
, NULL
);
2328 textiowrapper_repr(textio
*self
)
2330 PyObject
*nameobj
, *res
;
2331 PyObject
*namerepr
= NULL
, *encrepr
= NULL
;
2333 CHECK_INITIALIZED(self
);
2335 nameobj
= PyObject_GetAttrString((PyObject
*) self
, "name");
2336 if (nameobj
== NULL
) {
2337 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2341 encrepr
= PyObject_Repr(self
->encoding
);
2342 res
= PyString_FromFormat("<_io.TextIOWrapper encoding=%s>",
2343 PyString_AS_STRING(encrepr
));
2346 encrepr
= PyObject_Repr(self
->encoding
);
2347 namerepr
= PyObject_Repr(nameobj
);
2348 res
= PyString_FromFormat("<_io.TextIOWrapper name=%s encoding=%s>",
2349 PyString_AS_STRING(namerepr
),
2350 PyString_AS_STRING(encrepr
));
2353 Py_XDECREF(namerepr
);
2354 Py_XDECREF(encrepr
);
2358 Py_XDECREF(namerepr
);
2359 Py_XDECREF(encrepr
);
2367 textiowrapper_fileno(textio
*self
, PyObject
*args
)
2369 CHECK_INITIALIZED(self
);
2370 return PyObject_CallMethod(self
->buffer
, "fileno", NULL
);
2374 textiowrapper_seekable(textio
*self
, PyObject
*args
)
2376 CHECK_INITIALIZED(self
);
2377 return PyObject_CallMethod(self
->buffer
, "seekable", NULL
);
2381 textiowrapper_readable(textio
*self
, PyObject
*args
)
2383 CHECK_INITIALIZED(self
);
2384 return PyObject_CallMethod(self
->buffer
, "readable", NULL
);
2388 textiowrapper_writable(textio
*self
, PyObject
*args
)
2390 CHECK_INITIALIZED(self
);
2391 return PyObject_CallMethod(self
->buffer
, "writable", NULL
);
2395 textiowrapper_isatty(textio
*self
, PyObject
*args
)
2397 CHECK_INITIALIZED(self
);
2398 return PyObject_CallMethod(self
->buffer
, "isatty", NULL
);
2402 textiowrapper_flush(textio
*self
, PyObject
*args
)
2404 CHECK_INITIALIZED(self
);
2406 self
->telling
= self
->seekable
;
2407 if (_textiowrapper_writeflush(self
) < 0)
2409 return PyObject_CallMethod(self
->buffer
, "flush", NULL
);
2413 textiowrapper_close(textio
*self
, PyObject
*args
)
2416 CHECK_INITIALIZED(self
);
2417 res
= PyObject_CallMethod((PyObject
*)self
, "flush", NULL
);
2419 /* If flush() fails, just give up */
2425 return PyObject_CallMethod(self
->buffer
, "close", NULL
);
2429 textiowrapper_iternext(textio
*self
)
2433 CHECK_INITIALIZED(self
);
2436 if (Py_TYPE(self
) == &PyTextIOWrapper_Type
) {
2437 /* Skip method call overhead for speed */
2438 line
= _textiowrapper_readline(self
, -1);
2441 line
= PyObject_CallMethodObjArgs((PyObject
*)self
,
2442 _PyIO_str_readline
, NULL
);
2443 if (line
&& !PyUnicode_Check(line
)) {
2444 PyErr_Format(PyExc_IOError
,
2445 "readline() should have returned an str object, "
2446 "not '%.200s'", Py_TYPE(line
)->tp_name
);
2455 if (PyUnicode_GET_SIZE(line
) == 0) {
2456 /* Reached EOF or would have blocked */
2458 Py_CLEAR(self
->snapshot
);
2459 self
->telling
= self
->seekable
;
2467 textiowrapper_name_get(textio
*self
, void *context
)
2469 CHECK_INITIALIZED(self
);
2470 return PyObject_GetAttrString(self
->buffer
, "name");
2474 textiowrapper_closed_get(textio
*self
, void *context
)
2476 CHECK_INITIALIZED(self
);
2477 return PyObject_GetAttr(self
->buffer
, _PyIO_str_closed
);
2481 textiowrapper_newlines_get(textio
*self
, void *context
)
2484 CHECK_INITIALIZED(self
);
2485 if (self
->decoder
== NULL
)
2487 res
= PyObject_GetAttr(self
->decoder
, _PyIO_str_newlines
);
2489 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
2501 textiowrapper_errors_get(textio
*self
, void *context
)
2503 CHECK_INITIALIZED(self
);
2504 Py_INCREF(self
->errors
);
2505 return self
->errors
;
2509 textiowrapper_chunk_size_get(textio
*self
, void *context
)
2511 CHECK_INITIALIZED(self
);
2512 return PyLong_FromSsize_t(self
->chunk_size
);
2516 textiowrapper_chunk_size_set(textio
*self
, PyObject
*arg
, void *context
)
2519 CHECK_INITIALIZED_INT(self
);
2520 n
= PyNumber_AsSsize_t(arg
, PyExc_TypeError
);
2521 if (n
== -1 && PyErr_Occurred())
2524 PyErr_SetString(PyExc_ValueError
,
2525 "a strictly positive integer is required");
2528 self
->chunk_size
= n
;
2532 static PyMethodDef textiowrapper_methods
[] = {
2533 {"detach", (PyCFunction
)textiowrapper_detach
, METH_NOARGS
},
2534 {"write", (PyCFunction
)textiowrapper_write
, METH_VARARGS
},
2535 {"read", (PyCFunction
)textiowrapper_read
, METH_VARARGS
},
2536 {"readline", (PyCFunction
)textiowrapper_readline
, METH_VARARGS
},
2537 {"flush", (PyCFunction
)textiowrapper_flush
, METH_NOARGS
},
2538 {"close", (PyCFunction
)textiowrapper_close
, METH_NOARGS
},
2540 {"fileno", (PyCFunction
)textiowrapper_fileno
, METH_NOARGS
},
2541 {"seekable", (PyCFunction
)textiowrapper_seekable
, METH_NOARGS
},
2542 {"readable", (PyCFunction
)textiowrapper_readable
, METH_NOARGS
},
2543 {"writable", (PyCFunction
)textiowrapper_writable
, METH_NOARGS
},
2544 {"isatty", (PyCFunction
)textiowrapper_isatty
, METH_NOARGS
},
2546 {"seek", (PyCFunction
)textiowrapper_seek
, METH_VARARGS
},
2547 {"tell", (PyCFunction
)textiowrapper_tell
, METH_NOARGS
},
2548 {"truncate", (PyCFunction
)textiowrapper_truncate
, METH_VARARGS
},
2552 static PyMemberDef textiowrapper_members
[] = {
2553 {"encoding", T_OBJECT
, offsetof(textio
, encoding
), READONLY
},
2554 {"buffer", T_OBJECT
, offsetof(textio
, buffer
), READONLY
},
2555 {"line_buffering", T_BOOL
, offsetof(textio
, line_buffering
), READONLY
},
2559 static PyGetSetDef textiowrapper_getset
[] = {
2560 {"name", (getter
)textiowrapper_name_get
, NULL
, NULL
},
2561 {"closed", (getter
)textiowrapper_closed_get
, NULL
, NULL
},
2562 /* {"mode", (getter)TextIOWrapper_mode_get, NULL, NULL},
2564 {"newlines", (getter
)textiowrapper_newlines_get
, NULL
, NULL
},
2565 {"errors", (getter
)textiowrapper_errors_get
, NULL
, NULL
},
2566 {"_CHUNK_SIZE", (getter
)textiowrapper_chunk_size_get
,
2567 (setter
)textiowrapper_chunk_size_set
, NULL
},
2571 PyTypeObject PyTextIOWrapper_Type
= {
2572 PyVarObject_HEAD_INIT(NULL
, 0)
2573 "_io.TextIOWrapper", /*tp_name*/
2574 sizeof(textio
), /*tp_basicsize*/
2576 (destructor
)textiowrapper_dealloc
, /*tp_dealloc*/
2581 (reprfunc
)textiowrapper_repr
,/*tp_repr*/
2583 0, /*tp_as_sequence*/
2584 0, /*tp_as_mapping*/
2591 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
2592 | Py_TPFLAGS_HAVE_GC
, /*tp_flags*/
2593 textiowrapper_doc
, /* tp_doc */
2594 (traverseproc
)textiowrapper_traverse
, /* tp_traverse */
2595 (inquiry
)textiowrapper_clear
, /* tp_clear */
2596 0, /* tp_richcompare */
2597 offsetof(textio
, weakreflist
), /*tp_weaklistoffset*/
2599 (iternextfunc
)textiowrapper_iternext
, /* tp_iternext */
2600 textiowrapper_methods
, /* tp_methods */
2601 textiowrapper_members
, /* tp_members */
2602 textiowrapper_getset
, /* tp_getset */
2605 0, /* tp_descr_get */
2606 0, /* tp_descr_set */
2607 offsetof(textio
, dict
), /*tp_dictoffset*/
2608 (initproc
)textiowrapper_init
, /* tp_init */
2610 PyType_GenericNew
, /* tp_new */