blob: 6a94a04f4eb1cabfbf11f09f802def5bda62a129 [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{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200100 _Py_identifier(seek);
101
102 return _PyObject_CallMethodId(self, &PyId_seek, "ii", 0, 1);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000103}
104
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000105PyDoc_STRVAR(iobase_truncate_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000106 "Truncate file to size bytes.\n"
107 "\n"
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000108 "File pointer is left unchanged. Size defaults to the current IO\n"
109 "position as reported by tell(). Returns the new size.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000110
111static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000112iobase_truncate(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000113{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000114 return iobase_unsupported("truncate");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000115}
116
117/* Flush and close methods */
118
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000119PyDoc_STRVAR(iobase_flush_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000120 "Flush write buffers, if applicable.\n"
121 "\n"
122 "This is not implemented for read-only and non-blocking streams.\n");
123
124static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000125iobase_flush(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000126{
127 /* XXX Should this return the number of bytes written??? */
128 if (IS_CLOSED(self)) {
129 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
130 return NULL;
131 }
132 Py_RETURN_NONE;
133}
134
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000135PyDoc_STRVAR(iobase_close_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000136 "Flush and close the IO object.\n"
137 "\n"
138 "This method has no effect if the file is already closed.\n");
139
140static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000141iobase_closed(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000142{
143 PyObject *res;
144 int closed;
145 /* This gets the derived attribute, which is *not* __IOBase_closed
146 in most cases! */
147 res = PyObject_GetAttr(self, _PyIO_str_closed);
148 if (res == NULL)
149 return 0;
150 closed = PyObject_IsTrue(res);
151 Py_DECREF(res);
152 return closed;
153}
154
155static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000156iobase_closed_get(PyObject *self, void *context)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000157{
158 return PyBool_FromLong(IS_CLOSED(self));
159}
160
Benjamin Petersonf6f3a352011-09-03 09:26:20 -0400161static PyObject *
162iobase_get_dict(PyObject *self)
163{
164 PyObject **dictptr = _PyObject_GetDictPtr(self);
165 PyObject *dict;
166 assert(dictptr);
167 dict = *dictptr;
168 if (dict == NULL)
169 dict = *dictptr = PyDict_New();
170 Py_XINCREF(dict);
171 return dict;
172}
173
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000174PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000175_PyIOBase_check_closed(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000176{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000177 if (iobase_closed(self)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000178 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
179 return NULL;
180 }
181 if (args == Py_True)
182 return Py_None;
183 else
184 Py_RETURN_NONE;
185}
186
187/* XXX: IOBase thinks it has to maintain its own internal state in
188 `__IOBase_closed` and call flush() by itself, but it is redundant with
189 whatever behaviour a non-trivial derived class will implement. */
190
191static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000192iobase_close(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000193{
194 PyObject *res;
195
196 if (IS_CLOSED(self))
197 Py_RETURN_NONE;
198
199 res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
200 PyObject_SetAttrString(self, "__IOBase_closed", Py_True);
201 if (res == NULL) {
Antoine Pitrou6be88762010-05-03 16:48:20 +0000202 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000203 }
204 Py_XDECREF(res);
205 Py_RETURN_NONE;
206}
207
208/* Finalization and garbage collection support */
209
210int
211_PyIOBase_finalize(PyObject *self)
212{
213 PyObject *res;
214 PyObject *tp, *v, *tb;
215 int closed = 1;
216 int is_zombie;
217
218 /* If _PyIOBase_finalize() is called from a destructor, we need to
219 resurrect the object as calling close() can invoke arbitrary code. */
220 is_zombie = (Py_REFCNT(self) == 0);
221 if (is_zombie) {
222 ++Py_REFCNT(self);
223 }
224 PyErr_Fetch(&tp, &v, &tb);
225 /* If `closed` doesn't exist or can't be evaluated as bool, then the
226 object is probably in an unusable state, so ignore. */
227 res = PyObject_GetAttr(self, _PyIO_str_closed);
228 if (res == NULL)
229 PyErr_Clear();
230 else {
231 closed = PyObject_IsTrue(res);
232 Py_DECREF(res);
233 if (closed == -1)
234 PyErr_Clear();
235 }
236 if (closed == 0) {
237 res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
238 NULL);
239 /* Silencing I/O errors is bad, but printing spurious tracebacks is
240 equally as bad, and potentially more frequent (because of
241 shutdown issues). */
242 if (res == NULL)
243 PyErr_Clear();
244 else
245 Py_DECREF(res);
246 }
247 PyErr_Restore(tp, v, tb);
248 if (is_zombie) {
249 if (--Py_REFCNT(self) != 0) {
250 /* The object lives again. The following code is taken from
251 slot_tp_del in typeobject.c. */
252 Py_ssize_t refcnt = Py_REFCNT(self);
253 _Py_NewReference(self);
254 Py_REFCNT(self) = refcnt;
255 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
256 * we need to undo that. */
257 _Py_DEC_REFTOTAL;
258 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
259 * chain, so no more to do there.
260 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
261 * _Py_NewReference bumped tp_allocs: both of those need to be
262 * undone.
263 */
264#ifdef COUNT_ALLOCS
265 --Py_TYPE(self)->tp_frees;
266 --Py_TYPE(self)->tp_allocs;
267#endif
268 return -1;
269 }
270 }
271 return 0;
272}
273
274static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000275iobase_traverse(iobase *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000276{
277 Py_VISIT(self->dict);
278 return 0;
279}
280
281static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000282iobase_clear(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000283{
284 if (_PyIOBase_finalize((PyObject *) self) < 0)
285 return -1;
286 Py_CLEAR(self->dict);
287 return 0;
288}
289
290/* Destructor */
291
292static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000293iobase_dealloc(iobase *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000294{
295 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
296 are still available here for close() to use.
297 However, if the derived class declares a __slots__, those slots are
298 already gone.
299 */
300 if (_PyIOBase_finalize((PyObject *) self) < 0) {
301 /* When called from a heap type's dealloc, the type will be
302 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
303 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
304 Py_INCREF(Py_TYPE(self));
305 return;
306 }
307 _PyObject_GC_UNTRACK(self);
308 if (self->weakreflist != NULL)
309 PyObject_ClearWeakRefs((PyObject *) self);
310 Py_CLEAR(self->dict);
311 Py_TYPE(self)->tp_free((PyObject *) self);
312}
313
314/* Inquiry methods */
315
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000316PyDoc_STRVAR(iobase_seekable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000317 "Return whether object supports random access.\n"
318 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000319 "If False, seek(), tell() and truncate() will raise UnsupportedOperation.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000320 "This method may need to do a test seek().");
321
322static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000323iobase_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000324{
325 Py_RETURN_FALSE;
326}
327
328PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000329_PyIOBase_check_seekable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000330{
331 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
332 if (res == NULL)
333 return NULL;
334 if (res != Py_True) {
335 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000336 iobase_unsupported("File or stream is not seekable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000337 return NULL;
338 }
339 if (args == Py_True) {
340 Py_DECREF(res);
341 }
342 return res;
343}
344
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000345PyDoc_STRVAR(iobase_readable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000346 "Return whether object was opened for reading.\n"
347 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000348 "If False, read() will raise UnsupportedOperation.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000349
350static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000351iobase_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000352{
353 Py_RETURN_FALSE;
354}
355
356/* May be called with any object */
357PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000358_PyIOBase_check_readable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000359{
360 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
361 if (res == NULL)
362 return NULL;
363 if (res != Py_True) {
364 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000365 iobase_unsupported("File or stream is not readable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000366 return NULL;
367 }
368 if (args == Py_True) {
369 Py_DECREF(res);
370 }
371 return res;
372}
373
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000374PyDoc_STRVAR(iobase_writable_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000375 "Return whether object was opened for writing.\n"
376 "\n"
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000377 "If False, write() will raise UnsupportedOperation.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000378
379static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000380iobase_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000381{
382 Py_RETURN_FALSE;
383}
384
385/* May be called with any object */
386PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000387_PyIOBase_check_writable(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000388{
389 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
390 if (res == NULL)
391 return NULL;
392 if (res != Py_True) {
393 Py_CLEAR(res);
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000394 iobase_unsupported("File or stream is not writable.");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000395 return NULL;
396 }
397 if (args == Py_True) {
398 Py_DECREF(res);
399 }
400 return res;
401}
402
403/* Context manager */
404
405static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000406iobase_enter(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000407{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000408 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000409 return NULL;
410
411 Py_INCREF(self);
412 return self;
413}
414
415static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000416iobase_exit(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417{
418 return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
419}
420
421/* Lower-level APIs */
422
423/* XXX Should these be present even if unimplemented? */
424
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000425PyDoc_STRVAR(iobase_fileno_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426 "Returns underlying file descriptor if one exists.\n"
427 "\n"
428 "An IOError is raised if the IO object does not use a file descriptor.\n");
429
430static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000431iobase_fileno(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000432{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000433 return iobase_unsupported("fileno");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000434}
435
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000436PyDoc_STRVAR(iobase_isatty_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000437 "Return whether this is an 'interactive' stream.\n"
438 "\n"
439 "Return False if it can't be determined.\n");
440
441static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000442iobase_isatty(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000443{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000444 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000445 return NULL;
446 Py_RETURN_FALSE;
447}
448
449/* Readline(s) and writelines */
450
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000451PyDoc_STRVAR(iobase_readline_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000452 "Read and return a line from the stream.\n"
453 "\n"
454 "If limit is specified, at most limit bytes will be read.\n"
455 "\n"
456 "The line terminator is always b'\n' for binary files; for text\n"
457 "files, the newlines argument to open can be used to select the line\n"
458 "terminator(s) recognized.\n");
459
460static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000461iobase_readline(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000462{
463 /* For backwards compatibility, a (slowish) readline(). */
464
465 Py_ssize_t limit = -1;
466 int has_peek = 0;
467 PyObject *buffer, *result;
468 Py_ssize_t old_size = -1;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200469 _Py_identifier(read);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000470
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000471 if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000472 return NULL;
473 }
474
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000475 if (PyObject_HasAttrString(self, "peek"))
476 has_peek = 1;
477
478 buffer = PyByteArray_FromStringAndSize(NULL, 0);
479 if (buffer == NULL)
480 return NULL;
481
482 while (limit < 0 || Py_SIZE(buffer) < limit) {
483 Py_ssize_t nreadahead = 1;
484 PyObject *b;
485
486 if (has_peek) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200487 _Py_identifier(peek);
488 PyObject *readahead = _PyObject_CallMethodId(self, &PyId_peek, "i", 1);
489
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000490 if (readahead == NULL)
491 goto fail;
492 if (!PyBytes_Check(readahead)) {
493 PyErr_Format(PyExc_IOError,
494 "peek() should have returned a bytes object, "
495 "not '%.200s'", Py_TYPE(readahead)->tp_name);
496 Py_DECREF(readahead);
497 goto fail;
498 }
499 if (PyBytes_GET_SIZE(readahead) > 0) {
500 Py_ssize_t n = 0;
501 const char *buf = PyBytes_AS_STRING(readahead);
502 if (limit >= 0) {
503 do {
504 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
505 break;
506 if (buf[n++] == '\n')
507 break;
508 } while (1);
509 }
510 else {
511 do {
512 if (n >= PyBytes_GET_SIZE(readahead))
513 break;
514 if (buf[n++] == '\n')
515 break;
516 } while (1);
517 }
518 nreadahead = n;
519 }
520 Py_DECREF(readahead);
521 }
522
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200523 b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000524 if (b == NULL)
525 goto fail;
526 if (!PyBytes_Check(b)) {
527 PyErr_Format(PyExc_IOError,
528 "read() should have returned a bytes object, "
529 "not '%.200s'", Py_TYPE(b)->tp_name);
530 Py_DECREF(b);
531 goto fail;
532 }
533 if (PyBytes_GET_SIZE(b) == 0) {
534 Py_DECREF(b);
535 break;
536 }
537
538 old_size = PyByteArray_GET_SIZE(buffer);
539 PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b));
540 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
541 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
542
543 Py_DECREF(b);
544
545 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
546 break;
547 }
548
549 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
550 PyByteArray_GET_SIZE(buffer));
551 Py_DECREF(buffer);
552 return result;
553 fail:
554 Py_DECREF(buffer);
555 return NULL;
556}
557
558static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000559iobase_iter(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000560{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000561 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000562 return NULL;
563
564 Py_INCREF(self);
565 return self;
566}
567
568static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000569iobase_iternext(PyObject *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000570{
571 PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
572
573 if (line == NULL)
574 return NULL;
575
576 if (PyObject_Size(line) == 0) {
577 Py_DECREF(line);
578 return NULL;
579 }
580
581 return line;
582}
583
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000584PyDoc_STRVAR(iobase_readlines_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000585 "Return a list of lines from the stream.\n"
586 "\n"
587 "hint can be specified to control the number of lines read: no more\n"
588 "lines will be read if the total size (in bytes/characters) of all\n"
589 "lines so far exceeds hint.");
590
591static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000592iobase_readlines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000593{
594 Py_ssize_t hint = -1, length = 0;
Benjamin Peterson05516132009-12-13 19:28:09 +0000595 PyObject *result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000596
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000597 if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000598 return NULL;
599 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000600
601 result = PyList_New(0);
602 if (result == NULL)
603 return NULL;
604
605 if (hint <= 0) {
606 /* XXX special-casing this made sense in the Python version in order
607 to remove the bytecode interpretation overhead, but it could
608 probably be removed here. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200609 _Py_identifier(extend);
610 PyObject *ret = _PyObject_CallMethodId(result, &PyId_extend, "O", self);
611
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000612 if (ret == NULL) {
613 Py_DECREF(result);
614 return NULL;
615 }
616 Py_DECREF(ret);
617 return result;
618 }
619
620 while (1) {
621 PyObject *line = PyIter_Next(self);
622 if (line == NULL) {
623 if (PyErr_Occurred()) {
624 Py_DECREF(result);
625 return NULL;
626 }
627 else
628 break; /* StopIteration raised */
629 }
630
631 if (PyList_Append(result, line) < 0) {
632 Py_DECREF(line);
633 Py_DECREF(result);
634 return NULL;
635 }
636 length += PyObject_Size(line);
637 Py_DECREF(line);
638
639 if (length > hint)
640 break;
641 }
642 return result;
643}
644
645static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000646iobase_writelines(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000647{
648 PyObject *lines, *iter, *res;
649
650 if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
651 return NULL;
652 }
653
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000654 if (_PyIOBase_check_closed(self, Py_True) == NULL)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000655 return NULL;
656
657 iter = PyObject_GetIter(lines);
658 if (iter == NULL)
659 return NULL;
660
661 while (1) {
662 PyObject *line = PyIter_Next(iter);
663 if (line == NULL) {
664 if (PyErr_Occurred()) {
665 Py_DECREF(iter);
666 return NULL;
667 }
668 else
669 break; /* Stop Iteration */
670 }
671
672 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
673 Py_DECREF(line);
674 if (res == NULL) {
675 Py_DECREF(iter);
676 return NULL;
677 }
678 Py_DECREF(res);
679 }
680 Py_DECREF(iter);
681 Py_RETURN_NONE;
682}
683
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000684static PyMethodDef iobase_methods[] = {
685 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
686 {"tell", iobase_tell, METH_NOARGS, iobase_tell_doc},
687 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
688 {"flush", iobase_flush, METH_NOARGS, iobase_flush_doc},
689 {"close", iobase_close, METH_NOARGS, iobase_close_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000690
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000691 {"seekable", iobase_seekable, METH_NOARGS, iobase_seekable_doc},
692 {"readable", iobase_readable, METH_NOARGS, iobase_readable_doc},
693 {"writable", iobase_writable, METH_NOARGS, iobase_writable_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000694
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000695 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
696 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
697 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
698 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000699
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000700 {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
701 {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000702
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000703 {"__enter__", iobase_enter, METH_NOARGS},
704 {"__exit__", iobase_exit, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000705
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000706 {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
707 {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
708 {"writelines", iobase_writelines, METH_VARARGS},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000709
710 {NULL, NULL}
711};
712
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000713static PyGetSetDef iobase_getset[] = {
Benjamin Petersonf22913b2011-09-06 07:55:34 -0400714 {"__dict__", (getter)iobase_get_dict, NULL, NULL},
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000715 {"closed", (getter)iobase_closed_get, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000716 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000717};
718
719
720PyTypeObject PyIOBase_Type = {
721 PyVarObject_HEAD_INIT(NULL, 0)
722 "_io._IOBase", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000723 sizeof(iobase), /*tp_basicsize*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000724 0, /*tp_itemsize*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000725 (destructor)iobase_dealloc, /*tp_dealloc*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000726 0, /*tp_print*/
727 0, /*tp_getattr*/
728 0, /*tp_setattr*/
729 0, /*tp_compare */
730 0, /*tp_repr*/
731 0, /*tp_as_number*/
732 0, /*tp_as_sequence*/
733 0, /*tp_as_mapping*/
734 0, /*tp_hash */
735 0, /*tp_call*/
736 0, /*tp_str*/
737 0, /*tp_getattro*/
738 0, /*tp_setattro*/
739 0, /*tp_as_buffer*/
740 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
741 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000742 iobase_doc, /* tp_doc */
743 (traverseproc)iobase_traverse, /* tp_traverse */
744 (inquiry)iobase_clear, /* tp_clear */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000745 0, /* tp_richcompare */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000746 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
747 iobase_iter, /* tp_iter */
748 iobase_iternext, /* tp_iternext */
749 iobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000750 0, /* tp_members */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000751 iobase_getset, /* tp_getset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000752 0, /* tp_base */
753 0, /* tp_dict */
754 0, /* tp_descr_get */
755 0, /* tp_descr_set */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000756 offsetof(iobase, dict), /* tp_dictoffset */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000757 0, /* tp_init */
758 0, /* tp_alloc */
759 PyType_GenericNew, /* tp_new */
760};
761
762
763/*
764 * RawIOBase class, Inherits from IOBase.
765 */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000766PyDoc_STRVAR(rawiobase_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000767 "Base class for raw binary I/O.");
768
769/*
770 * The read() method is implemented by calling readinto(); derived classes
771 * that want to support read() only need to implement readinto() as a
772 * primitive operation. In general, readinto() can be more efficient than
773 * read().
774 *
775 * (It would be tempting to also provide an implementation of readinto() in
776 * terms of read(), in case the latter is a more suitable primitive operation,
777 * but that would lead to nasty recursion in case a subclass doesn't implement
778 * either.)
779*/
780
781static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000782rawiobase_read(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000783{
784 Py_ssize_t n = -1;
785 PyObject *b, *res;
786
787 if (!PyArg_ParseTuple(args, "|n:read", &n)) {
788 return NULL;
789 }
790
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200791 if (n < 0) {
792 _Py_identifier(readall);
793
794 return _PyObject_CallMethodId(self, &PyId_readall, NULL);
795 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000796
797 /* TODO: allocate a bytes object directly instead and manually construct
798 a writable memoryview pointing to it. */
799 b = PyByteArray_FromStringAndSize(NULL, n);
800 if (b == NULL)
801 return NULL;
802
803 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000804 if (res == NULL || res == Py_None) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000805 Py_DECREF(b);
Antoine Pitrou328ec742010-09-14 18:37:24 +0000806 return res;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000807 }
808
809 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
810 Py_DECREF(res);
811 if (n == -1 && PyErr_Occurred()) {
812 Py_DECREF(b);
813 return NULL;
814 }
815
816 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
817 Py_DECREF(b);
818 return res;
819}
820
821
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000822PyDoc_STRVAR(rawiobase_readall_doc,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000823 "Read until EOF, using multiple read() call.");
824
825static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000826rawiobase_readall(PyObject *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000827{
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000828 int r;
829 PyObject *chunks = PyList_New(0);
830 PyObject *result;
831
832 if (chunks == NULL)
833 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000834
835 while (1) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200836 _Py_identifier(read);
837 PyObject *data = _PyObject_CallMethodId(self, &PyId_read,
838 "i", DEFAULT_BUFFER_SIZE);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000839 if (!data) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000840 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000841 return NULL;
842 }
Victor Stinnera80987f2011-05-25 22:47:16 +0200843 if (data == Py_None) {
844 if (PyList_GET_SIZE(chunks) == 0) {
845 Py_DECREF(chunks);
846 return data;
847 }
848 Py_DECREF(data);
849 break;
850 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000851 if (!PyBytes_Check(data)) {
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000852 Py_DECREF(chunks);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000853 Py_DECREF(data);
854 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
855 return NULL;
856 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000857 if (PyBytes_GET_SIZE(data) == 0) {
858 /* EOF */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000859 Py_DECREF(data);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000860 break;
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000861 }
862 r = PyList_Append(chunks, data);
863 Py_DECREF(data);
864 if (r < 0) {
865 Py_DECREF(chunks);
866 return NULL;
867 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000868 }
Antoine Pitrou00a9b732009-03-29 19:19:49 +0000869 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
870 Py_DECREF(chunks);
871 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000872}
873
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000874static PyMethodDef rawiobase_methods[] = {
875 {"read", rawiobase_read, METH_VARARGS},
876 {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000877 {NULL, NULL}
878};
879
880PyTypeObject PyRawIOBase_Type = {
881 PyVarObject_HEAD_INIT(NULL, 0)
882 "_io._RawIOBase", /*tp_name*/
883 0, /*tp_basicsize*/
884 0, /*tp_itemsize*/
885 0, /*tp_dealloc*/
886 0, /*tp_print*/
887 0, /*tp_getattr*/
888 0, /*tp_setattr*/
889 0, /*tp_compare */
890 0, /*tp_repr*/
891 0, /*tp_as_number*/
892 0, /*tp_as_sequence*/
893 0, /*tp_as_mapping*/
894 0, /*tp_hash */
895 0, /*tp_call*/
896 0, /*tp_str*/
897 0, /*tp_getattro*/
898 0, /*tp_setattro*/
899 0, /*tp_as_buffer*/
900 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000901 rawiobase_doc, /* tp_doc */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000902 0, /* tp_traverse */
903 0, /* tp_clear */
904 0, /* tp_richcompare */
905 0, /* tp_weaklistoffset */
906 0, /* tp_iter */
907 0, /* tp_iternext */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000908 rawiobase_methods, /* tp_methods */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000909 0, /* tp_members */
910 0, /* tp_getset */
911 &PyIOBase_Type, /* tp_base */
912 0, /* tp_dict */
913 0, /* tp_descr_get */
914 0, /* tp_descr_set */
915 0, /* tp_dictoffset */
916 0, /* tp_init */
917 0, /* tp_alloc */
918 0, /* tp_new */
919};