blob: 5b71732ef19c652dfa85ea06a885909372205e94 [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"
13#include "structmember.h"
14#include "_iomodule.h"
15
Serhiy Storchakaf24131f2015-04-16 11:19:43 +030016/*[clinic input]
17module _io
18class _io._IOBase "PyObject *" "&PyIOBase_Type"
19class _io._RawIOBase "PyObject *" "&PyRawIOBase_Type"
20[clinic start generated code]*/
21/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d29a4d076c2b211c]*/
22
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000023/*
24 * IOBase class, an abstract class
25 */
26
27typedef struct {
28 PyObject_HEAD
Victor Stinnercc024d12013-10-29 02:23:46 +010029
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000030 PyObject *dict;
31 PyObject *weakreflist;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000032} iobase;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000033
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000034PyDoc_STRVAR(iobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000035 "The abstract base class for all I/O classes, acting on streams of\n"
36 "bytes. There is no public constructor.\n"
37 "\n"
38 "This class provides dummy implementations for many methods that\n"
39 "derived classes can override selectively; the default implementations\n"
40 "represent a file that cannot be read, written or seeked.\n"
41 "\n"
42 "Even though IOBase does not declare read, readinto, or write because\n"
43 "their signatures will vary, implementations and clients should\n"
44 "consider those methods part of the interface. Also, implementations\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +000045 "may raise UnsupportedOperation when operations they do not support are\n"
46 "called.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000047 "\n"
48 "The basic type used for binary data read from or written to a file is\n"
Martin Panter6bb91f32016-05-28 00:41:57 +000049 "bytes. Other bytes-like objects are accepted as method arguments too.\n"
50 "In some cases (such as readinto), a writable object is required. Text\n"
51 "I/O classes work with str data.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000052 "\n"
Andrew Kuchling76466202014-04-15 21:11:36 -040053 "Note that calling any method (except additional calls to close(),\n"
54 "which are ignored) on a closed stream should raise a ValueError.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000055 "\n"
56 "IOBase (and its subclasses) support the iterator protocol, meaning\n"
57 "that an IOBase object can be iterated over yielding the lines in a\n"
58 "stream.\n"
59 "\n"
60 "IOBase also supports the :keyword:`with` statement. In this example,\n"
Ezio Melotti13925002011-03-16 11:05:33 +020061 "fp is closed after the suite of the with statement is complete:\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000062 "\n"
63 "with open('spam.txt', 'r') as fp:\n"
64 " fp.write('Spam and eggs!')\n");
65
66/* Use this macro whenever you want to check the internal `closed` status
67 of the IOBase object rather than the virtual `closed` attribute as returned
68 by whatever subclass. */
69
Martin v. Löwis767046a2011-10-14 15:35:36 +020070_Py_IDENTIFIER(__IOBase_closed);
Victor Stinner3f36a572013-11-12 21:39:02 +010071_Py_IDENTIFIER(read);
72
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +020073
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000074/* Internal methods */
75static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000076iobase_unsupported(const char *message)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000077{
Antoine Pitrou712cb732013-12-21 15:51:54 +010078 _PyIO_State *state = IO_STATE();
79 if (state != NULL)
80 PyErr_SetString(state->unsupported_operation, message);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000081 return NULL;
82}
83
Raymond Hettinger15f44ab2016-08-30 10:47:49 -070084/* Positioning */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000085
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000086PyDoc_STRVAR(iobase_seek_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000087 "Change stream position.\n"
88 "\n"
Terry Jan Reedy0158af32013-03-11 17:42:46 -040089 "Change the stream position to the given byte offset. The offset is\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000090 "interpreted relative to the position indicated by whence. Values\n"
91 "for whence are:\n"
92 "\n"
93 "* 0 -- start of stream (the default); offset should be zero or positive\n"
94 "* 1 -- current stream position; offset may be negative\n"
95 "* 2 -- end of stream; offset is usually negative\n"
96 "\n"
97 "Return the new absolute position.");
98
99static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000100iobase_seek(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000101{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000102 return iobase_unsupported("seek");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000103}
104
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300105/*[clinic input]
106_io._IOBase.tell
107
108Return current stream position.
109[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000110
111static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300112_io__IOBase_tell_impl(PyObject *self)
113/*[clinic end generated code: output=89a1c0807935abe2 input=04e615fec128801f]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000114{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200115 _Py_IDENTIFIER(seek);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200116
117 return _PyObject_CallMethodId(self, &PyId_seek, "ii", 0, 1);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000118}
119
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000120PyDoc_STRVAR(iobase_truncate_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000121 "Truncate file to size bytes.\n"
122 "\n"
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000123 "File pointer is left unchanged. Size defaults to the current IO\n"
124 "position as reported by tell(). Returns the new size.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000125
126static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000127iobase_truncate(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000128{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000129 return iobase_unsupported("truncate");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000130}
131
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200132static int
133iobase_is_closed(PyObject *self)
134{
135 PyObject *res;
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200136 int ret;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200137 /* This gets the derived attribute, which is *not* __IOBase_closed
138 in most cases! */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200139 ret = _PyObject_LookupAttrId(self, &PyId___IOBase_closed, &res);
140 Py_XDECREF(res);
141 return ret;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200142}
143
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000144/* Flush and close methods */
145
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300146/*[clinic input]
147_io._IOBase.flush
148
149Flush write buffers, if applicable.
150
151This is not implemented for read-only and non-blocking streams.
152[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000153
154static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300155_io__IOBase_flush_impl(PyObject *self)
156/*[clinic end generated code: output=7cef4b4d54656a3b input=773be121abe270aa]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000157{
158 /* XXX Should this return the number of bytes written??? */
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200159 int closed = iobase_is_closed(self);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000160
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200161 if (!closed) {
162 Py_RETURN_NONE;
163 }
164 if (closed > 0) {
165 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
166 }
167 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000168}
169
170static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000171iobase_closed_get(PyObject *self, void *context)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000172{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200173 int closed = iobase_is_closed(self);
174 if (closed < 0) {
175 return NULL;
176 }
177 return PyBool_FromLong(closed);
178}
179
180static int
181iobase_check_closed(PyObject *self)
182{
183 PyObject *res;
184 int closed;
185 /* This gets the derived attribute, which is *not* __IOBase_closed
186 in most cases! */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200187 closed = _PyObject_LookupAttr(self, _PyIO_str_closed, &res);
188 if (closed > 0) {
189 closed = PyObject_IsTrue(res);
190 Py_DECREF(res);
191 if (closed > 0) {
192 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200193 return -1;
194 }
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200195 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200196 return closed;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000197}
198
199PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000200_PyIOBase_check_closed(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000201{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200202 if (iobase_check_closed(self)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000203 return NULL;
204 }
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200205 if (args == Py_True) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000206 return Py_None;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200207 }
208 Py_RETURN_NONE;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000209}
210
211/* XXX: IOBase thinks it has to maintain its own internal state in
212 `__IOBase_closed` and call flush() by itself, but it is redundant with
213 whatever behaviour a non-trivial derived class will implement. */
214
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300215/*[clinic input]
216_io._IOBase.close
217
218Flush and close the IO object.
219
220This method has no effect if the file is already closed.
221[clinic start generated code]*/
222
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000223static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300224_io__IOBase_close_impl(PyObject *self)
225/*[clinic end generated code: output=63c6a6f57d783d6d input=f4494d5c31dbc6b7]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000226{
Zackery Spytz28f07362018-07-17 00:31:44 -0600227 PyObject *res, *exc, *val, *tb;
228 int rc, closed = iobase_is_closed(self);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000229
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200230 if (closed < 0) {
231 return NULL;
232 }
233 if (closed) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000234 Py_RETURN_NONE;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200235 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000236
237 res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
Victor Stinneraa5bbfa2013-11-08 00:29:41 +0100238
Zackery Spytz28f07362018-07-17 00:31:44 -0600239 PyErr_Fetch(&exc, &val, &tb);
240 rc = _PyObject_SetAttrId(self, &PyId___IOBase_closed, Py_True);
241 _PyErr_ChainExceptions(exc, val, tb);
242 if (rc < 0) {
243 Py_CLEAR(res);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000244 }
Victor Stinneraa5bbfa2013-11-08 00:29:41 +0100245
246 if (res == NULL)
247 return NULL;
248
249 Py_DECREF(res);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000250 Py_RETURN_NONE;
251}
252
253/* Finalization and garbage collection support */
254
Antoine Pitrou796564c2013-07-30 19:59:21 +0200255static void
256iobase_finalize(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000257{
258 PyObject *res;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200259 PyObject *error_type, *error_value, *error_traceback;
260 int closed;
261 _Py_IDENTIFIER(_finalizing);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000262
Antoine Pitrou796564c2013-07-30 19:59:21 +0200263 /* Save the current exception, if any. */
264 PyErr_Fetch(&error_type, &error_value, &error_traceback);
265
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000266 /* If `closed` doesn't exist or can't be evaluated as bool, then the
267 object is probably in an unusable state, so ignore. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200268 if (_PyObject_LookupAttr(self, _PyIO_str_closed, &res) <= 0) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000269 PyErr_Clear();
Christian Heimes72f455e2013-07-31 01:33:50 +0200270 closed = -1;
271 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000272 else {
273 closed = PyObject_IsTrue(res);
274 Py_DECREF(res);
275 if (closed == -1)
276 PyErr_Clear();
277 }
278 if (closed == 0) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200279 /* Signal close() that it was called as part of the object
280 finalization process. */
281 if (_PyObject_SetAttrId(self, &PyId__finalizing, Py_True))
282 PyErr_Clear();
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000283 res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
284 NULL);
285 /* Silencing I/O errors is bad, but printing spurious tracebacks is
286 equally as bad, and potentially more frequent (because of
287 shutdown issues). */
288 if (res == NULL)
289 PyErr_Clear();
290 else
291 Py_DECREF(res);
292 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200293
294 /* Restore the saved exception. */
295 PyErr_Restore(error_type, error_value, error_traceback);
296}
297
298int
299_PyIOBase_finalize(PyObject *self)
300{
301 int is_zombie;
302
303 /* If _PyIOBase_finalize() is called from a destructor, we need to
304 resurrect the object as calling close() can invoke arbitrary code. */
305 is_zombie = (Py_REFCNT(self) == 0);
306 if (is_zombie)
307 return PyObject_CallFinalizerFromDealloc(self);
308 else {
309 PyObject_CallFinalizer(self);
310 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000311 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000312}
313
314static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000315iobase_traverse(iobase *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000316{
317 Py_VISIT(self->dict);
318 return 0;
319}
320
321static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000322iobase_clear(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000323{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000324 Py_CLEAR(self->dict);
325 return 0;
326}
327
328/* Destructor */
329
330static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000331iobase_dealloc(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000332{
333 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
334 are still available here for close() to use.
335 However, if the derived class declares a __slots__, those slots are
336 already gone.
337 */
338 if (_PyIOBase_finalize((PyObject *) self) < 0) {
339 /* When called from a heap type's dealloc, the type will be
340 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
341 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
342 Py_INCREF(Py_TYPE(self));
343 return;
344 }
345 _PyObject_GC_UNTRACK(self);
346 if (self->weakreflist != NULL)
347 PyObject_ClearWeakRefs((PyObject *) self);
348 Py_CLEAR(self->dict);
349 Py_TYPE(self)->tp_free((PyObject *) self);
350}
351
352/* Inquiry methods */
353
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300354/*[clinic input]
355_io._IOBase.seekable
356
357Return whether object supports random access.
358
Martin Panter754aab22016-03-31 07:21:56 +0000359If False, seek(), tell() and truncate() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300360This method may need to do a test seek().
361[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000362
363static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300364_io__IOBase_seekable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000365/*[clinic end generated code: output=4c24c67f5f32a43d input=b976622f7fdf3063]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000366{
367 Py_RETURN_FALSE;
368}
369
370PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000371_PyIOBase_check_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000372{
373 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
374 if (res == NULL)
375 return NULL;
376 if (res != Py_True) {
377 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000378 iobase_unsupported("File or stream is not seekable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000379 return NULL;
380 }
381 if (args == Py_True) {
382 Py_DECREF(res);
383 }
384 return res;
385}
386
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300387/*[clinic input]
388_io._IOBase.readable
389
390Return whether object was opened for reading.
391
Martin Panter754aab22016-03-31 07:21:56 +0000392If False, read() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300393[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000394
395static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300396_io__IOBase_readable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000397/*[clinic end generated code: output=e48089250686388b input=285b3b866a0ec35f]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000398{
399 Py_RETURN_FALSE;
400}
401
402/* May be called with any object */
403PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000404_PyIOBase_check_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000405{
406 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
407 if (res == NULL)
408 return NULL;
409 if (res != Py_True) {
410 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000411 iobase_unsupported("File or stream is not readable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000412 return NULL;
413 }
414 if (args == Py_True) {
415 Py_DECREF(res);
416 }
417 return res;
418}
419
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300420/*[clinic input]
421_io._IOBase.writable
422
423Return whether object was opened for writing.
424
Martin Panter754aab22016-03-31 07:21:56 +0000425If False, write() will raise OSError.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300426[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000427
428static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300429_io__IOBase_writable_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000430/*[clinic end generated code: output=406001d0985be14f input=9dcac18a013a05b5]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000431{
432 Py_RETURN_FALSE;
433}
434
435/* May be called with any object */
436PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000437_PyIOBase_check_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438{
439 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
440 if (res == NULL)
441 return NULL;
442 if (res != Py_True) {
443 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000444 iobase_unsupported("File or stream is not writable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000445 return NULL;
446 }
447 if (args == Py_True) {
448 Py_DECREF(res);
449 }
450 return res;
451}
452
453/* Context manager */
454
455static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000456iobase_enter(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000457{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200458 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000459 return NULL;
460
461 Py_INCREF(self);
462 return self;
463}
464
465static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000466iobase_exit(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000467{
468 return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
469}
470
471/* Lower-level APIs */
472
473/* XXX Should these be present even if unimplemented? */
474
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300475/*[clinic input]
476_io._IOBase.fileno
477
478Returns underlying file descriptor if one exists.
479
Martin Panter754aab22016-03-31 07:21:56 +0000480OSError is raised if the IO object does not use a file descriptor.
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300481[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000482
483static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300484_io__IOBase_fileno_impl(PyObject *self)
Martin Panter754aab22016-03-31 07:21:56 +0000485/*[clinic end generated code: output=7cc0973f0f5f3b73 input=4e37028947dc1cc8]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000486{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000487 return iobase_unsupported("fileno");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000488}
489
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300490/*[clinic input]
491_io._IOBase.isatty
492
493Return whether this is an 'interactive' stream.
494
495Return False if it can't be determined.
496[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000497
498static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300499_io__IOBase_isatty_impl(PyObject *self)
500/*[clinic end generated code: output=60cab77cede41cdd input=9ef76530d368458b]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000501{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200502 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000503 return NULL;
504 Py_RETURN_FALSE;
505}
506
507/* Readline(s) and writelines */
508
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300509/*[clinic input]
510_io._IOBase.readline
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300511 size as limit: Py_ssize_t(accept={int, NoneType}) = -1
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300512 /
513
514Read and return a line from the stream.
515
516If size is specified, at most size bytes will be read.
517
518The line terminator is always b'\n' for binary files; for text
519files, the newlines argument to open can be used to select the line
520terminator(s) recognized.
521[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000522
523static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300524_io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300525/*[clinic end generated code: output=4479f79b58187840 input=d0c596794e877bff]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000526{
527 /* For backwards compatibility, a (slowish) readline(). */
528
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200529 PyObject *peek, *buffer, *result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000530 Py_ssize_t old_size = -1;
531
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200532 if (_PyObject_LookupAttr(self, _PyIO_str_peek, &peek) < 0) {
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200533 return NULL;
534 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000535
536 buffer = PyByteArray_FromStringAndSize(NULL, 0);
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200537 if (buffer == NULL) {
538 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000539 return NULL;
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200540 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000541
Serhiy Storchakafff9a312017-03-21 08:53:25 +0200542 while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000543 Py_ssize_t nreadahead = 1;
544 PyObject *b;
545
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200546 if (peek != NULL) {
547 PyObject *readahead = PyObject_CallFunctionObjArgs(peek, _PyLong_One, NULL);
Gregory P. Smith51359922012-06-23 23:55:39 -0700548 if (readahead == NULL) {
549 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
550 when EINTR occurs so we needn't do it ourselves. */
551 if (_PyIO_trap_eintr()) {
552 continue;
553 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000554 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700555 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000556 if (!PyBytes_Check(readahead)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300557 PyErr_Format(PyExc_OSError,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000558 "peek() should have returned a bytes object, "
559 "not '%.200s'", Py_TYPE(readahead)->tp_name);
560 Py_DECREF(readahead);
561 goto fail;
562 }
563 if (PyBytes_GET_SIZE(readahead) > 0) {
564 Py_ssize_t n = 0;
565 const char *buf = PyBytes_AS_STRING(readahead);
566 if (limit >= 0) {
567 do {
568 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
569 break;
570 if (buf[n++] == '\n')
571 break;
572 } while (1);
573 }
574 else {
575 do {
576 if (n >= PyBytes_GET_SIZE(readahead))
577 break;
578 if (buf[n++] == '\n')
579 break;
580 } while (1);
581 }
582 nreadahead = n;
583 }
584 Py_DECREF(readahead);
585 }
586
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200587 b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
Gregory P. Smith51359922012-06-23 23:55:39 -0700588 if (b == NULL) {
589 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
590 when EINTR occurs so we needn't do it ourselves. */
591 if (_PyIO_trap_eintr()) {
592 continue;
593 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000594 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700595 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000596 if (!PyBytes_Check(b)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300597 PyErr_Format(PyExc_OSError,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000598 "read() should have returned a bytes object, "
599 "not '%.200s'", Py_TYPE(b)->tp_name);
600 Py_DECREF(b);
601 goto fail;
602 }
603 if (PyBytes_GET_SIZE(b) == 0) {
604 Py_DECREF(b);
605 break;
606 }
607
608 old_size = PyByteArray_GET_SIZE(buffer);
Victor Stinnercc024d12013-10-29 02:23:46 +0100609 if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
610 Py_DECREF(b);
611 goto fail;
612 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000613 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
614 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
615
616 Py_DECREF(b);
617
618 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
619 break;
620 }
621
622 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
623 PyByteArray_GET_SIZE(buffer));
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200624 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000625 Py_DECREF(buffer);
626 return result;
627 fail:
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200628 Py_XDECREF(peek);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000629 Py_DECREF(buffer);
630 return NULL;
631}
632
633static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000634iobase_iter(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000635{
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200636 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000637 return NULL;
638
639 Py_INCREF(self);
640 return self;
641}
642
643static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000644iobase_iternext(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000645{
646 PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
647
648 if (line == NULL)
649 return NULL;
650
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300651 if (PyObject_Size(line) <= 0) {
652 /* Error or empty */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000653 Py_DECREF(line);
654 return NULL;
655 }
656
657 return line;
658}
659
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300660/*[clinic input]
661_io._IOBase.readlines
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300662 hint: Py_ssize_t(accept={int, NoneType}) = -1
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300663 /
664
665Return a list of lines from the stream.
666
667hint can be specified to control the number of lines read: no more
668lines will be read if the total size (in bytes/characters) of all
669lines so far exceeds hint.
670[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000671
672static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300673_io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint)
Serhiy Storchaka762bf402017-03-30 09:15:31 +0300674/*[clinic end generated code: output=2f50421677fa3dea input=9400c786ea9dc416]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000675{
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300676 Py_ssize_t length = 0;
Xiang Zhang026435c2017-04-15 12:47:28 +0800677 PyObject *result, *it = NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000678
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000679 result = PyList_New(0);
680 if (result == NULL)
681 return NULL;
682
683 if (hint <= 0) {
684 /* XXX special-casing this made sense in the Python version in order
685 to remove the bytecode interpretation overhead, but it could
686 probably be removed here. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200687 _Py_IDENTIFIER(extend);
Victor Stinner61bdb0d2016-12-09 15:39:28 +0100688 PyObject *ret = _PyObject_CallMethodIdObjArgs(result, &PyId_extend,
689 self, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200690
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000691 if (ret == NULL) {
Xiang Zhang026435c2017-04-15 12:47:28 +0800692 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000693 }
694 Py_DECREF(ret);
695 return result;
696 }
697
Xiang Zhang026435c2017-04-15 12:47:28 +0800698 it = PyObject_GetIter(self);
699 if (it == NULL) {
700 goto error;
701 }
702
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000703 while (1) {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300704 Py_ssize_t line_length;
Xiang Zhang026435c2017-04-15 12:47:28 +0800705 PyObject *line = PyIter_Next(it);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000706 if (line == NULL) {
707 if (PyErr_Occurred()) {
Xiang Zhang026435c2017-04-15 12:47:28 +0800708 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000709 }
710 else
711 break; /* StopIteration raised */
712 }
713
714 if (PyList_Append(result, line) < 0) {
715 Py_DECREF(line);
Xiang Zhang026435c2017-04-15 12:47:28 +0800716 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000717 }
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300718 line_length = PyObject_Size(line);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000719 Py_DECREF(line);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300720 if (line_length < 0) {
721 goto error;
722 }
723 if (line_length > hint - length)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000724 break;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300725 length += line_length;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000726 }
Xiang Zhang026435c2017-04-15 12:47:28 +0800727
728 Py_DECREF(it);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000729 return result;
Xiang Zhang026435c2017-04-15 12:47:28 +0800730
731 error:
732 Py_XDECREF(it);
733 Py_DECREF(result);
734 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000735}
736
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300737/*[clinic input]
738_io._IOBase.writelines
739 lines: object
740 /
741[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000742
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300743static PyObject *
744_io__IOBase_writelines(PyObject *self, PyObject *lines)
745/*[clinic end generated code: output=976eb0a9b60a6628 input=432e729a8450b3cb]*/
746{
747 PyObject *iter, *res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000748
Serhiy Storchaka4d9aec02018-01-16 18:34:21 +0200749 if (iobase_check_closed(self))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000750 return NULL;
751
752 iter = PyObject_GetIter(lines);
753 if (iter == NULL)
754 return NULL;
755
756 while (1) {
757 PyObject *line = PyIter_Next(iter);
758 if (line == NULL) {
759 if (PyErr_Occurred()) {
760 Py_DECREF(iter);
761 return NULL;
762 }
763 else
764 break; /* Stop Iteration */
765 }
766
Gregory P. Smithb9817b02013-02-01 13:03:39 -0800767 res = NULL;
768 do {
769 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
770 } while (res == NULL && _PyIO_trap_eintr());
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000771 Py_DECREF(line);
772 if (res == NULL) {
773 Py_DECREF(iter);
774 return NULL;
775 }
776 Py_DECREF(res);
777 }
778 Py_DECREF(iter);
779 Py_RETURN_NONE;
780}
781
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300782#include "clinic/iobase.c.h"
783
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000784static PyMethodDef iobase_methods[] = {
785 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300786 _IO__IOBASE_TELL_METHODDEF
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000787 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300788 _IO__IOBASE_FLUSH_METHODDEF
789 _IO__IOBASE_CLOSE_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000790
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300791 _IO__IOBASE_SEEKABLE_METHODDEF
792 _IO__IOBASE_READABLE_METHODDEF
793 _IO__IOBASE_WRITABLE_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000794
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000795 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
796 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
797 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
798 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000799
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300800 _IO__IOBASE_FILENO_METHODDEF
801 _IO__IOBASE_ISATTY_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000802
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000803 {"__enter__", iobase_enter, METH_NOARGS},
804 {"__exit__", iobase_exit, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000805
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300806 _IO__IOBASE_READLINE_METHODDEF
807 _IO__IOBASE_READLINES_METHODDEF
808 _IO__IOBASE_WRITELINES_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000809
810 {NULL, NULL}
811};
812
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000813static PyGetSetDef iobase_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500814 {"__dict__", PyObject_GenericGetDict, NULL, NULL},
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000815 {"closed", (getter)iobase_closed_get, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000816 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000817};
818
819
820PyTypeObject PyIOBase_Type = {
821 PyVarObject_HEAD_INIT(NULL, 0)
822 "_io._IOBase", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000823 sizeof(iobase), /*tp_basicsize*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000824 0, /*tp_itemsize*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000825 (destructor)iobase_dealloc, /*tp_dealloc*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000826 0, /*tp_print*/
827 0, /*tp_getattr*/
828 0, /*tp_setattr*/
829 0, /*tp_compare */
830 0, /*tp_repr*/
831 0, /*tp_as_number*/
832 0, /*tp_as_sequence*/
833 0, /*tp_as_mapping*/
834 0, /*tp_hash */
835 0, /*tp_call*/
836 0, /*tp_str*/
837 0, /*tp_getattro*/
838 0, /*tp_setattro*/
839 0, /*tp_as_buffer*/
840 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
Antoine Pitrou796564c2013-07-30 19:59:21 +0200841 | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000842 iobase_doc, /* tp_doc */
843 (traverseproc)iobase_traverse, /* tp_traverse */
844 (inquiry)iobase_clear, /* tp_clear */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000845 0, /* tp_richcompare */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000846 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
847 iobase_iter, /* tp_iter */
848 iobase_iternext, /* tp_iternext */
849 iobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000850 0, /* tp_members */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000851 iobase_getset, /* tp_getset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000852 0, /* tp_base */
853 0, /* tp_dict */
854 0, /* tp_descr_get */
855 0, /* tp_descr_set */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000856 offsetof(iobase, dict), /* tp_dictoffset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000857 0, /* tp_init */
858 0, /* tp_alloc */
859 PyType_GenericNew, /* tp_new */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200860 0, /* tp_free */
861 0, /* tp_is_gc */
862 0, /* tp_bases */
863 0, /* tp_mro */
864 0, /* tp_cache */
865 0, /* tp_subclasses */
866 0, /* tp_weaklist */
867 0, /* tp_del */
868 0, /* tp_version_tag */
Victor Stinner928bff02016-03-19 10:36:36 +0100869 iobase_finalize, /* tp_finalize */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000870};
871
872
873/*
874 * RawIOBase class, Inherits from IOBase.
875 */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000876PyDoc_STRVAR(rawiobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000877 "Base class for raw binary I/O.");
878
879/*
880 * The read() method is implemented by calling readinto(); derived classes
881 * that want to support read() only need to implement readinto() as a
882 * primitive operation. In general, readinto() can be more efficient than
883 * read().
884 *
885 * (It would be tempting to also provide an implementation of readinto() in
886 * terms of read(), in case the latter is a more suitable primitive operation,
887 * but that would lead to nasty recursion in case a subclass doesn't implement
888 * either.)
889*/
890
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300891/*[clinic input]
892_io._RawIOBase.read
893 size as n: Py_ssize_t = -1
894 /
895[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000896
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300897static PyObject *
898_io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
899/*[clinic end generated code: output=6cdeb731e3c9f13c input=b6d0dcf6417d1374]*/
900{
901 PyObject *b, *res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000902
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200903 if (n < 0) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200904 _Py_IDENTIFIER(readall);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200905
906 return _PyObject_CallMethodId(self, &PyId_readall, NULL);
907 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000908
909 /* TODO: allocate a bytes object directly instead and manually construct
910 a writable memoryview pointing to it. */
911 b = PyByteArray_FromStringAndSize(NULL, n);
912 if (b == NULL)
913 return NULL;
914
915 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000916 if (res == NULL || res == Py_None) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000917 Py_DECREF(b);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000918 return res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000919 }
920
921 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
922 Py_DECREF(res);
923 if (n == -1 && PyErr_Occurred()) {
924 Py_DECREF(b);
925 return NULL;
926 }
927
928 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
929 Py_DECREF(b);
930 return res;
931}
932
933
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300934/*[clinic input]
935_io._RawIOBase.readall
936
937Read until EOF, using multiple read() call.
938[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000939
940static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300941_io__RawIOBase_readall_impl(PyObject *self)
942/*[clinic end generated code: output=1987b9ce929425a0 input=688874141213622a]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000943{
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000944 int r;
945 PyObject *chunks = PyList_New(0);
946 PyObject *result;
Victor Stinnercc024d12013-10-29 02:23:46 +0100947
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000948 if (chunks == NULL)
949 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000950
951 while (1) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200952 PyObject *data = _PyObject_CallMethodId(self, &PyId_read,
953 "i", DEFAULT_BUFFER_SIZE);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000954 if (!data) {
Gregory P. Smith51359922012-06-23 23:55:39 -0700955 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
956 when EINTR occurs so we needn't do it ourselves. */
957 if (_PyIO_trap_eintr()) {
958 continue;
959 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000960 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000961 return NULL;
962 }
Victor Stinnera80987f2011-05-25 22:47:16 +0200963 if (data == Py_None) {
964 if (PyList_GET_SIZE(chunks) == 0) {
965 Py_DECREF(chunks);
966 return data;
967 }
968 Py_DECREF(data);
969 break;
970 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000971 if (!PyBytes_Check(data)) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000972 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000973 Py_DECREF(data);
974 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
975 return NULL;
976 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000977 if (PyBytes_GET_SIZE(data) == 0) {
978 /* EOF */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000979 Py_DECREF(data);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000980 break;
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000981 }
982 r = PyList_Append(chunks, data);
983 Py_DECREF(data);
984 if (r < 0) {
985 Py_DECREF(chunks);
986 return NULL;
987 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000988 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000989 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
990 Py_DECREF(chunks);
991 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000992}
993
Antoine Pitrou45d61562015-05-20 21:50:59 +0200994static PyObject *
995rawiobase_readinto(PyObject *self, PyObject *args)
996{
997 PyErr_SetNone(PyExc_NotImplementedError);
998 return NULL;
999}
1000
1001static PyObject *
1002rawiobase_write(PyObject *self, PyObject *args)
1003{
1004 PyErr_SetNone(PyExc_NotImplementedError);
1005 return NULL;
1006}
1007
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001008static PyMethodDef rawiobase_methods[] = {
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001009 _IO__RAWIOBASE_READ_METHODDEF
1010 _IO__RAWIOBASE_READALL_METHODDEF
Antoine Pitrou45d61562015-05-20 21:50:59 +02001011 {"readinto", rawiobase_readinto, METH_VARARGS},
1012 {"write", rawiobase_write, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001013 {NULL, NULL}
1014};
1015
1016PyTypeObject PyRawIOBase_Type = {
1017 PyVarObject_HEAD_INIT(NULL, 0)
1018 "_io._RawIOBase", /*tp_name*/
1019 0, /*tp_basicsize*/
1020 0, /*tp_itemsize*/
1021 0, /*tp_dealloc*/
1022 0, /*tp_print*/
1023 0, /*tp_getattr*/
1024 0, /*tp_setattr*/
1025 0, /*tp_compare */
1026 0, /*tp_repr*/
1027 0, /*tp_as_number*/
1028 0, /*tp_as_sequence*/
1029 0, /*tp_as_mapping*/
1030 0, /*tp_hash */
1031 0, /*tp_call*/
1032 0, /*tp_str*/
1033 0, /*tp_getattro*/
1034 0, /*tp_setattro*/
1035 0, /*tp_as_buffer*/
Antoine Pitrou796564c2013-07-30 19:59:21 +02001036 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001037 rawiobase_doc, /* tp_doc */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001038 0, /* tp_traverse */
1039 0, /* tp_clear */
1040 0, /* tp_richcompare */
1041 0, /* tp_weaklistoffset */
1042 0, /* tp_iter */
1043 0, /* tp_iternext */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001044 rawiobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001045 0, /* tp_members */
1046 0, /* tp_getset */
1047 &PyIOBase_Type, /* tp_base */
1048 0, /* tp_dict */
1049 0, /* tp_descr_get */
1050 0, /* tp_descr_set */
1051 0, /* tp_dictoffset */
1052 0, /* tp_init */
1053 0, /* tp_alloc */
1054 0, /* tp_new */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001055 0, /* tp_free */
1056 0, /* tp_is_gc */
1057 0, /* tp_bases */
1058 0, /* tp_mro */
1059 0, /* tp_cache */
1060 0, /* tp_subclasses */
1061 0, /* tp_weaklist */
1062 0, /* tp_del */
1063 0, /* tp_version_tag */
1064 0, /* tp_finalize */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001065};