blob: d813daf6cfb354e5e0bcc2e9c6d3dc4a4550e4bc [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
Serhiy Storchaka64aa4df2017-04-19 22:34:58 +0300574 if (PyObject_Size(line) <= 0) {
575 /* Error or empty */
Antoine Pitrou19690592009-06-12 20:14:08 +0000576 Py_DECREF(line);
577 return NULL;
578 }
579
580 return line;
581}
582
583PyDoc_STRVAR(iobase_readlines_doc,
584 "Return a list of lines from the stream.\n"
585 "\n"
586 "hint can be specified to control the number of lines read: no more\n"
587 "lines will be read if the total size (in bytes/characters) of all\n"
588 "lines so far exceeds hint.");
589
590static PyObject *
591iobase_readlines(PyObject *self, PyObject *args)
592{
593 Py_ssize_t hint = -1, length = 0;
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800594 PyObject *result, *it = NULL;
Antoine Pitrou19690592009-06-12 20:14:08 +0000595
Benjamin Petersonddd392c2009-12-13 19:19:07 +0000596 if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000597 return NULL;
598 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000599
600 result = PyList_New(0);
601 if (result == NULL)
602 return NULL;
603
604 if (hint <= 0) {
605 /* XXX special-casing this made sense in the Python version in order
606 to remove the bytecode interpretation overhead, but it could
607 probably be removed here. */
608 PyObject *ret = PyObject_CallMethod(result, "extend", "O", self);
609 if (ret == NULL) {
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800610 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000611 }
612 Py_DECREF(ret);
613 return result;
614 }
615
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800616 it = PyObject_GetIter(self);
617 if (it == NULL) {
618 goto error;
619 }
620
Antoine Pitrou19690592009-06-12 20:14:08 +0000621 while (1) {
Serhiy Storchaka64aa4df2017-04-19 22:34:58 +0300622 Py_ssize_t line_length;
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800623 PyObject *line = PyIter_Next(it);
Antoine Pitrou19690592009-06-12 20:14:08 +0000624 if (line == NULL) {
625 if (PyErr_Occurred()) {
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800626 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000627 }
628 else
629 break; /* StopIteration raised */
630 }
631
632 if (PyList_Append(result, line) < 0) {
633 Py_DECREF(line);
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800634 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000635 }
Serhiy Storchaka64aa4df2017-04-19 22:34:58 +0300636 line_length = PyObject_Size(line);
Antoine Pitrou19690592009-06-12 20:14:08 +0000637 Py_DECREF(line);
Serhiy Storchaka64aa4df2017-04-19 22:34:58 +0300638 if (line_length < 0) {
639 goto error;
640 }
641 if (line_length > hint - length)
Antoine Pitrou19690592009-06-12 20:14:08 +0000642 break;
Serhiy Storchaka64aa4df2017-04-19 22:34:58 +0300643 length += line_length;
Antoine Pitrou19690592009-06-12 20:14:08 +0000644 }
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800645
646 Py_DECREF(it);
Antoine Pitrou19690592009-06-12 20:14:08 +0000647 return result;
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800648
649 error:
650 Py_XDECREF(it);
651 Py_DECREF(result);
652 return NULL;
Antoine Pitrou19690592009-06-12 20:14:08 +0000653}
654
655static PyObject *
656iobase_writelines(PyObject *self, PyObject *args)
657{
658 PyObject *lines, *iter, *res;
659
660 if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
661 return NULL;
662 }
663
664 if (_PyIOBase_check_closed(self, Py_True) == NULL)
665 return NULL;
666
667 iter = PyObject_GetIter(lines);
668 if (iter == NULL)
669 return NULL;
670
671 while (1) {
672 PyObject *line = PyIter_Next(iter);
673 if (line == NULL) {
674 if (PyErr_Occurred()) {
675 Py_DECREF(iter);
676 return NULL;
677 }
678 else
679 break; /* Stop Iteration */
680 }
681
Gregory P. Smitha998ad02013-02-01 13:02:59 -0800682 res = NULL;
683 do {
684 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
685 } while (res == NULL && _PyIO_trap_eintr());
Antoine Pitrou19690592009-06-12 20:14:08 +0000686 Py_DECREF(line);
687 if (res == NULL) {
688 Py_DECREF(iter);
689 return NULL;
690 }
691 Py_DECREF(res);
692 }
693 Py_DECREF(iter);
694 Py_RETURN_NONE;
695}
696
697static PyMethodDef iobase_methods[] = {
698 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
699 {"tell", iobase_tell, METH_NOARGS, iobase_tell_doc},
700 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
701 {"flush", iobase_flush, METH_NOARGS, iobase_flush_doc},
702 {"close", iobase_close, METH_NOARGS, iobase_close_doc},
703
704 {"seekable", iobase_seekable, METH_NOARGS, iobase_seekable_doc},
705 {"readable", iobase_readable, METH_NOARGS, iobase_readable_doc},
706 {"writable", iobase_writable, METH_NOARGS, iobase_writable_doc},
707
708 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
709 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
710 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
711 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
712
713 {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
714 {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
715
716 {"__enter__", iobase_enter, METH_NOARGS},
717 {"__exit__", iobase_exit, METH_VARARGS},
718
719 {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
720 {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
721 {"writelines", iobase_writelines, METH_VARARGS},
722
723 {NULL, NULL}
724};
725
726static PyGetSetDef iobase_getset[] = {
727 {"closed", (getter)iobase_closed_get, NULL, NULL},
728 {NULL}
729};
730
731
732PyTypeObject PyIOBase_Type = {
733 PyVarObject_HEAD_INIT(NULL, 0)
734 "_io._IOBase", /*tp_name*/
735 sizeof(iobase), /*tp_basicsize*/
736 0, /*tp_itemsize*/
737 (destructor)iobase_dealloc, /*tp_dealloc*/
738 0, /*tp_print*/
739 0, /*tp_getattr*/
740 0, /*tp_setattr*/
741 0, /*tp_compare */
742 0, /*tp_repr*/
743 0, /*tp_as_number*/
744 0, /*tp_as_sequence*/
745 0, /*tp_as_mapping*/
746 0, /*tp_hash */
747 0, /*tp_call*/
748 0, /*tp_str*/
749 0, /*tp_getattro*/
750 0, /*tp_setattro*/
751 0, /*tp_as_buffer*/
752 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
753 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
754 iobase_doc, /* tp_doc */
755 (traverseproc)iobase_traverse, /* tp_traverse */
756 (inquiry)iobase_clear, /* tp_clear */
757 0, /* tp_richcompare */
758 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
759 iobase_iter, /* tp_iter */
760 iobase_iternext, /* tp_iternext */
761 iobase_methods, /* tp_methods */
762 0, /* tp_members */
763 iobase_getset, /* tp_getset */
764 0, /* tp_base */
765 0, /* tp_dict */
766 0, /* tp_descr_get */
767 0, /* tp_descr_set */
768 offsetof(iobase, dict), /* tp_dictoffset */
769 0, /* tp_init */
770 0, /* tp_alloc */
771 PyType_GenericNew, /* tp_new */
772};
773
774
775/*
776 * RawIOBase class, Inherits from IOBase.
777 */
778PyDoc_STRVAR(rawiobase_doc,
779 "Base class for raw binary I/O.");
780
781/*
782 * The read() method is implemented by calling readinto(); derived classes
783 * that want to support read() only need to implement readinto() as a
784 * primitive operation. In general, readinto() can be more efficient than
785 * read().
786 *
787 * (It would be tempting to also provide an implementation of readinto() in
788 * terms of read(), in case the latter is a more suitable primitive operation,
789 * but that would lead to nasty recursion in case a subclass doesn't implement
790 * either.)
791*/
792
793static PyObject *
794rawiobase_read(PyObject *self, PyObject *args)
795{
796 Py_ssize_t n = -1;
797 PyObject *b, *res;
798
799 if (!PyArg_ParseTuple(args, "|n:read", &n)) {
800 return NULL;
801 }
802
803 if (n < 0)
804 return PyObject_CallMethod(self, "readall", NULL);
805
806 /* TODO: allocate a bytes object directly instead and manually construct
807 a writable memoryview pointing to it. */
808 b = PyByteArray_FromStringAndSize(NULL, n);
809 if (b == NULL)
810 return NULL;
811
812 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
Antoine Pitrou6391b342010-09-14 18:48:19 +0000813 if (res == NULL || res == Py_None) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000814 Py_DECREF(b);
Antoine Pitrou6391b342010-09-14 18:48:19 +0000815 return res;
Antoine Pitrou19690592009-06-12 20:14:08 +0000816 }
817
818 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
819 Py_DECREF(res);
820 if (n == -1 && PyErr_Occurred()) {
821 Py_DECREF(b);
822 return NULL;
823 }
824
825 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
826 Py_DECREF(b);
827 return res;
828}
829
830
831PyDoc_STRVAR(rawiobase_readall_doc,
832 "Read until EOF, using multiple read() call.");
833
834static PyObject *
835rawiobase_readall(PyObject *self, PyObject *args)
836{
837 int r;
838 PyObject *chunks = PyList_New(0);
839 PyObject *result;
Xiang Zhang5fbdfc32017-04-15 13:18:22 +0800840
Antoine Pitrou19690592009-06-12 20:14:08 +0000841 if (chunks == NULL)
842 return NULL;
843
844 while (1) {
845 PyObject *data = PyObject_CallMethod(self, "read",
846 "i", DEFAULT_BUFFER_SIZE);
847 if (!data) {
Gregory P. Smith99716162012-10-12 13:02:06 -0700848 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
849 when EINTR occurs so we needn't do it ourselves. */
850 if (_PyIO_trap_eintr()) {
851 continue;
852 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000853 Py_DECREF(chunks);
854 return NULL;
855 }
Victor Stinnerdaf17e92011-05-25 22:52:37 +0200856 if (data == Py_None) {
857 if (PyList_GET_SIZE(chunks) == 0) {
858 Py_DECREF(chunks);
859 return data;
860 }
861 Py_DECREF(data);
862 break;
863 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000864 if (!PyBytes_Check(data)) {
865 Py_DECREF(chunks);
866 Py_DECREF(data);
867 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
868 return NULL;
869 }
870 if (PyBytes_GET_SIZE(data) == 0) {
871 /* EOF */
872 Py_DECREF(data);
873 break;
874 }
875 r = PyList_Append(chunks, data);
876 Py_DECREF(data);
877 if (r < 0) {
878 Py_DECREF(chunks);
879 return NULL;
880 }
881 }
882 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
883 Py_DECREF(chunks);
884 return result;
885}
886
887static PyMethodDef rawiobase_methods[] = {
888 {"read", rawiobase_read, METH_VARARGS},
889 {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
890 {NULL, NULL}
891};
892
893PyTypeObject PyRawIOBase_Type = {
894 PyVarObject_HEAD_INIT(NULL, 0)
895 "_io._RawIOBase", /*tp_name*/
896 0, /*tp_basicsize*/
897 0, /*tp_itemsize*/
898 0, /*tp_dealloc*/
899 0, /*tp_print*/
900 0, /*tp_getattr*/
901 0, /*tp_setattr*/
902 0, /*tp_compare */
903 0, /*tp_repr*/
904 0, /*tp_as_number*/
905 0, /*tp_as_sequence*/
906 0, /*tp_as_mapping*/
907 0, /*tp_hash */
908 0, /*tp_call*/
909 0, /*tp_str*/
910 0, /*tp_getattro*/
911 0, /*tp_setattro*/
912 0, /*tp_as_buffer*/
913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
914 rawiobase_doc, /* tp_doc */
915 0, /* tp_traverse */
916 0, /* tp_clear */
917 0, /* tp_richcompare */
918 0, /* tp_weaklistoffset */
919 0, /* tp_iter */
920 0, /* tp_iternext */
921 rawiobase_methods, /* tp_methods */
922 0, /* tp_members */
923 0, /* tp_getset */
924 &PyIOBase_Type, /* tp_base */
925 0, /* tp_dict */
926 0, /* tp_descr_get */
927 0, /* tp_descr_set */
928 0, /* tp_dictoffset */
929 0, /* tp_init */
930 0, /* tp_alloc */
931 0, /* tp_new */
932};