Debian Codegraph @

Modules/_io/iobase.c

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