blob: 6a0d9bec5af3205716e4e6602e71dbe17a470b2e [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"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000014#include "structmember.h"
15#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
238 res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
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();
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000284 res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
285 NULL);
286 /* Silencing I/O errors is bad, but printing spurious tracebacks is
287 equally as bad, and potentially more frequent (because of
288 shutdown issues). */
Victor Stinner44235042019-04-12 17:06:47 +0200289 if (res == NULL) {
290#ifndef Py_DEBUG
291 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
292 if (config->dev_mode) {
293 PyErr_WriteUnraisable(self);
294 }
295 else {
296 PyErr_Clear();
297 }
298#else
299 PyErr_WriteUnraisable(self);
300#endif
301 }
302 else {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000303 Py_DECREF(res);
Victor Stinner44235042019-04-12 17:06:47 +0200304 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000305 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200306
307 /* Restore the saved exception. */
308 PyErr_Restore(error_type, error_value, error_traceback);
309}
310
311int
312_PyIOBase_finalize(PyObject *self)
313{
314 int is_zombie;
315
316 /* If _PyIOBase_finalize() is called from a destructor, we need to
317 resurrect the object as calling close() can invoke arbitrary code. */
318 is_zombie = (Py_REFCNT(self) == 0);
319 if (is_zombie)
320 return PyObject_CallFinalizerFromDealloc(self);
321 else {
322 PyObject_CallFinalizer(self);
323 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000324 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000325}
326
327static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000328iobase_traverse(iobase *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000329{
330 Py_VISIT(self->dict);
331 return 0;
332}
333
334static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000335iobase_clear(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000336{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000337 Py_CLEAR(self->dict);
338 return 0;
339}
340
341/* Destructor */
342
343static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000344iobase_dealloc(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000345{
346 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
347 are still available here for close() to use.
348 However, if the derived class declares a __slots__, those slots are
349 already gone.
350 */
351 if (_PyIOBase_finalize((PyObject *) self) < 0) {
352 /* When called from a heap type's dealloc, the type will be
353 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
354 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
355 Py_INCREF(Py_TYPE(self));
356 return;
357 }
358 _PyObject_GC_UNTRACK(self);
359 if (self->weakreflist != NULL)
360 PyObject_ClearWeakRefs((PyObject *) self);
361 Py_CLEAR(self->dict);
362 Py_TYPE(self)->tp_free((PyObject *) self);
363}
364
365/* Inquiry methods */
366
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300367/*[clinic input]
368_io._IOBase.seekable
369
370Return whether object supports random access.
371
Martin Panter754aab22016-03-31 07:21:56 +0000372If False, seek(), tell() and truncate() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300373This method may need to do a test seek().
374[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000375
376static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300377_io__IOBase_seekable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000378/*[clinic end generated code: output=4c24c67f5f32a43d input=b976622f7fdf3063]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000379{
380 Py_RETURN_FALSE;
381}
382
383PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000384_PyIOBase_check_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000385{
386 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
387 if (res == NULL)
388 return NULL;
389 if (res != Py_True) {
390 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000391 iobase_unsupported("File or stream is not seekable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000392 return NULL;
393 }
394 if (args == Py_True) {
395 Py_DECREF(res);
396 }
397 return res;
398}
399
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300400/*[clinic input]
401_io._IOBase.readable
402
403Return whether object was opened for reading.
404
Martin Panter754aab22016-03-31 07:21:56 +0000405If False, read() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300406[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000407
408static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300409_io__IOBase_readable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000410/*[clinic end generated code: output=e48089250686388b input=285b3b866a0ec35f]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000411{
412 Py_RETURN_FALSE;
413}
414
415/* May be called with any object */
416PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000417_PyIOBase_check_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000418{
419 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
420 if (res == NULL)
421 return NULL;
422 if (res != Py_True) {
423 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000424 iobase_unsupported("File or stream is not readable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000425 return NULL;
426 }
427 if (args == Py_True) {
428 Py_DECREF(res);
429 }
430 return res;
431}
432
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300433/*[clinic input]
434_io._IOBase.writable
435
436Return whether object was opened for writing.
437
Martin Panter754aab22016-03-31 07:21:56 +0000438If False, write() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300439[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000440
441static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300442_io__IOBase_writable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000443/*[clinic end generated code: output=406001d0985be14f input=9dcac18a013a05b5]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000444{
445 Py_RETURN_FALSE;
446}
447
448/* May be called with any object */
449PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000450_PyIOBase_check_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000451{
452 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
453 if (res == NULL)
454 return NULL;
455 if (res != Py_True) {
456 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000457 iobase_unsupported("File or stream is not writable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000458 return NULL;
459 }
460 if (args == Py_True) {
461 Py_DECREF(res);
462 }
463 return res;
464}
465
466/* Context manager */
467
468static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000469iobase_enter(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000470{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200471 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000472 return NULL;
473
474 Py_INCREF(self);
475 return self;
476}
477
478static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000479iobase_exit(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000480{
481 return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
482}
483
484/* Lower-level APIs */
485
486/* XXX Should these be present even if unimplemented? */
487
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300488/*[clinic input]
489_io._IOBase.fileno
490
491Returns underlying file descriptor if one exists.
492
Martin Panter754aab22016-03-31 07:21:56 +0000493OSError is raised if the IO object does not use a file descriptor.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300494[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000495
496static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300497_io__IOBase_fileno_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000498/*[clinic end generated code: output=7cc0973f0f5f3b73 input=4e37028947dc1cc8]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000499{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000500 return iobase_unsupported("fileno");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000501}
502
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300503/*[clinic input]
504_io._IOBase.isatty
505
506Return whether this is an 'interactive' stream.
507
508Return False if it can't be determined.
509[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000510
511static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300512_io__IOBase_isatty_impl(PyObject *self)
513/*[clinic end generated code: output=60cab77cede41cdd input=9ef76530d368458b]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000514{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200515 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000516 return NULL;
517 Py_RETURN_FALSE;
518}
519
520/* Readline(s) and writelines */
521
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300522/*[clinic input]
523_io._IOBase.readline
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300524 size as limit: Py_ssize_t(accept={int, NoneType}) = -1
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300525 /
526
527Read and return a line from the stream.
528
529If size is specified, at most size bytes will be read.
530
531The line terminator is always b'\n' for binary files; for text
532files, the newlines argument to open can be used to select the line
533terminator(s) recognized.
534[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000535
536static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300537_io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300538/*[clinic end generated code: output=4479f79b58187840 input=d0c596794e877bff]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000539{
540 /* For backwards compatibility, a (slowish) readline(). */
541
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200542 PyObject *peek, *buffer, *result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000543 Py_ssize_t old_size = -1;
544
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200545 if (_PyObject_LookupAttr(self, _PyIO_str_peek, &peek) < 0) {
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200546 return NULL;
547 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000548
549 buffer = PyByteArray_FromStringAndSize(NULL, 0);
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200550 if (buffer == NULL) {
551 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000552 return NULL;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200553 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000554
Serhiy Storchakafff9a312017-03-21 08:53:25 +0200555 while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000556 Py_ssize_t nreadahead = 1;
557 PyObject *b;
558
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200559 if (peek != NULL) {
560 PyObject *readahead = PyObject_CallFunctionObjArgs(peek, _PyLong_One, NULL);
Gregory P. Smith51359922012-06-23 23:55:39 -0700561 if (readahead == NULL) {
562 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
563 when EINTR occurs so we needn't do it ourselves. */
564 if (_PyIO_trap_eintr()) {
565 continue;
566 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700568 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000569 if (!PyBytes_Check(readahead)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300570 PyErr_Format(PyExc_OSError,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000571 "peek() should have returned a bytes object, "
572 "not '%.200s'", Py_TYPE(readahead)->tp_name);
573 Py_DECREF(readahead);
574 goto fail;
575 }
576 if (PyBytes_GET_SIZE(readahead) > 0) {
577 Py_ssize_t n = 0;
578 const char *buf = PyBytes_AS_STRING(readahead);
579 if (limit >= 0) {
580 do {
581 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
582 break;
583 if (buf[n++] == '\n')
584 break;
585 } while (1);
586 }
587 else {
588 do {
589 if (n >= PyBytes_GET_SIZE(readahead))
590 break;
591 if (buf[n++] == '\n')
592 break;
593 } while (1);
594 }
595 nreadahead = n;
596 }
597 Py_DECREF(readahead);
598 }
599
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200600 b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
Gregory P. Smith51359922012-06-23 23:55:39 -0700601 if (b == NULL) {
602 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
603 when EINTR occurs so we needn't do it ourselves. */
604 if (_PyIO_trap_eintr()) {
605 continue;
606 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000607 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700608 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000609 if (!PyBytes_Check(b)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300610 PyErr_Format(PyExc_OSError,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000611 "read() should have returned a bytes object, "
612 "not '%.200s'", Py_TYPE(b)->tp_name);
613 Py_DECREF(b);
614 goto fail;
615 }
616 if (PyBytes_GET_SIZE(b) == 0) {
617 Py_DECREF(b);
618 break;
619 }
620
621 old_size = PyByteArray_GET_SIZE(buffer);
Victor Stinnercc024d12013-10-29 02:23:46 +0100622 if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
623 Py_DECREF(b);
624 goto fail;
625 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000626 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
627 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
628
629 Py_DECREF(b);
630
631 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
632 break;
633 }
634
635 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
636 PyByteArray_GET_SIZE(buffer));
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200637 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000638 Py_DECREF(buffer);
639 return result;
640 fail:
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200641 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000642 Py_DECREF(buffer);
643 return NULL;
644}
645
646static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000647iobase_iter(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000648{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200649 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000650 return NULL;
651
652 Py_INCREF(self);
653 return self;
654}
655
656static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000657iobase_iternext(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000658{
659 PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
660
661 if (line == NULL)
662 return NULL;
663
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300664 if (PyObject_Size(line) <= 0) {
665 /* Error or empty */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000666 Py_DECREF(line);
667 return NULL;
668 }
669
670 return line;
671}
672
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300673/*[clinic input]
674_io._IOBase.readlines
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300675 hint: Py_ssize_t(accept={int, NoneType}) = -1
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300676 /
677
678Return a list of lines from the stream.
679
680hint can be specified to control the number of lines read: no more
681lines will be read if the total size (in bytes/characters) of all
682lines so far exceeds hint.
683[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000684
685static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300686_io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint)
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300687/*[clinic end generated code: output=2f50421677fa3dea input=9400c786ea9dc416]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000688{
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300689 Py_ssize_t length = 0;
Xiang Zhang026435c2017-04-15 12:47:28 +0800690 PyObject *result, *it = NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000691
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000692 result = PyList_New(0);
693 if (result == NULL)
694 return NULL;
695
696 if (hint <= 0) {
697 /* XXX special-casing this made sense in the Python version in order
698 to remove the bytecode interpretation overhead, but it could
699 probably be removed here. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200700 _Py_IDENTIFIER(extend);
Victor Stinner61bdb0d2016-12-09 15:39:28 +0100701 PyObject *ret = _PyObject_CallMethodIdObjArgs(result, &PyId_extend,
702 self, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200703
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000704 if (ret == NULL) {
Xiang Zhang026435c2017-04-15 12:47:28 +0800705 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000706 }
707 Py_DECREF(ret);
708 return result;
709 }
710
Xiang Zhang026435c2017-04-15 12:47:28 +0800711 it = PyObject_GetIter(self);
712 if (it == NULL) {
713 goto error;
714 }
715
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000716 while (1) {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300717 Py_ssize_t line_length;
Xiang Zhang026435c2017-04-15 12:47:28 +0800718 PyObject *line = PyIter_Next(it);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000719 if (line == NULL) {
720 if (PyErr_Occurred()) {
Xiang Zhang026435c2017-04-15 12:47:28 +0800721 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000722 }
723 else
724 break; /* StopIteration raised */
725 }
726
727 if (PyList_Append(result, line) < 0) {
728 Py_DECREF(line);
Xiang Zhang026435c2017-04-15 12:47:28 +0800729 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000730 }
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300731 line_length = PyObject_Size(line);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000732 Py_DECREF(line);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300733 if (line_length < 0) {
734 goto error;
735 }
736 if (line_length > hint - length)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000737 break;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300738 length += line_length;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000739 }
Xiang Zhang026435c2017-04-15 12:47:28 +0800740
741 Py_DECREF(it);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000742 return result;
Xiang Zhang026435c2017-04-15 12:47:28 +0800743
744 error:
745 Py_XDECREF(it);
746 Py_DECREF(result);
747 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000748}
749
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300750/*[clinic input]
751_io._IOBase.writelines
752 lines: object
753 /
Marcin Niemiraab865212019-04-22 21:13:51 +1000754
755Write a list of lines to stream.
756
757Line separators are not added, so it is usual for each of the
758lines provided to have a line separator at the end.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300759[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000760
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300761static PyObject *
762_io__IOBase_writelines(PyObject *self, PyObject *lines)
Marcin Niemiraab865212019-04-22 21:13:51 +1000763/*[clinic end generated code: output=976eb0a9b60a6628 input=cac3fc8864183359]*/
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300764{
765 PyObject *iter, *res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000766
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200767 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000768 return NULL;
769
770 iter = PyObject_GetIter(lines);
771 if (iter == NULL)
772 return NULL;
773
774 while (1) {
775 PyObject *line = PyIter_Next(iter);
776 if (line == NULL) {
777 if (PyErr_Occurred()) {
778 Py_DECREF(iter);
779 return NULL;
780 }
781 else
782 break; /* Stop Iteration */
783 }
784
Gregory P. Smithb9817b02013-02-01 13:03:39 -0800785 res = NULL;
786 do {
787 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
788 } while (res == NULL && _PyIO_trap_eintr());
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000789 Py_DECREF(line);
790 if (res == NULL) {
791 Py_DECREF(iter);
792 return NULL;
793 }
794 Py_DECREF(res);
795 }
796 Py_DECREF(iter);
797 Py_RETURN_NONE;
798}
799
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300800#include "clinic/iobase.c.h"
801
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000802static PyMethodDef iobase_methods[] = {
803 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300804 _IO__IOBASE_TELL_METHODDEF
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000805 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300806 _IO__IOBASE_FLUSH_METHODDEF
807 _IO__IOBASE_CLOSE_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000808
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300809 _IO__IOBASE_SEEKABLE_METHODDEF
810 _IO__IOBASE_READABLE_METHODDEF
811 _IO__IOBASE_WRITABLE_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000812
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000813 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
814 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
815 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
816 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000817
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300818 _IO__IOBASE_FILENO_METHODDEF
819 _IO__IOBASE_ISATTY_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000820
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000821 {"__enter__", iobase_enter, METH_NOARGS},
822 {"__exit__", iobase_exit, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000823
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300824 _IO__IOBASE_READLINE_METHODDEF
825 _IO__IOBASE_READLINES_METHODDEF
826 _IO__IOBASE_WRITELINES_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000827
828 {NULL, NULL}
829};
830
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000831static PyGetSetDef iobase_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500832 {"__dict__", PyObject_GenericGetDict, NULL, NULL},
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000833 {"closed", (getter)iobase_closed_get, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000834 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000835};
836
837
838PyTypeObject PyIOBase_Type = {
839 PyVarObject_HEAD_INIT(NULL, 0)
840 "_io._IOBase", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000841 sizeof(iobase), /*tp_basicsize*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000842 0, /*tp_itemsize*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000843 (destructor)iobase_dealloc, /*tp_dealloc*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000844 0, /*tp_print*/
845 0, /*tp_getattr*/
846 0, /*tp_setattr*/
847 0, /*tp_compare */
848 0, /*tp_repr*/
849 0, /*tp_as_number*/
850 0, /*tp_as_sequence*/
851 0, /*tp_as_mapping*/
852 0, /*tp_hash */
853 0, /*tp_call*/
854 0, /*tp_str*/
855 0, /*tp_getattro*/
856 0, /*tp_setattro*/
857 0, /*tp_as_buffer*/
858 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
Antoine Pitrou796564c2013-07-30 19:59:21 +0200859 | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000860 iobase_doc, /* tp_doc */
861 (traverseproc)iobase_traverse, /* tp_traverse */
862 (inquiry)iobase_clear, /* tp_clear */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000863 0, /* tp_richcompare */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000864 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
865 iobase_iter, /* tp_iter */
866 iobase_iternext, /* tp_iternext */
867 iobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000868 0, /* tp_members */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000869 iobase_getset, /* tp_getset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000870 0, /* tp_base */
871 0, /* tp_dict */
872 0, /* tp_descr_get */
873 0, /* tp_descr_set */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000874 offsetof(iobase, dict), /* tp_dictoffset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000875 0, /* tp_init */
876 0, /* tp_alloc */
877 PyType_GenericNew, /* tp_new */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200878 0, /* tp_free */
879 0, /* tp_is_gc */
880 0, /* tp_bases */
881 0, /* tp_mro */
882 0, /* tp_cache */
883 0, /* tp_subclasses */
884 0, /* tp_weaklist */
885 0, /* tp_del */
886 0, /* tp_version_tag */
Victor Stinner928bff02016-03-19 10:36:36 +0100887 iobase_finalize, /* tp_finalize */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000888};
889
890
891/*
892 * RawIOBase class, Inherits from IOBase.
893 */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000894PyDoc_STRVAR(rawiobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000895 "Base class for raw binary I/O.");
896
897/*
898 * The read() method is implemented by calling readinto(); derived classes
899 * that want to support read() only need to implement readinto() as a
900 * primitive operation. In general, readinto() can be more efficient than
901 * read().
902 *
903 * (It would be tempting to also provide an implementation of readinto() in
904 * terms of read(), in case the latter is a more suitable primitive operation,
905 * but that would lead to nasty recursion in case a subclass doesn't implement
906 * either.)
907*/
908
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300909/*[clinic input]
910_io._RawIOBase.read
911 size as n: Py_ssize_t = -1
912 /
913[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000914
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300915static PyObject *
916_io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
917/*[clinic end generated code: output=6cdeb731e3c9f13c input=b6d0dcf6417d1374]*/
918{
919 PyObject *b, *res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000920
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200921 if (n < 0) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200922 _Py_IDENTIFIER(readall);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200923
924 return _PyObject_CallMethodId(self, &PyId_readall, NULL);
925 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000926
927 /* TODO: allocate a bytes object directly instead and manually construct
928 a writable memoryview pointing to it. */
929 b = PyByteArray_FromStringAndSize(NULL, n);
930 if (b == NULL)
931 return NULL;
932
933 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000934 if (res == NULL || res == Py_None) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000935 Py_DECREF(b);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000936 return res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000937 }
938
939 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
940 Py_DECREF(res);
941 if (n == -1 && PyErr_Occurred()) {
942 Py_DECREF(b);
943 return NULL;
944 }
945
946 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
947 Py_DECREF(b);
948 return res;
949}
950
951
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300952/*[clinic input]
953_io._RawIOBase.readall
954
955Read until EOF, using multiple read() call.
956[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000957
958static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300959_io__RawIOBase_readall_impl(PyObject *self)
960/*[clinic end generated code: output=1987b9ce929425a0 input=688874141213622a]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000961{
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000962 int r;
963 PyObject *chunks = PyList_New(0);
964 PyObject *result;
Victor Stinnercc024d12013-10-29 02:23:46 +0100965
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000966 if (chunks == NULL)
967 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000968
969 while (1) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200970 PyObject *data = _PyObject_CallMethodId(self, &PyId_read,
971 "i", DEFAULT_BUFFER_SIZE);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000972 if (!data) {
Gregory P. Smith51359922012-06-23 23:55:39 -0700973 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
974 when EINTR occurs so we needn't do it ourselves. */
975 if (_PyIO_trap_eintr()) {
976 continue;
977 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000978 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000979 return NULL;
980 }
Victor Stinnera80987f2011-05-25 22:47:16 +0200981 if (data == Py_None) {
982 if (PyList_GET_SIZE(chunks) == 0) {
983 Py_DECREF(chunks);
984 return data;
985 }
986 Py_DECREF(data);
987 break;
988 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000989 if (!PyBytes_Check(data)) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000990 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000991 Py_DECREF(data);
992 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
993 return NULL;
994 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000995 if (PyBytes_GET_SIZE(data) == 0) {
996 /* EOF */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000997 Py_DECREF(data);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000998 break;
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000999 }
1000 r = PyList_Append(chunks, data);
1001 Py_DECREF(data);
1002 if (r < 0) {
1003 Py_DECREF(chunks);
1004 return NULL;
1005 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001006 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +00001007 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
1008 Py_DECREF(chunks);
1009 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001010}
1011
Antoine Pitrou45d61562015-05-20 21:50:59 +02001012static PyObject *
1013rawiobase_readinto(PyObject *self, PyObject *args)
1014{
1015 PyErr_SetNone(PyExc_NotImplementedError);
1016 return NULL;
1017}
1018
1019static PyObject *
1020rawiobase_write(PyObject *self, PyObject *args)
1021{
1022 PyErr_SetNone(PyExc_NotImplementedError);
1023 return NULL;
1024}
1025
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001026static PyMethodDef rawiobase_methods[] = {
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001027 _IO__RAWIOBASE_READ_METHODDEF
1028 _IO__RAWIOBASE_READALL_METHODDEF
Antoine Pitrou45d61562015-05-20 21:50:59 +02001029 {"readinto", rawiobase_readinto, METH_VARARGS},
1030 {"write", rawiobase_write, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001031 {NULL, NULL}
1032};
1033
1034PyTypeObject PyRawIOBase_Type = {
1035 PyVarObject_HEAD_INIT(NULL, 0)
1036 "_io._RawIOBase", /*tp_name*/
1037 0, /*tp_basicsize*/
1038 0, /*tp_itemsize*/
1039 0, /*tp_dealloc*/
1040 0, /*tp_print*/
1041 0, /*tp_getattr*/
1042 0, /*tp_setattr*/
1043 0, /*tp_compare */
1044 0, /*tp_repr*/
1045 0, /*tp_as_number*/
1046 0, /*tp_as_sequence*/
1047 0, /*tp_as_mapping*/
1048 0, /*tp_hash */
1049 0, /*tp_call*/
1050 0, /*tp_str*/
1051 0, /*tp_getattro*/
1052 0, /*tp_setattro*/
1053 0, /*tp_as_buffer*/
Antoine Pitrou796564c2013-07-30 19:59:21 +02001054 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001055 rawiobase_doc, /* tp_doc */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001056 0, /* tp_traverse */
1057 0, /* tp_clear */
1058 0, /* tp_richcompare */
1059 0, /* tp_weaklistoffset */
1060 0, /* tp_iter */
1061 0, /* tp_iternext */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001062 rawiobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001063 0, /* tp_members */
1064 0, /* tp_getset */
1065 &PyIOBase_Type, /* tp_base */
1066 0, /* tp_dict */
1067 0, /* tp_descr_get */
1068 0, /* tp_descr_set */
1069 0, /* tp_dictoffset */
1070 0, /* tp_init */
1071 0, /* tp_alloc */
1072 0, /* tp_new */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001073 0, /* tp_free */
1074 0, /* tp_is_gc */
1075 0, /* tp_bases */
1076 0, /* tp_mro */
1077 0, /* tp_cache */
1078 0, /* tp_subclasses */
1079 0, /* tp_weaklist */
1080 0, /* tp_del */
1081 0, /* tp_version_tag */
1082 0, /* tp_finalize */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001083};