blob: 066dc8edad6adbb70e7fe99a5eaedaa7eef115d7 [file] [log] [blame]
Antoine Pitrou19690592009-06-12 20:14:08 +00001/*
2 An implementation of the I/O abstract base classes hierarchy
3 as defined by PEP 3116 - "New I/O"
Xiang Zhang5fbdfc32017-04-15 13:18:22 +08004
Antoine Pitrou19690592009-06-12 20:14:08 +00005 Classes defined here: IOBase, RawIOBase.
Xiang Zhang5fbdfc32017-04-15 13:18:22 +08006
Antoine Pitrou19690592009-06-12 20:14:08 +00007 Written by Amaury Forgeot d'Arc and Antoine Pitrou
8*/
9
10
11#define PY_SSIZE_T_CLEAN
12#include "Python.h"
13#include "structmember.h"
14#include "_iomodule.h"
15
16/*
17 * IOBase class, an abstract class
18 */
19
20typedef struct {
21 PyObject_HEAD
Xiang Zhang5fbdfc32017-04-15 13:18:22 +080022
Antoine Pitrou19690592009-06-12 20:14:08 +000023 PyObject *dict;
24 PyObject *weakreflist;
25} iobase;
26
27PyDoc_STRVAR(iobase_doc,
28 "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"
Martin Panterb362f752015-11-02 03:37:02 +000038 "may raise an IOError when operations they do not support are called.\n"
Antoine Pitrou19690592009-06-12 20:14:08 +000039 "\n"
40 "The basic type used for binary data read from or written to a file is\n"
Martin Panterc9813d82016-06-03 05:59:20 +000041 "the bytes type. Method arguments may also be bytearray or memoryview\n"
42 "of arrays of bytes. In some cases, such as readinto, a writable\n"
43 "object such as bytearray is required. Text I/O classes work with\n"
44 "unicode data.\n"
Antoine Pitrou19690592009-06-12 20:14:08 +000045 "\n"
Andrew Kuchling68e85e52014-04-15 16:07:52 -040046 "Note that calling any method (except additional calls to close(),\n"
47 "which are ignored) on a closed stream should raise a ValueError.\n"
Antoine Pitrou19690592009-06-12 20:14:08 +000048 "\n"
49 "IOBase (and its subclasses) support the iterator protocol, meaning\n"
50 "that an IOBase object can be iterated over yielding the lines in a\n"
51 "stream.\n"
52 "\n"
53 "IOBase also supports the :keyword:`with` statement. In this example,\n"
Ezio Melottic2077b02011-03-16 12:34:31 +020054 "fp is closed after the suite of the with statement is complete:\n"
Antoine Pitrou19690592009-06-12 20:14:08 +000055 "\n"
56 "with open('spam.txt', 'r') as fp:\n"
57 " fp.write('Spam and eggs!')\n");
58
59/* Use this macro whenever you want to check the internal `closed` status
60 of the IOBase object rather than the virtual `closed` attribute as returned
61 by whatever subclass. */
62
63#define IS_CLOSED(self) \
64 PyObject_HasAttrString(self, "__IOBase_closed")
65
66/* Internal methods */
67static PyObject *
68iobase_unsupported(const char *message)
69{
70 PyErr_SetString(_PyIO_unsupported_operation, message);
71 return NULL;
72}
73
Martin Panter65076572016-09-07 12:03:06 +000074/* Positioning */
Antoine Pitrou19690592009-06-12 20:14:08 +000075
76PyDoc_STRVAR(iobase_seek_doc,
77 "Change stream position.\n"
78 "\n"
Terry Jan Reedyce9cc492013-03-11 17:41:44 -040079 "Change the stream position to the given byte offset. The offset is\n"
Antoine Pitrou19690592009-06-12 20:14:08 +000080 "interpreted relative to the position indicated by whence. Values\n"
81 "for whence are:\n"
82 "\n"
83 "* 0 -- start of stream (the default); offset should be zero or positive\n"
84 "* 1 -- current stream position; offset may be negative\n"
85 "* 2 -- end of stream; offset is usually negative\n"
86 "\n"
87 "Return the new absolute position.");
88
89static PyObject *
90iobase_seek(PyObject *self, PyObject *args)
91{
92 return iobase_unsupported("seek");
93}
94
95PyDoc_STRVAR(iobase_tell_doc,
96 "Return current stream position.");
97
98static PyObject *
99iobase_tell(PyObject *self, PyObject *args)
100{
101 return PyObject_CallMethod(self, "seek", "ii", 0, 1);
102}
103
104PyDoc_STRVAR(iobase_truncate_doc,
105 "Truncate file to size bytes.\n"
106 "\n"
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000107 "File pointer is left unchanged. Size defaults to the current IO\n"
108 "position as reported by tell(). Returns the new size.");
Antoine Pitrou19690592009-06-12 20:14:08 +0000109
110static PyObject *
111iobase_truncate(PyObject *self, PyObject *args)
112{
113 return iobase_unsupported("truncate");
114}
115
116/* Flush and close methods */
117
118PyDoc_STRVAR(iobase_flush_doc,
119 "Flush write buffers, if applicable.\n"
120 "\n"
121 "This is not implemented for read-only and non-blocking streams.\n");
122
123static PyObject *
124iobase_flush(PyObject *self, PyObject *args)
125{
126 /* XXX Should this return the number of bytes written??? */
127 if (IS_CLOSED(self)) {
128 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
129 return NULL;
130 }
131 Py_RETURN_NONE;
132}
133
134PyDoc_STRVAR(iobase_close_doc,
135 "Flush and close the IO object.\n"
136 "\n"
137 "This method has no effect if the file is already closed.\n");
138
139static int
140iobase_closed(PyObject *self)
141{
142 PyObject *res;
143 int closed;
144 /* This gets the derived attribute, which is *not* __IOBase_closed
145 in most cases! */
146 res = PyObject_GetAttr(self, _PyIO_str_closed);
147 if (res == NULL)
148 return 0;
149 closed = PyObject_IsTrue(res);
150 Py_DECREF(res);
151 return closed;
152}
153
154static PyObject *
155iobase_closed_get(PyObject *self, void *context)
156{
157 return PyBool_FromLong(IS_CLOSED(self));
158}
159
160PyObject *
161_PyIOBase_check_closed(PyObject *self, PyObject *args)
162{
163 if (iobase_closed(self)) {
164 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
165 return NULL;
166 }
167 if (args == Py_True)
168 return Py_None;
169 else
170 Py_RETURN_NONE;
171}
172
173/* XXX: IOBase thinks it has to maintain its own internal state in
174 `__IOBase_closed` and call flush() by itself, but it is redundant with
175 whatever behaviour a non-trivial derived class will implement. */
176
177static PyObject *
178iobase_close(PyObject *self, PyObject *args)
179{
180 PyObject *res;
181
182 if (IS_CLOSED(self))
183 Py_RETURN_NONE;
184
185 res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
186 PyObject_SetAttrString(self, "__IOBase_closed", Py_True);
187 if (res == NULL) {
Antoine Pitrouf7fd8e42010-05-03 16:25:33 +0000188 return NULL;
Antoine Pitrou19690592009-06-12 20:14:08 +0000189 }
190 Py_XDECREF(res);
191 Py_RETURN_NONE;
192}
193
194/* Finalization and garbage collection support */
195
196int
197_PyIOBase_finalize(PyObject *self)
198{
199 PyObject *res;
200 PyObject *tp, *v, *tb;
201 int closed = 1;
202 int is_zombie;
203
204 /* If _PyIOBase_finalize() is called from a destructor, we need to
205 resurrect the object as calling close() can invoke arbitrary code. */
206 is_zombie = (Py_REFCNT(self) == 0);
207 if (is_zombie) {
208 ++Py_REFCNT(self);
209 }
210 PyErr_Fetch(&tp, &v, &tb);
211 /* If `closed` doesn't exist or can't be evaluated as bool, then the
212 object is probably in an unusable state, so ignore. */
213 res = PyObject_GetAttr(self, _PyIO_str_closed);
214 if (res == NULL)
215 PyErr_Clear();
216 else {
217 closed = PyObject_IsTrue(res);
218 Py_DECREF(res);
219 if (closed == -1)
220 PyErr_Clear();
221 }
222 if (closed == 0) {
223 res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
224 NULL);
225 /* Silencing I/O errors is bad, but printing spurious tracebacks is
226 equally as bad, and potentially more frequent (because of
227 shutdown issues). */
228 if (res == NULL)
229 PyErr_Clear();
230 else
231 Py_DECREF(res);
232 }
233 PyErr_Restore(tp, v, tb);
234 if (is_zombie) {
235 if (--Py_REFCNT(self) != 0) {
236 /* The object lives again. The following code is taken from
237 slot_tp_del in typeobject.c. */
238 Py_ssize_t refcnt = Py_REFCNT(self);
239 _Py_NewReference(self);
240 Py_REFCNT(self) = refcnt;
241 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
242 * we need to undo that. */
243 _Py_DEC_REFTOTAL;
244 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
245 * chain, so no more to do there.
246 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
247 * _Py_NewReference bumped tp_allocs: both of those need to be
248 * undone.
249 */
250#ifdef COUNT_ALLOCS
251 --Py_TYPE(self)->tp_frees;
252 --Py_TYPE(self)->tp_allocs;
253#endif
254 return -1;
255 }
256 }
257 return 0;
258}
259
260static int
261iobase_traverse(iobase *self, visitproc visit, void *arg)
262{
263 Py_VISIT(self->dict);
264 return 0;
265}
266
267static int
268iobase_clear(iobase *self)
269{
270 if (_PyIOBase_finalize((PyObject *) self) < 0)
271 return -1;
272 Py_CLEAR(self->dict);
273 return 0;
274}
275
276/* Destructor */
277
278static void
279iobase_dealloc(iobase *self)
280{
281 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
282 are still available here for close() to use.
283 However, if the derived class declares a __slots__, those slots are
284 already gone.
285 */
286 if (_PyIOBase_finalize((PyObject *) self) < 0) {
287 /* When called from a heap type's dealloc, the type will be
288 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
289 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
290 Py_INCREF(Py_TYPE(self));
291 return;
292 }
293 _PyObject_GC_UNTRACK(self);
294 if (self->weakreflist != NULL)
295 PyObject_ClearWeakRefs((PyObject *) self);
296 Py_CLEAR(self->dict);
297 Py_TYPE(self)->tp_free((PyObject *) self);
298}
299
300/* Inquiry methods */
301
302PyDoc_STRVAR(iobase_seekable_doc,
303 "Return whether object supports random access.\n"
304 "\n"
305 "If False, seek(), tell() and truncate() will raise IOError.\n"
306 "This method may need to do a test seek().");
307
308static PyObject *
309iobase_seekable(PyObject *self, PyObject *args)
310{
311 Py_RETURN_FALSE;
312}
313
314PyObject *
315_PyIOBase_check_seekable(PyObject *self, PyObject *args)
316{
317 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
318 if (res == NULL)
319 return NULL;
320 if (res != Py_True) {
321 Py_CLEAR(res);
322 PyErr_SetString(PyExc_IOError, "File or stream is not seekable.");
323 return NULL;
324 }
325 if (args == Py_True) {
326 Py_DECREF(res);
327 }
328 return res;
329}
330
331PyDoc_STRVAR(iobase_readable_doc,
332 "Return whether object was opened for reading.\n"
333 "\n"
334 "If False, read() will raise IOError.");
335
336static PyObject *
337iobase_readable(PyObject *self, PyObject *args)
338{
339 Py_RETURN_FALSE;
340}
341
342/* May be called with any object */
343PyObject *
344_PyIOBase_check_readable(PyObject *self, PyObject *args)
345{
346 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
347 if (res == NULL)
348 return NULL;
349 if (res != Py_True) {
350 Py_CLEAR(res);
351 PyErr_SetString(PyExc_IOError, "File or stream is not readable.");
352 return NULL;
353 }
354 if (args == Py_True) {
355 Py_DECREF(res);
356 }
357 return res;
358}
359
360PyDoc_STRVAR(iobase_writable_doc,
361 "Return whether object was opened for writing.\n"
362 "\n"
363 "If False, read() will raise IOError.");
364
365static PyObject *
366iobase_writable(PyObject *self, PyObject *args)
367{
368 Py_RETURN_FALSE;
369}
370
371/* May be called with any object */
372PyObject *
373_PyIOBase_check_writable(PyObject *self, PyObject *args)
374{
375 PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
376 if (res == NULL)
377 return NULL;
378 if (res != Py_True) {
379 Py_CLEAR(res);
380 PyErr_SetString(PyExc_IOError, "File or stream is not writable.");
381 return NULL;
382 }
383 if (args == Py_True) {
384 Py_DECREF(res);
385 }
386 return res;
387}
388
389/* Context manager */
390
391static PyObject *
392iobase_enter(PyObject *self, PyObject *args)
393{
394 if (_PyIOBase_check_closed(self, Py_True) == NULL)
395 return NULL;
396
397 Py_INCREF(self);
398 return self;
399}
400
401static PyObject *
402iobase_exit(PyObject *self, PyObject *args)
403{
404 return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
405}
406
407/* Lower-level APIs */
408
409/* XXX Should these be present even if unimplemented? */
410
411PyDoc_STRVAR(iobase_fileno_doc,
412 "Returns underlying file descriptor if one exists.\n"
413 "\n"
414 "An IOError is raised if the IO object does not use a file descriptor.\n");
415
416static PyObject *
417iobase_fileno(PyObject *self, PyObject *args)
418{
419 return iobase_unsupported("fileno");
420}
421
422PyDoc_STRVAR(iobase_isatty_doc,
423 "Return whether this is an 'interactive' stream.\n"
424 "\n"
425 "Return False if it can't be determined.\n");
426
427static PyObject *
428iobase_isatty(PyObject *self, PyObject *args)
429{
430 if (_PyIOBase_check_closed(self, Py_True) == NULL)
431 return NULL;
432 Py_RETURN_FALSE;
433}
434
435/* Readline(s) and writelines */
436
437PyDoc_STRVAR(iobase_readline_doc,
438 "Read and return a line from the stream.\n"
439 "\n"
440 "If limit is specified, at most limit bytes will be read.\n"
441 "\n"
Ezio Melottiba372a52012-09-18 07:17:49 +0300442 "The line terminator is always b'\\n' for binary files; for text\n"
Antoine Pitrou19690592009-06-12 20:14:08 +0000443 "files, the newlines argument to open can be used to select the line\n"
444 "terminator(s) recognized.\n");
445
446static PyObject *
447iobase_readline(PyObject *self, PyObject *args)
448{
449 /* For backwards compatibility, a (slowish) readline(). */
450
451 Py_ssize_t limit = -1;
452 int has_peek = 0;
453 PyObject *buffer, *result;
454 Py_ssize_t old_size = -1;
455
Benjamin Petersonddd392c2009-12-13 19:19:07 +0000456 if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000457 return NULL;
458 }
459
460 if (PyObject_HasAttrString(self, "peek"))
461 has_peek = 1;
462
463 buffer = PyByteArray_FromStringAndSize(NULL, 0);
464 if (buffer == NULL)
465 return NULL;
466
467 while (limit < 0 || Py_SIZE(buffer) < limit) {
468 Py_ssize_t nreadahead = 1;
469 PyObject *b;
470
471 if (has_peek) {
472 PyObject *readahead = PyObject_CallMethod(self, "peek", "i", 1);
Gregory P. Smith99716162012-10-12 13:02:06 -0700473 if (readahead == NULL) {
474 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
475 when EINTR occurs so we needn't do it ourselves. */
476 if (_PyIO_trap_eintr()) {
477 continue;
478 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000479 goto fail;
Gregory P. Smith99716162012-10-12 13:02:06 -0700480 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000481 if (!PyBytes_Check(readahead)) {
482 PyErr_Format(PyExc_IOError,
483 "peek() should have returned a bytes object, "
484 "not '%.200s'", Py_TYPE(readahead)->tp_name);
485 Py_DECREF(readahead);
486 goto fail;
487 }
488 if (PyBytes_GET_SIZE(readahead) > 0) {
489 Py_ssize_t n = 0;
490 const char *buf = PyBytes_AS_STRING(readahead);
491 if (limit >= 0) {
492 do {
493 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
494 break;
495 if (buf[n++] == '\n')
496 break;
497 } while (1);
498 }
499 else {
500 do {
501 if (n >= PyBytes_GET_SIZE(readahead))
502 break;
503 if (buf[n++] == '\n')
504 break;
505 } while (1);
506 }
507 nreadahead = n;
508 }
509 Py_DECREF(readahead);
510 }
511
512 b = PyObject_CallMethod(self, "read", "n", nreadahead);
Gregory P. Smith99716162012-10-12 13:02:06 -0700513 if (b == NULL) {
514 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
515 when EINTR occurs so we needn't do it ourselves. */
516 if (_PyIO_trap_eintr()) {
517 continue;
518 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000519 goto fail;
Gregory P. Smith99716162012-10-12 13:02:06 -0700520 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000521 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);
Benjamin Petersona48aa852016-06-03 22:20:44 -0700534 if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
535 Py_DECREF(b);
536 goto fail;
537 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000538 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
539 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
540
541 Py_DECREF(b);
542
543 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
544 break;
545 }
546
547 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
548 PyByteArray_GET_SIZE(buffer));
549 Py_DECREF(buffer);
550 return result;
551 fail:
552 Py_DECREF(buffer);
553 return NULL;
554}
555
556static PyObject *
557iobase_iter(PyObject *self)
558{
559 if (_PyIOBase_check_closed(self, Py_True) == NULL)
560 return NULL;
561
562 Py_INCREF(self);
563 return self;
564}
565
566static PyObject *
567iobase_iternext(PyObject *self)
568{
569 PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
570
571 if (line == NULL)
572 return NULL;
573
574 if (PyObject_Size(line) == 0) {
575 Py_DECREF(line);
576 return NULL;
577 }
578
579 return line;
580}
581
582PyDoc_STRVAR(iobase_readlines_doc,
583 "Return a list of lines from the stream.\n"
584 "\n"
585 "hint can be specified to control the number of lines read: no more\n"
586 "lines will be read if the total size (in bytes/characters) of all\n"
587 "lines so far exceeds hint.");
588
589static PyObject *
590iobase_readlines(PyObject *self, PyObject *args)
591{
592 Py_ssize_t hint = -1, length = 0;
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800593 PyObject *result, *it = NULL;
Antoine Pitrou19690592009-06-12 20:14:08 +0000594
Benjamin Petersonddd392c2009-12-13 19:19:07 +0000595 if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000596 return NULL;
597 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000598
599 result = PyList_New(0);
600 if (result == NULL)
601 return NULL;
602
603 if (hint <= 0) {
604 /* XXX special-casing this made sense in the Python version in order
605 to remove the bytecode interpretation overhead, but it could
606 probably be removed here. */
607 PyObject *ret = PyObject_CallMethod(result, "extend", "O", self);
608 if (ret == NULL) {
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800609 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000610 }
611 Py_DECREF(ret);
612 return result;
613 }
614
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800615 it = PyObject_GetIter(self);
616 if (it == NULL) {
617 goto error;
618 }
619
Antoine Pitrou19690592009-06-12 20:14:08 +0000620 while (1) {
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800621 PyObject *line = PyIter_Next(it);
Antoine Pitrou19690592009-06-12 20:14:08 +0000622 if (line == NULL) {
623 if (PyErr_Occurred()) {
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800624 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000625 }
626 else
627 break; /* StopIteration raised */
628 }
629
630 if (PyList_Append(result, line) < 0) {
631 Py_DECREF(line);
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800632 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000633 }
634 length += PyObject_Size(line);
635 Py_DECREF(line);
636
637 if (length > hint)
638 break;
639 }
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800640
641 Py_DECREF(it);
Antoine Pitrou19690592009-06-12 20:14:08 +0000642 return result;
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800643
644 error:
645 Py_XDECREF(it);
646 Py_DECREF(result);
647 return NULL;
Antoine Pitrou19690592009-06-12 20:14:08 +0000648}
649
650static PyObject *
651iobase_writelines(PyObject *self, PyObject *args)
652{
653 PyObject *lines, *iter, *res;
654
655 if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
656 return NULL;
657 }
658
659 if (_PyIOBase_check_closed(self, Py_True) == NULL)
660 return NULL;
661
662 iter = PyObject_GetIter(lines);
663 if (iter == NULL)
664 return NULL;
665
666 while (1) {
667 PyObject *line = PyIter_Next(iter);
668 if (line == NULL) {
669 if (PyErr_Occurred()) {
670 Py_DECREF(iter);
671 return NULL;
672 }
673 else
674 break; /* Stop Iteration */
675 }
676
Gregory P. Smitha998ad02013-02-01 13:02:59 -0800677 res = NULL;
678 do {
679 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
680 } while (res == NULL && _PyIO_trap_eintr());
Antoine Pitrou19690592009-06-12 20:14:08 +0000681 Py_DECREF(line);
682 if (res == NULL) {
683 Py_DECREF(iter);
684 return NULL;
685 }
686 Py_DECREF(res);
687 }
688 Py_DECREF(iter);
689 Py_RETURN_NONE;
690}
691
692static PyMethodDef iobase_methods[] = {
693 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
694 {"tell", iobase_tell, METH_NOARGS, iobase_tell_doc},
695 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
696 {"flush", iobase_flush, METH_NOARGS, iobase_flush_doc},
697 {"close", iobase_close, METH_NOARGS, iobase_close_doc},
698
699 {"seekable", iobase_seekable, METH_NOARGS, iobase_seekable_doc},
700 {"readable", iobase_readable, METH_NOARGS, iobase_readable_doc},
701 {"writable", iobase_writable, METH_NOARGS, iobase_writable_doc},
702
703 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
704 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
705 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
706 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
707
708 {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
709 {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
710
711 {"__enter__", iobase_enter, METH_NOARGS},
712 {"__exit__", iobase_exit, METH_VARARGS},
713
714 {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
715 {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
716 {"writelines", iobase_writelines, METH_VARARGS},
717
718 {NULL, NULL}
719};
720
721static PyGetSetDef iobase_getset[] = {
722 {"closed", (getter)iobase_closed_get, NULL, NULL},
723 {NULL}
724};
725
726
727PyTypeObject PyIOBase_Type = {
728 PyVarObject_HEAD_INIT(NULL, 0)
729 "_io._IOBase", /*tp_name*/
730 sizeof(iobase), /*tp_basicsize*/
731 0, /*tp_itemsize*/
732 (destructor)iobase_dealloc, /*tp_dealloc*/
733 0, /*tp_print*/
734 0, /*tp_getattr*/
735 0, /*tp_setattr*/
736 0, /*tp_compare */
737 0, /*tp_repr*/
738 0, /*tp_as_number*/
739 0, /*tp_as_sequence*/
740 0, /*tp_as_mapping*/
741 0, /*tp_hash */
742 0, /*tp_call*/
743 0, /*tp_str*/
744 0, /*tp_getattro*/
745 0, /*tp_setattro*/
746 0, /*tp_as_buffer*/
747 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
748 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
749 iobase_doc, /* tp_doc */
750 (traverseproc)iobase_traverse, /* tp_traverse */
751 (inquiry)iobase_clear, /* tp_clear */
752 0, /* tp_richcompare */
753 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
754 iobase_iter, /* tp_iter */
755 iobase_iternext, /* tp_iternext */
756 iobase_methods, /* tp_methods */
757 0, /* tp_members */
758 iobase_getset, /* tp_getset */
759 0, /* tp_base */
760 0, /* tp_dict */
761 0, /* tp_descr_get */
762 0, /* tp_descr_set */
763 offsetof(iobase, dict), /* tp_dictoffset */
764 0, /* tp_init */
765 0, /* tp_alloc */
766 PyType_GenericNew, /* tp_new */
767};
768
769
770/*
771 * RawIOBase class, Inherits from IOBase.
772 */
773PyDoc_STRVAR(rawiobase_doc,
774 "Base class for raw binary I/O.");
775
776/*
777 * The read() method is implemented by calling readinto(); derived classes
778 * that want to support read() only need to implement readinto() as a
779 * primitive operation. In general, readinto() can be more efficient than
780 * read().
781 *
782 * (It would be tempting to also provide an implementation of readinto() in
783 * terms of read(), in case the latter is a more suitable primitive operation,
784 * but that would lead to nasty recursion in case a subclass doesn't implement
785 * either.)
786*/
787
788static PyObject *
789rawiobase_read(PyObject *self, PyObject *args)
790{
791 Py_ssize_t n = -1;
792 PyObject *b, *res;
793
794 if (!PyArg_ParseTuple(args, "|n:read", &n)) {
795 return NULL;
796 }
797
798 if (n < 0)
799 return PyObject_CallMethod(self, "readall", NULL);
800
801 /* TODO: allocate a bytes object directly instead and manually construct
802 a writable memoryview pointing to it. */
803 b = PyByteArray_FromStringAndSize(NULL, n);
804 if (b == NULL)
805 return NULL;
806
807 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou6391b342010-09-14 18:48:19 +0000808 if (res == NULL || res == Py_None) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000809 Py_DECREF(b);
Antoine Pitrou6391b342010-09-14 18:48:19 +0000810 return res;
Antoine Pitrou19690592009-06-12 20:14:08 +0000811 }
812
813 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
814 Py_DECREF(res);
815 if (n == -1 && PyErr_Occurred()) {
816 Py_DECREF(b);
817 return NULL;
818 }
819
820 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
821 Py_DECREF(b);
822 return res;
823}
824
825
826PyDoc_STRVAR(rawiobase_readall_doc,
827 "Read until EOF, using multiple read() call.");
828
829static PyObject *
830rawiobase_readall(PyObject *self, PyObject *args)
831{
832 int r;
833 PyObject *chunks = PyList_New(0);
834 PyObject *result;
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800835
Antoine Pitrou19690592009-06-12 20:14:08 +0000836 if (chunks == NULL)
837 return NULL;
838
839 while (1) {
840 PyObject *data = PyObject_CallMethod(self, "read",
841 "i", DEFAULT_BUFFER_SIZE);
842 if (!data) {
Gregory P. Smith99716162012-10-12 13:02:06 -0700843 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
844 when EINTR occurs so we needn't do it ourselves. */
845 if (_PyIO_trap_eintr()) {
846 continue;
847 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000848 Py_DECREF(chunks);
849 return NULL;
850 }
Victor Stinnerdaf17e92011-05-25 22:52:37 +0200851 if (data == Py_None) {
852 if (PyList_GET_SIZE(chunks) == 0) {
853 Py_DECREF(chunks);
854 return data;
855 }
856 Py_DECREF(data);
857 break;
858 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000859 if (!PyBytes_Check(data)) {
860 Py_DECREF(chunks);
861 Py_DECREF(data);
862 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
863 return NULL;
864 }
865 if (PyBytes_GET_SIZE(data) == 0) {
866 /* EOF */
867 Py_DECREF(data);
868 break;
869 }
870 r = PyList_Append(chunks, data);
871 Py_DECREF(data);
872 if (r < 0) {
873 Py_DECREF(chunks);
874 return NULL;
875 }
876 }
877 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
878 Py_DECREF(chunks);
879 return result;
880}
881
882static PyMethodDef rawiobase_methods[] = {
883 {"read", rawiobase_read, METH_VARARGS},
884 {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
885 {NULL, NULL}
886};
887
888PyTypeObject PyRawIOBase_Type = {
889 PyVarObject_HEAD_INIT(NULL, 0)
890 "_io._RawIOBase", /*tp_name*/
891 0, /*tp_basicsize*/
892 0, /*tp_itemsize*/
893 0, /*tp_dealloc*/
894 0, /*tp_print*/
895 0, /*tp_getattr*/
896 0, /*tp_setattr*/
897 0, /*tp_compare */
898 0, /*tp_repr*/
899 0, /*tp_as_number*/
900 0, /*tp_as_sequence*/
901 0, /*tp_as_mapping*/
902 0, /*tp_hash */
903 0, /*tp_call*/
904 0, /*tp_str*/
905 0, /*tp_getattro*/
906 0, /*tp_setattro*/
907 0, /*tp_as_buffer*/
908 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
909 rawiobase_doc, /* tp_doc */
910 0, /* tp_traverse */
911 0, /* tp_clear */
912 0, /* tp_richcompare */
913 0, /* tp_weaklistoffset */
914 0, /* tp_iter */
915 0, /* tp_iternext */
916 rawiobase_methods, /* tp_methods */
917 0, /* tp_members */
918 0, /* tp_getset */
919 &PyIOBase_Type, /* tp_base */
920 0, /* tp_dict */
921 0, /* tp_descr_get */
922 0, /* tp_descr_set */
923 0, /* tp_dictoffset */
924 0, /* tp_init */
925 0, /* tp_alloc */
926 0, /* tp_new */
927};