blob: 35c7cdd480dccf0d5e71851e44a0ad2b66ce5449 [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"
454 "The line terminator is always b'\n' for binary files; for text\n"
455 "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);
485 if (readahead == NULL)
486 goto fail;
487 if (!PyBytes_Check(readahead)) {
488 PyErr_Format(PyExc_IOError,
489 "peek() should have returned a bytes object, "
490 "not '%.200s'", Py_TYPE(readahead)->tp_name);
491 Py_DECREF(readahead);
492 goto fail;
493 }
494 if (PyBytes_GET_SIZE(readahead) > 0) {
495 Py_ssize_t n = 0;
496 const char *buf = PyBytes_AS_STRING(readahead);
497 if (limit >= 0) {
498 do {
499 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
500 break;
501 if (buf[n++] == '\n')
502 break;
503 } while (1);
504 }
505 else {
506 do {
507 if (n >= PyBytes_GET_SIZE(readahead))
508 break;
509 if (buf[n++] == '\n')
510 break;
511 } while (1);
512 }
513 nreadahead = n;
514 }
515 Py_DECREF(readahead);
516 }
517
518 b = PyObject_CallMethod(self, "read", "n", nreadahead);
519 if (b == NULL)
520 goto fail;
521 if (!PyBytes_Check(b)) {
522 PyErr_Format(PyExc_IOError,
523 "read() should have returned a bytes object, "
524 "not '%.200s'", Py_TYPE(b)->tp_name);
525 Py_DECREF(b);
526 goto fail;
527 }
528 if (PyBytes_GET_SIZE(b) == 0) {
529 Py_DECREF(b);
530 break;
531 }
532
533 old_size = PyByteArray_GET_SIZE(buffer);
534 PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b));
535 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
536 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
537
538 Py_DECREF(b);
539
540 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
541 break;
542 }
543
544 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
545 PyByteArray_GET_SIZE(buffer));
546 Py_DECREF(buffer);
547 return result;
548 fail:
549 Py_DECREF(buffer);
550 return NULL;
551}
552
553static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000554iobase_iter(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000555{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000556 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000557 return NULL;
558
559 Py_INCREF(self);
560 return self;
561}
562
563static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000564iobase_iternext(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000565{
566 PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
567
568 if (line == NULL)
569 return NULL;
570
571 if (PyObject_Size(line) == 0) {
572 Py_DECREF(line);
573 return NULL;
574 }
575
576 return line;
577}
578
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000579PyDoc_STRVAR(iobase_readlines_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000580 "Return a list of lines from the stream.\n"
581 "\n"
582 "hint can be specified to control the number of lines read: no more\n"
583 "lines will be read if the total size (in bytes/characters) of all\n"
584 "lines so far exceeds hint.");
585
586static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000587iobase_readlines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000588{
589 Py_ssize_t hint = -1, length = 0;
Benjamin Peterson05516132009-12-13 19:28:09 +0000590 PyObject *result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000591
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000592 if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000593 return NULL;
594 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000595
596 result = PyList_New(0);
597 if (result == NULL)
598 return NULL;
599
600 if (hint <= 0) {
601 /* XXX special-casing this made sense in the Python version in order
602 to remove the bytecode interpretation overhead, but it could
603 probably be removed here. */
604 PyObject *ret = PyObject_CallMethod(result, "extend", "O", self);
605 if (ret == NULL) {
606 Py_DECREF(result);
607 return NULL;
608 }
609 Py_DECREF(ret);
610 return result;
611 }
612
613 while (1) {
614 PyObject *line = PyIter_Next(self);
615 if (line == NULL) {
616 if (PyErr_Occurred()) {
617 Py_DECREF(result);
618 return NULL;
619 }
620 else
621 break; /* StopIteration raised */
622 }
623
624 if (PyList_Append(result, line) < 0) {
625 Py_DECREF(line);
626 Py_DECREF(result);
627 return NULL;
628 }
629 length += PyObject_Size(line);
630 Py_DECREF(line);
631
632 if (length > hint)
633 break;
634 }
635 return result;
636}
637
638static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000639iobase_writelines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000640{
641 PyObject *lines, *iter, *res;
642
643 if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
644 return NULL;
645 }
646
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000647 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000648 return NULL;
649
650 iter = PyObject_GetIter(lines);
651 if (iter == NULL)
652 return NULL;
653
654 while (1) {
655 PyObject *line = PyIter_Next(iter);
656 if (line == NULL) {
657 if (PyErr_Occurred()) {
658 Py_DECREF(iter);
659 return NULL;
660 }
661 else
662 break; /* Stop Iteration */
663 }
664
665 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
666 Py_DECREF(line);
667 if (res == NULL) {
668 Py_DECREF(iter);
669 return NULL;
670 }
671 Py_DECREF(res);
672 }
673 Py_DECREF(iter);
674 Py_RETURN_NONE;
675}
676
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000677static PyMethodDef iobase_methods[] = {
678 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
679 {"tell", iobase_tell, METH_NOARGS, iobase_tell_doc},
680 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
681 {"flush", iobase_flush, METH_NOARGS, iobase_flush_doc},
682 {"close", iobase_close, METH_NOARGS, iobase_close_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000683
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000684 {"seekable", iobase_seekable, METH_NOARGS, iobase_seekable_doc},
685 {"readable", iobase_readable, METH_NOARGS, iobase_readable_doc},
686 {"writable", iobase_writable, METH_NOARGS, iobase_writable_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000687
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000688 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
689 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
690 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
691 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000692
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000693 {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
694 {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000695
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000696 {"__enter__", iobase_enter, METH_NOARGS},
697 {"__exit__", iobase_exit, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000698
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000699 {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
700 {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
701 {"writelines", iobase_writelines, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000702
703 {NULL, NULL}
704};
705
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000706static PyGetSetDef iobase_getset[] = {
Benjamin Petersonf22913b2011-09-06 07:55:34 -0400707 {"__dict__", (getter)iobase_get_dict, NULL, NULL},
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000708 {"closed", (getter)iobase_closed_get, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000709 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000710};
711
712
713PyTypeObject PyIOBase_Type = {
714 PyVarObject_HEAD_INIT(NULL, 0)
715 "_io._IOBase", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000716 sizeof(iobase), /*tp_basicsize*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000717 0, /*tp_itemsize*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000718 (destructor)iobase_dealloc, /*tp_dealloc*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000719 0, /*tp_print*/
720 0, /*tp_getattr*/
721 0, /*tp_setattr*/
722 0, /*tp_compare */
723 0, /*tp_repr*/
724 0, /*tp_as_number*/
725 0, /*tp_as_sequence*/
726 0, /*tp_as_mapping*/
727 0, /*tp_hash */
728 0, /*tp_call*/
729 0, /*tp_str*/
730 0, /*tp_getattro*/
731 0, /*tp_setattro*/
732 0, /*tp_as_buffer*/
733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
734 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000735 iobase_doc, /* tp_doc */
736 (traverseproc)iobase_traverse, /* tp_traverse */
737 (inquiry)iobase_clear, /* tp_clear */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000738 0, /* tp_richcompare */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000739 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
740 iobase_iter, /* tp_iter */
741 iobase_iternext, /* tp_iternext */
742 iobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000743 0, /* tp_members */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000744 iobase_getset, /* tp_getset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000745 0, /* tp_base */
746 0, /* tp_dict */
747 0, /* tp_descr_get */
748 0, /* tp_descr_set */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000749 offsetof(iobase, dict), /* tp_dictoffset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000750 0, /* tp_init */
751 0, /* tp_alloc */
752 PyType_GenericNew, /* tp_new */
753};
754
755
756/*
757 * RawIOBase class, Inherits from IOBase.
758 */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000759PyDoc_STRVAR(rawiobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000760 "Base class for raw binary I/O.");
761
762/*
763 * The read() method is implemented by calling readinto(); derived classes
764 * that want to support read() only need to implement readinto() as a
765 * primitive operation. In general, readinto() can be more efficient than
766 * read().
767 *
768 * (It would be tempting to also provide an implementation of readinto() in
769 * terms of read(), in case the latter is a more suitable primitive operation,
770 * but that would lead to nasty recursion in case a subclass doesn't implement
771 * either.)
772*/
773
774static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000775rawiobase_read(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000776{
777 Py_ssize_t n = -1;
778 PyObject *b, *res;
779
780 if (!PyArg_ParseTuple(args, "|n:read", &n)) {
781 return NULL;
782 }
783
784 if (n < 0)
785 return PyObject_CallMethod(self, "readall", NULL);
786
787 /* TODO: allocate a bytes object directly instead and manually construct
788 a writable memoryview pointing to it. */
789 b = PyByteArray_FromStringAndSize(NULL, n);
790 if (b == NULL)
791 return NULL;
792
793 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000794 if (res == NULL || res == Py_None) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000795 Py_DECREF(b);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000796 return res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000797 }
798
799 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
800 Py_DECREF(res);
801 if (n == -1 && PyErr_Occurred()) {
802 Py_DECREF(b);
803 return NULL;
804 }
805
806 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
807 Py_DECREF(b);
808 return res;
809}
810
811
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000812PyDoc_STRVAR(rawiobase_readall_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000813 "Read until EOF, using multiple read() call.");
814
815static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000816rawiobase_readall(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000817{
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000818 int r;
819 PyObject *chunks = PyList_New(0);
820 PyObject *result;
821
822 if (chunks == NULL)
823 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000824
825 while (1) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000826 PyObject *data = PyObject_CallMethod(self, "read",
827 "i", DEFAULT_BUFFER_SIZE);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000828 if (!data) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000829 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000830 return NULL;
831 }
Victor Stinnera80987f2011-05-25 22:47:16 +0200832 if (data == Py_None) {
833 if (PyList_GET_SIZE(chunks) == 0) {
834 Py_DECREF(chunks);
835 return data;
836 }
837 Py_DECREF(data);
838 break;
839 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000840 if (!PyBytes_Check(data)) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000841 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000842 Py_DECREF(data);
843 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
844 return NULL;
845 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000846 if (PyBytes_GET_SIZE(data) == 0) {
847 /* EOF */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000848 Py_DECREF(data);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000849 break;
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000850 }
851 r = PyList_Append(chunks, data);
852 Py_DECREF(data);
853 if (r < 0) {
854 Py_DECREF(chunks);
855 return NULL;
856 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000857 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000858 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
859 Py_DECREF(chunks);
860 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000861}
862
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000863static PyMethodDef rawiobase_methods[] = {
864 {"read", rawiobase_read, METH_VARARGS},
865 {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000866 {NULL, NULL}
867};
868
869PyTypeObject PyRawIOBase_Type = {
870 PyVarObject_HEAD_INIT(NULL, 0)
871 "_io._RawIOBase", /*tp_name*/
872 0, /*tp_basicsize*/
873 0, /*tp_itemsize*/
874 0, /*tp_dealloc*/
875 0, /*tp_print*/
876 0, /*tp_getattr*/
877 0, /*tp_setattr*/
878 0, /*tp_compare */
879 0, /*tp_repr*/
880 0, /*tp_as_number*/
881 0, /*tp_as_sequence*/
882 0, /*tp_as_mapping*/
883 0, /*tp_hash */
884 0, /*tp_call*/
885 0, /*tp_str*/
886 0, /*tp_getattro*/
887 0, /*tp_setattro*/
888 0, /*tp_as_buffer*/
889 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000890 rawiobase_doc, /* tp_doc */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000891 0, /* tp_traverse */
892 0, /* tp_clear */
893 0, /* tp_richcompare */
894 0, /* tp_weaklistoffset */
895 0, /* tp_iter */
896 0, /* tp_iternext */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000897 rawiobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000898 0, /* tp_members */
899 0, /* tp_getset */
900 &PyIOBase_Type, /* tp_base */
901 0, /* tp_dict */
902 0, /* tp_descr_get */
903 0, /* tp_descr_set */
904 0, /* tp_dictoffset */
905 0, /* tp_init */
906 0, /* tp_alloc */
907 0, /* tp_new */
908};