blob: 9b58137fb9059fef7a6e8ac5c637c42f5e7dcfb3 [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"
53 "fp is closed after the suite of the with statment is complete:\n"
54 "\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
159PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000160_PyIOBase_check_closed(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000161{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000162 if (iobase_closed(self)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000163 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
164 return NULL;
165 }
166 if (args == Py_True)
167 return Py_None;
168 else
169 Py_RETURN_NONE;
170}
171
172/* XXX: IOBase thinks it has to maintain its own internal state in
173 `__IOBase_closed` and call flush() by itself, but it is redundant with
174 whatever behaviour a non-trivial derived class will implement. */
175
176static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000177iobase_close(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000178{
179 PyObject *res;
180
181 if (IS_CLOSED(self))
182 Py_RETURN_NONE;
183
184 res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
185 PyObject_SetAttrString(self, "__IOBase_closed", Py_True);
186 if (res == NULL) {
Antoine Pitrou6be88762010-05-03 16:48:20 +0000187 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000188 }
189 Py_XDECREF(res);
190 Py_RETURN_NONE;
191}
192
193/* Finalization and garbage collection support */
194
195int
196_PyIOBase_finalize(PyObject *self)
197{
198 PyObject *res;
199 PyObject *tp, *v, *tb;
200 int closed = 1;
201 int is_zombie;
202
203 /* If _PyIOBase_finalize() is called from a destructor, we need to
204 resurrect the object as calling close() can invoke arbitrary code. */
205 is_zombie = (Py_REFCNT(self) == 0);
206 if (is_zombie) {
207 ++Py_REFCNT(self);
208 }
209 PyErr_Fetch(&tp, &v, &tb);
210 /* If `closed` doesn't exist or can't be evaluated as bool, then the
211 object is probably in an unusable state, so ignore. */
212 res = PyObject_GetAttr(self, _PyIO_str_closed);
213 if (res == NULL)
214 PyErr_Clear();
215 else {
216 closed = PyObject_IsTrue(res);
217 Py_DECREF(res);
218 if (closed == -1)
219 PyErr_Clear();
220 }
221 if (closed == 0) {
222 res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
223 NULL);
224 /* Silencing I/O errors is bad, but printing spurious tracebacks is
225 equally as bad, and potentially more frequent (because of
226 shutdown issues). */
227 if (res == NULL)
228 PyErr_Clear();
229 else
230 Py_DECREF(res);
231 }
232 PyErr_Restore(tp, v, tb);
233 if (is_zombie) {
234 if (--Py_REFCNT(self) != 0) {
235 /* The object lives again. The following code is taken from
236 slot_tp_del in typeobject.c. */
237 Py_ssize_t refcnt = Py_REFCNT(self);
238 _Py_NewReference(self);
239 Py_REFCNT(self) = refcnt;
240 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
241 * we need to undo that. */
242 _Py_DEC_REFTOTAL;
243 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
244 * chain, so no more to do there.
245 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
246 * _Py_NewReference bumped tp_allocs: both of those need to be
247 * undone.
248 */
249#ifdef COUNT_ALLOCS
250 --Py_TYPE(self)->tp_frees;
251 --Py_TYPE(self)->tp_allocs;
252#endif
253 return -1;
254 }
255 }
256 return 0;
257}
258
259static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000260iobase_traverse(iobase *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000261{
262 Py_VISIT(self->dict);
263 return 0;
264}
265
266static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000267iobase_clear(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000268{
269 if (_PyIOBase_finalize((PyObject *) self) < 0)
270 return -1;
271 Py_CLEAR(self->dict);
272 return 0;
273}
274
275/* Destructor */
276
277static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000278iobase_dealloc(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000279{
280 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
281 are still available here for close() to use.
282 However, if the derived class declares a __slots__, those slots are
283 already gone.
284 */
285 if (_PyIOBase_finalize((PyObject *) self) < 0) {
286 /* When called from a heap type's dealloc, the type will be
287 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
288 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
289 Py_INCREF(Py_TYPE(self));
290 return;
291 }
292 _PyObject_GC_UNTRACK(self);
293 if (self->weakreflist != NULL)
294 PyObject_ClearWeakRefs((PyObject *) self);
295 Py_CLEAR(self->dict);
296 Py_TYPE(self)->tp_free((PyObject *) self);
297}
298
299/* Inquiry methods */
300
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000301PyDoc_STRVAR(iobase_seekable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000302 "Return whether object supports random access.\n"
303 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000304 "If False, seek(), tell() and truncate() will raise UnsupportedOperation.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000305 "This method may need to do a test seek().");
306
307static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000308iobase_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000309{
310 Py_RETURN_FALSE;
311}
312
313PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000314_PyIOBase_check_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000315{
316 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
317 if (res == NULL)
318 return NULL;
319 if (res != Py_True) {
320 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000321 iobase_unsupported("File or stream is not seekable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000322 return NULL;
323 }
324 if (args == Py_True) {
325 Py_DECREF(res);
326 }
327 return res;
328}
329
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000330PyDoc_STRVAR(iobase_readable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000331 "Return whether object was opened for reading.\n"
332 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000333 "If False, read() will raise UnsupportedOperation.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000334
335static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000336iobase_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000337{
338 Py_RETURN_FALSE;
339}
340
341/* May be called with any object */
342PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000343_PyIOBase_check_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000344{
345 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
346 if (res == NULL)
347 return NULL;
348 if (res != Py_True) {
349 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000350 iobase_unsupported("File or stream is not readable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000351 return NULL;
352 }
353 if (args == Py_True) {
354 Py_DECREF(res);
355 }
356 return res;
357}
358
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000359PyDoc_STRVAR(iobase_writable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000360 "Return whether object was opened for writing.\n"
361 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000362 "If False, write() will raise UnsupportedOperation.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000363
364static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000365iobase_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000366{
367 Py_RETURN_FALSE;
368}
369
370/* May be called with any object */
371PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000372_PyIOBase_check_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000373{
374 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
375 if (res == NULL)
376 return NULL;
377 if (res != Py_True) {
378 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000379 iobase_unsupported("File or stream is not writable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000380 return NULL;
381 }
382 if (args == Py_True) {
383 Py_DECREF(res);
384 }
385 return res;
386}
387
388/* Context manager */
389
390static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000391iobase_enter(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000392{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000393 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000394 return NULL;
395
396 Py_INCREF(self);
397 return self;
398}
399
400static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000401iobase_exit(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000402{
403 return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
404}
405
406/* Lower-level APIs */
407
408/* XXX Should these be present even if unimplemented? */
409
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000410PyDoc_STRVAR(iobase_fileno_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000411 "Returns underlying file descriptor if one exists.\n"
412 "\n"
413 "An IOError is raised if the IO object does not use a file descriptor.\n");
414
415static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000416iobase_fileno(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000418 return iobase_unsupported("fileno");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000419}
420
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000421PyDoc_STRVAR(iobase_isatty_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422 "Return whether this is an 'interactive' stream.\n"
423 "\n"
424 "Return False if it can't be determined.\n");
425
426static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000427iobase_isatty(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000428{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000429 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000430 return NULL;
431 Py_RETURN_FALSE;
432}
433
434/* Readline(s) and writelines */
435
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000436PyDoc_STRVAR(iobase_readline_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000437 "Read and return a line from the stream.\n"
438 "\n"
439 "If limit is specified, at most limit bytes will be read.\n"
440 "\n"
441 "The line terminator is always b'\n' for binary files; for text\n"
442 "files, the newlines argument to open can be used to select the line\n"
443 "terminator(s) recognized.\n");
444
445static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000446iobase_readline(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000447{
448 /* For backwards compatibility, a (slowish) readline(). */
449
450 Py_ssize_t limit = -1;
451 int has_peek = 0;
452 PyObject *buffer, *result;
453 Py_ssize_t old_size = -1;
454
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000455 if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000456 return NULL;
457 }
458
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000459 if (PyObject_HasAttrString(self, "peek"))
460 has_peek = 1;
461
462 buffer = PyByteArray_FromStringAndSize(NULL, 0);
463 if (buffer == NULL)
464 return NULL;
465
466 while (limit < 0 || Py_SIZE(buffer) < limit) {
467 Py_ssize_t nreadahead = 1;
468 PyObject *b;
469
470 if (has_peek) {
471 PyObject *readahead = PyObject_CallMethod(self, "peek", "i", 1);
472 if (readahead == NULL)
473 goto fail;
474 if (!PyBytes_Check(readahead)) {
475 PyErr_Format(PyExc_IOError,
476 "peek() should have returned a bytes object, "
477 "not '%.200s'", Py_TYPE(readahead)->tp_name);
478 Py_DECREF(readahead);
479 goto fail;
480 }
481 if (PyBytes_GET_SIZE(readahead) > 0) {
482 Py_ssize_t n = 0;
483 const char *buf = PyBytes_AS_STRING(readahead);
484 if (limit >= 0) {
485 do {
486 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
487 break;
488 if (buf[n++] == '\n')
489 break;
490 } while (1);
491 }
492 else {
493 do {
494 if (n >= PyBytes_GET_SIZE(readahead))
495 break;
496 if (buf[n++] == '\n')
497 break;
498 } while (1);
499 }
500 nreadahead = n;
501 }
502 Py_DECREF(readahead);
503 }
504
505 b = PyObject_CallMethod(self, "read", "n", nreadahead);
506 if (b == NULL)
507 goto fail;
508 if (!PyBytes_Check(b)) {
509 PyErr_Format(PyExc_IOError,
510 "read() should have returned a bytes object, "
511 "not '%.200s'", Py_TYPE(b)->tp_name);
512 Py_DECREF(b);
513 goto fail;
514 }
515 if (PyBytes_GET_SIZE(b) == 0) {
516 Py_DECREF(b);
517 break;
518 }
519
520 old_size = PyByteArray_GET_SIZE(buffer);
521 PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b));
522 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
523 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
524
525 Py_DECREF(b);
526
527 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
528 break;
529 }
530
531 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
532 PyByteArray_GET_SIZE(buffer));
533 Py_DECREF(buffer);
534 return result;
535 fail:
536 Py_DECREF(buffer);
537 return NULL;
538}
539
540static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000541iobase_iter(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000542{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000543 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000544 return NULL;
545
546 Py_INCREF(self);
547 return self;
548}
549
550static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000551iobase_iternext(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000552{
553 PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
554
555 if (line == NULL)
556 return NULL;
557
558 if (PyObject_Size(line) == 0) {
559 Py_DECREF(line);
560 return NULL;
561 }
562
563 return line;
564}
565
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000566PyDoc_STRVAR(iobase_readlines_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567 "Return a list of lines from the stream.\n"
568 "\n"
569 "hint can be specified to control the number of lines read: no more\n"
570 "lines will be read if the total size (in bytes/characters) of all\n"
571 "lines so far exceeds hint.");
572
573static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000574iobase_readlines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000575{
576 Py_ssize_t hint = -1, length = 0;
Benjamin Peterson05516132009-12-13 19:28:09 +0000577 PyObject *result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000578
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000579 if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000580 return NULL;
581 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000582
583 result = PyList_New(0);
584 if (result == NULL)
585 return NULL;
586
587 if (hint <= 0) {
588 /* XXX special-casing this made sense in the Python version in order
589 to remove the bytecode interpretation overhead, but it could
590 probably be removed here. */
591 PyObject *ret = PyObject_CallMethod(result, "extend", "O", self);
592 if (ret == NULL) {
593 Py_DECREF(result);
594 return NULL;
595 }
596 Py_DECREF(ret);
597 return result;
598 }
599
600 while (1) {
601 PyObject *line = PyIter_Next(self);
602 if (line == NULL) {
603 if (PyErr_Occurred()) {
604 Py_DECREF(result);
605 return NULL;
606 }
607 else
608 break; /* StopIteration raised */
609 }
610
611 if (PyList_Append(result, line) < 0) {
612 Py_DECREF(line);
613 Py_DECREF(result);
614 return NULL;
615 }
616 length += PyObject_Size(line);
617 Py_DECREF(line);
618
619 if (length > hint)
620 break;
621 }
622 return result;
623}
624
625static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000626iobase_writelines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000627{
628 PyObject *lines, *iter, *res;
629
630 if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
631 return NULL;
632 }
633
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000634 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000635 return NULL;
636
637 iter = PyObject_GetIter(lines);
638 if (iter == NULL)
639 return NULL;
640
641 while (1) {
642 PyObject *line = PyIter_Next(iter);
643 if (line == NULL) {
644 if (PyErr_Occurred()) {
645 Py_DECREF(iter);
646 return NULL;
647 }
648 else
649 break; /* Stop Iteration */
650 }
651
652 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
653 Py_DECREF(line);
654 if (res == NULL) {
655 Py_DECREF(iter);
656 return NULL;
657 }
658 Py_DECREF(res);
659 }
660 Py_DECREF(iter);
661 Py_RETURN_NONE;
662}
663
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000664static PyMethodDef iobase_methods[] = {
665 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
666 {"tell", iobase_tell, METH_NOARGS, iobase_tell_doc},
667 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
668 {"flush", iobase_flush, METH_NOARGS, iobase_flush_doc},
669 {"close", iobase_close, METH_NOARGS, iobase_close_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000670
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000671 {"seekable", iobase_seekable, METH_NOARGS, iobase_seekable_doc},
672 {"readable", iobase_readable, METH_NOARGS, iobase_readable_doc},
673 {"writable", iobase_writable, METH_NOARGS, iobase_writable_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000674
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000675 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
676 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
677 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
678 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000679
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000680 {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
681 {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000682
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000683 {"__enter__", iobase_enter, METH_NOARGS},
684 {"__exit__", iobase_exit, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000685
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000686 {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
687 {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
688 {"writelines", iobase_writelines, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000689
690 {NULL, NULL}
691};
692
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000693static PyGetSetDef iobase_getset[] = {
694 {"closed", (getter)iobase_closed_get, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000695 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000696};
697
698
699PyTypeObject PyIOBase_Type = {
700 PyVarObject_HEAD_INIT(NULL, 0)
701 "_io._IOBase", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000702 sizeof(iobase), /*tp_basicsize*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000703 0, /*tp_itemsize*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000704 (destructor)iobase_dealloc, /*tp_dealloc*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000705 0, /*tp_print*/
706 0, /*tp_getattr*/
707 0, /*tp_setattr*/
708 0, /*tp_compare */
709 0, /*tp_repr*/
710 0, /*tp_as_number*/
711 0, /*tp_as_sequence*/
712 0, /*tp_as_mapping*/
713 0, /*tp_hash */
714 0, /*tp_call*/
715 0, /*tp_str*/
716 0, /*tp_getattro*/
717 0, /*tp_setattro*/
718 0, /*tp_as_buffer*/
719 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
720 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000721 iobase_doc, /* tp_doc */
722 (traverseproc)iobase_traverse, /* tp_traverse */
723 (inquiry)iobase_clear, /* tp_clear */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000724 0, /* tp_richcompare */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000725 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
726 iobase_iter, /* tp_iter */
727 iobase_iternext, /* tp_iternext */
728 iobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000729 0, /* tp_members */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000730 iobase_getset, /* tp_getset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000731 0, /* tp_base */
732 0, /* tp_dict */
733 0, /* tp_descr_get */
734 0, /* tp_descr_set */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000735 offsetof(iobase, dict), /* tp_dictoffset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000736 0, /* tp_init */
737 0, /* tp_alloc */
738 PyType_GenericNew, /* tp_new */
739};
740
741
742/*
743 * RawIOBase class, Inherits from IOBase.
744 */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000745PyDoc_STRVAR(rawiobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000746 "Base class for raw binary I/O.");
747
748/*
749 * The read() method is implemented by calling readinto(); derived classes
750 * that want to support read() only need to implement readinto() as a
751 * primitive operation. In general, readinto() can be more efficient than
752 * read().
753 *
754 * (It would be tempting to also provide an implementation of readinto() in
755 * terms of read(), in case the latter is a more suitable primitive operation,
756 * but that would lead to nasty recursion in case a subclass doesn't implement
757 * either.)
758*/
759
760static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000761rawiobase_read(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000762{
763 Py_ssize_t n = -1;
764 PyObject *b, *res;
765
766 if (!PyArg_ParseTuple(args, "|n:read", &n)) {
767 return NULL;
768 }
769
770 if (n < 0)
771 return PyObject_CallMethod(self, "readall", NULL);
772
773 /* TODO: allocate a bytes object directly instead and manually construct
774 a writable memoryview pointing to it. */
775 b = PyByteArray_FromStringAndSize(NULL, n);
776 if (b == NULL)
777 return NULL;
778
779 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000780 if (res == NULL || res == Py_None) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000781 Py_DECREF(b);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000782 return res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000783 }
784
785 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
786 Py_DECREF(res);
787 if (n == -1 && PyErr_Occurred()) {
788 Py_DECREF(b);
789 return NULL;
790 }
791
792 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
793 Py_DECREF(b);
794 return res;
795}
796
797
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000798PyDoc_STRVAR(rawiobase_readall_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000799 "Read until EOF, using multiple read() call.");
800
801static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000802rawiobase_readall(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000803{
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000804 int r;
805 PyObject *chunks = PyList_New(0);
806 PyObject *result;
807
808 if (chunks == NULL)
809 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000810
811 while (1) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000812 PyObject *data = PyObject_CallMethod(self, "read",
813 "i", DEFAULT_BUFFER_SIZE);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000814 if (!data) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000815 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000816 return NULL;
817 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000818 if (!PyBytes_Check(data)) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000819 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000820 Py_DECREF(data);
821 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
822 return NULL;
823 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000824 if (PyBytes_GET_SIZE(data) == 0) {
825 /* EOF */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000826 Py_DECREF(data);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000827 break;
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000828 }
829 r = PyList_Append(chunks, data);
830 Py_DECREF(data);
831 if (r < 0) {
832 Py_DECREF(chunks);
833 return NULL;
834 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000835 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000836 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
837 Py_DECREF(chunks);
838 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000839}
840
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000841static PyMethodDef rawiobase_methods[] = {
842 {"read", rawiobase_read, METH_VARARGS},
843 {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000844 {NULL, NULL}
845};
846
847PyTypeObject PyRawIOBase_Type = {
848 PyVarObject_HEAD_INIT(NULL, 0)
849 "_io._RawIOBase", /*tp_name*/
850 0, /*tp_basicsize*/
851 0, /*tp_itemsize*/
852 0, /*tp_dealloc*/
853 0, /*tp_print*/
854 0, /*tp_getattr*/
855 0, /*tp_setattr*/
856 0, /*tp_compare */
857 0, /*tp_repr*/
858 0, /*tp_as_number*/
859 0, /*tp_as_sequence*/
860 0, /*tp_as_mapping*/
861 0, /*tp_hash */
862 0, /*tp_call*/
863 0, /*tp_str*/
864 0, /*tp_getattro*/
865 0, /*tp_setattro*/
866 0, /*tp_as_buffer*/
867 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000868 rawiobase_doc, /* tp_doc */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000869 0, /* tp_traverse */
870 0, /* tp_clear */
871 0, /* tp_richcompare */
872 0, /* tp_weaklistoffset */
873 0, /* tp_iter */
874 0, /* tp_iternext */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000875 rawiobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000876 0, /* tp_members */
877 0, /* tp_getset */
878 &PyIOBase_Type, /* tp_base */
879 0, /* tp_dict */
880 0, /* tp_descr_get */
881 0, /* tp_descr_set */
882 0, /* tp_dictoffset */
883 0, /* tp_init */
884 0, /* tp_alloc */
885 0, /* tp_new */
886};