blob: ba861467904e2f25972071166e3888b2457efcf6 [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"
4
5 Classes defined here: IOBase, RawIOBase.
6
7 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
16/*
17 * IOBase class, an abstract class
18 */
19
20typedef struct {
21 PyObject_HEAD
22
23 PyObject *dict;
24 PyObject *weakreflist;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000025} iobase;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000026
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000027PyDoc_STRVAR(iobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000028 "The abstract base class for all I/O classes, acting on streams of\n"
29 "bytes. There is no public constructor.\n"
30 "\n"
31 "This class provides dummy implementations for many methods that\n"
32 "derived classes can override selectively; the default implementations\n"
33 "represent a file that cannot be read, written or seeked.\n"
34 "\n"
35 "Even though IOBase does not declare read, readinto, or write because\n"
36 "their signatures will vary, implementations and clients should\n"
37 "consider those methods part of the interface. Also, implementations\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +000038 "may raise UnsupportedOperation when operations they do not support are\n"
39 "called.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000040 "\n"
41 "The basic type used for binary data read from or written to a file is\n"
42 "bytes. bytearrays are accepted too, and in some cases (such as\n"
43 "readinto) needed. Text I/O classes work with str data.\n"
44 "\n"
45 "Note that calling any method (even inquiries) on a closed stream is\n"
46 "undefined. Implementations may raise IOError in this case.\n"
47 "\n"
48 "IOBase (and its subclasses) support the iterator protocol, meaning\n"
49 "that an IOBase object can be iterated over yielding the lines in a\n"
50 "stream.\n"
51 "\n"
52 "IOBase also supports the :keyword:`with` statement. In this example,\n"
Ezio Melotti13925002011-03-16 11:05:33 +020053 "fp is closed after the suite of the with statement is complete:\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000054 "\n"
55 "with open('spam.txt', 'r') as fp:\n"
56 " fp.write('Spam and eggs!')\n");
57
58/* Use this macro whenever you want to check the internal `closed` status
59 of the IOBase object rather than the virtual `closed` attribute as returned
60 by whatever subclass. */
61
62#define IS_CLOSED(self) \
63 PyObject_HasAttrString(self, "__IOBase_closed")
64
65/* Internal methods */
66static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000067iobase_unsupported(const char *message)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000068{
69 PyErr_SetString(IO_STATE->unsupported_operation, message);
70 return NULL;
71}
72
73/* Positionning */
74
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000075PyDoc_STRVAR(iobase_seek_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000076 "Change stream position.\n"
77 "\n"
78 "Change the stream position to byte offset offset. offset is\n"
79 "interpreted relative to the position indicated by whence. Values\n"
80 "for whence are:\n"
81 "\n"
82 "* 0 -- start of stream (the default); offset should be zero or positive\n"
83 "* 1 -- current stream position; offset may be negative\n"
84 "* 2 -- end of stream; offset is usually negative\n"
85 "\n"
86 "Return the new absolute position.");
87
88static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000089iobase_seek(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000090{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000091 return iobase_unsupported("seek");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000092}
93
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000094PyDoc_STRVAR(iobase_tell_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000095 "Return current stream position.");
96
97static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000098iobase_tell(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000099{
100 return PyObject_CallMethod(self, "seek", "ii", 0, 1);
101}
102
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000103PyDoc_STRVAR(iobase_truncate_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000104 "Truncate file to size bytes.\n"
105 "\n"
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000106 "File pointer is left unchanged. Size defaults to the current IO\n"
107 "position as reported by tell(). Returns the new size.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000108
109static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000110iobase_truncate(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000111{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000112 return iobase_unsupported("truncate");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000113}
114
115/* Flush and close methods */
116
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000117PyDoc_STRVAR(iobase_flush_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000118 "Flush write buffers, if applicable.\n"
119 "\n"
120 "This is not implemented for read-only and non-blocking streams.\n");
121
122static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000123iobase_flush(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000124{
125 /* XXX Should this return the number of bytes written??? */
126 if (IS_CLOSED(self)) {
127 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
128 return NULL;
129 }
130 Py_RETURN_NONE;
131}
132
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000133PyDoc_STRVAR(iobase_close_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000134 "Flush and close the IO object.\n"
135 "\n"
136 "This method has no effect if the file is already closed.\n");
137
138static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000139iobase_closed(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000140{
141 PyObject *res;
142 int closed;
143 /* This gets the derived attribute, which is *not* __IOBase_closed
144 in most cases! */
145 res = PyObject_GetAttr(self, _PyIO_str_closed);
146 if (res == NULL)
147 return 0;
148 closed = PyObject_IsTrue(res);
149 Py_DECREF(res);
150 return closed;
151}
152
153static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000154iobase_closed_get(PyObject *self, void *context)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000155{
156 return PyBool_FromLong(IS_CLOSED(self));
157}
158
Benjamin Petersonf6f3a352011-09-03 09:26:20 -0400159static PyObject *
160iobase_get_dict(PyObject *self)
161{
162 PyObject **dictptr = _PyObject_GetDictPtr(self);
163 PyObject *dict;
164 assert(dictptr);
165 dict = *dictptr;
166 if (dict == NULL)
167 dict = *dictptr = PyDict_New();
168 Py_XINCREF(dict);
169 return dict;
170}
171
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000172PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000173_PyIOBase_check_closed(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000174{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000175 if (iobase_closed(self)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000176 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
177 return NULL;
178 }
179 if (args == Py_True)
180 return Py_None;
181 else
182 Py_RETURN_NONE;
183}
184
185/* XXX: IOBase thinks it has to maintain its own internal state in
186 `__IOBase_closed` and call flush() by itself, but it is redundant with
187 whatever behaviour a non-trivial derived class will implement. */
188
189static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000190iobase_close(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000191{
192 PyObject *res;
193
194 if (IS_CLOSED(self))
195 Py_RETURN_NONE;
196
197 res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
198 PyObject_SetAttrString(self, "__IOBase_closed", Py_True);
199 if (res == NULL) {
Antoine Pitrou6be88762010-05-03 16:48:20 +0000200 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000201 }
202 Py_XDECREF(res);
203 Py_RETURN_NONE;
204}
205
206/* Finalization and garbage collection support */
207
208int
209_PyIOBase_finalize(PyObject *self)
210{
211 PyObject *res;
212 PyObject *tp, *v, *tb;
213 int closed = 1;
214 int is_zombie;
215
216 /* If _PyIOBase_finalize() is called from a destructor, we need to
217 resurrect the object as calling close() can invoke arbitrary code. */
218 is_zombie = (Py_REFCNT(self) == 0);
219 if (is_zombie) {
220 ++Py_REFCNT(self);
221 }
222 PyErr_Fetch(&tp, &v, &tb);
223 /* If `closed` doesn't exist or can't be evaluated as bool, then the
224 object is probably in an unusable state, so ignore. */
225 res = PyObject_GetAttr(self, _PyIO_str_closed);
226 if (res == NULL)
227 PyErr_Clear();
228 else {
229 closed = PyObject_IsTrue(res);
230 Py_DECREF(res);
231 if (closed == -1)
232 PyErr_Clear();
233 }
234 if (closed == 0) {
235 res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
236 NULL);
237 /* Silencing I/O errors is bad, but printing spurious tracebacks is
238 equally as bad, and potentially more frequent (because of
239 shutdown issues). */
240 if (res == NULL)
241 PyErr_Clear();
242 else
243 Py_DECREF(res);
244 }
245 PyErr_Restore(tp, v, tb);
246 if (is_zombie) {
247 if (--Py_REFCNT(self) != 0) {
248 /* The object lives again. The following code is taken from
249 slot_tp_del in typeobject.c. */
250 Py_ssize_t refcnt = Py_REFCNT(self);
251 _Py_NewReference(self);
252 Py_REFCNT(self) = refcnt;
253 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
254 * we need to undo that. */
255 _Py_DEC_REFTOTAL;
256 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
257 * chain, so no more to do there.
258 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
259 * _Py_NewReference bumped tp_allocs: both of those need to be
260 * undone.
261 */
262#ifdef COUNT_ALLOCS
263 --Py_TYPE(self)->tp_frees;
264 --Py_TYPE(self)->tp_allocs;
265#endif
266 return -1;
267 }
268 }
269 return 0;
270}
271
272static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000273iobase_traverse(iobase *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000274{
275 Py_VISIT(self->dict);
276 return 0;
277}
278
279static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000280iobase_clear(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000281{
282 if (_PyIOBase_finalize((PyObject *) self) < 0)
283 return -1;
284 Py_CLEAR(self->dict);
285 return 0;
286}
287
288/* Destructor */
289
290static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000291iobase_dealloc(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000292{
293 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
294 are still available here for close() to use.
295 However, if the derived class declares a __slots__, those slots are
296 already gone.
297 */
298 if (_PyIOBase_finalize((PyObject *) self) < 0) {
299 /* When called from a heap type's dealloc, the type will be
300 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
301 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
302 Py_INCREF(Py_TYPE(self));
303 return;
304 }
305 _PyObject_GC_UNTRACK(self);
306 if (self->weakreflist != NULL)
307 PyObject_ClearWeakRefs((PyObject *) self);
308 Py_CLEAR(self->dict);
309 Py_TYPE(self)->tp_free((PyObject *) self);
310}
311
312/* Inquiry methods */
313
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000314PyDoc_STRVAR(iobase_seekable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000315 "Return whether object supports random access.\n"
316 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000317 "If False, seek(), tell() and truncate() will raise UnsupportedOperation.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000318 "This method may need to do a test seek().");
319
320static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000321iobase_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000322{
323 Py_RETURN_FALSE;
324}
325
326PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000327_PyIOBase_check_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000328{
329 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
330 if (res == NULL)
331 return NULL;
332 if (res != Py_True) {
333 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000334 iobase_unsupported("File or stream is not seekable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000335 return NULL;
336 }
337 if (args == Py_True) {
338 Py_DECREF(res);
339 }
340 return res;
341}
342
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000343PyDoc_STRVAR(iobase_readable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000344 "Return whether object was opened for reading.\n"
345 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000346 "If False, read() will raise UnsupportedOperation.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000347
348static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000349iobase_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000350{
351 Py_RETURN_FALSE;
352}
353
354/* May be called with any object */
355PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000356_PyIOBase_check_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000357{
358 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
359 if (res == NULL)
360 return NULL;
361 if (res != Py_True) {
362 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000363 iobase_unsupported("File or stream is not readable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000364 return NULL;
365 }
366 if (args == Py_True) {
367 Py_DECREF(res);
368 }
369 return res;
370}
371
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000372PyDoc_STRVAR(iobase_writable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000373 "Return whether object was opened for writing.\n"
374 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000375 "If False, write() will raise UnsupportedOperation.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000376
377static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000378iobase_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000379{
380 Py_RETURN_FALSE;
381}
382
383/* May be called with any object */
384PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000385_PyIOBase_check_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000386{
387 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
388 if (res == NULL)
389 return NULL;
390 if (res != Py_True) {
391 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000392 iobase_unsupported("File or stream is not writable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393 return NULL;
394 }
395 if (args == Py_True) {
396 Py_DECREF(res);
397 }
398 return res;
399}
400
401/* Context manager */
402
403static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000404iobase_enter(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000405{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000406 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000407 return NULL;
408
409 Py_INCREF(self);
410 return self;
411}
412
413static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000414iobase_exit(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000415{
416 return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
417}
418
419/* Lower-level APIs */
420
421/* XXX Should these be present even if unimplemented? */
422
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000423PyDoc_STRVAR(iobase_fileno_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000424 "Returns underlying file descriptor if one exists.\n"
425 "\n"
426 "An IOError is raised if the IO object does not use a file descriptor.\n");
427
428static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000429iobase_fileno(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000430{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000431 return iobase_unsupported("fileno");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000432}
433
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000434PyDoc_STRVAR(iobase_isatty_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000435 "Return whether this is an 'interactive' stream.\n"
436 "\n"
437 "Return False if it can't be determined.\n");
438
439static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000440iobase_isatty(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000441{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000442 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000443 return NULL;
444 Py_RETURN_FALSE;
445}
446
447/* Readline(s) and writelines */
448
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000449PyDoc_STRVAR(iobase_readline_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000450 "Read and return a line from the stream.\n"
451 "\n"
452 "If limit is specified, at most limit bytes will be read.\n"
453 "\n"
Ezio Melotti16d2b472012-09-18 07:20:18 +0300454 "The line terminator is always b'\\n' for binary files; for text\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000455 "files, the newlines argument to open can be used to select the line\n"
456 "terminator(s) recognized.\n");
457
458static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000459iobase_readline(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000460{
461 /* For backwards compatibility, a (slowish) readline(). */
462
463 Py_ssize_t limit = -1;
464 int has_peek = 0;
465 PyObject *buffer, *result;
466 Py_ssize_t old_size = -1;
467
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000468 if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000469 return NULL;
470 }
471
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000472 if (PyObject_HasAttrString(self, "peek"))
473 has_peek = 1;
474
475 buffer = PyByteArray_FromStringAndSize(NULL, 0);
476 if (buffer == NULL)
477 return NULL;
478
479 while (limit < 0 || Py_SIZE(buffer) < limit) {
480 Py_ssize_t nreadahead = 1;
481 PyObject *b;
482
483 if (has_peek) {
484 PyObject *readahead = PyObject_CallMethod(self, "peek", "i", 1);
Gregory P. Smith51359922012-06-23 23:55:39 -0700485 if (readahead == NULL) {
486 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
487 when EINTR occurs so we needn't do it ourselves. */
488 if (_PyIO_trap_eintr()) {
489 continue;
490 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000491 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700492 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000493 if (!PyBytes_Check(readahead)) {
494 PyErr_Format(PyExc_IOError,
495 "peek() should have returned a bytes object, "
496 "not '%.200s'", Py_TYPE(readahead)->tp_name);
497 Py_DECREF(readahead);
498 goto fail;
499 }
500 if (PyBytes_GET_SIZE(readahead) > 0) {
501 Py_ssize_t n = 0;
502 const char *buf = PyBytes_AS_STRING(readahead);
503 if (limit >= 0) {
504 do {
505 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
506 break;
507 if (buf[n++] == '\n')
508 break;
509 } while (1);
510 }
511 else {
512 do {
513 if (n >= PyBytes_GET_SIZE(readahead))
514 break;
515 if (buf[n++] == '\n')
516 break;
517 } while (1);
518 }
519 nreadahead = n;
520 }
521 Py_DECREF(readahead);
522 }
523
524 b = PyObject_CallMethod(self, "read", "n", nreadahead);
Gregory P. Smith51359922012-06-23 23:55:39 -0700525 if (b == NULL) {
526 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
527 when EINTR occurs so we needn't do it ourselves. */
528 if (_PyIO_trap_eintr()) {
529 continue;
530 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000531 goto fail;
Gregory P. Smith51359922012-06-23 23:55:39 -0700532 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000533 if (!PyBytes_Check(b)) {
534 PyErr_Format(PyExc_IOError,
535 "read() should have returned a bytes object, "
536 "not '%.200s'", Py_TYPE(b)->tp_name);
537 Py_DECREF(b);
538 goto fail;
539 }
540 if (PyBytes_GET_SIZE(b) == 0) {
541 Py_DECREF(b);
542 break;
543 }
544
545 old_size = PyByteArray_GET_SIZE(buffer);
546 PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b));
547 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
548 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
549
550 Py_DECREF(b);
551
552 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
553 break;
554 }
555
556 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
557 PyByteArray_GET_SIZE(buffer));
558 Py_DECREF(buffer);
559 return result;
560 fail:
561 Py_DECREF(buffer);
562 return NULL;
563}
564
565static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000566iobase_iter(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000568 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000569 return NULL;
570
571 Py_INCREF(self);
572 return self;
573}
574
575static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000576iobase_iternext(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000577{
578 PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
579
580 if (line == NULL)
581 return NULL;
582
583 if (PyObject_Size(line) == 0) {
584 Py_DECREF(line);
585 return NULL;
586 }
587
588 return line;
589}
590
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000591PyDoc_STRVAR(iobase_readlines_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000592 "Return a list of lines from the stream.\n"
593 "\n"
594 "hint can be specified to control the number of lines read: no more\n"
595 "lines will be read if the total size (in bytes/characters) of all\n"
596 "lines so far exceeds hint.");
597
598static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000599iobase_readlines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000600{
601 Py_ssize_t hint = -1, length = 0;
Benjamin Peterson05516132009-12-13 19:28:09 +0000602 PyObject *result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000603
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000604 if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000605 return NULL;
606 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000607
608 result = PyList_New(0);
609 if (result == NULL)
610 return NULL;
611
612 if (hint <= 0) {
613 /* XXX special-casing this made sense in the Python version in order
614 to remove the bytecode interpretation overhead, but it could
615 probably be removed here. */
616 PyObject *ret = PyObject_CallMethod(result, "extend", "O", self);
617 if (ret == NULL) {
618 Py_DECREF(result);
619 return NULL;
620 }
621 Py_DECREF(ret);
622 return result;
623 }
624
625 while (1) {
626 PyObject *line = PyIter_Next(self);
627 if (line == NULL) {
628 if (PyErr_Occurred()) {
629 Py_DECREF(result);
630 return NULL;
631 }
632 else
633 break; /* StopIteration raised */
634 }
635
636 if (PyList_Append(result, line) < 0) {
637 Py_DECREF(line);
638 Py_DECREF(result);
639 return NULL;
640 }
641 length += PyObject_Size(line);
642 Py_DECREF(line);
643
644 if (length > hint)
645 break;
646 }
647 return result;
648}
649
650static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000651iobase_writelines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000652{
653 PyObject *lines, *iter, *res;
654
655 if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
656 return NULL;
657 }
658
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000659 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000660 return NULL;
661
662 iter = PyObject_GetIter(lines);
663 if (iter == NULL)
664 return NULL;
665
666 while (1) {
667 PyObject *line = PyIter_Next(iter);
668 if (line == NULL) {
669 if (PyErr_Occurred()) {
670 Py_DECREF(iter);
671 return NULL;
672 }
673 else
674 break; /* Stop Iteration */
675 }
676
677 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
678 Py_DECREF(line);
679 if (res == NULL) {
680 Py_DECREF(iter);
681 return NULL;
682 }
683 Py_DECREF(res);
684 }
685 Py_DECREF(iter);
686 Py_RETURN_NONE;
687}
688
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000689static PyMethodDef iobase_methods[] = {
690 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
691 {"tell", iobase_tell, METH_NOARGS, iobase_tell_doc},
692 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
693 {"flush", iobase_flush, METH_NOARGS, iobase_flush_doc},
694 {"close", iobase_close, METH_NOARGS, iobase_close_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000695
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000696 {"seekable", iobase_seekable, METH_NOARGS, iobase_seekable_doc},
697 {"readable", iobase_readable, METH_NOARGS, iobase_readable_doc},
698 {"writable", iobase_writable, METH_NOARGS, iobase_writable_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000699
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000700 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
701 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
702 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
703 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000704
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000705 {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
706 {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000707
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000708 {"__enter__", iobase_enter, METH_NOARGS},
709 {"__exit__", iobase_exit, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000710
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000711 {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
712 {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
713 {"writelines", iobase_writelines, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000714
715 {NULL, NULL}
716};
717
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000718static PyGetSetDef iobase_getset[] = {
Benjamin Petersonf22913b2011-09-06 07:55:34 -0400719 {"__dict__", (getter)iobase_get_dict, NULL, NULL},
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000720 {"closed", (getter)iobase_closed_get, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000721 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000722};
723
724
725PyTypeObject PyIOBase_Type = {
726 PyVarObject_HEAD_INIT(NULL, 0)
727 "_io._IOBase", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000728 sizeof(iobase), /*tp_basicsize*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000729 0, /*tp_itemsize*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000730 (destructor)iobase_dealloc, /*tp_dealloc*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000731 0, /*tp_print*/
732 0, /*tp_getattr*/
733 0, /*tp_setattr*/
734 0, /*tp_compare */
735 0, /*tp_repr*/
736 0, /*tp_as_number*/
737 0, /*tp_as_sequence*/
738 0, /*tp_as_mapping*/
739 0, /*tp_hash */
740 0, /*tp_call*/
741 0, /*tp_str*/
742 0, /*tp_getattro*/
743 0, /*tp_setattro*/
744 0, /*tp_as_buffer*/
745 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
746 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000747 iobase_doc, /* tp_doc */
748 (traverseproc)iobase_traverse, /* tp_traverse */
749 (inquiry)iobase_clear, /* tp_clear */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000750 0, /* tp_richcompare */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000751 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
752 iobase_iter, /* tp_iter */
753 iobase_iternext, /* tp_iternext */
754 iobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000755 0, /* tp_members */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000756 iobase_getset, /* tp_getset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000757 0, /* tp_base */
758 0, /* tp_dict */
759 0, /* tp_descr_get */
760 0, /* tp_descr_set */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000761 offsetof(iobase, dict), /* tp_dictoffset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000762 0, /* tp_init */
763 0, /* tp_alloc */
764 PyType_GenericNew, /* tp_new */
765};
766
767
768/*
769 * RawIOBase class, Inherits from IOBase.
770 */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000771PyDoc_STRVAR(rawiobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000772 "Base class for raw binary I/O.");
773
774/*
775 * The read() method is implemented by calling readinto(); derived classes
776 * that want to support read() only need to implement readinto() as a
777 * primitive operation. In general, readinto() can be more efficient than
778 * read().
779 *
780 * (It would be tempting to also provide an implementation of readinto() in
781 * terms of read(), in case the latter is a more suitable primitive operation,
782 * but that would lead to nasty recursion in case a subclass doesn't implement
783 * either.)
784*/
785
786static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000787rawiobase_read(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000788{
789 Py_ssize_t n = -1;
790 PyObject *b, *res;
791
792 if (!PyArg_ParseTuple(args, "|n:read", &n)) {
793 return NULL;
794 }
795
796 if (n < 0)
797 return PyObject_CallMethod(self, "readall", NULL);
798
799 /* TODO: allocate a bytes object directly instead and manually construct
800 a writable memoryview pointing to it. */
801 b = PyByteArray_FromStringAndSize(NULL, n);
802 if (b == NULL)
803 return NULL;
804
805 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000806 if (res == NULL || res == Py_None) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000807 Py_DECREF(b);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000808 return res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000809 }
810
811 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
812 Py_DECREF(res);
813 if (n == -1 && PyErr_Occurred()) {
814 Py_DECREF(b);
815 return NULL;
816 }
817
818 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
819 Py_DECREF(b);
820 return res;
821}
822
823
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000824PyDoc_STRVAR(rawiobase_readall_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000825 "Read until EOF, using multiple read() call.");
826
827static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000828rawiobase_readall(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000829{
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000830 int r;
831 PyObject *chunks = PyList_New(0);
832 PyObject *result;
833
834 if (chunks == NULL)
835 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000836
837 while (1) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000838 PyObject *data = PyObject_CallMethod(self, "read",
839 "i", DEFAULT_BUFFER_SIZE);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000840 if (!data) {
Gregory P. Smith51359922012-06-23 23:55:39 -0700841 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
842 when EINTR occurs so we needn't do it ourselves. */
843 if (_PyIO_trap_eintr()) {
844 continue;
845 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000846 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000847 return NULL;
848 }
Victor Stinnera80987f2011-05-25 22:47:16 +0200849 if (data == Py_None) {
850 if (PyList_GET_SIZE(chunks) == 0) {
851 Py_DECREF(chunks);
852 return data;
853 }
854 Py_DECREF(data);
855 break;
856 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000857 if (!PyBytes_Check(data)) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000858 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000859 Py_DECREF(data);
860 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
861 return NULL;
862 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000863 if (PyBytes_GET_SIZE(data) == 0) {
864 /* EOF */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000865 Py_DECREF(data);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000866 break;
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000867 }
868 r = PyList_Append(chunks, data);
869 Py_DECREF(data);
870 if (r < 0) {
871 Py_DECREF(chunks);
872 return NULL;
873 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000874 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000875 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
876 Py_DECREF(chunks);
877 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000878}
879
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000880static PyMethodDef rawiobase_methods[] = {
881 {"read", rawiobase_read, METH_VARARGS},
882 {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000883 {NULL, NULL}
884};
885
886PyTypeObject PyRawIOBase_Type = {
887 PyVarObject_HEAD_INIT(NULL, 0)
888 "_io._RawIOBase", /*tp_name*/
889 0, /*tp_basicsize*/
890 0, /*tp_itemsize*/
891 0, /*tp_dealloc*/
892 0, /*tp_print*/
893 0, /*tp_getattr*/
894 0, /*tp_setattr*/
895 0, /*tp_compare */
896 0, /*tp_repr*/
897 0, /*tp_as_number*/
898 0, /*tp_as_sequence*/
899 0, /*tp_as_mapping*/
900 0, /*tp_hash */
901 0, /*tp_call*/
902 0, /*tp_str*/
903 0, /*tp_getattro*/
904 0, /*tp_setattro*/
905 0, /*tp_as_buffer*/
906 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000907 rawiobase_doc, /* tp_doc */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000908 0, /* tp_traverse */
909 0, /* tp_clear */
910 0, /* tp_richcompare */
911 0, /* tp_weaklistoffset */
912 0, /* tp_iter */
913 0, /* tp_iternext */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000914 rawiobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000915 0, /* tp_members */
916 0, /* tp_getset */
917 &PyIOBase_Type, /* tp_base */
918 0, /* tp_dict */
919 0, /* tp_descr_get */
920 0, /* tp_descr_set */
921 0, /* tp_dictoffset */
922 0, /* tp_init */
923 0, /* tp_alloc */
924 0, /* tp_new */
925};