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