blob: a8e55c34799bd5b02728461c0f2755a741930c77 [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001/*
2 An implementation of the I/O abstract base classes hierarchy
3 as defined by PEP 3116 - "New I/O"
Victor Stinnercc024d12013-10-29 02:23:46 +01004
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00005 Classes defined here: IOBase, RawIOBase.
Victor Stinnercc024d12013-10-29 02:23:46 +01006
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00007 Written by Amaury Forgeot d'Arc and Antoine Pitrou
8*/
9
10
11#define PY_SSIZE_T_CLEAN
12#include "Python.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +010013#include "pycore_object.h"
Victor Stinner4a21e572020-04-15 02:35:41 +020014#include <stddef.h> // offsetof()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000015#include "_iomodule.h"
16
Serhiy Storchakaf24131f2015-04-16 11:19:43 +030017/*[clinic input]
18module _io
19class _io._IOBase "PyObject *" "&PyIOBase_Type"
20class _io._RawIOBase "PyObject *" "&PyRawIOBase_Type"
21[clinic start generated code]*/
22/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d29a4d076c2b211c]*/
23
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000024/*
25 * IOBase class, an abstract class
26 */
27
28typedef struct {
29 PyObject_HEAD
Victor Stinnercc024d12013-10-29 02:23:46 +010030
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000031 PyObject *dict;
32 PyObject *weakreflist;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000033} iobase;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000034
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000035PyDoc_STRVAR(iobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000036 "The abstract base class for all I/O classes, acting on streams of\n"
37 "bytes. There is no public constructor.\n"
38 "\n"
39 "This class provides dummy implementations for many methods that\n"
40 "derived classes can override selectively; the default implementations\n"
41 "represent a file that cannot be read, written or seeked.\n"
42 "\n"
43 "Even though IOBase does not declare read, readinto, or write because\n"
44 "their signatures will vary, implementations and clients should\n"
45 "consider those methods part of the interface. Also, implementations\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +000046 "may raise UnsupportedOperation when operations they do not support are\n"
47 "called.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000048 "\n"
49 "The basic type used for binary data read from or written to a file is\n"
Martin Panter6bb91f32016-05-28 00:41:57 +000050 "bytes. Other bytes-like objects are accepted as method arguments too.\n"
51 "In some cases (such as readinto), a writable object is required. Text\n"
52 "I/O classes work with str data.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000053 "\n"
Andrew Kuchling76466202014-04-15 21:11:36 -040054 "Note that calling any method (except additional calls to close(),\n"
55 "which are ignored) on a closed stream should raise a ValueError.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000056 "\n"
57 "IOBase (and its subclasses) support the iterator protocol, meaning\n"
58 "that an IOBase object can be iterated over yielding the lines in a\n"
59 "stream.\n"
60 "\n"
61 "IOBase also supports the :keyword:`with` statement. In this example,\n"
Ezio Melotti13925002011-03-16 11:05:33 +020062 "fp is closed after the suite of the with statement is complete:\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000063 "\n"
64 "with open('spam.txt', 'r') as fp:\n"
65 " fp.write('Spam and eggs!')\n");
66
67/* Use this macro whenever you want to check the internal `closed` status
68 of the IOBase object rather than the virtual `closed` attribute as returned
69 by whatever subclass. */
70
Martin v. Löwis767046a2011-10-14 15:35:36 +020071_Py_IDENTIFIER(__IOBase_closed);
Victor Stinner3f36a572013-11-12 21:39:02 +010072_Py_IDENTIFIER(read);
73
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +020074
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000075/* Internal methods */
76static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000077iobase_unsupported(const char *message)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000078{
Antoine Pitrou712cb732013-12-21 15:51:54 +010079 _PyIO_State *state = IO_STATE();
80 if (state != NULL)
81 PyErr_SetString(state->unsupported_operation, message);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000082 return NULL;
83}
84
Raymond Hettinger15f44ab2016-08-30 10:47:49 -070085/* Positioning */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000086
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000087PyDoc_STRVAR(iobase_seek_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000088 "Change stream position.\n"
89 "\n"
Terry Jan Reedy0158af32013-03-11 17:42:46 -040090 "Change the stream position to the given byte offset. The offset is\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000091 "interpreted relative to the position indicated by whence. Values\n"
92 "for whence are:\n"
93 "\n"
94 "* 0 -- start of stream (the default); offset should be zero or positive\n"
95 "* 1 -- current stream position; offset may be negative\n"
96 "* 2 -- end of stream; offset is usually negative\n"
97 "\n"
98 "Return the new absolute position.");
99
100static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000101iobase_seek(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000102{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000103 return iobase_unsupported("seek");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000104}
105
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300106/*[clinic input]
107_io._IOBase.tell
108
109Return current stream position.
110[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000111
112static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300113_io__IOBase_tell_impl(PyObject *self)
114/*[clinic end generated code: output=89a1c0807935abe2 input=04e615fec128801f]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000115{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200116 _Py_IDENTIFIER(seek);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200117
118 return _PyObject_CallMethodId(self, &PyId_seek, "ii", 0, 1);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000119}
120
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000121PyDoc_STRVAR(iobase_truncate_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000122 "Truncate file to size bytes.\n"
123 "\n"
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000124 "File pointer is left unchanged. Size defaults to the current IO\n"
125 "position as reported by tell(). Returns the new size.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000126
127static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000128iobase_truncate(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000129{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000130 return iobase_unsupported("truncate");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000131}
132
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200133static int
134iobase_is_closed(PyObject *self)
135{
136 PyObject *res;
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200137 int ret;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200138 /* This gets the derived attribute, which is *not* __IOBase_closed
139 in most cases! */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200140 ret = _PyObject_LookupAttrId(self, &PyId___IOBase_closed, &res);
141 Py_XDECREF(res);
142 return ret;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200143}
144
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000145/* Flush and close methods */
146
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300147/*[clinic input]
148_io._IOBase.flush
149
150Flush write buffers, if applicable.
151
152This is not implemented for read-only and non-blocking streams.
153[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000154
155static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300156_io__IOBase_flush_impl(PyObject *self)
157/*[clinic end generated code: output=7cef4b4d54656a3b input=773be121abe270aa]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000158{
159 /* XXX Should this return the number of bytes written??? */
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200160 int closed = iobase_is_closed(self);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000161
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200162 if (!closed) {
163 Py_RETURN_NONE;
164 }
165 if (closed > 0) {
166 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
167 }
168 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000169}
170
171static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000172iobase_closed_get(PyObject *self, void *context)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000173{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200174 int closed = iobase_is_closed(self);
175 if (closed < 0) {
176 return NULL;
177 }
178 return PyBool_FromLong(closed);
179}
180
181static int
182iobase_check_closed(PyObject *self)
183{
184 PyObject *res;
185 int closed;
186 /* This gets the derived attribute, which is *not* __IOBase_closed
187 in most cases! */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200188 closed = _PyObject_LookupAttr(self, _PyIO_str_closed, &res);
189 if (closed > 0) {
190 closed = PyObject_IsTrue(res);
191 Py_DECREF(res);
192 if (closed > 0) {
193 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200194 return -1;
195 }
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200196 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200197 return closed;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000198}
199
200PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000201_PyIOBase_check_closed(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000202{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200203 if (iobase_check_closed(self)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000204 return NULL;
205 }
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200206 if (args == Py_True) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000207 return Py_None;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200208 }
209 Py_RETURN_NONE;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000210}
211
212/* XXX: IOBase thinks it has to maintain its own internal state in
213 `__IOBase_closed` and call flush() by itself, but it is redundant with
214 whatever behaviour a non-trivial derived class will implement. */
215
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300216/*[clinic input]
217_io._IOBase.close
218
219Flush and close the IO object.
220
221This method has no effect if the file is already closed.
222[clinic start generated code]*/
223
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000224static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300225_io__IOBase_close_impl(PyObject *self)
226/*[clinic end generated code: output=63c6a6f57d783d6d input=f4494d5c31dbc6b7]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000227{
Zackery Spytz28f07362018-07-17 00:31:44 -0600228 PyObject *res, *exc, *val, *tb;
229 int rc, closed = iobase_is_closed(self);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000230
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200231 if (closed < 0) {
232 return NULL;
233 }
234 if (closed) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000235 Py_RETURN_NONE;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200236 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000237
Petr Viktorinffd97532020-02-11 17:46:57 +0100238 res = PyObject_CallMethodNoArgs(self, _PyIO_str_flush);
Victor Stinneraa5bbfa2013-11-08 00:29:41 +0100239
Zackery Spytz28f07362018-07-17 00:31:44 -0600240 PyErr_Fetch(&exc, &val, &tb);
241 rc = _PyObject_SetAttrId(self, &PyId___IOBase_closed, Py_True);
242 _PyErr_ChainExceptions(exc, val, tb);
243 if (rc < 0) {
244 Py_CLEAR(res);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000245 }
Victor Stinneraa5bbfa2013-11-08 00:29:41 +0100246
247 if (res == NULL)
248 return NULL;
249
250 Py_DECREF(res);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000251 Py_RETURN_NONE;
252}
253
254/* Finalization and garbage collection support */
255
Antoine Pitrou796564c2013-07-30 19:59:21 +0200256static void
257iobase_finalize(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000258{
259 PyObject *res;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200260 PyObject *error_type, *error_value, *error_traceback;
261 int closed;
262 _Py_IDENTIFIER(_finalizing);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000263
Antoine Pitrou796564c2013-07-30 19:59:21 +0200264 /* Save the current exception, if any. */
265 PyErr_Fetch(&error_type, &error_value, &error_traceback);
266
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000267 /* If `closed` doesn't exist or can't be evaluated as bool, then the
268 object is probably in an unusable state, so ignore. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200269 if (_PyObject_LookupAttr(self, _PyIO_str_closed, &res) <= 0) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000270 PyErr_Clear();
Christian Heimes72f455e2013-07-31 01:33:50 +0200271 closed = -1;
272 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000273 else {
274 closed = PyObject_IsTrue(res);
275 Py_DECREF(res);
276 if (closed == -1)
277 PyErr_Clear();
278 }
279 if (closed == 0) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200280 /* Signal close() that it was called as part of the object
281 finalization process. */
282 if (_PyObject_SetAttrId(self, &PyId__finalizing, Py_True))
283 PyErr_Clear();
Petr Viktorinffd97532020-02-11 17:46:57 +0100284 res = PyObject_CallMethodNoArgs((PyObject *)self, _PyIO_str_close);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000285 /* Silencing I/O errors is bad, but printing spurious tracebacks is
286 equally as bad, and potentially more frequent (because of
287 shutdown issues). */
Victor Stinner44235042019-04-12 17:06:47 +0200288 if (res == NULL) {
289#ifndef Py_DEBUG
Victor Stinnerda7933e2020-04-13 03:04:28 +0200290 if (_Py_GetConfig()->dev_mode) {
Victor Stinner44235042019-04-12 17:06:47 +0200291 PyErr_WriteUnraisable(self);
292 }
293 else {
294 PyErr_Clear();
295 }
296#else
297 PyErr_WriteUnraisable(self);
298#endif
299 }
300 else {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000301 Py_DECREF(res);
Victor Stinner44235042019-04-12 17:06:47 +0200302 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000303 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200304
305 /* Restore the saved exception. */
306 PyErr_Restore(error_type, error_value, error_traceback);
307}
308
309int
310_PyIOBase_finalize(PyObject *self)
311{
312 int is_zombie;
313
314 /* If _PyIOBase_finalize() is called from a destructor, we need to
315 resurrect the object as calling close() can invoke arbitrary code. */
316 is_zombie = (Py_REFCNT(self) == 0);
317 if (is_zombie)
318 return PyObject_CallFinalizerFromDealloc(self);
319 else {
320 PyObject_CallFinalizer(self);
321 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000322 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000323}
324
325static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000326iobase_traverse(iobase *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000327{
328 Py_VISIT(self->dict);
329 return 0;
330}
331
332static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000333iobase_clear(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000334{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000335 Py_CLEAR(self->dict);
336 return 0;
337}
338
339/* Destructor */
340
341static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000342iobase_dealloc(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000343{
344 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
345 are still available here for close() to use.
346 However, if the derived class declares a __slots__, those slots are
347 already gone.
348 */
349 if (_PyIOBase_finalize((PyObject *) self) < 0) {
350 /* When called from a heap type's dealloc, the type will be
351 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
352 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
353 Py_INCREF(Py_TYPE(self));
354 return;
355 }
356 _PyObject_GC_UNTRACK(self);
357 if (self->weakreflist != NULL)
358 PyObject_ClearWeakRefs((PyObject *) self);
359 Py_CLEAR(self->dict);
360 Py_TYPE(self)->tp_free((PyObject *) self);
361}
362
363/* Inquiry methods */
364
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300365/*[clinic input]
366_io._IOBase.seekable
367
368Return whether object supports random access.
369
Martin Panter754aab22016-03-31 07:21:56 +0000370If False, seek(), tell() and truncate() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300371This method may need to do a test seek().
372[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000373
374static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300375_io__IOBase_seekable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000376/*[clinic end generated code: output=4c24c67f5f32a43d input=b976622f7fdf3063]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000377{
378 Py_RETURN_FALSE;
379}
380
381PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000382_PyIOBase_check_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000383{
Petr Viktorinffd97532020-02-11 17:46:57 +0100384 PyObject *res = PyObject_CallMethodNoArgs(self, _PyIO_str_seekable);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000385 if (res == NULL)
386 return NULL;
387 if (res != Py_True) {
388 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000389 iobase_unsupported("File or stream is not seekable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000390 return NULL;
391 }
392 if (args == Py_True) {
393 Py_DECREF(res);
394 }
395 return res;
396}
397
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300398/*[clinic input]
399_io._IOBase.readable
400
401Return whether object was opened for reading.
402
Martin Panter754aab22016-03-31 07:21:56 +0000403If False, read() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300404[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000405
406static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300407_io__IOBase_readable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000408/*[clinic end generated code: output=e48089250686388b input=285b3b866a0ec35f]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000409{
410 Py_RETURN_FALSE;
411}
412
413/* May be called with any object */
414PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000415_PyIOBase_check_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000416{
Petr Viktorinffd97532020-02-11 17:46:57 +0100417 PyObject *res = PyObject_CallMethodNoArgs(self, _PyIO_str_readable);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000418 if (res == NULL)
419 return NULL;
420 if (res != Py_True) {
421 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000422 iobase_unsupported("File or stream is not readable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000423 return NULL;
424 }
425 if (args == Py_True) {
426 Py_DECREF(res);
427 }
428 return res;
429}
430
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300431/*[clinic input]
432_io._IOBase.writable
433
434Return whether object was opened for writing.
435
Martin Panter754aab22016-03-31 07:21:56 +0000436If False, write() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300437[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438
439static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300440_io__IOBase_writable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000441/*[clinic end generated code: output=406001d0985be14f input=9dcac18a013a05b5]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000442{
443 Py_RETURN_FALSE;
444}
445
446/* May be called with any object */
447PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000448_PyIOBase_check_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000449{
Petr Viktorinffd97532020-02-11 17:46:57 +0100450 PyObject *res = PyObject_CallMethodNoArgs(self, _PyIO_str_writable);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000451 if (res == NULL)
452 return NULL;
453 if (res != Py_True) {
454 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000455 iobase_unsupported("File or stream is not writable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000456 return NULL;
457 }
458 if (args == Py_True) {
459 Py_DECREF(res);
460 }
461 return res;
462}
463
464/* Context manager */
465
466static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000467iobase_enter(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000468{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200469 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000470 return NULL;
471
472 Py_INCREF(self);
473 return self;
474}
475
476static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000477iobase_exit(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000478{
Petr Viktorinffd97532020-02-11 17:46:57 +0100479 return PyObject_CallMethodNoArgs(self, _PyIO_str_close);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000480}
481
482/* Lower-level APIs */
483
484/* XXX Should these be present even if unimplemented? */
485
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300486/*[clinic input]
487_io._IOBase.fileno
488
489Returns underlying file descriptor if one exists.
490
Martin Panter754aab22016-03-31 07:21:56 +0000491OSError is raised if the IO object does not use a file descriptor.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300492[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000493
494static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300495_io__IOBase_fileno_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000496/*[clinic end generated code: output=7cc0973f0f5f3b73 input=4e37028947dc1cc8]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000497{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000498 return iobase_unsupported("fileno");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000499}
500
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300501/*[clinic input]
502_io._IOBase.isatty
503
504Return whether this is an 'interactive' stream.
505
506Return False if it can't be determined.
507[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000508
509static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300510_io__IOBase_isatty_impl(PyObject *self)
511/*[clinic end generated code: output=60cab77cede41cdd input=9ef76530d368458b]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000512{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200513 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000514 return NULL;
515 Py_RETURN_FALSE;
516}
517
518/* Readline(s) and writelines */
519
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300520/*[clinic input]
521_io._IOBase.readline
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300522 size as limit: Py_ssize_t(accept={int, NoneType}) = -1
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300523 /
524
525Read and return a line from the stream.
526
527If size is specified, at most size bytes will be read.
528
529The line terminator is always b'\n' for binary files; for text
530files, the newlines argument to open can be used to select the line
531terminator(s) recognized.
532[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000533
534static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300535_io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300536/*[clinic end generated code: output=4479f79b58187840 input=d0c596794e877bff]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000537{
538 /* For backwards compatibility, a (slowish) readline(). */
539
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200540 PyObject *peek, *buffer, *result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000541 Py_ssize_t old_size = -1;
542
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200543 if (_PyObject_LookupAttr(self, _PyIO_str_peek, &peek) < 0) {
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200544 return NULL;
545 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000546
547 buffer = PyByteArray_FromStringAndSize(NULL, 0);
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200548 if (buffer == NULL) {
549 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000550 return NULL;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200551 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000552
Serhiy Storchakafff9a312017-03-21 08:53:25 +0200553 while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000554 Py_ssize_t nreadahead = 1;
555 PyObject *b;
556
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200557 if (peek != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +0100558 PyObject *readahead = PyObject_CallOneArg(peek, _PyLong_One);
Gregory P. Smith51359922012-06-23 23:55:39 -0700559 if (readahead == NULL) {
560 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
561 when EINTR occurs so we needn't do it ourselves. */
562 if (_PyIO_trap_eintr()) {
563 continue;
564 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000565 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700566 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567 if (!PyBytes_Check(readahead)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300568 PyErr_Format(PyExc_OSError,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000569 "peek() should have returned a bytes object, "
570 "not '%.200s'", Py_TYPE(readahead)->tp_name);
571 Py_DECREF(readahead);
572 goto fail;
573 }
574 if (PyBytes_GET_SIZE(readahead) > 0) {
575 Py_ssize_t n = 0;
576 const char *buf = PyBytes_AS_STRING(readahead);
577 if (limit >= 0) {
578 do {
579 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
580 break;
581 if (buf[n++] == '\n')
582 break;
583 } while (1);
584 }
585 else {
586 do {
587 if (n >= PyBytes_GET_SIZE(readahead))
588 break;
589 if (buf[n++] == '\n')
590 break;
591 } while (1);
592 }
593 nreadahead = n;
594 }
595 Py_DECREF(readahead);
596 }
597
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200598 b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
Gregory P. Smith51359922012-06-23 23:55:39 -0700599 if (b == NULL) {
600 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
601 when EINTR occurs so we needn't do it ourselves. */
602 if (_PyIO_trap_eintr()) {
603 continue;
604 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000605 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700606 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000607 if (!PyBytes_Check(b)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300608 PyErr_Format(PyExc_OSError,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000609 "read() should have returned a bytes object, "
610 "not '%.200s'", Py_TYPE(b)->tp_name);
611 Py_DECREF(b);
612 goto fail;
613 }
614 if (PyBytes_GET_SIZE(b) == 0) {
615 Py_DECREF(b);
616 break;
617 }
618
619 old_size = PyByteArray_GET_SIZE(buffer);
Victor Stinnercc024d12013-10-29 02:23:46 +0100620 if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
621 Py_DECREF(b);
622 goto fail;
623 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000624 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
625 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
626
627 Py_DECREF(b);
628
629 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
630 break;
631 }
632
633 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
634 PyByteArray_GET_SIZE(buffer));
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200635 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000636 Py_DECREF(buffer);
637 return result;
638 fail:
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200639 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000640 Py_DECREF(buffer);
641 return NULL;
642}
643
644static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000645iobase_iter(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000646{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200647 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000648 return NULL;
649
650 Py_INCREF(self);
651 return self;
652}
653
654static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000655iobase_iternext(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000656{
Petr Viktorinffd97532020-02-11 17:46:57 +0100657 PyObject *line = PyObject_CallMethodNoArgs(self, _PyIO_str_readline);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000658
659 if (line == NULL)
660 return NULL;
661
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300662 if (PyObject_Size(line) <= 0) {
663 /* Error or empty */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000664 Py_DECREF(line);
665 return NULL;
666 }
667
668 return line;
669}
670
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300671/*[clinic input]
672_io._IOBase.readlines
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300673 hint: Py_ssize_t(accept={int, NoneType}) = -1
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300674 /
675
676Return a list of lines from the stream.
677
678hint can be specified to control the number of lines read: no more
679lines will be read if the total size (in bytes/characters) of all
680lines so far exceeds hint.
681[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000682
683static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300684_io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint)
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300685/*[clinic end generated code: output=2f50421677fa3dea input=9400c786ea9dc416]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000686{
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300687 Py_ssize_t length = 0;
Xiang Zhang026435c2017-04-15 12:47:28 +0800688 PyObject *result, *it = NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000689
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000690 result = PyList_New(0);
691 if (result == NULL)
692 return NULL;
693
694 if (hint <= 0) {
695 /* XXX special-casing this made sense in the Python version in order
696 to remove the bytecode interpretation overhead, but it could
697 probably be removed here. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200698 _Py_IDENTIFIER(extend);
Victor Stinner61bdb0d2016-12-09 15:39:28 +0100699 PyObject *ret = _PyObject_CallMethodIdObjArgs(result, &PyId_extend,
700 self, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200701
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000702 if (ret == NULL) {
Xiang Zhang026435c2017-04-15 12:47:28 +0800703 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000704 }
705 Py_DECREF(ret);
706 return result;
707 }
708
Xiang Zhang026435c2017-04-15 12:47:28 +0800709 it = PyObject_GetIter(self);
710 if (it == NULL) {
711 goto error;
712 }
713
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000714 while (1) {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300715 Py_ssize_t line_length;
Xiang Zhang026435c2017-04-15 12:47:28 +0800716 PyObject *line = PyIter_Next(it);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000717 if (line == NULL) {
718 if (PyErr_Occurred()) {
Xiang Zhang026435c2017-04-15 12:47:28 +0800719 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000720 }
721 else
722 break; /* StopIteration raised */
723 }
724
725 if (PyList_Append(result, line) < 0) {
726 Py_DECREF(line);
Xiang Zhang026435c2017-04-15 12:47:28 +0800727 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000728 }
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300729 line_length = PyObject_Size(line);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000730 Py_DECREF(line);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300731 if (line_length < 0) {
732 goto error;
733 }
734 if (line_length > hint - length)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000735 break;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300736 length += line_length;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000737 }
Xiang Zhang026435c2017-04-15 12:47:28 +0800738
739 Py_DECREF(it);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000740 return result;
Xiang Zhang026435c2017-04-15 12:47:28 +0800741
742 error:
743 Py_XDECREF(it);
744 Py_DECREF(result);
745 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000746}
747
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300748/*[clinic input]
749_io._IOBase.writelines
750 lines: object
751 /
Marcin Niemiraab865212019-04-22 21:13:51 +1000752
753Write a list of lines to stream.
754
755Line separators are not added, so it is usual for each of the
756lines provided to have a line separator at the end.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300757[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000758
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300759static PyObject *
760_io__IOBase_writelines(PyObject *self, PyObject *lines)
Marcin Niemiraab865212019-04-22 21:13:51 +1000761/*[clinic end generated code: output=976eb0a9b60a6628 input=cac3fc8864183359]*/
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300762{
763 PyObject *iter, *res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000764
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200765 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000766 return NULL;
767
768 iter = PyObject_GetIter(lines);
769 if (iter == NULL)
770 return NULL;
771
772 while (1) {
773 PyObject *line = PyIter_Next(iter);
774 if (line == NULL) {
775 if (PyErr_Occurred()) {
776 Py_DECREF(iter);
777 return NULL;
778 }
779 else
780 break; /* Stop Iteration */
781 }
782
Gregory P. Smithb9817b02013-02-01 13:03:39 -0800783 res = NULL;
784 do {
785 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
786 } while (res == NULL && _PyIO_trap_eintr());
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000787 Py_DECREF(line);
788 if (res == NULL) {
789 Py_DECREF(iter);
790 return NULL;
791 }
792 Py_DECREF(res);
793 }
794 Py_DECREF(iter);
795 Py_RETURN_NONE;
796}
797
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300798#include "clinic/iobase.c.h"
799
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000800static PyMethodDef iobase_methods[] = {
801 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300802 _IO__IOBASE_TELL_METHODDEF
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000803 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300804 _IO__IOBASE_FLUSH_METHODDEF
805 _IO__IOBASE_CLOSE_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000806
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300807 _IO__IOBASE_SEEKABLE_METHODDEF
808 _IO__IOBASE_READABLE_METHODDEF
809 _IO__IOBASE_WRITABLE_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000810
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000811 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
812 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
813 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
814 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000815
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300816 _IO__IOBASE_FILENO_METHODDEF
817 _IO__IOBASE_ISATTY_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000818
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000819 {"__enter__", iobase_enter, METH_NOARGS},
820 {"__exit__", iobase_exit, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000821
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300822 _IO__IOBASE_READLINE_METHODDEF
823 _IO__IOBASE_READLINES_METHODDEF
824 _IO__IOBASE_WRITELINES_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000825
826 {NULL, NULL}
827};
828
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000829static PyGetSetDef iobase_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500830 {"__dict__", PyObject_GenericGetDict, NULL, NULL},
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000831 {"closed", (getter)iobase_closed_get, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000832 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000833};
834
835
836PyTypeObject PyIOBase_Type = {
837 PyVarObject_HEAD_INIT(NULL, 0)
838 "_io._IOBase", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000839 sizeof(iobase), /*tp_basicsize*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000840 0, /*tp_itemsize*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000841 (destructor)iobase_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200842 0, /*tp_vectorcall_offset*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000843 0, /*tp_getattr*/
844 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200845 0, /*tp_as_async*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000846 0, /*tp_repr*/
847 0, /*tp_as_number*/
848 0, /*tp_as_sequence*/
849 0, /*tp_as_mapping*/
850 0, /*tp_hash */
851 0, /*tp_call*/
852 0, /*tp_str*/
853 0, /*tp_getattro*/
854 0, /*tp_setattro*/
855 0, /*tp_as_buffer*/
856 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
Antoine Pitrouada319b2019-05-29 22:12:38 +0200857 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000858 iobase_doc, /* tp_doc */
859 (traverseproc)iobase_traverse, /* tp_traverse */
860 (inquiry)iobase_clear, /* tp_clear */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000861 0, /* tp_richcompare */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000862 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
863 iobase_iter, /* tp_iter */
864 iobase_iternext, /* tp_iternext */
865 iobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000866 0, /* tp_members */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000867 iobase_getset, /* tp_getset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000868 0, /* tp_base */
869 0, /* tp_dict */
870 0, /* tp_descr_get */
871 0, /* tp_descr_set */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000872 offsetof(iobase, dict), /* tp_dictoffset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000873 0, /* tp_init */
874 0, /* tp_alloc */
875 PyType_GenericNew, /* tp_new */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200876 0, /* tp_free */
877 0, /* tp_is_gc */
878 0, /* tp_bases */
879 0, /* tp_mro */
880 0, /* tp_cache */
881 0, /* tp_subclasses */
882 0, /* tp_weaklist */
883 0, /* tp_del */
884 0, /* tp_version_tag */
Victor Stinner928bff02016-03-19 10:36:36 +0100885 iobase_finalize, /* tp_finalize */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000886};
887
888
889/*
890 * RawIOBase class, Inherits from IOBase.
891 */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000892PyDoc_STRVAR(rawiobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000893 "Base class for raw binary I/O.");
894
895/*
896 * The read() method is implemented by calling readinto(); derived classes
897 * that want to support read() only need to implement readinto() as a
898 * primitive operation. In general, readinto() can be more efficient than
899 * read().
900 *
901 * (It would be tempting to also provide an implementation of readinto() in
902 * terms of read(), in case the latter is a more suitable primitive operation,
903 * but that would lead to nasty recursion in case a subclass doesn't implement
904 * either.)
905*/
906
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300907/*[clinic input]
908_io._RawIOBase.read
909 size as n: Py_ssize_t = -1
910 /
911[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000912
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300913static PyObject *
914_io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
915/*[clinic end generated code: output=6cdeb731e3c9f13c input=b6d0dcf6417d1374]*/
916{
917 PyObject *b, *res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000918
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200919 if (n < 0) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200920 _Py_IDENTIFIER(readall);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200921
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200922 return _PyObject_CallMethodIdNoArgs(self, &PyId_readall);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200923 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000924
925 /* TODO: allocate a bytes object directly instead and manually construct
926 a writable memoryview pointing to it. */
927 b = PyByteArray_FromStringAndSize(NULL, n);
928 if (b == NULL)
929 return NULL;
930
931 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000932 if (res == NULL || res == Py_None) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000933 Py_DECREF(b);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000934 return res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000935 }
936
937 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
938 Py_DECREF(res);
939 if (n == -1 && PyErr_Occurred()) {
940 Py_DECREF(b);
941 return NULL;
942 }
943
944 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
945 Py_DECREF(b);
946 return res;
947}
948
949
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300950/*[clinic input]
951_io._RawIOBase.readall
952
953Read until EOF, using multiple read() call.
954[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000955
956static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300957_io__RawIOBase_readall_impl(PyObject *self)
958/*[clinic end generated code: output=1987b9ce929425a0 input=688874141213622a]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000959{
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000960 int r;
961 PyObject *chunks = PyList_New(0);
962 PyObject *result;
Victor Stinnercc024d12013-10-29 02:23:46 +0100963
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000964 if (chunks == NULL)
965 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000966
967 while (1) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200968 PyObject *data = _PyObject_CallMethodId(self, &PyId_read,
969 "i", DEFAULT_BUFFER_SIZE);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000970 if (!data) {
Gregory P. Smith51359922012-06-23 23:55:39 -0700971 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
972 when EINTR occurs so we needn't do it ourselves. */
973 if (_PyIO_trap_eintr()) {
974 continue;
975 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000976 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000977 return NULL;
978 }
Victor Stinnera80987f2011-05-25 22:47:16 +0200979 if (data == Py_None) {
980 if (PyList_GET_SIZE(chunks) == 0) {
981 Py_DECREF(chunks);
982 return data;
983 }
984 Py_DECREF(data);
985 break;
986 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000987 if (!PyBytes_Check(data)) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000988 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000989 Py_DECREF(data);
990 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
991 return NULL;
992 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000993 if (PyBytes_GET_SIZE(data) == 0) {
994 /* EOF */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000995 Py_DECREF(data);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000996 break;
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000997 }
998 r = PyList_Append(chunks, data);
999 Py_DECREF(data);
1000 if (r < 0) {
1001 Py_DECREF(chunks);
1002 return NULL;
1003 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001004 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +00001005 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
1006 Py_DECREF(chunks);
1007 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001008}
1009
Antoine Pitrou45d61562015-05-20 21:50:59 +02001010static PyObject *
1011rawiobase_readinto(PyObject *self, PyObject *args)
1012{
1013 PyErr_SetNone(PyExc_NotImplementedError);
1014 return NULL;
1015}
1016
1017static PyObject *
1018rawiobase_write(PyObject *self, PyObject *args)
1019{
1020 PyErr_SetNone(PyExc_NotImplementedError);
1021 return NULL;
1022}
1023
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001024static PyMethodDef rawiobase_methods[] = {
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001025 _IO__RAWIOBASE_READ_METHODDEF
1026 _IO__RAWIOBASE_READALL_METHODDEF
Antoine Pitrou45d61562015-05-20 21:50:59 +02001027 {"readinto", rawiobase_readinto, METH_VARARGS},
1028 {"write", rawiobase_write, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001029 {NULL, NULL}
1030};
1031
1032PyTypeObject PyRawIOBase_Type = {
1033 PyVarObject_HEAD_INIT(NULL, 0)
1034 "_io._RawIOBase", /*tp_name*/
1035 0, /*tp_basicsize*/
1036 0, /*tp_itemsize*/
1037 0, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001038 0, /*tp_vectorcall_offset*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001039 0, /*tp_getattr*/
1040 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001041 0, /*tp_as_async*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001042 0, /*tp_repr*/
1043 0, /*tp_as_number*/
1044 0, /*tp_as_sequence*/
1045 0, /*tp_as_mapping*/
1046 0, /*tp_hash */
1047 0, /*tp_call*/
1048 0, /*tp_str*/
1049 0, /*tp_getattro*/
1050 0, /*tp_setattro*/
1051 0, /*tp_as_buffer*/
Antoine Pitrouada319b2019-05-29 22:12:38 +02001052 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001053 rawiobase_doc, /* tp_doc */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001054 0, /* tp_traverse */
1055 0, /* tp_clear */
1056 0, /* tp_richcompare */
1057 0, /* tp_weaklistoffset */
1058 0, /* tp_iter */
1059 0, /* tp_iternext */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001060 rawiobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001061 0, /* tp_members */
1062 0, /* tp_getset */
1063 &PyIOBase_Type, /* tp_base */
1064 0, /* tp_dict */
1065 0, /* tp_descr_get */
1066 0, /* tp_descr_set */
1067 0, /* tp_dictoffset */
1068 0, /* tp_init */
1069 0, /* tp_alloc */
1070 0, /* tp_new */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001071 0, /* tp_free */
1072 0, /* tp_is_gc */
1073 0, /* tp_bases */
1074 0, /* tp_mro */
1075 0, /* tp_cache */
1076 0, /* tp_subclasses */
1077 0, /* tp_weaklist */
1078 0, /* tp_del */
1079 0, /* tp_version_tag */
1080 0, /* tp_finalize */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001081};