Line data Source code
1 : /*
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 :
20 : typedef struct {
21 : PyObject_HEAD
22 :
23 : PyObject *dict;
24 : PyObject *weakreflist;
25 : } iobase;
26 :
27 : PyDoc_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"
38 : "may raise UnsupportedOperation when operations they do not support are\n"
39 : "called.\n"
40 : "\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 statement 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 : _Py_IDENTIFIER(__IOBase_closed);
63 : #define IS_CLOSED(self) \
64 : _PyObject_HasAttrId(self, &PyId___IOBase_closed)
65 :
66 : /* Internal methods */
67 : static PyObject *
68 0 : iobase_unsupported(const char *message)
69 : {
70 0 : PyErr_SetString(IO_STATE->unsupported_operation, message);
71 0 : return NULL;
72 : }
73 :
74 : /* Positionning */
75 :
76 : PyDoc_STRVAR(iobase_seek_doc,
77 : "Change stream position.\n"
78 : "\n"
79 : "Change the stream position to byte offset offset. offset is\n"
80 : "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 :
89 : static PyObject *
90 0 : iobase_seek(PyObject *self, PyObject *args)
91 : {
92 0 : return iobase_unsupported("seek");
93 : }
94 :
95 : PyDoc_STRVAR(iobase_tell_doc,
96 : "Return current stream position.");
97 :
98 : static PyObject *
99 0 : iobase_tell(PyObject *self, PyObject *args)
100 : {
101 : _Py_IDENTIFIER(seek);
102 :
103 0 : return _PyObject_CallMethodId(self, &PyId_seek, "ii", 0, 1);
104 : }
105 :
106 : PyDoc_STRVAR(iobase_truncate_doc,
107 : "Truncate file to size bytes.\n"
108 : "\n"
109 : "File pointer is left unchanged. Size defaults to the current IO\n"
110 : "position as reported by tell(). Returns the new size.");
111 :
112 : static PyObject *
113 0 : iobase_truncate(PyObject *self, PyObject *args)
114 : {
115 0 : return iobase_unsupported("truncate");
116 : }
117 :
118 : /* Flush and close methods */
119 :
120 : PyDoc_STRVAR(iobase_flush_doc,
121 : "Flush write buffers, if applicable.\n"
122 : "\n"
123 : "This is not implemented for read-only and non-blocking streams.\n");
124 :
125 : static PyObject *
126 48 : iobase_flush(PyObject *self, PyObject *args)
127 : {
128 : /* XXX Should this return the number of bytes written??? */
129 48 : if (IS_CLOSED(self)) {
130 0 : PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
131 0 : return NULL;
132 : }
133 48 : Py_RETURN_NONE;
134 : }
135 :
136 : PyDoc_STRVAR(iobase_close_doc,
137 : "Flush and close the IO object.\n"
138 : "\n"
139 : "This method has no effect if the file is already closed.\n");
140 :
141 : static int
142 45 : iobase_closed(PyObject *self)
143 : {
144 : PyObject *res;
145 : int closed;
146 : /* This gets the derived attribute, which is *not* __IOBase_closed
147 : in most cases! */
148 45 : res = PyObject_GetAttr(self, _PyIO_str_closed);
149 45 : if (res == NULL)
150 0 : return 0;
151 45 : closed = PyObject_IsTrue(res);
152 45 : Py_DECREF(res);
153 45 : return closed;
154 : }
155 :
156 : static PyObject *
157 0 : iobase_closed_get(PyObject *self, void *context)
158 : {
159 0 : return PyBool_FromLong(IS_CLOSED(self));
160 : }
161 :
162 : PyObject *
163 45 : _PyIOBase_check_closed(PyObject *self, PyObject *args)
164 : {
165 45 : if (iobase_closed(self)) {
166 0 : PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
167 0 : return NULL;
168 : }
169 45 : if (args == Py_True)
170 45 : return Py_None;
171 : else
172 0 : Py_RETURN_NONE;
173 : }
174 :
175 : /* XXX: IOBase thinks it has to maintain its own internal state in
176 : `__IOBase_closed` and call flush() by itself, but it is redundant with
177 : whatever behaviour a non-trivial derived class will implement. */
178 :
179 : static PyObject *
180 46 : iobase_close(PyObject *self, PyObject *args)
181 : {
182 : PyObject *res;
183 : _Py_IDENTIFIER(__IOBase_closed);
184 :
185 46 : if (IS_CLOSED(self))
186 0 : Py_RETURN_NONE;
187 :
188 46 : res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
189 46 : _PyObject_SetAttrId(self, &PyId___IOBase_closed, Py_True);
190 46 : if (res == NULL) {
191 0 : return NULL;
192 : }
193 46 : Py_XDECREF(res);
194 46 : Py_RETURN_NONE;
195 : }
196 :
197 : /* Finalization and garbage collection support */
198 :
199 : int
200 48 : _PyIOBase_finalize(PyObject *self)
201 : {
202 : PyObject *res;
203 : PyObject *tp, *v, *tb;
204 48 : int closed = 1;
205 : int is_zombie;
206 :
207 : /* If _PyIOBase_finalize() is called from a destructor, we need to
208 : resurrect the object as calling close() can invoke arbitrary code. */
209 48 : is_zombie = (Py_REFCNT(self) == 0);
210 48 : if (is_zombie) {
211 48 : ++Py_REFCNT(self);
212 : }
213 48 : PyErr_Fetch(&tp, &v, &tb);
214 : /* If `closed` doesn't exist or can't be evaluated as bool, then the
215 : object is probably in an unusable state, so ignore. */
216 48 : res = PyObject_GetAttr(self, _PyIO_str_closed);
217 48 : if (res == NULL)
218 0 : PyErr_Clear();
219 : else {
220 48 : closed = PyObject_IsTrue(res);
221 48 : Py_DECREF(res);
222 48 : if (closed == -1)
223 0 : PyErr_Clear();
224 : }
225 48 : if (closed == 0) {
226 1 : res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
227 : NULL);
228 : /* Silencing I/O errors is bad, but printing spurious tracebacks is
229 : equally as bad, and potentially more frequent (because of
230 : shutdown issues). */
231 1 : if (res == NULL)
232 0 : PyErr_Clear();
233 : else
234 1 : Py_DECREF(res);
235 : }
236 48 : PyErr_Restore(tp, v, tb);
237 48 : if (is_zombie) {
238 48 : if (--Py_REFCNT(self) != 0) {
239 : /* The object lives again. The following code is taken from
240 : slot_tp_del in typeobject.c. */
241 0 : Py_ssize_t refcnt = Py_REFCNT(self);
242 0 : _Py_NewReference(self);
243 0 : Py_REFCNT(self) = refcnt;
244 : /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
245 : * we need to undo that. */
246 : _Py_DEC_REFTOTAL;
247 : /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
248 : * chain, so no more to do there.
249 : * If COUNT_ALLOCS, the original decref bumped tp_frees, and
250 : * _Py_NewReference bumped tp_allocs: both of those need to be
251 : * undone.
252 : */
253 : #ifdef COUNT_ALLOCS
254 : --Py_TYPE(self)->tp_frees;
255 : --Py_TYPE(self)->tp_allocs;
256 : #endif
257 0 : return -1;
258 : }
259 : }
260 48 : return 0;
261 : }
262 :
263 : static int
264 0 : iobase_traverse(iobase *self, visitproc visit, void *arg)
265 : {
266 0 : Py_VISIT(self->dict);
267 0 : return 0;
268 : }
269 :
270 : static int
271 0 : iobase_clear(iobase *self)
272 : {
273 0 : if (_PyIOBase_finalize((PyObject *) self) < 0)
274 0 : return -1;
275 0 : Py_CLEAR(self->dict);
276 0 : return 0;
277 : }
278 :
279 : /* Destructor */
280 :
281 : static void
282 0 : iobase_dealloc(iobase *self)
283 : {
284 : /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
285 : are still available here for close() to use.
286 : However, if the derived class declares a __slots__, those slots are
287 : already gone.
288 : */
289 0 : if (_PyIOBase_finalize((PyObject *) self) < 0) {
290 : /* When called from a heap type's dealloc, the type will be
291 : decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
292 0 : if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
293 0 : Py_INCREF(Py_TYPE(self));
294 0 : return;
295 : }
296 0 : _PyObject_GC_UNTRACK(self);
297 0 : if (self->weakreflist != NULL)
298 0 : PyObject_ClearWeakRefs((PyObject *) self);
299 0 : Py_CLEAR(self->dict);
300 0 : Py_TYPE(self)->tp_free((PyObject *) self);
301 : }
302 :
303 : /* Inquiry methods */
304 :
305 : PyDoc_STRVAR(iobase_seekable_doc,
306 : "Return whether object supports random access.\n"
307 : "\n"
308 : "If False, seek(), tell() and truncate() will raise UnsupportedOperation.\n"
309 : "This method may need to do a test seek().");
310 :
311 : static PyObject *
312 0 : iobase_seekable(PyObject *self, PyObject *args)
313 : {
314 0 : Py_RETURN_FALSE;
315 : }
316 :
317 : PyObject *
318 0 : _PyIOBase_check_seekable(PyObject *self, PyObject *args)
319 : {
320 0 : PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
321 0 : if (res == NULL)
322 0 : return NULL;
323 0 : if (res != Py_True) {
324 0 : Py_CLEAR(res);
325 0 : iobase_unsupported("File or stream is not seekable.");
326 0 : return NULL;
327 : }
328 0 : if (args == Py_True) {
329 0 : Py_DECREF(res);
330 : }
331 0 : return res;
332 : }
333 :
334 : PyDoc_STRVAR(iobase_readable_doc,
335 : "Return whether object was opened for reading.\n"
336 : "\n"
337 : "If False, read() will raise UnsupportedOperation.");
338 :
339 : static PyObject *
340 0 : iobase_readable(PyObject *self, PyObject *args)
341 : {
342 0 : Py_RETURN_FALSE;
343 : }
344 :
345 : /* May be called with any object */
346 : PyObject *
347 2 : _PyIOBase_check_readable(PyObject *self, PyObject *args)
348 : {
349 2 : PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
350 2 : if (res == NULL)
351 0 : return NULL;
352 2 : if (res != Py_True) {
353 0 : Py_CLEAR(res);
354 0 : iobase_unsupported("File or stream is not readable.");
355 0 : return NULL;
356 : }
357 2 : if (args == Py_True) {
358 2 : Py_DECREF(res);
359 : }
360 2 : return res;
361 : }
362 :
363 : PyDoc_STRVAR(iobase_writable_doc,
364 : "Return whether object was opened for writing.\n"
365 : "\n"
366 : "If False, write() will raise UnsupportedOperation.");
367 :
368 : static PyObject *
369 0 : iobase_writable(PyObject *self, PyObject *args)
370 : {
371 0 : Py_RETURN_FALSE;
372 : }
373 :
374 : /* May be called with any object */
375 : PyObject *
376 2 : _PyIOBase_check_writable(PyObject *self, PyObject *args)
377 : {
378 2 : PyObject *res = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
379 2 : if (res == NULL)
380 0 : return NULL;
381 2 : if (res != Py_True) {
382 0 : Py_CLEAR(res);
383 0 : iobase_unsupported("File or stream is not writable.");
384 0 : return NULL;
385 : }
386 2 : if (args == Py_True) {
387 2 : Py_DECREF(res);
388 : }
389 2 : return res;
390 : }
391 :
392 : /* Context manager */
393 :
394 : static PyObject *
395 45 : iobase_enter(PyObject *self, PyObject *args)
396 : {
397 45 : if (_PyIOBase_check_closed(self, Py_True) == NULL)
398 0 : return NULL;
399 :
400 45 : Py_INCREF(self);
401 45 : return self;
402 : }
403 :
404 : static PyObject *
405 45 : iobase_exit(PyObject *self, PyObject *args)
406 : {
407 45 : return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
408 : }
409 :
410 : /* Lower-level APIs */
411 :
412 : /* XXX Should these be present even if unimplemented? */
413 :
414 : PyDoc_STRVAR(iobase_fileno_doc,
415 : "Returns underlying file descriptor if one exists.\n"
416 : "\n"
417 : "An IOError is raised if the IO object does not use a file descriptor.\n");
418 :
419 : static PyObject *
420 0 : iobase_fileno(PyObject *self, PyObject *args)
421 : {
422 0 : return iobase_unsupported("fileno");
423 : }
424 :
425 : PyDoc_STRVAR(iobase_isatty_doc,
426 : "Return whether this is an 'interactive' stream.\n"
427 : "\n"
428 : "Return False if it can't be determined.\n");
429 :
430 : static PyObject *
431 0 : iobase_isatty(PyObject *self, PyObject *args)
432 : {
433 0 : if (_PyIOBase_check_closed(self, Py_True) == NULL)
434 0 : return NULL;
435 0 : Py_RETURN_FALSE;
436 : }
437 :
438 : /* Readline(s) and writelines */
439 :
440 : PyDoc_STRVAR(iobase_readline_doc,
441 : "Read and return a line from the stream.\n"
442 : "\n"
443 : "If limit is specified, at most limit bytes will be read.\n"
444 : "\n"
445 : "The line terminator is always b'\n' for binary files; for text\n"
446 : "files, the newlines argument to open can be used to select the line\n"
447 : "terminator(s) recognized.\n");
448 :
449 : static PyObject *
450 0 : iobase_readline(PyObject *self, PyObject *args)
451 : {
452 : /* For backwards compatibility, a (slowish) readline(). */
453 :
454 0 : Py_ssize_t limit = -1;
455 0 : int has_peek = 0;
456 : PyObject *buffer, *result;
457 0 : Py_ssize_t old_size = -1;
458 : _Py_IDENTIFIER(read);
459 : _Py_IDENTIFIER(peek);
460 :
461 0 : if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) {
462 0 : return NULL;
463 : }
464 :
465 0 : if (_PyObject_HasAttrId(self, &PyId_peek))
466 0 : has_peek = 1;
467 :
468 0 : buffer = PyByteArray_FromStringAndSize(NULL, 0);
469 0 : if (buffer == NULL)
470 0 : return NULL;
471 :
472 0 : while (limit < 0 || Py_SIZE(buffer) < limit) {
473 0 : Py_ssize_t nreadahead = 1;
474 : PyObject *b;
475 :
476 0 : if (has_peek) {
477 0 : PyObject *readahead = _PyObject_CallMethodId(self, &PyId_peek, "i", 1);
478 0 : if (readahead == NULL) {
479 : /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
480 : when EINTR occurs so we needn't do it ourselves. */
481 0 : if (_PyIO_trap_eintr()) {
482 0 : continue;
483 : }
484 0 : goto fail;
485 : }
486 0 : if (!PyBytes_Check(readahead)) {
487 0 : PyErr_Format(PyExc_IOError,
488 : "peek() should have returned a bytes object, "
489 0 : "not '%.200s'", Py_TYPE(readahead)->tp_name);
490 0 : Py_DECREF(readahead);
491 0 : goto fail;
492 : }
493 0 : if (PyBytes_GET_SIZE(readahead) > 0) {
494 0 : Py_ssize_t n = 0;
495 0 : const char *buf = PyBytes_AS_STRING(readahead);
496 0 : if (limit >= 0) {
497 : do {
498 0 : if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
499 : break;
500 0 : if (buf[n++] == '\n')
501 0 : break;
502 0 : } while (1);
503 : }
504 : else {
505 : do {
506 0 : if (n >= PyBytes_GET_SIZE(readahead))
507 0 : break;
508 0 : if (buf[n++] == '\n')
509 0 : break;
510 0 : } while (1);
511 : }
512 0 : nreadahead = n;
513 : }
514 0 : Py_DECREF(readahead);
515 : }
516 :
517 0 : b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
518 0 : if (b == NULL) {
519 : /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
520 : when EINTR occurs so we needn't do it ourselves. */
521 0 : if (_PyIO_trap_eintr()) {
522 0 : continue;
523 : }
524 0 : goto fail;
525 : }
526 0 : if (!PyBytes_Check(b)) {
527 0 : PyErr_Format(PyExc_IOError,
528 : "read() should have returned a bytes object, "
529 0 : "not '%.200s'", Py_TYPE(b)->tp_name);
530 0 : Py_DECREF(b);
531 0 : goto fail;
532 : }
533 0 : if (PyBytes_GET_SIZE(b) == 0) {
534 0 : Py_DECREF(b);
535 0 : break;
536 : }
537 :
538 0 : old_size = PyByteArray_GET_SIZE(buffer);
539 0 : PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b));
540 0 : memcpy(PyByteArray_AS_STRING(buffer) + old_size,
541 0 : PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
542 :
543 0 : Py_DECREF(b);
544 :
545 0 : if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
546 0 : break;
547 : }
548 :
549 0 : result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
550 : PyByteArray_GET_SIZE(buffer));
551 0 : Py_DECREF(buffer);
552 0 : return result;
553 : fail:
554 0 : Py_DECREF(buffer);
555 0 : return NULL;
556 : }
557 :
558 : static PyObject *
559 0 : iobase_iter(PyObject *self)
560 : {
561 0 : if (_PyIOBase_check_closed(self, Py_True) == NULL)
562 0 : return NULL;
563 :
564 0 : Py_INCREF(self);
565 0 : return self;
566 : }
567 :
568 : static PyObject *
569 0 : iobase_iternext(PyObject *self)
570 : {
571 0 : PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);
572 :
573 0 : if (line == NULL)
574 0 : return NULL;
575 :
576 0 : if (PyObject_Size(line) == 0) {
577 0 : Py_DECREF(line);
578 0 : return NULL;
579 : }
580 :
581 0 : return line;
582 : }
583 :
584 : PyDoc_STRVAR(iobase_readlines_doc,
585 : "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 :
591 : static PyObject *
592 0 : iobase_readlines(PyObject *self, PyObject *args)
593 : {
594 0 : Py_ssize_t hint = -1, length = 0;
595 : PyObject *result;
596 :
597 0 : if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
598 0 : return NULL;
599 : }
600 :
601 0 : result = PyList_New(0);
602 0 : if (result == NULL)
603 0 : return NULL;
604 :
605 0 : 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. */
609 : _Py_IDENTIFIER(extend);
610 0 : PyObject *ret = _PyObject_CallMethodId(result, &PyId_extend, "O", self);
611 :
612 0 : if (ret == NULL) {
613 0 : Py_DECREF(result);
614 0 : return NULL;
615 : }
616 0 : Py_DECREF(ret);
617 0 : return result;
618 : }
619 :
620 : while (1) {
621 0 : PyObject *line = PyIter_Next(self);
622 0 : if (line == NULL) {
623 0 : if (PyErr_Occurred()) {
624 0 : Py_DECREF(result);
625 0 : return NULL;
626 : }
627 : else
628 0 : break; /* StopIteration raised */
629 : }
630 :
631 0 : if (PyList_Append(result, line) < 0) {
632 0 : Py_DECREF(line);
633 0 : Py_DECREF(result);
634 0 : return NULL;
635 : }
636 0 : length += PyObject_Size(line);
637 0 : Py_DECREF(line);
638 :
639 0 : if (length > hint)
640 0 : break;
641 0 : }
642 0 : return result;
643 : }
644 :
645 : static PyObject *
646 0 : iobase_writelines(PyObject *self, PyObject *args)
647 : {
648 : PyObject *lines, *iter, *res;
649 :
650 0 : if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
651 0 : return NULL;
652 : }
653 :
654 0 : if (_PyIOBase_check_closed(self, Py_True) == NULL)
655 0 : return NULL;
656 :
657 0 : iter = PyObject_GetIter(lines);
658 0 : if (iter == NULL)
659 0 : return NULL;
660 :
661 : while (1) {
662 0 : PyObject *line = PyIter_Next(iter);
663 0 : if (line == NULL) {
664 0 : if (PyErr_Occurred()) {
665 0 : Py_DECREF(iter);
666 0 : return NULL;
667 : }
668 : else
669 0 : break; /* Stop Iteration */
670 : }
671 :
672 0 : res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
673 0 : Py_DECREF(line);
674 0 : if (res == NULL) {
675 0 : Py_DECREF(iter);
676 0 : return NULL;
677 : }
678 0 : Py_DECREF(res);
679 0 : }
680 0 : Py_DECREF(iter);
681 0 : Py_RETURN_NONE;
682 : }
683 :
684 : static 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},
690 :
691 : {"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},
694 :
695 : {"_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},
699 :
700 : {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
701 : {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
702 :
703 : {"__enter__", iobase_enter, METH_NOARGS},
704 : {"__exit__", iobase_exit, METH_VARARGS},
705 :
706 : {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
707 : {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
708 : {"writelines", iobase_writelines, METH_VARARGS},
709 :
710 : {NULL, NULL}
711 : };
712 :
713 : static PyGetSetDef iobase_getset[] = {
714 : {"__dict__", PyObject_GenericGetDict, NULL, NULL},
715 : {"closed", (getter)iobase_closed_get, NULL, NULL},
716 : {NULL}
717 : };
718 :
719 :
720 : PyTypeObject PyIOBase_Type = {
721 : PyVarObject_HEAD_INIT(NULL, 0)
722 : "_io._IOBase", /*tp_name*/
723 : sizeof(iobase), /*tp_basicsize*/
724 : 0, /*tp_itemsize*/
725 : (destructor)iobase_dealloc, /*tp_dealloc*/
726 : 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*/
742 : iobase_doc, /* tp_doc */
743 : (traverseproc)iobase_traverse, /* tp_traverse */
744 : (inquiry)iobase_clear, /* tp_clear */
745 : 0, /* tp_richcompare */
746 : offsetof(iobase, weakreflist), /* tp_weaklistoffset */
747 : iobase_iter, /* tp_iter */
748 : iobase_iternext, /* tp_iternext */
749 : iobase_methods, /* tp_methods */
750 : 0, /* tp_members */
751 : iobase_getset, /* tp_getset */
752 : 0, /* tp_base */
753 : 0, /* tp_dict */
754 : 0, /* tp_descr_get */
755 : 0, /* tp_descr_set */
756 : offsetof(iobase, dict), /* tp_dictoffset */
757 : 0, /* tp_init */
758 : 0, /* tp_alloc */
759 : PyType_GenericNew, /* tp_new */
760 : };
761 :
762 :
763 : /*
764 : * RawIOBase class, Inherits from IOBase.
765 : */
766 : PyDoc_STRVAR(rawiobase_doc,
767 : "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 :
781 : static PyObject *
782 0 : rawiobase_read(PyObject *self, PyObject *args)
783 : {
784 0 : Py_ssize_t n = -1;
785 : PyObject *b, *res;
786 :
787 0 : if (!PyArg_ParseTuple(args, "|n:read", &n)) {
788 0 : return NULL;
789 : }
790 :
791 0 : if (n < 0) {
792 : _Py_IDENTIFIER(readall);
793 :
794 0 : return _PyObject_CallMethodId(self, &PyId_readall, NULL);
795 : }
796 :
797 : /* TODO: allocate a bytes object directly instead and manually construct
798 : a writable memoryview pointing to it. */
799 0 : b = PyByteArray_FromStringAndSize(NULL, n);
800 0 : if (b == NULL)
801 0 : return NULL;
802 :
803 0 : res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
804 0 : if (res == NULL || res == Py_None) {
805 0 : Py_DECREF(b);
806 0 : return res;
807 : }
808 :
809 0 : n = PyNumber_AsSsize_t(res, PyExc_ValueError);
810 0 : Py_DECREF(res);
811 0 : if (n == -1 && PyErr_Occurred()) {
812 0 : Py_DECREF(b);
813 0 : return NULL;
814 : }
815 :
816 0 : res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
817 0 : Py_DECREF(b);
818 0 : return res;
819 : }
820 :
821 :
822 : PyDoc_STRVAR(rawiobase_readall_doc,
823 : "Read until EOF, using multiple read() call.");
824 :
825 : static PyObject *
826 0 : rawiobase_readall(PyObject *self, PyObject *args)
827 : {
828 : int r;
829 0 : PyObject *chunks = PyList_New(0);
830 : PyObject *result;
831 :
832 0 : if (chunks == NULL)
833 0 : return NULL;
834 :
835 : while (1) {
836 : _Py_IDENTIFIER(read);
837 0 : PyObject *data = _PyObject_CallMethodId(self, &PyId_read,
838 : "i", DEFAULT_BUFFER_SIZE);
839 0 : if (!data) {
840 : /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
841 : when EINTR occurs so we needn't do it ourselves. */
842 0 : if (_PyIO_trap_eintr()) {
843 0 : continue;
844 : }
845 0 : Py_DECREF(chunks);
846 0 : return NULL;
847 : }
848 0 : if (data == Py_None) {
849 0 : if (PyList_GET_SIZE(chunks) == 0) {
850 0 : Py_DECREF(chunks);
851 0 : return data;
852 : }
853 0 : Py_DECREF(data);
854 0 : break;
855 : }
856 0 : if (!PyBytes_Check(data)) {
857 0 : Py_DECREF(chunks);
858 0 : Py_DECREF(data);
859 0 : PyErr_SetString(PyExc_TypeError, "read() should return bytes");
860 0 : return NULL;
861 : }
862 0 : if (PyBytes_GET_SIZE(data) == 0) {
863 : /* EOF */
864 0 : Py_DECREF(data);
865 0 : break;
866 : }
867 0 : r = PyList_Append(chunks, data);
868 0 : Py_DECREF(data);
869 0 : if (r < 0) {
870 0 : Py_DECREF(chunks);
871 0 : return NULL;
872 : }
873 0 : }
874 0 : result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
875 0 : Py_DECREF(chunks);
876 0 : return result;
877 : }
878 :
879 : static PyMethodDef rawiobase_methods[] = {
880 : {"read", rawiobase_read, METH_VARARGS},
881 : {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
882 : {NULL, NULL}
883 : };
884 :
885 : PyTypeObject PyRawIOBase_Type = {
886 : PyVarObject_HEAD_INIT(NULL, 0)
887 : "_io._RawIOBase", /*tp_name*/
888 : 0, /*tp_basicsize*/
889 : 0, /*tp_itemsize*/
890 : 0, /*tp_dealloc*/
891 : 0, /*tp_print*/
892 : 0, /*tp_getattr*/
893 : 0, /*tp_setattr*/
894 : 0, /*tp_compare */
895 : 0, /*tp_repr*/
896 : 0, /*tp_as_number*/
897 : 0, /*tp_as_sequence*/
898 : 0, /*tp_as_mapping*/
899 : 0, /*tp_hash */
900 : 0, /*tp_call*/
901 : 0, /*tp_str*/
902 : 0, /*tp_getattro*/
903 : 0, /*tp_setattro*/
904 : 0, /*tp_as_buffer*/
905 : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
906 : rawiobase_doc, /* tp_doc */
907 : 0, /* tp_traverse */
908 : 0, /* tp_clear */
909 : 0, /* tp_richcompare */
910 : 0, /* tp_weaklistoffset */
911 : 0, /* tp_iter */
912 : 0, /* tp_iternext */
913 : rawiobase_methods, /* tp_methods */
914 : 0, /* tp_members */
915 : 0, /* tp_getset */
916 : &PyIOBase_Type, /* tp_base */
917 : 0, /* tp_dict */
918 : 0, /* tp_descr_get */
919 : 0, /* tp_descr_set */
920 : 0, /* tp_dictoffset */
921 : 0, /* tp_init */
922 : 0, /* tp_alloc */
923 : 0, /* tp_new */
924 : };
|