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 "pycore_object.h"
14 #include <stddef.h> // offsetof()
15 #include "_iomodule.h"
16
17 /*[clinic input]
18 module _io
19 class _io._IOBase "PyObject *" "&PyIOBase_Type"
20 class _io._RawIOBase "PyObject *" "&PyRawIOBase_Type"
21 [clinic start generated code]*/
22 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d29a4d076c2b211c]*/
23
24 /*
25 * IOBase class, an abstract class
26 */
27
28 typedef struct {
29 PyObject_HEAD
30
31 PyObject *dict;
32 PyObject *weakreflist;
33 } iobase;
34
35 PyDoc_STRVAR(iobase_doc,
36 "The abstract base class for all I/O classes, acting on streams of\n"
37 "bytes. There is no public constructor.\n"
38 "\n"
39 "This class provides dummy implementations for many methods that\n"
40 "derived classes can override selectively; the default implementations\n"
41 "represent a file that cannot be read, written or seeked.\n"
42 "\n"
43 "Even though IOBase does not declare read, readinto, or write because\n"
44 "their signatures will vary, implementations and clients should\n"
45 "consider those methods part of the interface. Also, implementations\n"
46 "may raise UnsupportedOperation when operations they do not support are\n"
47 "called.\n"
48 "\n"
49 "The basic type used for binary data read from or written to a file is\n"
50 "bytes. Other bytes-like objects are accepted as method arguments too.\n"
51 "In some cases (such as readinto), a writable object is required. Text\n"
52 "I/O classes work with str data.\n"
53 "\n"
54 "Note that calling any method (except additional calls to close(),\n"
55 "which are ignored) on a closed stream should raise a ValueError.\n"
56 "\n"
57 "IOBase (and its subclasses) support the iterator protocol, meaning\n"
58 "that an IOBase object can be iterated over yielding the lines in a\n"
59 "stream.\n"
60 "\n"
61 "IOBase also supports the :keyword:`with` statement. In this example,\n"
62 "fp is closed after the suite of the with statement is complete:\n"
63 "\n"
64 "with open('spam.txt', 'r') as fp:\n"
65 " fp.write('Spam and eggs!')\n");
66
67 /* Use this macro whenever you want to check the internal `closed` status
68 of the IOBase object rather than the virtual `closed` attribute as returned
69 by whatever subclass. */
70
71 _Py_IDENTIFIER(__IOBase_closed);
72 _Py_IDENTIFIER(read);
73
74
75 /* Internal methods */
76 static PyObject *
iobase_unsupported(const char * message)77 iobase_unsupported(const char *message)
78 {
79 _PyIO_State *state = IO_STATE();
80 if (state != NULL)
81 PyErr_SetString(state->unsupported_operation, message);
82 return NULL;
83 }
84
85 /* Positioning */
86
87 PyDoc_STRVAR(iobase_seek_doc,
88 "Change stream position.\n"
89 "\n"
90 "Change the stream position to the given byte offset. The offset is\n"
91 "interpreted relative to the position indicated by whence. Values\n"
92 "for whence are:\n"
93 "\n"
94 "* 0 -- start of stream (the default); offset should be zero or positive\n"
95 "* 1 -- current stream position; offset may be negative\n"
96 "* 2 -- end of stream; offset is usually negative\n"
97 "\n"
98 "Return the new absolute position.");
99
100 static PyObject *
iobase_seek(PyObject * self,PyObject * args)101 iobase_seek(PyObject *self, PyObject *args)
102 {
103 return iobase_unsupported("seek");
104 }
105
106 /*[clinic input]
107 _io._IOBase.tell
108
109 Return current stream position.
110 [clinic start generated code]*/
111
112 static PyObject *
_io__IOBase_tell_impl(PyObject * self)113 _io__IOBase_tell_impl(PyObject *self)
114 /*[clinic end generated code: output=89a1c0807935abe2 input=04e615fec128801f]*/
115 {
116 _Py_IDENTIFIER(seek);
117
118 return _PyObject_CallMethodId(self, &PyId_seek, "ii", 0, 1);
119 }
120
121 PyDoc_STRVAR(iobase_truncate_doc,
122 "Truncate file to size bytes.\n"
123 "\n"
124 "File pointer is left unchanged. Size defaults to the current IO\n"
125 "position as reported by tell(). Returns the new size.");
126
127 static PyObject *
iobase_truncate(PyObject * self,PyObject * args)128 iobase_truncate(PyObject *self, PyObject *args)
129 {
130 return iobase_unsupported("truncate");
131 }
132
133 static int
iobase_is_closed(PyObject * self)134 iobase_is_closed(PyObject *self)
135 {
136 PyObject *res;
137 int ret;
138 /* This gets the derived attribute, which is *not* __IOBase_closed
139 in most cases! */
140 ret = _PyObject_LookupAttrId(self, &PyId___IOBase_closed, &res);
141 Py_XDECREF(res);
142 return ret;
143 }
144
145 /* Flush and close methods */
146
147 /*[clinic input]
148 _io._IOBase.flush
149
150 Flush write buffers, if applicable.
151
152 This is not implemented for read-only and non-blocking streams.
153 [clinic start generated code]*/
154
155 static PyObject *
_io__IOBase_flush_impl(PyObject * self)156 _io__IOBase_flush_impl(PyObject *self)
157 /*[clinic end generated code: output=7cef4b4d54656a3b input=773be121abe270aa]*/
158 {
159 /* XXX Should this return the number of bytes written??? */
160 int closed = iobase_is_closed(self);
161
162 if (!closed) {
163 Py_RETURN_NONE;
164 }
165 if (closed > 0) {
166 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
167 }
168 return NULL;
169 }
170
171 static PyObject *
iobase_closed_get(PyObject * self,void * context)172 iobase_closed_get(PyObject *self, void *context)
173 {
174 int closed = iobase_is_closed(self);
175 if (closed < 0) {
176 return NULL;
177 }
178 return PyBool_FromLong(closed);
179 }
180
181 static int
iobase_check_closed(PyObject * self)182 iobase_check_closed(PyObject *self)
183 {
184 PyObject *res;
185 int closed;
186 /* This gets the derived attribute, which is *not* __IOBase_closed
187 in most cases! */
188 closed = _PyObject_LookupAttr(self, _PyIO_str_closed, &res);
189 if (closed > 0) {
190 closed = PyObject_IsTrue(res);
191 Py_DECREF(res);
192 if (closed > 0) {
193 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
194 return -1;
195 }
196 }
197 return closed;
198 }
199
200 PyObject *
_PyIOBase_check_closed(PyObject * self,PyObject * args)201 _PyIOBase_check_closed(PyObject *self, PyObject *args)
202 {
203 if (iobase_check_closed(self)) {
204 return NULL;
205 }
206 if (args == Py_True) {
207 return Py_None;
208 }
209 Py_RETURN_NONE;
210 }
211
212 /* XXX: IOBase thinks it has to maintain its own internal state in
213 `__IOBase_closed` and call flush() by itself, but it is redundant with
214 whatever behaviour a non-trivial derived class will implement. */
215
216 /*[clinic input]
217 _io._IOBase.close
218
219 Flush and close the IO object.
220
221 This method has no effect if the file is already closed.
222 [clinic start generated code]*/
223
224 static PyObject *
_io__IOBase_close_impl(PyObject * self)225 _io__IOBase_close_impl(PyObject *self)
226 /*[clinic end generated code: output=63c6a6f57d783d6d input=f4494d5c31dbc6b7]*/
227 {
228 PyObject *res, *exc, *val, *tb;
229 int rc, closed = iobase_is_closed(self);
230
231 if (closed < 0) {
232 return NULL;
233 }
234 if (closed) {
235 Py_RETURN_NONE;
236 }
237
238 res = PyObject_CallMethodNoArgs(self, _PyIO_str_flush);
239
240 PyErr_Fetch(&exc, &val, &tb);
241 rc = _PyObject_SetAttrId(self, &PyId___IOBase_closed, Py_True);
242 _PyErr_ChainExceptions(exc, val, tb);
243 if (rc < 0) {
244 Py_CLEAR(res);
245 }
246
247 if (res == NULL)
248 return NULL;
249
250 Py_DECREF(res);
251 Py_RETURN_NONE;
252 }
253
254 /* Finalization and garbage collection support */
255
256 static void
iobase_finalize(PyObject * self)257 iobase_finalize(PyObject *self)
258 {
259 PyObject *res;
260 PyObject *error_type, *error_value, *error_traceback;
261 int closed;
262 _Py_IDENTIFIER(_finalizing);
263
264 /* Save the current exception, if any. */
265 PyErr_Fetch(&error_type, &error_value, &error_traceback);
266
267 /* If `closed` doesn't exist or can't be evaluated as bool, then the
268 object is probably in an unusable state, so ignore. */
269 if (_PyObject_LookupAttr(self, _PyIO_str_closed, &res) <= 0) {
270 PyErr_Clear();
271 closed = -1;
272 }
273 else {
274 closed = PyObject_IsTrue(res);
275 Py_DECREF(res);
276 if (closed == -1)
277 PyErr_Clear();
278 }
279 if (closed == 0) {
280 /* Signal close() that it was called as part of the object
281 finalization process. */
282 if (_PyObject_SetAttrId(self, &PyId__finalizing, Py_True))
283 PyErr_Clear();
284 res = PyObject_CallMethodNoArgs((PyObject *)self, _PyIO_str_close);
285 /* Silencing I/O errors is bad, but printing spurious tracebacks is
286 equally as bad, and potentially more frequent (because of
287 shutdown issues). */
288 if (res == NULL) {
289 #ifndef Py_DEBUG
290 if (_Py_GetConfig()->dev_mode) {
291 PyErr_WriteUnraisable(self);
292 }
293 else {
294 PyErr_Clear();
295 }
296 #else
297 PyErr_WriteUnraisable(self);
298 #endif
299 }
300 else {
301 Py_DECREF(res);
302 }
303 }
304
305 /* Restore the saved exception. */
306 PyErr_Restore(error_type, error_value, error_traceback);
307 }
308
309 int
_PyIOBase_finalize(PyObject * self)310 _PyIOBase_finalize(PyObject *self)
311 {
312 int is_zombie;
313
314 /* If _PyIOBase_finalize() is called from a destructor, we need to
315 resurrect the object as calling close() can invoke arbitrary code. */
316 is_zombie = (Py_REFCNT(self) == 0);
317 if (is_zombie)
318 return PyObject_CallFinalizerFromDealloc(self);
319 else {
320 PyObject_CallFinalizer(self);
321 return 0;
322 }
323 }
324
325 static int
iobase_traverse(iobase * self,visitproc visit,void * arg)326 iobase_traverse(iobase *self, visitproc visit, void *arg)
327 {
328 Py_VISIT(self->dict);
329 return 0;
330 }
331
332 static int
iobase_clear(iobase * self)333 iobase_clear(iobase *self)
334 {
335 Py_CLEAR(self->dict);
336 return 0;
337 }
338
339 /* Destructor */
340
341 static void
iobase_dealloc(iobase * self)342 iobase_dealloc(iobase *self)
343 {
344 /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
345 are still available here for close() to use.
346 However, if the derived class declares a __slots__, those slots are
347 already gone.
348 */
349 if (_PyIOBase_finalize((PyObject *) self) < 0) {
350 /* When called from a heap type's dealloc, the type will be
351 decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
352 if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
353 Py_INCREF(Py_TYPE(self));
354 return;
355 }
356 _PyObject_GC_UNTRACK(self);
357 if (self->weakreflist != NULL)
358 PyObject_ClearWeakRefs((PyObject *) self);
359 Py_CLEAR(self->dict);
360 Py_TYPE(self)->tp_free((PyObject *) self);
361 }
362
363 /* Inquiry methods */
364
365 /*[clinic input]
366 _io._IOBase.seekable
367
368 Return whether object supports random access.
369
370 If False, seek(), tell() and truncate() will raise OSError.
371 This method may need to do a test seek().
372 [clinic start generated code]*/
373
374 static PyObject *
_io__IOBase_seekable_impl(PyObject * self)375 _io__IOBase_seekable_impl(PyObject *self)
376 /*[clinic end generated code: output=4c24c67f5f32a43d input=b976622f7fdf3063]*/
377 {
378 Py_RETURN_FALSE;
379 }
380
381 PyObject *
_PyIOBase_check_seekable(PyObject * self,PyObject * args)382 _PyIOBase_check_seekable(PyObject *self, PyObject *args)
383 {
384 PyObject *res = PyObject_CallMethodNoArgs(self, _PyIO_str_seekable);
385 if (res == NULL)
386 return NULL;
387 if (res != Py_True) {
388 Py_CLEAR(res);
389 iobase_unsupported("File or stream is not seekable.");
390 return NULL;
391 }
392 if (args == Py_True) {
393 Py_DECREF(res);
394 }
395 return res;
396 }
397
398 /*[clinic input]
399 _io._IOBase.readable
400
401 Return whether object was opened for reading.
402
403 If False, read() will raise OSError.
404 [clinic start generated code]*/
405
406 static PyObject *
_io__IOBase_readable_impl(PyObject * self)407 _io__IOBase_readable_impl(PyObject *self)
408 /*[clinic end generated code: output=e48089250686388b input=285b3b866a0ec35f]*/
409 {
410 Py_RETURN_FALSE;
411 }
412
413 /* May be called with any object */
414 PyObject *
_PyIOBase_check_readable(PyObject * self,PyObject * args)415 _PyIOBase_check_readable(PyObject *self, PyObject *args)
416 {
417 PyObject *res = PyObject_CallMethodNoArgs(self, _PyIO_str_readable);
418 if (res == NULL)
419 return NULL;
420 if (res != Py_True) {
421 Py_CLEAR(res);
422 iobase_unsupported("File or stream is not readable.");
423 return NULL;
424 }
425 if (args == Py_True) {
426 Py_DECREF(res);
427 }
428 return res;
429 }
430
431 /*[clinic input]
432 _io._IOBase.writable
433
434 Return whether object was opened for writing.
435
436 If False, write() will raise OSError.
437 [clinic start generated code]*/
438
439 static PyObject *
_io__IOBase_writable_impl(PyObject * self)440 _io__IOBase_writable_impl(PyObject *self)
441 /*[clinic end generated code: output=406001d0985be14f input=9dcac18a013a05b5]*/
442 {
443 Py_RETURN_FALSE;
444 }
445
446 /* May be called with any object */
447 PyObject *
_PyIOBase_check_writable(PyObject * self,PyObject * args)448 _PyIOBase_check_writable(PyObject *self, PyObject *args)
449 {
450 PyObject *res = PyObject_CallMethodNoArgs(self, _PyIO_str_writable);
451 if (res == NULL)
452 return NULL;
453 if (res != Py_True) {
454 Py_CLEAR(res);
455 iobase_unsupported("File or stream is not writable.");
456 return NULL;
457 }
458 if (args == Py_True) {
459 Py_DECREF(res);
460 }
461 return res;
462 }
463
464 /* Context manager */
465
466 static PyObject *
iobase_enter(PyObject * self,PyObject * args)467 iobase_enter(PyObject *self, PyObject *args)
468 {
469 if (iobase_check_closed(self))
470 return NULL;
471
472 Py_INCREF(self);
473 return self;
474 }
475
476 static PyObject *
iobase_exit(PyObject * self,PyObject * args)477 iobase_exit(PyObject *self, PyObject *args)
478 {
479 return PyObject_CallMethodNoArgs(self, _PyIO_str_close);
480 }
481
482 /* Lower-level APIs */
483
484 /* XXX Should these be present even if unimplemented? */
485
486 /*[clinic input]
487 _io._IOBase.fileno
488
489 Returns underlying file descriptor if one exists.
490
491 OSError is raised if the IO object does not use a file descriptor.
492 [clinic start generated code]*/
493
494 static PyObject *
_io__IOBase_fileno_impl(PyObject * self)495 _io__IOBase_fileno_impl(PyObject *self)
496 /*[clinic end generated code: output=7cc0973f0f5f3b73 input=4e37028947dc1cc8]*/
497 {
498 return iobase_unsupported("fileno");
499 }
500
501 /*[clinic input]
502 _io._IOBase.isatty
503
504 Return whether this is an 'interactive' stream.
505
506 Return False if it can't be determined.
507 [clinic start generated code]*/
508
509 static PyObject *
_io__IOBase_isatty_impl(PyObject * self)510 _io__IOBase_isatty_impl(PyObject *self)
511 /*[clinic end generated code: output=60cab77cede41cdd input=9ef76530d368458b]*/
512 {
513 if (iobase_check_closed(self))
514 return NULL;
515 Py_RETURN_FALSE;
516 }
517
518 /* Readline(s) and writelines */
519
520 /*[clinic input]
521 _io._IOBase.readline
522 size as limit: Py_ssize_t(accept={int, NoneType}) = -1
523 /
524
525 Read and return a line from the stream.
526
527 If size is specified, at most size bytes will be read.
528
529 The line terminator is always b'\n' for binary files; for text
530 files, the newlines argument to open can be used to select the line
531 terminator(s) recognized.
532 [clinic start generated code]*/
533
534 static PyObject *
_io__IOBase_readline_impl(PyObject * self,Py_ssize_t limit)535 _io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
536 /*[clinic end generated code: output=4479f79b58187840 input=d0c596794e877bff]*/
537 {
538 /* For backwards compatibility, a (slowish) readline(). */
539
540 PyObject *peek, *buffer, *result;
541 Py_ssize_t old_size = -1;
542
543 if (_PyObject_LookupAttr(self, _PyIO_str_peek, &peek) < 0) {
544 return NULL;
545 }
546
547 buffer = PyByteArray_FromStringAndSize(NULL, 0);
548 if (buffer == NULL) {
549 Py_XDECREF(peek);
550 return NULL;
551 }
552
553 while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
554 Py_ssize_t nreadahead = 1;
555 PyObject *b;
556
557 if (peek != NULL) {
558 PyObject *readahead = PyObject_CallOneArg(peek, _PyLong_One);
559 if (readahead == NULL) {
560 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
561 when EINTR occurs so we needn't do it ourselves. */
562 if (_PyIO_trap_eintr()) {
563 continue;
564 }
565 goto fail;
566 }
567 if (!PyBytes_Check(readahead)) {
568 PyErr_Format(PyExc_OSError,
569 "peek() should have returned a bytes object, "
570 "not '%.200s'", Py_TYPE(readahead)->tp_name);
571 Py_DECREF(readahead);
572 goto fail;
573 }
574 if (PyBytes_GET_SIZE(readahead) > 0) {
575 Py_ssize_t n = 0;
576 const char *buf = PyBytes_AS_STRING(readahead);
577 if (limit >= 0) {
578 do {
579 if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
580 break;
581 if (buf[n++] == '\n')
582 break;
583 } while (1);
584 }
585 else {
586 do {
587 if (n >= PyBytes_GET_SIZE(readahead))
588 break;
589 if (buf[n++] == '\n')
590 break;
591 } while (1);
592 }
593 nreadahead = n;
594 }
595 Py_DECREF(readahead);
596 }
597
598 b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
599 if (b == NULL) {
600 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
601 when EINTR occurs so we needn't do it ourselves. */
602 if (_PyIO_trap_eintr()) {
603 continue;
604 }
605 goto fail;
606 }
607 if (!PyBytes_Check(b)) {
608 PyErr_Format(PyExc_OSError,
609 "read() should have returned a bytes object, "
610 "not '%.200s'", Py_TYPE(b)->tp_name);
611 Py_DECREF(b);
612 goto fail;
613 }
614 if (PyBytes_GET_SIZE(b) == 0) {
615 Py_DECREF(b);
616 break;
617 }
618
619 old_size = PyByteArray_GET_SIZE(buffer);
620 if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
621 Py_DECREF(b);
622 goto fail;
623 }
624 memcpy(PyByteArray_AS_STRING(buffer) + old_size,
625 PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
626
627 Py_DECREF(b);
628
629 if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
630 break;
631 }
632
633 result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
634 PyByteArray_GET_SIZE(buffer));
635 Py_XDECREF(peek);
636 Py_DECREF(buffer);
637 return result;
638 fail:
639 Py_XDECREF(peek);
640 Py_DECREF(buffer);
641 return NULL;
642 }
643
644 static PyObject *
iobase_iter(PyObject * self)645 iobase_iter(PyObject *self)
646 {
647 if (iobase_check_closed(self))
648 return NULL;
649
650 Py_INCREF(self);
651 return self;
652 }
653
654 static PyObject *
iobase_iternext(PyObject * self)655 iobase_iternext(PyObject *self)
656 {
657 PyObject *line = PyObject_CallMethodNoArgs(self, _PyIO_str_readline);
658
659 if (line == NULL)
660 return NULL;
661
662 if (PyObject_Size(line) <= 0) {
663 /* Error or empty */
664 Py_DECREF(line);
665 return NULL;
666 }
667
668 return line;
669 }
670
671 /*[clinic input]
672 _io._IOBase.readlines
673 hint: Py_ssize_t(accept={int, NoneType}) = -1
674 /
675
676 Return a list of lines from the stream.
677
678 hint can be specified to control the number of lines read: no more
679 lines will be read if the total size (in bytes/characters) of all
680 lines so far exceeds hint.
681 [clinic start generated code]*/
682
683 static PyObject *
_io__IOBase_readlines_impl(PyObject * self,Py_ssize_t hint)684 _io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint)
685 /*[clinic end generated code: output=2f50421677fa3dea input=9400c786ea9dc416]*/
686 {
687 Py_ssize_t length = 0;
688 PyObject *result, *it = NULL;
689
690 result = PyList_New(0);
691 if (result == NULL)
692 return NULL;
693
694 if (hint <= 0) {
695 /* XXX special-casing this made sense in the Python version in order
696 to remove the bytecode interpretation overhead, but it could
697 probably be removed here. */
698 _Py_IDENTIFIER(extend);
699 PyObject *ret = _PyObject_CallMethodIdObjArgs(result, &PyId_extend,
700 self, NULL);
701
702 if (ret == NULL) {
703 goto error;
704 }
705 Py_DECREF(ret);
706 return result;
707 }
708
709 it = PyObject_GetIter(self);
710 if (it == NULL) {
711 goto error;
712 }
713
714 while (1) {
715 Py_ssize_t line_length;
716 PyObject *line = PyIter_Next(it);
717 if (line == NULL) {
718 if (PyErr_Occurred()) {
719 goto error;
720 }
721 else
722 break; /* StopIteration raised */
723 }
724
725 if (PyList_Append(result, line) < 0) {
726 Py_DECREF(line);
727 goto error;
728 }
729 line_length = PyObject_Size(line);
730 Py_DECREF(line);
731 if (line_length < 0) {
732 goto error;
733 }
734 if (line_length > hint - length)
735 break;
736 length += line_length;
737 }
738
739 Py_DECREF(it);
740 return result;
741
742 error:
743 Py_XDECREF(it);
744 Py_DECREF(result);
745 return NULL;
746 }
747
748 /*[clinic input]
749 _io._IOBase.writelines
750 lines: object
751 /
752
753 Write a list of lines to stream.
754
755 Line separators are not added, so it is usual for each of the
756 lines provided to have a line separator at the end.
757 [clinic start generated code]*/
758
759 static PyObject *
_io__IOBase_writelines(PyObject * self,PyObject * lines)760 _io__IOBase_writelines(PyObject *self, PyObject *lines)
761 /*[clinic end generated code: output=976eb0a9b60a6628 input=cac3fc8864183359]*/
762 {
763 PyObject *iter, *res;
764
765 if (iobase_check_closed(self))
766 return NULL;
767
768 iter = PyObject_GetIter(lines);
769 if (iter == NULL)
770 return NULL;
771
772 while (1) {
773 PyObject *line = PyIter_Next(iter);
774 if (line == NULL) {
775 if (PyErr_Occurred()) {
776 Py_DECREF(iter);
777 return NULL;
778 }
779 else
780 break; /* Stop Iteration */
781 }
782
783 res = NULL;
784 do {
785 res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
786 } while (res == NULL && _PyIO_trap_eintr());
787 Py_DECREF(line);
788 if (res == NULL) {
789 Py_DECREF(iter);
790 return NULL;
791 }
792 Py_DECREF(res);
793 }
794 Py_DECREF(iter);
795 Py_RETURN_NONE;
796 }
797
798 #include "clinic/iobase.c.h"
799
800 static PyMethodDef iobase_methods[] = {
801 {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
802 _IO__IOBASE_TELL_METHODDEF
803 {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
804 _IO__IOBASE_FLUSH_METHODDEF
805 _IO__IOBASE_CLOSE_METHODDEF
806
807 _IO__IOBASE_SEEKABLE_METHODDEF
808 _IO__IOBASE_READABLE_METHODDEF
809 _IO__IOBASE_WRITABLE_METHODDEF
810
811 {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
812 {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
813 {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
814 {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
815
816 _IO__IOBASE_FILENO_METHODDEF
817 _IO__IOBASE_ISATTY_METHODDEF
818
819 {"__enter__", iobase_enter, METH_NOARGS},
820 {"__exit__", iobase_exit, METH_VARARGS},
821
822 _IO__IOBASE_READLINE_METHODDEF
823 _IO__IOBASE_READLINES_METHODDEF
824 _IO__IOBASE_WRITELINES_METHODDEF
825
826 {NULL, NULL}
827 };
828
829 static PyGetSetDef iobase_getset[] = {
830 {"__dict__", PyObject_GenericGetDict, NULL, NULL},
831 {"closed", (getter)iobase_closed_get, NULL, NULL},
832 {NULL}
833 };
834
835
836 PyTypeObject PyIOBase_Type = {
837 PyVarObject_HEAD_INIT(NULL, 0)
838 "_io._IOBase", /*tp_name*/
839 sizeof(iobase), /*tp_basicsize*/
840 0, /*tp_itemsize*/
841 (destructor)iobase_dealloc, /*tp_dealloc*/
842 0, /*tp_vectorcall_offset*/
843 0, /*tp_getattr*/
844 0, /*tp_setattr*/
845 0, /*tp_as_async*/
846 0, /*tp_repr*/
847 0, /*tp_as_number*/
848 0, /*tp_as_sequence*/
849 0, /*tp_as_mapping*/
850 0, /*tp_hash */
851 0, /*tp_call*/
852 0, /*tp_str*/
853 0, /*tp_getattro*/
854 0, /*tp_setattro*/
855 0, /*tp_as_buffer*/
856 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
857 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
858 iobase_doc, /* tp_doc */
859 (traverseproc)iobase_traverse, /* tp_traverse */
860 (inquiry)iobase_clear, /* tp_clear */
861 0, /* tp_richcompare */
862 offsetof(iobase, weakreflist), /* tp_weaklistoffset */
863 iobase_iter, /* tp_iter */
864 iobase_iternext, /* tp_iternext */
865 iobase_methods, /* tp_methods */
866 0, /* tp_members */
867 iobase_getset, /* tp_getset */
868 0, /* tp_base */
869 0, /* tp_dict */
870 0, /* tp_descr_get */
871 0, /* tp_descr_set */
872 offsetof(iobase, dict), /* tp_dictoffset */
873 0, /* tp_init */
874 0, /* tp_alloc */
875 PyType_GenericNew, /* tp_new */
876 0, /* tp_free */
877 0, /* tp_is_gc */
878 0, /* tp_bases */
879 0, /* tp_mro */
880 0, /* tp_cache */
881 0, /* tp_subclasses */
882 0, /* tp_weaklist */
883 0, /* tp_del */
884 0, /* tp_version_tag */
885 iobase_finalize, /* tp_finalize */
886 };
887
888
889 /*
890 * RawIOBase class, Inherits from IOBase.
891 */
892 PyDoc_STRVAR(rawiobase_doc,
893 "Base class for raw binary I/O.");
894
895 /*
896 * The read() method is implemented by calling readinto(); derived classes
897 * that want to support read() only need to implement readinto() as a
898 * primitive operation. In general, readinto() can be more efficient than
899 * read().
900 *
901 * (It would be tempting to also provide an implementation of readinto() in
902 * terms of read(), in case the latter is a more suitable primitive operation,
903 * but that would lead to nasty recursion in case a subclass doesn't implement
904 * either.)
905 */
906
907 /*[clinic input]
908 _io._RawIOBase.read
909 size as n: Py_ssize_t = -1
910 /
911 [clinic start generated code]*/
912
913 static PyObject *
_io__RawIOBase_read_impl(PyObject * self,Py_ssize_t n)914 _io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
915 /*[clinic end generated code: output=6cdeb731e3c9f13c input=b6d0dcf6417d1374]*/
916 {
917 PyObject *b, *res;
918
919 if (n < 0) {
920 _Py_IDENTIFIER(readall);
921
922 return _PyObject_CallMethodIdNoArgs(self, &PyId_readall);
923 }
924
925 /* TODO: allocate a bytes object directly instead and manually construct
926 a writable memoryview pointing to it. */
927 b = PyByteArray_FromStringAndSize(NULL, n);
928 if (b == NULL)
929 return NULL;
930
931 res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
932 if (res == NULL || res == Py_None) {
933 Py_DECREF(b);
934 return res;
935 }
936
937 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
938 Py_DECREF(res);
939 if (n == -1 && PyErr_Occurred()) {
940 Py_DECREF(b);
941 return NULL;
942 }
943
944 res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
945 Py_DECREF(b);
946 return res;
947 }
948
949
950 /*[clinic input]
951 _io._RawIOBase.readall
952
953 Read until EOF, using multiple read() call.
954 [clinic start generated code]*/
955
956 static PyObject *
_io__RawIOBase_readall_impl(PyObject * self)957 _io__RawIOBase_readall_impl(PyObject *self)
958 /*[clinic end generated code: output=1987b9ce929425a0 input=688874141213622a]*/
959 {
960 int r;
961 PyObject *chunks = PyList_New(0);
962 PyObject *result;
963
964 if (chunks == NULL)
965 return NULL;
966
967 while (1) {
968 PyObject *data = _PyObject_CallMethodId(self, &PyId_read,
969 "i", DEFAULT_BUFFER_SIZE);
970 if (!data) {
971 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
972 when EINTR occurs so we needn't do it ourselves. */
973 if (_PyIO_trap_eintr()) {
974 continue;
975 }
976 Py_DECREF(chunks);
977 return NULL;
978 }
979 if (data == Py_None) {
980 if (PyList_GET_SIZE(chunks) == 0) {
981 Py_DECREF(chunks);
982 return data;
983 }
984 Py_DECREF(data);
985 break;
986 }
987 if (!PyBytes_Check(data)) {
988 Py_DECREF(chunks);
989 Py_DECREF(data);
990 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
991 return NULL;
992 }
993 if (PyBytes_GET_SIZE(data) == 0) {
994 /* EOF */
995 Py_DECREF(data);
996 break;
997 }
998 r = PyList_Append(chunks, data);
999 Py_DECREF(data);
1000 if (r < 0) {
1001 Py_DECREF(chunks);
1002 return NULL;
1003 }
1004 }
1005 result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
1006 Py_DECREF(chunks);
1007 return result;
1008 }
1009
1010 static PyObject *
rawiobase_readinto(PyObject * self,PyObject * args)1011 rawiobase_readinto(PyObject *self, PyObject *args)
1012 {
1013 PyErr_SetNone(PyExc_NotImplementedError);
1014 return NULL;
1015 }
1016
1017 static PyObject *
rawiobase_write(PyObject * self,PyObject * args)1018 rawiobase_write(PyObject *self, PyObject *args)
1019 {
1020 PyErr_SetNone(PyExc_NotImplementedError);
1021 return NULL;
1022 }
1023
1024 static PyMethodDef rawiobase_methods[] = {
1025 _IO__RAWIOBASE_READ_METHODDEF
1026 _IO__RAWIOBASE_READALL_METHODDEF
1027 {"readinto", rawiobase_readinto, METH_VARARGS},
1028 {"write", rawiobase_write, METH_VARARGS},
1029 {NULL, NULL}
1030 };
1031
1032 PyTypeObject PyRawIOBase_Type = {
1033 PyVarObject_HEAD_INIT(NULL, 0)
1034 "_io._RawIOBase", /*tp_name*/
1035 0, /*tp_basicsize*/
1036 0, /*tp_itemsize*/
1037 0, /*tp_dealloc*/
1038 0, /*tp_vectorcall_offset*/
1039 0, /*tp_getattr*/
1040 0, /*tp_setattr*/
1041 0, /*tp_as_async*/
1042 0, /*tp_repr*/
1043 0, /*tp_as_number*/
1044 0, /*tp_as_sequence*/
1045 0, /*tp_as_mapping*/
1046 0, /*tp_hash */
1047 0, /*tp_call*/
1048 0, /*tp_str*/
1049 0, /*tp_getattro*/
1050 0, /*tp_setattro*/
1051 0, /*tp_as_buffer*/
1052 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1053 rawiobase_doc, /* tp_doc */
1054 0, /* tp_traverse */
1055 0, /* tp_clear */
1056 0, /* tp_richcompare */
1057 0, /* tp_weaklistoffset */
1058 0, /* tp_iter */
1059 0, /* tp_iternext */
1060 rawiobase_methods, /* tp_methods */
1061 0, /* tp_members */
1062 0, /* tp_getset */
1063 &PyIOBase_Type, /* tp_base */
1064 0, /* tp_dict */
1065 0, /* tp_descr_get */
1066 0, /* tp_descr_set */
1067 0, /* tp_dictoffset */
1068 0, /* tp_init */
1069 0, /* tp_alloc */
1070 0, /* tp_new */
1071 0, /* tp_free */
1072 0, /* tp_is_gc */
1073 0, /* tp_bases */
1074 0, /* tp_mro */
1075 0, /* tp_cache */
1076 0, /* tp_subclasses */
1077 0, /* tp_weaklist */
1078 0, /* tp_del */
1079 0, /* tp_version_tag */
1080 0, /* tp_finalize */
1081 };
1082