Debian Codegraph @

Modules/_io/bufferedio.c

raw
1 /*
2 An implementation of Buffered I/O as defined by PEP 3116 - "New I/O"
3
4 Classes defined here: BufferedIOBase, BufferedReader, BufferedWriter,
5 BufferedRandom.
6
7 Written by Amaury Forgeot d'Arc and Antoine Pitrou
8 */
9
10 #include "Python.h"
11 #include "pycore_call.h" // _PyObject_CallNoArgs()
12 #include "pycore_object.h" // _PyObject_GC_UNTRACK()
13 #include "pycore_pyerrors.h" // _Py_FatalErrorFormat()
14 #include "pycore_pylifecycle.h" // _Py_IsInterpreterFinalizing()
15 #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
16
17 #include "_iomodule.h"
18
19 /*[clinic input]
20 module _io
21 class _io._BufferedIOBase "PyObject *" "clinic_state()->PyBufferedIOBase_Type"
22 class _io._Buffered "buffered *" "clinic_state()->PyBufferedIOBase_Type"
23 class _io.BufferedReader "buffered *" "clinic_state()->PyBufferedReader_Type"
24 class _io.BufferedWriter "buffered *" "clinic_state()->PyBufferedWriter_Type"
25 class _io.BufferedRWPair "rwpair *" "clinic_state()->PyBufferedRWPair_Type"
26 class _io.BufferedRandom "buffered *" "clinic_state()->PyBufferedRandom_Type"
27 [clinic start generated code]*/
28 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3b3ef9cbbbad4590]*/
29
30 /*
31 * BufferedIOBase class, inherits from IOBase.
32 */
33 PyDoc_STRVAR(bufferediobase_doc,
34 "Base class for buffered IO objects.\n"
35 "\n"
36 "The main difference with RawIOBase is that the read() method\n"
37 "supports omitting the size argument, and does not have a default\n"
38 "implementation that defers to readinto().\n"
39 "\n"
40 "In addition, read(), readinto() and write() may raise\n"
41 "BlockingIOError if the underlying raw stream is in non-blocking\n"
42 "mode and not ready; unlike their raw counterparts, they will never\n"
43 "return None.\n"
44 "\n"
45 "A typical implementation should not inherit from a RawIOBase\n"
46 "implementation, but wrap one.\n"
47 );
48
49 static PyObject *
50 _bufferediobase_readinto_generic(PyObject *self, Py_buffer *buffer, char readinto1)
51 {
52 Py_ssize_t len;
53 PyObject *data;
54
55 PyObject *attr = readinto1
56 ? &_Py_ID(read1)
57 : &_Py_ID(read);
58 data = _PyObject_CallMethod(self, attr, "n", buffer->len);
59 if (data == NULL)
60 return NULL;
61
62 if (!PyBytes_Check(data)) {
63 Py_DECREF(data);
64 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
65 return NULL;
66 }
67
68 len = PyBytes_GET_SIZE(data);
69 if (len > buffer->len) {
70 PyErr_Format(PyExc_ValueError,
71 "read() returned too much data: "
72 "%zd bytes requested, %zd returned",
73 buffer->len, len);
74 Py_DECREF(data);
75 return NULL;
76 }
77 memcpy(buffer->buf, PyBytes_AS_STRING(data), len);
78
79 Py_DECREF(data);
80
81 return PyLong_FromSsize_t(len);
82 }
83
84 /*[clinic input]
85 @critical_section
86 _io._BufferedIOBase.readinto
87 buffer: Py_buffer(accept={rwbuffer})
88 /
89 [clinic start generated code]*/
90
91 static PyObject *
92 _io__BufferedIOBase_readinto_impl(PyObject *self, Py_buffer *buffer)
93 /*[clinic end generated code: output=8c8cda6684af8038 input=5273d20db7f56e1a]*/
94 {
95 return _bufferediobase_readinto_generic(self, buffer, 0);
96 }
97
98 /*[clinic input]
99 @critical_section
100 _io._BufferedIOBase.readinto1
101 buffer: Py_buffer(accept={rwbuffer})
102 /
103 [clinic start generated code]*/
104
105 static PyObject *
106 _io__BufferedIOBase_readinto1_impl(PyObject *self, Py_buffer *buffer)
107 /*[clinic end generated code: output=358623e4fd2b69d3 input=d6eb723dedcee654]*/
108 {
109 return _bufferediobase_readinto_generic(self, buffer, 1);
110 }
111
112 static PyObject *
113 bufferediobase_unsupported(_PyIO_State *state, const char *message)
114 {
115 PyErr_SetString(state->unsupported_operation, message);
116 return NULL;
117 }
118
119 /*[clinic input]
120 _io._BufferedIOBase.detach
121
122 cls: defining_class
123 /
124
125 Disconnect this buffer from its underlying raw stream and return it.
126
127 After the raw stream has been detached, the buffer is in an unusable
128 state.
129 [clinic start generated code]*/
130
131 static PyObject *
132 _io__BufferedIOBase_detach_impl(PyObject *self, PyTypeObject *cls)
133 /*[clinic end generated code: output=b87b135d67cd4448 input=0b61a7b4357c1ea7]*/
134 {
135 _PyIO_State *state = get_io_state_by_cls(cls);
136 return bufferediobase_unsupported(state, "detach");
137 }
138
139 /*[clinic input]
140 _io._BufferedIOBase.read
141
142 cls: defining_class
143 size: int(unused=True) = -1
144 /
145
146 Read and return up to n bytes.
147
148 If the size argument is omitted, None, or negative, read and
149 return all data until EOF.
150
151 If the size argument is positive, and the underlying raw stream is
152 not 'interactive', multiple raw reads may be issued to satisfy
153 the byte count (unless EOF is reached first).
154 However, for interactive raw streams (as well as sockets and pipes),
155 at most one raw read will be issued, and a short result does not
156 imply that EOF is imminent.
157
158 Return an empty bytes object on EOF.
159
160 Return None if the underlying raw stream was open in non-blocking
161 mode and no data is available at the moment.
162 [clinic start generated code]*/
163
164 static PyObject *
165 _io__BufferedIOBase_read_impl(PyObject *self, PyTypeObject *cls,
166 int Py_UNUSED(size))
167 /*[clinic end generated code: output=aceb2765587b0a29 input=824f6f910465e61a]*/
168 {
169 _PyIO_State *state = get_io_state_by_cls(cls);
170 return bufferediobase_unsupported(state, "read");
171 }
172
173 /*[clinic input]
174 _io._BufferedIOBase.read1
175
176 cls: defining_class
177 size: int(unused=True) = -1
178 /
179
180 Read and return up to size bytes, with at most one read() call to the underlying raw stream.
181
182 Return an empty bytes object on EOF.
183 A short result does not imply that EOF is imminent.
184 [clinic start generated code]*/
185
186 static PyObject *
187 _io__BufferedIOBase_read1_impl(PyObject *self, PyTypeObject *cls,
188 int Py_UNUSED(size))
189 /*[clinic end generated code: output=2e7fc62972487eaa input=af76380e020fd9e6]*/
190 {
191 _PyIO_State *state = get_io_state_by_cls(cls);
192 return bufferediobase_unsupported(state, "read1");
193 }
194
195 /*[clinic input]
196 _io._BufferedIOBase.write
197
198 cls: defining_class
199 b: object(unused=True)
200 /
201
202 Write buffer b to the IO stream.
203
204 Return the number of bytes written, which is always
205 the length of b in bytes.
206
207 Raise BlockingIOError if the buffer is full and the
208 underlying raw stream cannot accept more data at the moment.
209 [clinic start generated code]*/
210
211 static PyObject *
212 _io__BufferedIOBase_write_impl(PyObject *self, PyTypeObject *cls,
213 PyObject *Py_UNUSED(b))
214 /*[clinic end generated code: output=712c635246bf2306 input=9793f5c8f71029ad]*/
215 {
216 _PyIO_State *state = get_io_state_by_cls(cls);
217 return bufferediobase_unsupported(state, "write");
218 }
219
220
221 typedef struct {
222 PyObject_HEAD
223
224 PyObject *raw;
225 int ok; /* Initialized? */
226 int detached;
227 int readable;
228 int writable;
229 char finalizing;
230
231 /* True if this is a vanilla Buffered object (rather than a user derived
232 class) *and* the raw stream is a vanilla FileIO object. */
233 int fast_closed_checks;
234
235 /* Absolute position inside the raw stream (-1 if unknown). */
236 Py_off_t abs_pos;
237
238 /* A static buffer of size `buffer_size` */
239 char *buffer;
240 /* Current logical position in the buffer. */
241 Py_off_t pos;
242 /* Position of the raw stream in the buffer. */
243 Py_off_t raw_pos;
244
245 /* Just after the last buffered byte in the buffer, or -1 if the buffer
246 isn't ready for reading. */
247 Py_off_t read_end;
248
249 /* Just after the last byte actually written */
250 Py_off_t write_pos;
251 /* Just after the last byte waiting to be written, or -1 if the buffer
252 isn't ready for writing. */
253 Py_off_t write_end;
254
255 PyThread_type_lock lock;
256 volatile unsigned long owner;
257
258 Py_ssize_t buffer_size;
259 Py_ssize_t buffer_mask;
260
261 PyObject *dict;
262 PyObject *weakreflist;
263 } buffered;
264
265 /*
266 Implementation notes:
267
268 * BufferedReader, BufferedWriter and BufferedRandom try to share most
269 methods (this is helped by the members `readable` and `writable`, which
270 are initialized in the respective constructors)
271 * They also share a single buffer for reading and writing. This enables
272 interleaved reads and writes without flushing. It also makes the logic
273 a bit trickier to get right.
274 * The absolute position of the raw stream is cached, if possible, in the
275 `abs_pos` member. It must be updated every time an operation is done
276 on the raw stream. If not sure, it can be reinitialized by calling
277 _buffered_raw_tell(), which queries the raw stream (_buffered_raw_seek()
278 also does it). To read it, use RAW_TELL().
279 * Three helpers, _bufferedreader_raw_read, _bufferedwriter_raw_write and
280 _bufferedwriter_flush_unlocked do a lot of useful housekeeping.
281
282 NOTE: we should try to maintain block alignment of reads and writes to the
283 raw stream (according to the buffer size), but for now it is only done
284 in read() and friends.
285
286 */
287
288 /* These macros protect the buffered object against concurrent operations. */
289
290 static int
291 _enter_buffered_busy(buffered *self)
292 {
293 int relax_locking;
294 PyLockStatus st;
295 if (self->owner == PyThread_get_thread_ident()) {
296 PyErr_Format(PyExc_RuntimeError,
297 "reentrant call inside %R", self);
298 return 0;
299 }
300 PyInterpreterState *interp = _PyInterpreterState_GET();
301 relax_locking = _Py_IsInterpreterFinalizing(interp);
302 Py_BEGIN_ALLOW_THREADS
303 if (!relax_locking)
304 st = PyThread_acquire_lock(self->lock, 1);
305 else {
306 /* When finalizing, we don't want a deadlock to happen with daemon
307 * threads abruptly shut down while they owned the lock.
308 * Therefore, only wait for a grace period (1 s.).
309 * Note that non-daemon threads have already exited here, so this
310 * shouldn't affect carefully written threaded I/O code.
311 */
312 st = PyThread_acquire_lock_timed(self->lock, (PY_TIMEOUT_T)1e6, 0);
313 }
314 Py_END_ALLOW_THREADS
315 if (relax_locking && st != PY_LOCK_ACQUIRED) {
316 PyObject *ascii = PyObject_ASCII((PyObject*)self);
317 _Py_FatalErrorFormat(__func__,
318 "could not acquire lock for %s at interpreter "
319 "shutdown, possibly due to daemon threads",
320 ascii ? PyUnicode_AsUTF8(ascii) : "<ascii(self) failed>");
321 }
322 return 1;
323 }
324
325 #define ENTER_BUFFERED(self) \
326 ( (PyThread_acquire_lock(self->lock, 0) ? \
327 1 : _enter_buffered_busy(self)) \
328 && (self->owner = PyThread_get_thread_ident(), 1) )
329
330 #define LEAVE_BUFFERED(self) \
331 do { \
332 self->owner = 0; \
333 PyThread_release_lock(self->lock); \
334 } while(0);
335
336 #define CHECK_INITIALIZED(self) \
337 if (self->ok <= 0) { \
338 if (self->detached) { \
339 PyErr_SetString(PyExc_ValueError, \
340 "raw stream has been detached"); \
341 } else { \
342 PyErr_SetString(PyExc_ValueError, \
343 "I/O operation on uninitialized object"); \
344 } \
345 return NULL; \
346 }
347
348 #define CHECK_INITIALIZED_INT(self) \
349 if (self->ok <= 0) { \
350 if (self->detached) { \
351 PyErr_SetString(PyExc_ValueError, \
352 "raw stream has been detached"); \
353 } else { \
354 PyErr_SetString(PyExc_ValueError, \
355 "I/O operation on uninitialized object"); \
356 } \
357 return -1; \
358 }
359
360 #define IS_CLOSED(self) \
361 (!self->buffer || \
362 (self->fast_closed_checks \
363 ? _PyFileIO_closed(self->raw) \
364 : buffered_closed(self)))
365
366 #define CHECK_CLOSED(self, error_msg) \
367 if (IS_CLOSED(self) && (Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t) == 0)) { \
368 PyErr_SetString(PyExc_ValueError, error_msg); \
369 return NULL; \
370 } \
371
372 #define VALID_READ_BUFFER(self) \
373 (self->readable && self->read_end != -1)
374
375 #define VALID_WRITE_BUFFER(self) \
376 (self->writable && self->write_end != -1)
377
378 #define ADJUST_POSITION(self, _new_pos) \
379 do { \
380 self->pos = _new_pos; \
381 if (VALID_READ_BUFFER(self) && self->read_end < self->pos) \
382 self->read_end = self->pos; \
383 } while(0)
384
385 #define READAHEAD(self) \
386 ((self->readable && VALID_READ_BUFFER(self)) \
387 ? (self->read_end - self->pos) : 0)
388
389 #define RAW_OFFSET(self) \
390 (((VALID_READ_BUFFER(self) || VALID_WRITE_BUFFER(self)) \
391 && self->raw_pos >= 0) ? self->raw_pos - self->pos : 0)
392
393 #define RAW_TELL(self) \
394 (self->abs_pos != -1 ? self->abs_pos : _buffered_raw_tell(self))
395
396 #define MINUS_LAST_BLOCK(self, size) \
397 (self->buffer_mask ? \
398 (size & ~self->buffer_mask) : \
399 (self->buffer_size * (size / self->buffer_size)))
400
401
402 static int
403 buffered_clear(buffered *self)
404 {
405 self->ok = 0;
406 Py_CLEAR(self->raw);
407 Py_CLEAR(self->dict);
408 return 0;
409 }
410
411 static void
412 buffered_dealloc(buffered *self)
413 {
414 PyTypeObject *tp = Py_TYPE(self);
415 self->finalizing = 1;
416 if (_PyIOBase_finalize((PyObject *) self) < 0)
417 return;
418 _PyObject_GC_UNTRACK(self);
419 self->ok = 0;
420 FT_CLEAR_WEAKREFS((PyObject*)self, self->weakreflist);
421 if (self->buffer) {
422 PyMem_Free(self->buffer);
423 self->buffer = NULL;
424 }
425 if (self->lock) {
426 PyThread_free_lock(self->lock);
427 self->lock = NULL;
428 }
429 (void)buffered_clear(self);
430 tp->tp_free((PyObject *)self);
431 Py_DECREF(tp);
432 }
433
434 /*[clinic input]
435 @critical_section
436 _io._Buffered.__sizeof__
437 [clinic start generated code]*/
438
439 static PyObject *
440 _io__Buffered___sizeof___impl(buffered *self)
441 /*[clinic end generated code: output=0231ef7f5053134e input=07a32d578073ea64]*/
442 {
443 size_t res = _PyObject_SIZE(Py_TYPE(self));
444 if (self->buffer) {
445 res += (size_t)self->buffer_size;
446 }
447 return PyLong_FromSize_t(res);
448 }
449
450 static int
451 buffered_traverse(buffered *self, visitproc visit, void *arg)
452 {
453 Py_VISIT(Py_TYPE(self));
454 Py_VISIT(self->raw);
455 Py_VISIT(self->dict);
456 return 0;
457 }
458
459 /* Because this can call arbitrary code, it shouldn't be called when
460 the refcount is 0 (that is, not directly from tp_dealloc unless
461 the refcount has been temporarily re-incremented). */
462 /*[clinic input]
463 _io._Buffered._dealloc_warn
464
465 source: object
466 /
467
468 [clinic start generated code]*/
469
470 static PyObject *
471 _io__Buffered__dealloc_warn(buffered *self, PyObject *source)
472 /*[clinic end generated code: output=690dcc3df8967162 input=8f845f2a4786391c]*/
473 {
474 if (self->ok && self->raw) {
475 PyObject *r;
476 r = PyObject_CallMethodOneArg(self->raw, &_Py_ID(_dealloc_warn), source);
477 if (r)
478 Py_DECREF(r);
479 else
480 PyErr_Clear();
481 }
482 Py_RETURN_NONE;
483 }
484
485 /*
486 * _BufferedIOMixin methods
487 * This is not a class, just a collection of methods that will be reused
488 * by BufferedReader and BufferedWriter
489 */
490
491 /* Flush and close */
492 /*[clinic input]
493 @critical_section
494 _io._Buffered.flush as _io__Buffered_simple_flush
495 [clinic start generated code]*/
496
497 static PyObject *
498 _io__Buffered_simple_flush_impl(buffered *self)
499 /*[clinic end generated code: output=29ebb3820db1bdfd input=5248cb84a65f80bd]*/
500 {
501 CHECK_INITIALIZED(self)
502 return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(flush));
503 }
504
505 static int
506 buffered_closed(buffered *self)
507 {
508 int closed;
509 PyObject *res;
510 CHECK_INITIALIZED_INT(self)
511 res = PyObject_GetAttr(self->raw, &_Py_ID(closed));
512 if (res == NULL)
513 return -1;
514 closed = PyObject_IsTrue(res);
515 Py_DECREF(res);
516 return closed;
517 }
518
519 /*[clinic input]
520 @critical_section
521 @getter
522 _io._Buffered.closed
523 [clinic start generated code]*/
524
525 static PyObject *
526 _io__Buffered_closed_get_impl(buffered *self)
527 /*[clinic end generated code: output=f08ce57290703a1a input=18eddefdfe4a3d2f]*/
528 {
529 CHECK_INITIALIZED(self)
530 return PyObject_GetAttr(self->raw, &_Py_ID(closed));
531 }
532
533 /*[clinic input]
534 @critical_section
535 _io._Buffered.close
536 [clinic start generated code]*/
537
538 static PyObject *
539 _io__Buffered_close_impl(buffered *self)
540 /*[clinic end generated code: output=7280b7b42033be0c input=56d95935b03fd326]*/
541 {
542 PyObject *res = NULL;
543 int r;
544
545 CHECK_INITIALIZED(self)
546 if (!ENTER_BUFFERED(self)) {
547 return NULL;
548 }
549
550 r = buffered_closed(self);
551 if (r < 0)
552 goto end;
553 if (r > 0) {
554 res = Py_NewRef(Py_None);
555 goto end;
556 }
557
558 if (self->finalizing) {
559 PyObject *r = _io__Buffered__dealloc_warn(self, (PyObject *) self);
560 if (r)
561 Py_DECREF(r);
562 else
563 PyErr_Clear();
564 }
565 /* flush() will most probably re-take the lock, so drop it first */
566 LEAVE_BUFFERED(self)
567 r = _PyFile_Flush((PyObject *)self);
568 if (!ENTER_BUFFERED(self)) {
569 return NULL;
570 }
571 PyObject *exc = NULL;
572 if (r < 0) {
573 exc = PyErr_GetRaisedException();
574 }
575
576 res = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(close));
577
578 if (self->buffer) {
579 PyMem_Free(self->buffer);
580 self->buffer = NULL;
581 }
582
583 if (exc != NULL) {
584 _PyErr_ChainExceptions1(exc);
585 Py_CLEAR(res);
586 }
587
588 self->read_end = 0;
589 self->pos = 0;
590
591 end:
592 LEAVE_BUFFERED(self)
593 return res;
594 }
595
596 /*[clinic input]
597 @critical_section
598 _io._Buffered.detach
599 [clinic start generated code]*/
600
601 static PyObject *
602 _io__Buffered_detach_impl(buffered *self)
603 /*[clinic end generated code: output=dd0fc057b8b779f7 input=d4ef1828a678be37]*/
604 {
605 PyObject *raw;
606 CHECK_INITIALIZED(self)
607 if (_PyFile_Flush((PyObject *)self) < 0) {
608 return NULL;
609 }
610 raw = self->raw;
611 self->raw = NULL;
612 self->detached = 1;
613 self->ok = 0;
614 return raw;
615 }
616
617 /* Inquiries */
618
619 /*[clinic input]
620 @critical_section
621 _io._Buffered.seekable
622 [clinic start generated code]*/
623
624 static PyObject *
625 _io__Buffered_seekable_impl(buffered *self)
626 /*[clinic end generated code: output=90172abb5ceb6e8f input=e3a4fc1d297b2fd3]*/
627 {
628 CHECK_INITIALIZED(self)
629 return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(seekable));
630 }
631
632 /*[clinic input]
633 @critical_section
634 _io._Buffered.readable
635 [clinic start generated code]*/
636
637 static PyObject *
638 _io__Buffered_readable_impl(buffered *self)
639 /*[clinic end generated code: output=92afa07661ecb698 input=abe54107d59bca9a]*/
640 {
641 CHECK_INITIALIZED(self)
642 return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(readable));
643 }
644
645 /*[clinic input]
646 @critical_section
647 _io._Buffered.writable
648 [clinic start generated code]*/
649
650 static PyObject *
651 _io__Buffered_writable_impl(buffered *self)
652 /*[clinic end generated code: output=4e3eee8d6f9d8552 input=45eb76bf6a10e6f7]*/
653 {
654 CHECK_INITIALIZED(self)
655 return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(writable));
656 }
657
658
659 /*[clinic input]
660 @critical_section
661 @getter
662 _io._Buffered.name
663 [clinic start generated code]*/
664
665 static PyObject *
666 _io__Buffered_name_get_impl(buffered *self)
667 /*[clinic end generated code: output=d2adf384051d3d10 input=6b84a0e6126f545e]*/
668 {
669 CHECK_INITIALIZED(self)
670 return PyObject_GetAttr(self->raw, &_Py_ID(name));
671 }
672
673 /*[clinic input]
674 @critical_section
675 @getter
676 _io._Buffered.mode
677 [clinic start generated code]*/
678
679 static PyObject *
680 _io__Buffered_mode_get_impl(buffered *self)
681 /*[clinic end generated code: output=0feb205748892fa4 input=0762d5e28542fd8c]*/
682 {
683 CHECK_INITIALIZED(self)
684 return PyObject_GetAttr(self->raw, &_Py_ID(mode));
685 }
686
687 /* Lower-level APIs */
688
689 /*[clinic input]
690 @critical_section
691 _io._Buffered.fileno
692 [clinic start generated code]*/
693
694 static PyObject *
695 _io__Buffered_fileno_impl(buffered *self)
696 /*[clinic end generated code: output=b717648d58a95ee3 input=1c4fead777bae20a]*/
697 {
698 CHECK_INITIALIZED(self)
699 return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(fileno));
700 }
701
702 /*[clinic input]
703 @critical_section
704 _io._Buffered.isatty
705 [clinic start generated code]*/
706
707 static PyObject *
708 _io__Buffered_isatty_impl(buffered *self)
709 /*[clinic end generated code: output=c20e55caae67baea input=e53d182d7e490e3a]*/
710 {
711 CHECK_INITIALIZED(self)
712 return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(isatty));
713 }
714
715 /* Forward decls */
716 static PyObject *
717 _bufferedwriter_flush_unlocked(buffered *);
718 static Py_ssize_t
719 _bufferedreader_fill_buffer(buffered *self);
720 static void
721 _bufferedreader_reset_buf(buffered *self);
722 static void
723 _bufferedwriter_reset_buf(buffered *self);
724 static PyObject *
725 _bufferedreader_peek_unlocked(buffered *self);
726 static PyObject *
727 _bufferedreader_read_all(buffered *self);
728 static PyObject *
729 _bufferedreader_read_fast(buffered *self, Py_ssize_t);
730 static PyObject *
731 _bufferedreader_read_generic(buffered *self, Py_ssize_t);
732 static Py_ssize_t
733 _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len);
734
735 /*
736 * Helpers
737 */
738
739 /* Sets the current error to BlockingIOError */
740 static void
741 _set_BlockingIOError(const char *msg, Py_ssize_t written)
742 {
743 PyObject *err;
744 PyErr_Clear();
745 err = PyObject_CallFunction(PyExc_BlockingIOError, "isn",
746 errno, msg, written);
747 if (err)
748 PyErr_SetObject(PyExc_BlockingIOError, err);
749 Py_XDECREF(err);
750 }
751
752 /* Returns the address of the `written` member if a BlockingIOError was
753 raised, NULL otherwise. The error is always re-raised. */
754 static Py_ssize_t *
755 _buffered_check_blocking_error(void)
756 {
757 PyObject *exc = PyErr_GetRaisedException();
758 if (exc == NULL || !PyErr_GivenExceptionMatches(exc, PyExc_BlockingIOError)) {
759 PyErr_SetRaisedException(exc);
760 return NULL;
761 }
762 PyOSErrorObject *err = (PyOSErrorObject *)exc;
763 /* TODO: sanity check (err->written >= 0) */
764 PyErr_SetRaisedException(exc);
765 return &err->written;
766 }
767
768 static Py_off_t
769 _buffered_raw_tell(buffered *self)
770 {
771 Py_off_t n;
772 PyObject *res;
773 res = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(tell));
774 if (res == NULL)
775 return -1;
776 n = PyNumber_AsOff_t(res, PyExc_ValueError);
777 Py_DECREF(res);
778 if (n < 0) {
779 if (!PyErr_Occurred())
780 PyErr_Format(PyExc_OSError,
781 "Raw stream returned invalid position %" PY_PRIdOFF,
782 (PY_OFF_T_COMPAT)n);
783 return -1;
784 }
785 self->abs_pos = n;
786 return n;
787 }
788
789 static Py_off_t
790 _buffered_raw_seek(buffered *self, Py_off_t target, int whence)
791 {
792 PyObject *res, *posobj, *whenceobj;
793 Py_off_t n;
794
795 posobj = PyLong_FromOff_t(target);
796 if (posobj == NULL)
797 return -1;
798 whenceobj = PyLong_FromLong(whence);
799 if (whenceobj == NULL) {
800 Py_DECREF(posobj);
801 return -1;
802 }
803 res = PyObject_CallMethodObjArgs(self->raw, &_Py_ID(seek),
804 posobj, whenceobj, NULL);
805 Py_DECREF(posobj);
806 Py_DECREF(whenceobj);
807 if (res == NULL)
808 return -1;
809 n = PyNumber_AsOff_t(res, PyExc_ValueError);
810 Py_DECREF(res);
811 if (n < 0) {
812 if (!PyErr_Occurred())
813 PyErr_Format(PyExc_OSError,
814 "Raw stream returned invalid position %" PY_PRIdOFF,
815 (PY_OFF_T_COMPAT)n);
816 return -1;
817 }
818 self->abs_pos = n;
819 return n;
820 }
821
822 static int
823 _buffered_init(buffered *self)
824 {
825 Py_ssize_t n;
826 if (self->buffer_size <= 0) {
827 PyErr_SetString(PyExc_ValueError,
828 "buffer size must be strictly positive");
829 return -1;
830 }
831 if (self->buffer)
832 PyMem_Free(self->buffer);
833 self->buffer = PyMem_Malloc(self->buffer_size);
834 if (self->buffer == NULL) {
835 PyErr_NoMemory();
836 return -1;
837 }
838 if (self->lock)
839 PyThread_free_lock(self->lock);
840 self->lock = PyThread_allocate_lock();
841 if (self->lock == NULL) {
842 PyErr_SetString(PyExc_RuntimeError, "can't allocate read lock");
843 return -1;
844 }
845 self->owner = 0;
846 /* Find out whether buffer_size is a power of 2 */
847 /* XXX is this optimization useful? */
848 for (n = self->buffer_size - 1; n & 1; n >>= 1)
849 ;
850 if (n == 0)
851 self->buffer_mask = self->buffer_size - 1;
852 else
853 self->buffer_mask = 0;
854 if (_buffered_raw_tell(self) == -1)
855 PyErr_Clear();
856 return 0;
857 }
858
859 /* Return 1 if an OSError with errno == EINTR is set (and then
860 clears the error indicator), 0 otherwise.
861 Should only be called when PyErr_Occurred() is true.
862 */
863 int
864 _PyIO_trap_eintr(void)
865 {
866 if (!PyErr_ExceptionMatches(PyExc_OSError)) {
867 return 0;
868 }
869 PyObject *exc = PyErr_GetRaisedException();
870 PyOSErrorObject *env_err = (PyOSErrorObject *)exc;
871 assert(env_err != NULL);
872 if (env_err->myerrno != NULL) {
873 assert(EINTR > 0 && EINTR < INT_MAX);
874 assert(PyLong_CheckExact(env_err->myerrno));
875 int overflow;
876 int myerrno = PyLong_AsLongAndOverflow(env_err->myerrno, &overflow);
877 PyErr_Clear();
878 if (myerrno == EINTR) {
879 Py_DECREF(exc);
880 return 1;
881 }
882 }
883 /* This silences any error set by PyObject_RichCompareBool() */
884 PyErr_SetRaisedException(exc);
885 return 0;
886 }
887
888 /*
889 * Shared methods and wrappers
890 */
891
892 static PyObject *
893 buffered_flush_and_rewind_unlocked(buffered *self)
894 {
895 PyObject *res;
896
897 res = _bufferedwriter_flush_unlocked(self);
898 if (res == NULL)
899 return NULL;
900 Py_DECREF(res);
901
902 if (self->readable) {
903 /* Rewind the raw stream so that its position corresponds to
904 the current logical position. */
905 Py_off_t n;
906 n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1);
907 _bufferedreader_reset_buf(self);
908 if (n == -1)
909 return NULL;
910 }
911 Py_RETURN_NONE;
912 }
913
914 /*[clinic input]
915 @critical_section
916 _io._Buffered.flush
917 [clinic start generated code]*/
918
919 static PyObject *
920 _io__Buffered_flush_impl(buffered *self)
921 /*[clinic end generated code: output=da2674ef1ce71f3a input=6b30de9f083419c2]*/
922 {
923 PyObject *res;
924
925 CHECK_INITIALIZED(self)
926 CHECK_CLOSED(self, "flush of closed file")
927
928 if (!ENTER_BUFFERED(self))
929 return NULL;
930 res = buffered_flush_and_rewind_unlocked(self);
931 LEAVE_BUFFERED(self)
932
933 return res;
934 }
935
936 /*[clinic input]
937 @critical_section
938 _io._Buffered.peek
939 size: Py_ssize_t = 0
940 /
941
942 [clinic start generated code]*/
943
944 static PyObject *
945 _io__Buffered_peek_impl(buffered *self, Py_ssize_t size)
946 /*[clinic end generated code: output=ba7a097ca230102b input=56733376f926d982]*/
947 {
948 PyObject *res = NULL;
949
950 CHECK_INITIALIZED(self)
951 CHECK_CLOSED(self, "peek of closed file")
952
953 if (!ENTER_BUFFERED(self))
954 return NULL;
955
956 if (self->writable) {
957 res = buffered_flush_and_rewind_unlocked(self);
958 if (res == NULL)
959 goto end;
960 Py_CLEAR(res);
961 }
962 res = _bufferedreader_peek_unlocked(self);
963
964 end:
965 LEAVE_BUFFERED(self)
966 return res;
967 }
968
969 /*[clinic input]
970 @critical_section
971 _io._Buffered.read
972 size as n: Py_ssize_t(accept={int, NoneType}) = -1
973 /
974 [clinic start generated code]*/
975
976 static PyObject *
977 _io__Buffered_read_impl(buffered *self, Py_ssize_t n)
978 /*[clinic end generated code: output=f41c78bb15b9bbe9 input=bdb4b0425b295472]*/
979 {
980 PyObject *res;
981
982 CHECK_INITIALIZED(self)
983 if (n < -1) {
984 PyErr_SetString(PyExc_ValueError,
985 "read length must be non-negative or -1");
986 return NULL;
987 }
988
989 CHECK_CLOSED(self, "read of closed file")
990
991 if (n == -1) {
992 /* The number of bytes is unspecified, read until the end of stream */
993 if (!ENTER_BUFFERED(self))
994 return NULL;
995 res = _bufferedreader_read_all(self);
996 }
997 else {
998 res = _bufferedreader_read_fast(self, n);
999 if (res != Py_None)
1000 return res;
1001 Py_DECREF(res);
1002 if (!ENTER_BUFFERED(self))
1003 return NULL;
1004 res = _bufferedreader_read_generic(self, n);
1005 }
1006
1007 LEAVE_BUFFERED(self)
1008 return res;
1009 }
1010
1011 /*[clinic input]
1012 @critical_section
1013 _io._Buffered.read1
1014 size as n: Py_ssize_t = -1
1015 /
1016 [clinic start generated code]*/
1017
1018 static PyObject *
1019 _io__Buffered_read1_impl(buffered *self, Py_ssize_t n)
1020 /*[clinic end generated code: output=bcc4fb4e54d103a3 input=3d0ad241aa52b36c]*/
1021 {
1022 Py_ssize_t have, r;
1023 PyObject *res = NULL;
1024
1025 CHECK_INITIALIZED(self)
1026 if (n < 0) {
1027 n = self->buffer_size;
1028 }
1029
1030 CHECK_CLOSED(self, "read of closed file")
1031
1032 if (n == 0)
1033 return PyBytes_FromStringAndSize(NULL, 0);
1034
1035 /* Return up to n bytes. If at least one byte is buffered, we
1036 only return buffered bytes. Otherwise, we do one raw read. */
1037
1038 have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
1039 if (have > 0) {
1040 n = Py_MIN(have, n);
1041 res = _bufferedreader_read_fast(self, n);
1042 assert(res != Py_None);
1043 return res;
1044 }
1045 res = PyBytes_FromStringAndSize(NULL, n);
1046 if (res == NULL)
1047 return NULL;
1048 if (!ENTER_BUFFERED(self)) {
1049 Py_DECREF(res);
1050 return NULL;
1051 }
1052 /* Flush the write buffer if necessary */
1053 if (self->writable) {
1054 PyObject *r = buffered_flush_and_rewind_unlocked(self);
1055 if (r == NULL) {
1056 LEAVE_BUFFERED(self)
1057 Py_DECREF(res);
1058 return NULL;
1059 }
1060 Py_DECREF(r);
1061 }
1062 _bufferedreader_reset_buf(self);
1063 r = _bufferedreader_raw_read(self, PyBytes_AS_STRING(res), n);
1064 LEAVE_BUFFERED(self)
1065 if (r == -1) {
1066 Py_DECREF(res);
1067 return NULL;
1068 }
1069 if (r == -2)
1070 r = 0;
1071 if (n > r)
1072 _PyBytes_Resize(&res, r);
1073 return res;
1074 }
1075
1076 static PyObject *
1077 _buffered_readinto_generic(buffered *self, Py_buffer *buffer, char readinto1)
1078 {
1079 Py_ssize_t n, written = 0, remaining;
1080 PyObject *res = NULL;
1081
1082 CHECK_INITIALIZED(self)
1083 CHECK_CLOSED(self, "readinto of closed file")
1084
1085 n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
1086 if (n > 0) {
1087 if (n >= buffer->len) {
1088 memcpy(buffer->buf, self->buffer + self->pos, buffer->len);
1089 self->pos += buffer->len;
1090 return PyLong_FromSsize_t(buffer->len);
1091 }
1092 memcpy(buffer->buf, self->buffer + self->pos, n);
1093 self->pos += n;
1094 written = n;
1095 }
1096
1097 if (!ENTER_BUFFERED(self))
1098 return NULL;
1099
1100 if (self->writable) {
1101 res = buffered_flush_and_rewind_unlocked(self);
1102 if (res == NULL)
1103 goto end;
1104 Py_CLEAR(res);
1105 }
1106
1107 _bufferedreader_reset_buf(self);
1108 self->pos = 0;
1109
1110 for (remaining = buffer->len - written;
1111 remaining > 0;
1112 written += n, remaining -= n) {
1113 /* If remaining bytes is larger than internal buffer size, copy
1114 * directly into caller's buffer. */
1115 if (remaining > self->buffer_size) {
1116 n = _bufferedreader_raw_read(self, (char *) buffer->buf + written,
1117 remaining);
1118 }
1119
1120 /* In readinto1 mode, we do not want to fill the internal
1121 buffer if we already have some data to return */
1122 else if (!(readinto1 && written)) {
1123 n = _bufferedreader_fill_buffer(self);
1124 if (n > 0) {
1125 if (n > remaining)
1126 n = remaining;
1127 memcpy((char *) buffer->buf + written,
1128 self->buffer + self->pos, n);
1129 self->pos += n;
1130 continue; /* short circuit */
1131 }
1132 }
1133 else
1134 n = 0;
1135
1136 if (n == 0 || (n == -2 && written > 0))
1137 break;
1138 if (n < 0) {
1139 if (n == -2) {
1140 res = Py_NewRef(Py_None);
1141 }
1142 goto end;
1143 }
1144
1145 /* At most one read in readinto1 mode */
1146 if (readinto1) {
1147 written += n;
1148 break;
1149 }
1150 }
1151 res = PyLong_FromSsize_t(written);
1152
1153 end:
1154 LEAVE_BUFFERED(self);
1155 return res;
1156 }
1157
1158 /*[clinic input]
1159 @critical_section
1160 _io._Buffered.readinto
1161 buffer: Py_buffer(accept={rwbuffer})
1162 /
1163 [clinic start generated code]*/
1164
1165 static PyObject *
1166 _io__Buffered_readinto_impl(buffered *self, Py_buffer *buffer)
1167 /*[clinic end generated code: output=bcb376580b1d8170 input=777c33e7adaa2bcd]*/
1168 {
1169 return _buffered_readinto_generic(self, buffer, 0);
1170 }
1171
1172 /*[clinic input]
1173 @critical_section
1174 _io._Buffered.readinto1
1175 buffer: Py_buffer(accept={rwbuffer})
1176 /
1177 [clinic start generated code]*/
1178
1179 static PyObject *
1180 _io__Buffered_readinto1_impl(buffered *self, Py_buffer *buffer)
1181 /*[clinic end generated code: output=6e5c6ac5868205d6 input=ef03cc5fc92a6895]*/
1182 {
1183 return _buffered_readinto_generic(self, buffer, 1);
1184 }
1185
1186
1187 static PyObject *
1188 _buffered_readline(buffered *self, Py_ssize_t limit)
1189 {
1190 PyObject *res = NULL;
1191 PyObject *chunks = NULL;
1192 Py_ssize_t n;
1193 const char *start, *s, *end;
1194
1195 CHECK_CLOSED(self, "readline of closed file")
1196
1197 /* First, try to find a line in the buffer. This can run unlocked because
1198 the calls to the C API are simple enough that they can't trigger
1199 any thread switch. */
1200 n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
1201 if (limit >= 0 && n > limit)
1202 n = limit;
1203 start = self->buffer + self->pos;
1204 s = memchr(start, '\n', n);
1205 if (s != NULL) {
1206 res = PyBytes_FromStringAndSize(start, s - start + 1);
1207 if (res != NULL)
1208 self->pos += s - start + 1;
1209 goto end_unlocked;
1210 }
1211 if (n == limit) {
1212 res = PyBytes_FromStringAndSize(start, n);
1213 if (res != NULL)
1214 self->pos += n;
1215 goto end_unlocked;
1216 }
1217
1218 if (!ENTER_BUFFERED(self))
1219 goto end_unlocked;
1220
1221 /* Now we try to get some more from the raw stream */
1222 chunks = PyList_New(0);
1223 if (chunks == NULL)
1224 goto end;
1225 if (n > 0) {
1226 res = PyBytes_FromStringAndSize(start, n);
1227 if (res == NULL)
1228 goto end;
1229 if (PyList_Append(chunks, res) < 0) {
1230 Py_CLEAR(res);
1231 goto end;
1232 }
1233 Py_CLEAR(res);
1234 self->pos += n;
1235 if (limit >= 0)
1236 limit -= n;
1237 }
1238 if (self->writable) {
1239 PyObject *r = buffered_flush_and_rewind_unlocked(self);
1240 if (r == NULL)
1241 goto end;
1242 Py_DECREF(r);
1243 }
1244
1245 for (;;) {
1246 _bufferedreader_reset_buf(self);
1247 n = _bufferedreader_fill_buffer(self);
1248 if (n == -1)
1249 goto end;
1250 if (n <= 0)
1251 break;
1252 if (limit >= 0 && n > limit)
1253 n = limit;
1254 start = self->buffer;
1255 end = start + n;
1256 s = start;
1257 while (s < end) {
1258 if (*s++ == '\n') {
1259 res = PyBytes_FromStringAndSize(start, s - start);
1260 if (res == NULL)
1261 goto end;
1262 self->pos = s - start;
1263 goto found;
1264 }
1265 }
1266 res = PyBytes_FromStringAndSize(start, n);
1267 if (res == NULL)
1268 goto end;
1269 if (n == limit) {
1270 self->pos = n;
1271 break;
1272 }
1273 if (PyList_Append(chunks, res) < 0) {
1274 Py_CLEAR(res);
1275 goto end;
1276 }
1277 Py_CLEAR(res);
1278 if (limit >= 0)
1279 limit -= n;
1280 }
1281 found:
1282 if (res != NULL && PyList_Append(chunks, res) < 0) {
1283 Py_CLEAR(res);
1284 goto end;
1285 }
1286 Py_XSETREF(res, _PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), chunks));
1287
1288 end:
1289 LEAVE_BUFFERED(self)
1290 end_unlocked:
1291 Py_XDECREF(chunks);
1292 return res;
1293 }
1294
1295 /*[clinic input]
1296 @critical_section
1297 _io._Buffered.readline
1298 size: Py_ssize_t(accept={int, NoneType}) = -1
1299 /
1300 [clinic start generated code]*/
1301
1302 static PyObject *
1303 _io__Buffered_readline_impl(buffered *self, Py_ssize_t size)
1304 /*[clinic end generated code: output=24dd2aa6e33be83c input=e81ca5abd4280776]*/
1305 {
1306 CHECK_INITIALIZED(self)
1307 return _buffered_readline(self, size);
1308 }
1309
1310
1311 /*[clinic input]
1312 @critical_section
1313 _io._Buffered.tell
1314 [clinic start generated code]*/
1315
1316 static PyObject *
1317 _io__Buffered_tell_impl(buffered *self)
1318 /*[clinic end generated code: output=386972ae84716c1e input=ab12e67d8abcb42f]*/
1319 {
1320 Py_off_t pos;
1321
1322 CHECK_INITIALIZED(self)
1323 pos = _buffered_raw_tell(self);
1324 if (pos == -1)
1325 return NULL;
1326 pos -= RAW_OFFSET(self);
1327
1328 // GH-95782
1329 if (pos < 0)
1330 pos = 0;
1331
1332 return PyLong_FromOff_t(pos);
1333 }
1334
1335 /*[clinic input]
1336 @critical_section
1337 _io._Buffered.seek
1338 target as targetobj: object
1339 whence: int = 0
1340 /
1341 [clinic start generated code]*/
1342
1343 static PyObject *
1344 _io__Buffered_seek_impl(buffered *self, PyObject *targetobj, int whence)
1345 /*[clinic end generated code: output=7ae0e8dc46efdefb input=b5a12be70e0ad07b]*/
1346 {
1347 Py_off_t target, n;
1348 PyObject *res = NULL;
1349
1350 CHECK_INITIALIZED(self)
1351
1352 /* Do some error checking instead of trusting OS 'seek()'
1353 ** error detection, just in case.
1354 */
1355 if ((whence < 0 || whence >2)
1356 #ifdef SEEK_HOLE
1357 && (whence != SEEK_HOLE)
1358 #endif
1359 #ifdef SEEK_DATA
1360 && (whence != SEEK_DATA)
1361 #endif
1362 ) {
1363 PyErr_Format(PyExc_ValueError,
1364 "whence value %d unsupported", whence);
1365 return NULL;
1366 }
1367
1368 CHECK_CLOSED(self, "seek of closed file")
1369
1370 _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
1371 if (_PyIOBase_check_seekable(state, self->raw, Py_True) == NULL) {
1372 return NULL;
1373 }
1374
1375 target = PyNumber_AsOff_t(targetobj, PyExc_ValueError);
1376 if (target == -1 && PyErr_Occurred())
1377 return NULL;
1378
1379 /* SEEK_SET and SEEK_CUR are special because we could seek inside the
1380 buffer. Other whence values must be managed without this optimization.
1381 Some Operating Systems can provide additional values, like
1382 SEEK_HOLE/SEEK_DATA. */
1383 if (((whence == 0) || (whence == 1)) && self->readable) {
1384 Py_off_t current, avail;
1385 /* Check if seeking leaves us inside the current buffer,
1386 so as to return quickly if possible. Also, we needn't take the
1387 lock in this fast path.
1388 Don't know how to do that when whence == 2, though. */
1389 /* NOTE: RAW_TELL() can release the GIL but the object is in a stable
1390 state at this point. */
1391 current = RAW_TELL(self);
1392 avail = READAHEAD(self);
1393 if (avail > 0) {
1394 Py_off_t offset;
1395 if (whence == 0)
1396 offset = target - (current - RAW_OFFSET(self));
1397 else
1398 offset = target;
1399 if (offset >= -self->pos && offset <= avail) {
1400 self->pos += offset;
1401
1402 // GH-95782
1403 if (current - avail + offset < 0)
1404 return PyLong_FromOff_t(0);
1405
1406 return PyLong_FromOff_t(current - avail + offset);
1407 }
1408 }
1409 }
1410
1411 if (!ENTER_BUFFERED(self))
1412 return NULL;
1413
1414 /* Fallback: invoke raw seek() method and clear buffer */
1415 if (self->writable) {
1416 res = _bufferedwriter_flush_unlocked(self);
1417 if (res == NULL)
1418 goto end;
1419 Py_CLEAR(res);
1420 }
1421
1422 /* TODO: align on block boundary and read buffer if needed? */
1423 if (whence == 1)
1424 target -= RAW_OFFSET(self);
1425 n = _buffered_raw_seek(self, target, whence);
1426 if (n == -1)
1427 goto end;
1428 self->raw_pos = -1;
1429 res = PyLong_FromOff_t(n);
1430 if (res != NULL && self->readable)
1431 _bufferedreader_reset_buf(self);
1432
1433 end:
1434 LEAVE_BUFFERED(self)
1435 return res;
1436 }
1437
1438 /*[clinic input]
1439 @critical_section
1440 _io._Buffered.truncate
1441 cls: defining_class
1442 pos: object = None
1443 /
1444 [clinic start generated code]*/
1445
1446 static PyObject *
1447 _io__Buffered_truncate_impl(buffered *self, PyTypeObject *cls, PyObject *pos)
1448 /*[clinic end generated code: output=fe3882fbffe79f1a input=e3cbf794575bd794]*/
1449 {
1450 PyObject *res = NULL;
1451
1452 CHECK_INITIALIZED(self)
1453 CHECK_CLOSED(self, "truncate of closed file")
1454 if (!self->writable) {
1455 _PyIO_State *state = get_io_state_by_cls(cls);
1456 return bufferediobase_unsupported(state, "truncate");
1457 }
1458 if (!ENTER_BUFFERED(self))
1459 return NULL;
1460
1461 res = buffered_flush_and_rewind_unlocked(self);
1462 if (res == NULL) {
1463 goto end;
1464 }
1465 Py_CLEAR(res);
1466
1467 res = PyObject_CallMethodOneArg(self->raw, &_Py_ID(truncate), pos);
1468 if (res == NULL)
1469 goto end;
1470 /* Reset cached position */
1471 if (_buffered_raw_tell(self) == -1)
1472 PyErr_Clear();
1473
1474 end:
1475 LEAVE_BUFFERED(self)
1476 return res;
1477 }
1478
1479 static PyObject *
1480 buffered_iternext(buffered *self)
1481 {
1482 PyObject *line;
1483 PyTypeObject *tp;
1484
1485 CHECK_INITIALIZED(self);
1486
1487 _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
1488 tp = Py_TYPE(self);
1489 if (tp == state->PyBufferedReader_Type ||
1490 tp == state->PyBufferedRandom_Type)
1491 {
1492 /* Skip method call overhead for speed */
1493 line = _buffered_readline(self, -1);
1494 }
1495 else {
1496 line = PyObject_CallMethodNoArgs((PyObject *)self,
1497 &_Py_ID(readline));
1498 if (line && !PyBytes_Check(line)) {
1499 PyErr_Format(PyExc_OSError,
1500 "readline() should have returned a bytes object, "
1501 "not '%.200s'", Py_TYPE(line)->tp_name);
1502 Py_DECREF(line);
1503 return NULL;
1504 }
1505 }
1506
1507 if (line == NULL)
1508 return NULL;
1509
1510 if (PyBytes_GET_SIZE(line) == 0) {
1511 /* Reached EOF or would have blocked */
1512 Py_DECREF(line);
1513 return NULL;
1514 }
1515
1516 return line;
1517 }
1518
1519 static PyObject *
1520 buffered_repr(buffered *self)
1521 {
1522 PyObject *nameobj, *res;
1523
1524 if (PyObject_GetOptionalAttr((PyObject *) self, &_Py_ID(name), &nameobj) < 0) {
1525 if (!PyErr_ExceptionMatches(PyExc_ValueError)) {
1526 return NULL;
1527 }
1528 /* Ignore ValueError raised if the underlying stream was detached */
1529 PyErr_Clear();
1530 }
1531 if (nameobj == NULL) {
1532 res = PyUnicode_FromFormat("<%s>", Py_TYPE(self)->tp_name);
1533 }
1534 else {
1535 int status = Py_ReprEnter((PyObject *)self);
1536 res = NULL;
1537 if (status == 0) {
1538 res = PyUnicode_FromFormat("<%s name=%R>",
1539 Py_TYPE(self)->tp_name, nameobj);
1540 Py_ReprLeave((PyObject *)self);
1541 }
1542 else if (status > 0) {
1543 PyErr_Format(PyExc_RuntimeError,
1544 "reentrant call inside %s.__repr__",
1545 Py_TYPE(self)->tp_name);
1546 }
1547 Py_DECREF(nameobj);
1548 }
1549 return res;
1550 }
1551
1552 /*
1553 * class BufferedReader
1554 */
1555
1556 static void _bufferedreader_reset_buf(buffered *self)
1557 {
1558 self->read_end = -1;
1559 }
1560
1561 /*[clinic input]
1562 _io.BufferedReader.__init__
1563 raw: object
1564 buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
1565
1566 Create a new buffered reader using the given readable raw IO object.
1567 [clinic start generated code]*/
1568
1569 static int
1570 _io_BufferedReader___init___impl(buffered *self, PyObject *raw,
1571 Py_ssize_t buffer_size)
1572 /*[clinic end generated code: output=cddcfefa0ed294c4 input=fb887e06f11b4e48]*/
1573 {
1574 self->ok = 0;
1575 self->detached = 0;
1576
1577 _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
1578 if (_PyIOBase_check_readable(state, raw, Py_True) == NULL) {
1579 return -1;
1580 }
1581
1582 Py_XSETREF(self->raw, Py_NewRef(raw));
1583 self->buffer_size = buffer_size;
1584 self->readable = 1;
1585 self->writable = 0;
1586
1587 if (_buffered_init(self) < 0)
1588 return -1;
1589 _bufferedreader_reset_buf(self);
1590
1591 self->fast_closed_checks = (
1592 Py_IS_TYPE(self, state->PyBufferedReader_Type) &&
1593 Py_IS_TYPE(raw, state->PyFileIO_Type)
1594 );
1595
1596 self->ok = 1;
1597 return 0;
1598 }
1599
1600 static Py_ssize_t
1601 _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len)
1602 {
1603 Py_buffer buf;
1604 PyObject *memobj, *res;
1605 Py_ssize_t n;
1606 /* NOTE: the buffer needn't be released as its object is NULL. */
1607 if (PyBuffer_FillInfo(&buf, NULL, start, len, 0, PyBUF_CONTIG) == -1)
1608 return -1;
1609 memobj = PyMemoryView_FromBuffer(&buf);
1610 if (memobj == NULL)
1611 return -1;
1612 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR
1613 occurs so we needn't do it ourselves.
1614 We then retry reading, ignoring the signal if no handler has
1615 raised (see issue #10956).
1616 */
1617 do {
1618 res = PyObject_CallMethodOneArg(self->raw, &_Py_ID(readinto), memobj);
1619 } while (res == NULL && _PyIO_trap_eintr());
1620 Py_DECREF(memobj);
1621 if (res == NULL)
1622 return -1;
1623 if (res == Py_None) {
1624 /* Non-blocking stream would have blocked. Special return code! */
1625 Py_DECREF(res);
1626 return -2;
1627 }
1628 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
1629 Py_DECREF(res);
1630
1631 if (n == -1 && PyErr_Occurred()) {
1632 _PyErr_FormatFromCause(
1633 PyExc_OSError,
1634 "raw readinto() failed"
1635 );
1636 return -1;
1637 }
1638
1639 if (n < 0 || n > len) {
1640 PyErr_Format(PyExc_OSError,
1641 "raw readinto() returned invalid length %zd "
1642 "(should have been between 0 and %zd)", n, len);
1643 return -1;
1644 }
1645 if (n > 0 && self->abs_pos != -1)
1646 self->abs_pos += n;
1647 return n;
1648 }
1649
1650 static Py_ssize_t
1651 _bufferedreader_fill_buffer(buffered *self)
1652 {
1653 Py_ssize_t start, len, n;
1654 if (VALID_READ_BUFFER(self))
1655 start = Py_SAFE_DOWNCAST(self->read_end, Py_off_t, Py_ssize_t);
1656 else
1657 start = 0;
1658 len = self->buffer_size - start;
1659 n = _bufferedreader_raw_read(self, self->buffer + start, len);
1660 if (n <= 0)
1661 return n;
1662 self->read_end = start + n;
1663 self->raw_pos = start + n;
1664 return n;
1665 }
1666
1667 static PyObject *
1668 _bufferedreader_read_all(buffered *self)
1669 {
1670 Py_ssize_t current_size;
1671 PyObject *res = NULL, *data = NULL, *tmp = NULL, *chunks = NULL, *readall;
1672
1673 /* First copy what we have in the current buffer. */
1674 current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
1675 if (current_size) {
1676 data = PyBytes_FromStringAndSize(
1677 self->buffer + self->pos, current_size);
1678 if (data == NULL)
1679 return NULL;
1680 self->pos += current_size;
1681 }
1682 /* We're going past the buffer's bounds, flush it */
1683 if (self->writable) {
1684 tmp = buffered_flush_and_rewind_unlocked(self);
1685 if (tmp == NULL)
1686 goto cleanup;
1687 Py_CLEAR(tmp);
1688 }
1689 _bufferedreader_reset_buf(self);
1690
1691 if (PyObject_GetOptionalAttr(self->raw, &_Py_ID(readall), &readall) < 0) {
1692 goto cleanup;
1693 }
1694 if (readall) {
1695 tmp = _PyObject_CallNoArgs(readall);
1696 Py_DECREF(readall);
1697 if (tmp == NULL)
1698 goto cleanup;
1699 if (tmp != Py_None && !PyBytes_Check(tmp)) {
1700 PyErr_SetString(PyExc_TypeError, "readall() should return bytes");
1701 goto cleanup;
1702 }
1703 if (current_size == 0) {
1704 res = tmp;
1705 } else {
1706 if (tmp != Py_None) {
1707 PyBytes_Concat(&data, tmp);
1708 }
1709 res = data;
1710 }
1711 goto cleanup;
1712 }
1713
1714 chunks = PyList_New(0);
1715 if (chunks == NULL)
1716 goto cleanup;
1717
1718 while (1) {
1719 if (data) {
1720 if (PyList_Append(chunks, data) < 0)
1721 goto cleanup;
1722 Py_CLEAR(data);
1723 }
1724
1725 /* Read until EOF or until read() would block. */
1726 data = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(read));
1727 if (data == NULL)
1728 goto cleanup;
1729 if (data != Py_None && !PyBytes_Check(data)) {
1730 PyErr_SetString(PyExc_TypeError, "read() should return bytes");
1731 goto cleanup;
1732 }
1733 if (data == Py_None || PyBytes_GET_SIZE(data) == 0) {
1734 if (current_size == 0) {
1735 res = data;
1736 goto cleanup;
1737 }
1738 else {
1739 tmp = _PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), chunks);
1740 res = tmp;
1741 goto cleanup;
1742 }
1743 }
1744 current_size += PyBytes_GET_SIZE(data);
1745 if (self->abs_pos != -1)
1746 self->abs_pos += PyBytes_GET_SIZE(data);
1747 }
1748 cleanup:
1749 /* res is either NULL or a borrowed ref */
1750 Py_XINCREF(res);
1751 Py_XDECREF(data);
1752 Py_XDECREF(tmp);
1753 Py_XDECREF(chunks);
1754 return res;
1755 }
1756
1757 /* Read n bytes from the buffer if it can, otherwise return None.
1758 This function is simple enough that it can run unlocked. */
1759 static PyObject *
1760 _bufferedreader_read_fast(buffered *self, Py_ssize_t n)
1761 {
1762 Py_ssize_t current_size;
1763
1764 current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
1765 if (n <= current_size) {
1766 /* Fast path: the data to read is fully buffered. */
1767 PyObject *res = PyBytes_FromStringAndSize(self->buffer + self->pos, n);
1768 if (res != NULL)
1769 self->pos += n;
1770 return res;
1771 }
1772 Py_RETURN_NONE;
1773 }
1774
1775 /* Generic read function: read from the stream until enough bytes are read,
1776 * or until an EOF occurs or until read() would block.
1777 */
1778 static PyObject *
1779 _bufferedreader_read_generic(buffered *self, Py_ssize_t n)
1780 {
1781 PyObject *res = NULL;
1782 Py_ssize_t current_size, remaining, written;
1783 char *out;
1784
1785 current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
1786 if (n <= current_size)
1787 return _bufferedreader_read_fast(self, n);
1788
1789 res = PyBytes_FromStringAndSize(NULL, n);
1790 if (res == NULL)
1791 goto error;
1792 out = PyBytes_AS_STRING(res);
1793 remaining = n;
1794 written = 0;
1795 if (current_size > 0) {
1796 memcpy(out, self->buffer + self->pos, current_size);
1797 remaining -= current_size;
1798 written += current_size;
1799 self->pos += current_size;
1800 }
1801 /* Flush the write buffer if necessary */
1802 if (self->writable) {
1803 PyObject *r = buffered_flush_and_rewind_unlocked(self);
1804 if (r == NULL)
1805 goto error;
1806 Py_DECREF(r);
1807 }
1808 _bufferedreader_reset_buf(self);
1809 while (remaining > 0) {
1810 /* We want to read a whole block at the end into buffer.
1811 If we had readv() we could do this in one pass. */
1812 Py_ssize_t r = MINUS_LAST_BLOCK(self, remaining);
1813 if (r == 0)
1814 break;
1815 r = _bufferedreader_raw_read(self, out + written, r);
1816 if (r == -1)
1817 goto error;
1818 if (r == 0 || r == -2) {
1819 /* EOF occurred or read() would block. */
1820 if (r == 0 || written > 0) {
1821 if (_PyBytes_Resize(&res, written))
1822 goto error;
1823 return res;
1824 }
1825 Py_DECREF(res);
1826 Py_RETURN_NONE;
1827 }
1828 remaining -= r;
1829 written += r;
1830 }
1831 assert(remaining <= self->buffer_size);
1832 self->pos = 0;
1833 self->raw_pos = 0;
1834 self->read_end = 0;
1835 /* NOTE: when the read is satisfied, we avoid issuing any additional
1836 reads, which could block indefinitely (e.g. on a socket).
1837 See issue #9550. */
1838 while (remaining > 0 && self->read_end < self->buffer_size) {
1839 Py_ssize_t r = _bufferedreader_fill_buffer(self);
1840 if (r == -1)
1841 goto error;
1842 if (r == 0 || r == -2) {
1843 /* EOF occurred or read() would block. */
1844 if (r == 0 || written > 0) {
1845 if (_PyBytes_Resize(&res, written))
1846 goto error;
1847 return res;
1848 }
1849 Py_DECREF(res);
1850 Py_RETURN_NONE;
1851 }
1852 if (remaining > r) {
1853 memcpy(out + written, self->buffer + self->pos, r);
1854 written += r;
1855 self->pos += r;
1856 remaining -= r;
1857 }
1858 else if (remaining > 0) {
1859 memcpy(out + written, self->buffer + self->pos, remaining);
1860 written += remaining;
1861 self->pos += remaining;
1862 remaining = 0;
1863 }
1864 if (remaining == 0)
1865 break;
1866 }
1867
1868 return res;
1869
1870 error:
1871 Py_XDECREF(res);
1872 return NULL;
1873 }
1874
1875 static PyObject *
1876 _bufferedreader_peek_unlocked(buffered *self)
1877 {
1878 Py_ssize_t have, r;
1879
1880 have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
1881 /* Constraints:
1882 1. we don't want to advance the file position.
1883 2. we don't want to lose block alignment, so we can't shift the buffer
1884 to make some place.
1885 Therefore, we either return `have` bytes (if > 0), or a full buffer.
1886 */
1887 if (have > 0) {
1888 return PyBytes_FromStringAndSize(self->buffer + self->pos, have);
1889 }
1890
1891 /* Fill the buffer from the raw stream, and copy it to the result. */
1892 _bufferedreader_reset_buf(self);
1893 r = _bufferedreader_fill_buffer(self);
1894 if (r == -1)
1895 return NULL;
1896 if (r == -2)
1897 r = 0;
1898 self->pos = 0;
1899 return PyBytes_FromStringAndSize(self->buffer, r);
1900 }
1901
1902
1903 /*
1904 * class BufferedWriter
1905 */
1906 static void
1907 _bufferedwriter_reset_buf(buffered *self)
1908 {
1909 self->write_pos = 0;
1910 self->write_end = -1;
1911 }
1912
1913 /*[clinic input]
1914 _io.BufferedWriter.__init__
1915 raw: object
1916 buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
1917
1918 A buffer for a writeable sequential RawIO object.
1919
1920 The constructor creates a BufferedWriter for the given writeable raw
1921 stream. If the buffer_size is not given, it defaults to
1922 DEFAULT_BUFFER_SIZE.
1923 [clinic start generated code]*/
1924
1925 static int
1926 _io_BufferedWriter___init___impl(buffered *self, PyObject *raw,
1927 Py_ssize_t buffer_size)
1928 /*[clinic end generated code: output=c8942a020c0dee64 input=914be9b95e16007b]*/
1929 {
1930 self->ok = 0;
1931 self->detached = 0;
1932
1933 _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
1934 if (_PyIOBase_check_writable(state, raw, Py_True) == NULL) {
1935 return -1;
1936 }
1937
1938 Py_INCREF(raw);
1939 Py_XSETREF(self->raw, raw);
1940 self->readable = 0;
1941 self->writable = 1;
1942
1943 self->buffer_size = buffer_size;
1944 if (_buffered_init(self) < 0)
1945 return -1;
1946 _bufferedwriter_reset_buf(self);
1947 self->pos = 0;
1948
1949 self->fast_closed_checks = (
1950 Py_IS_TYPE(self, state->PyBufferedWriter_Type) &&
1951 Py_IS_TYPE(raw, state->PyFileIO_Type)
1952 );
1953
1954 self->ok = 1;
1955 return 0;
1956 }
1957
1958 static Py_ssize_t
1959 _bufferedwriter_raw_write(buffered *self, char *start, Py_ssize_t len)
1960 {
1961 Py_buffer buf;
1962 PyObject *memobj, *res;
1963 Py_ssize_t n;
1964 int errnum;
1965 /* NOTE: the buffer needn't be released as its object is NULL. */
1966 if (PyBuffer_FillInfo(&buf, NULL, start, len, 1, PyBUF_CONTIG_RO) == -1)
1967 return -1;
1968 memobj = PyMemoryView_FromBuffer(&buf);
1969 if (memobj == NULL)
1970 return -1;
1971 /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR
1972 occurs so we needn't do it ourselves.
1973 We then retry writing, ignoring the signal if no handler has
1974 raised (see issue #10956).
1975 */
1976 do {
1977 errno = 0;
1978 res = PyObject_CallMethodOneArg(self->raw, &_Py_ID(write), memobj);
1979 errnum = errno;
1980 } while (res == NULL && _PyIO_trap_eintr());
1981 Py_DECREF(memobj);
1982 if (res == NULL)
1983 return -1;
1984 if (res == Py_None) {
1985 /* Non-blocking stream would have blocked. Special return code!
1986 Being paranoid we reset errno in case it is changed by code
1987 triggered by a decref. errno is used by _set_BlockingIOError(). */
1988 Py_DECREF(res);
1989 errno = errnum;
1990 return -2;
1991 }
1992 n = PyNumber_AsSsize_t(res, PyExc_ValueError);
1993 Py_DECREF(res);
1994 if (n < 0 || n > len) {
1995 PyErr_Format(PyExc_OSError,
1996 "raw write() returned invalid length %zd "
1997 "(should have been between 0 and %zd)", n, len);
1998 return -1;
1999 }
2000 if (n > 0 && self->abs_pos != -1)
2001 self->abs_pos += n;
2002 return n;
2003 }
2004
2005 static PyObject *
2006 _bufferedwriter_flush_unlocked(buffered *self)
2007 {
2008 Py_off_t n, rewind;
2009
2010 if (!VALID_WRITE_BUFFER(self) || self->write_pos == self->write_end)
2011 goto end;
2012 /* First, rewind */
2013 rewind = RAW_OFFSET(self) + (self->pos - self->write_pos);
2014 if (rewind != 0) {
2015 n = _buffered_raw_seek(self, -rewind, 1);
2016 if (n < 0) {
2017 goto error;
2018 }
2019 self->raw_pos -= rewind;
2020 }
2021 while (self->write_pos < self->write_end) {
2022 n = _bufferedwriter_raw_write(self,
2023 self->buffer + self->write_pos,
2024 Py_SAFE_DOWNCAST(self->write_end - self->write_pos,
2025 Py_off_t, Py_ssize_t));
2026 if (n == -1) {
2027 goto error;
2028 }
2029 else if (n == -2) {
2030 _set_BlockingIOError("write could not complete without blocking",
2031 0);
2032 goto error;
2033 }
2034 self->write_pos += n;
2035 self->raw_pos = self->write_pos;
2036 /* Partial writes can return successfully when interrupted by a
2037 signal (see write(2)). We must run signal handlers before
2038 blocking another time, possibly indefinitely. */
2039 if (PyErr_CheckSignals() < 0)
2040 goto error;
2041 }
2042
2043
2044 end:
2045 /* This ensures that after return from this function,
2046 VALID_WRITE_BUFFER(self) returns false.
2047
2048 This is a required condition because when a tell() is called
2049 after flushing and if VALID_READ_BUFFER(self) is false, we need
2050 VALID_WRITE_BUFFER(self) to be false to have
2051 RAW_OFFSET(self) == 0.
2052
2053 Issue: https://bugs.python.org/issue32228 */
2054 _bufferedwriter_reset_buf(self);
2055 Py_RETURN_NONE;
2056
2057 error:
2058 return NULL;
2059 }
2060
2061 /*[clinic input]
2062 @critical_section
2063 _io.BufferedWriter.write
2064 buffer: Py_buffer
2065 /
2066 [clinic start generated code]*/
2067
2068 static PyObject *
2069 _io_BufferedWriter_write_impl(buffered *self, Py_buffer *buffer)
2070 /*[clinic end generated code: output=7f8d1365759bfc6b input=6a9c041de0c337be]*/
2071 {
2072 PyObject *res = NULL;
2073 Py_ssize_t written, avail, remaining;
2074 Py_off_t offset;
2075
2076 CHECK_INITIALIZED(self)
2077
2078 if (!ENTER_BUFFERED(self))
2079 return NULL;
2080
2081 /* Issue #31976: Check for closed file after acquiring the lock. Another
2082 thread could be holding the lock while closing the file. */
2083 if (IS_CLOSED(self)) {
2084 PyErr_SetString(PyExc_ValueError, "write to closed file");
2085 goto error;
2086 }
2087
2088 /* Fast path: the data to write can be fully buffered. */
2089 if (!VALID_READ_BUFFER(self) && !VALID_WRITE_BUFFER(self)) {
2090 self->pos = 0;
2091 self->raw_pos = 0;
2092 }
2093 avail = Py_SAFE_DOWNCAST(self->buffer_size - self->pos, Py_off_t, Py_ssize_t);
2094 if (buffer->len <= avail && buffer->len < self->buffer_size) {
2095 memcpy(self->buffer + self->pos, buffer->buf, buffer->len);
2096 if (!VALID_WRITE_BUFFER(self) || self->write_pos > self->pos) {
2097 self->write_pos = self->pos;
2098 }
2099 ADJUST_POSITION(self, self->pos + buffer->len);
2100 if (self->pos > self->write_end)
2101 self->write_end = self->pos;
2102 written = buffer->len;
2103 goto end;
2104 }
2105
2106 /* First write the current buffer */
2107 res = _bufferedwriter_flush_unlocked(self);
2108 if (res == NULL) {
2109 Py_ssize_t *w = _buffered_check_blocking_error();
2110 if (w == NULL)
2111 goto error;
2112 if (self->readable)
2113 _bufferedreader_reset_buf(self);
2114 /* Make some place by shifting the buffer. */
2115 assert(VALID_WRITE_BUFFER(self));
2116 memmove(self->buffer, self->buffer + self->write_pos,
2117 Py_SAFE_DOWNCAST(self->write_end - self->write_pos,
2118 Py_off_t, Py_ssize_t));
2119 self->write_end -= self->write_pos;
2120 self->raw_pos -= self->write_pos;
2121 self->pos -= self->write_pos;
2122 self->write_pos = 0;
2123 avail = Py_SAFE_DOWNCAST(self->buffer_size - self->write_end,
2124 Py_off_t, Py_ssize_t);
2125 if (buffer->len <= avail) {
2126 /* Everything can be buffered */
2127 PyErr_Clear();
2128 memcpy(self->buffer + self->write_end, buffer->buf, buffer->len);
2129 self->write_end += buffer->len;
2130 self->pos += buffer->len;
2131 written = buffer->len;
2132 goto end;
2133 }
2134 /* Buffer as much as possible. */
2135 memcpy(self->buffer + self->write_end, buffer->buf, avail);
2136 self->write_end += avail;
2137 self->pos += avail;
2138 /* XXX Modifying the existing exception e using the pointer w
2139 will change e.characters_written but not e.args[2].
2140 Therefore we just replace with a new error. */
2141 _set_BlockingIOError("write could not complete without blocking",
2142 avail);
2143 goto error;
2144 }
2145 Py_CLEAR(res);
2146
2147 /* Adjust the raw stream position if it is away from the logical stream
2148 position. This happens if the read buffer has been filled but not
2149 modified (and therefore _bufferedwriter_flush_unlocked() didn't rewind
2150 the raw stream by itself).
2151 Fixes issue #6629.
2152 */
2153 offset = RAW_OFFSET(self);
2154 if (offset != 0) {
2155 if (_buffered_raw_seek(self, -offset, 1) < 0)
2156 goto error;
2157 self->raw_pos -= offset;
2158 }
2159
2160 /* Then write buf itself. At this point the buffer has been emptied. */
2161 remaining = buffer->len;
2162 written = 0;
2163 while (remaining >= self->buffer_size) {
2164 Py_ssize_t n = _bufferedwriter_raw_write(
2165 self, (char *) buffer->buf + written, buffer->len - written);
2166 if (n == -1) {
2167 goto error;
2168 } else if (n == -2) {
2169 /* Write failed because raw file is non-blocking */
2170 if (remaining > self->buffer_size) {
2171 /* Can't buffer everything, still buffer as much as possible */
2172 memcpy(self->buffer,
2173 (char *) buffer->buf + written, self->buffer_size);
2174 self->raw_pos = 0;
2175 ADJUST_POSITION(self, self->buffer_size);
2176 self->write_end = self->buffer_size;
2177 written += self->buffer_size;
2178 _set_BlockingIOError("write could not complete without "
2179 "blocking", written);
2180 goto error;
2181 }
2182 PyErr_Clear();
2183 break;
2184 }
2185 written += n;
2186 remaining -= n;
2187 /* Partial writes can return successfully when interrupted by a
2188 signal (see write(2)). We must run signal handlers before
2189 blocking another time, possibly indefinitely. */
2190 if (PyErr_CheckSignals() < 0)
2191 goto error;
2192 }
2193 if (self->readable)
2194 _bufferedreader_reset_buf(self);
2195 if (remaining > 0) {
2196 memcpy(self->buffer, (char *) buffer->buf + written, remaining);
2197 written += remaining;
2198 }
2199 self->write_pos = 0;
2200 /* TODO: sanity check (remaining >= 0) */
2201 self->write_end = remaining;
2202 ADJUST_POSITION(self, remaining);
2203 self->raw_pos = 0;
2204
2205 end:
2206 res = PyLong_FromSsize_t(written);
2207
2208 error:
2209 LEAVE_BUFFERED(self)
2210 return res;
2211 }
2212
2213
2214 /*
2215 * BufferedRWPair
2216 */
2217
2218 /* XXX The usefulness of this (compared to having two separate IO objects) is
2219 * questionable.
2220 */
2221
2222 typedef struct {
2223 PyObject_HEAD
2224 buffered *reader;
2225 buffered *writer;
2226 PyObject *dict;
2227 PyObject *weakreflist;
2228 } rwpair;
2229
2230 /*[clinic input]
2231 _io.BufferedRWPair.__init__
2232 reader: object
2233 writer: object
2234 buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
2235 /
2236
2237 A buffered reader and writer object together.
2238
2239 A buffered reader object and buffered writer object put together to
2240 form a sequential IO object that can read and write. This is typically
2241 used with a socket or two-way pipe.
2242
2243 reader and writer are RawIOBase objects that are readable and
2244 writeable respectively. If the buffer_size is omitted it defaults to
2245 DEFAULT_BUFFER_SIZE.
2246 [clinic start generated code]*/
2247
2248 static int
2249 _io_BufferedRWPair___init___impl(rwpair *self, PyObject *reader,
2250 PyObject *writer, Py_ssize_t buffer_size)
2251 /*[clinic end generated code: output=327e73d1aee8f984 input=620d42d71f33a031]*/
2252 {
2253 _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
2254 if (_PyIOBase_check_readable(state, reader, Py_True) == NULL) {
2255 return -1;
2256 }
2257 if (_PyIOBase_check_writable(state, writer, Py_True) == NULL) {
2258 return -1;
2259 }
2260
2261 self->reader = (buffered *) PyObject_CallFunction(
2262 (PyObject *)state->PyBufferedReader_Type,
2263 "On", reader, buffer_size);
2264 if (self->reader == NULL)
2265 return -1;
2266
2267 self->writer = (buffered *) PyObject_CallFunction(
2268 (PyObject *)state->PyBufferedWriter_Type,
2269 "On", writer, buffer_size);
2270 if (self->writer == NULL) {
2271 Py_CLEAR(self->reader);
2272 return -1;
2273 }
2274
2275 return 0;
2276 }
2277
2278 static int
2279 bufferedrwpair_traverse(rwpair *self, visitproc visit, void *arg)
2280 {
2281 Py_VISIT(Py_TYPE(self));
2282 Py_VISIT(self->dict);
2283 Py_VISIT(self->reader);
2284 Py_VISIT(self->writer);
2285 return 0;
2286 }
2287
2288 static int
2289 bufferedrwpair_clear(rwpair *self)
2290 {
2291 Py_CLEAR(self->reader);
2292 Py_CLEAR(self->writer);
2293 Py_CLEAR(self->dict);
2294 return 0;
2295 }
2296
2297 static void
2298 bufferedrwpair_dealloc(rwpair *self)
2299 {
2300 PyTypeObject *tp = Py_TYPE(self);
2301 _PyObject_GC_UNTRACK(self);
2302 FT_CLEAR_WEAKREFS((PyObject *)self, self->weakreflist);
2303 (void)bufferedrwpair_clear(self);
2304 tp->tp_free((PyObject *) self);
2305 Py_DECREF(tp);
2306 }
2307
2308 static PyObject *
2309 _forward_call(buffered *self, PyObject *name, PyObject *args)
2310 {
2311 PyObject *func, *ret;
2312 if (self == NULL) {
2313 PyErr_SetString(PyExc_ValueError,
2314 "I/O operation on uninitialized object");
2315 return NULL;
2316 }
2317
2318 func = PyObject_GetAttr((PyObject *)self, name);
2319 if (func == NULL) {
2320 PyErr_SetObject(PyExc_AttributeError, name);
2321 return NULL;
2322 }
2323
2324 ret = PyObject_CallObject(func, args);
2325 Py_DECREF(func);
2326 return ret;
2327 }
2328
2329 static PyObject *
2330 bufferedrwpair_read(rwpair *self, PyObject *args)
2331 {
2332 return _forward_call(self->reader, &_Py_ID(read), args);
2333 }
2334
2335 static PyObject *
2336 bufferedrwpair_peek(rwpair *self, PyObject *args)
2337 {
2338 return _forward_call(self->reader, &_Py_ID(peek), args);
2339 }
2340
2341 static PyObject *
2342 bufferedrwpair_read1(rwpair *self, PyObject *args)
2343 {
2344 return _forward_call(self->reader, &_Py_ID(read1), args);
2345 }
2346
2347 static PyObject *
2348 bufferedrwpair_readinto(rwpair *self, PyObject *args)
2349 {
2350 return _forward_call(self->reader, &_Py_ID(readinto), args);
2351 }
2352
2353 static PyObject *
2354 bufferedrwpair_readinto1(rwpair *self, PyObject *args)
2355 {
2356 return _forward_call(self->reader, &_Py_ID(readinto1), args);
2357 }
2358
2359 static PyObject *
2360 bufferedrwpair_write(rwpair *self, PyObject *args)
2361 {
2362 return _forward_call(self->writer, &_Py_ID(write), args);
2363 }
2364
2365 static PyObject *
2366 bufferedrwpair_flush(rwpair *self, PyObject *Py_UNUSED(ignored))
2367 {
2368 return _forward_call(self->writer, &_Py_ID(flush), NULL);
2369 }
2370
2371 static PyObject *
2372 bufferedrwpair_readable(rwpair *self, PyObject *Py_UNUSED(ignored))
2373 {
2374 return _forward_call(self->reader, &_Py_ID(readable), NULL);
2375 }
2376
2377 static PyObject *
2378 bufferedrwpair_writable(rwpair *self, PyObject *Py_UNUSED(ignored))
2379 {
2380 return _forward_call(self->writer, &_Py_ID(writable), NULL);
2381 }
2382
2383 static PyObject *
2384 bufferedrwpair_close(rwpair *self, PyObject *Py_UNUSED(ignored))
2385 {
2386 PyObject *exc = NULL;
2387 PyObject *ret = _forward_call(self->writer, &_Py_ID(close), NULL);
2388 if (ret == NULL) {
2389 exc = PyErr_GetRaisedException();
2390 }
2391 else {
2392 Py_DECREF(ret);
2393 }
2394 ret = _forward_call(self->reader, &_Py_ID(close), NULL);
2395 if (exc != NULL) {
2396 _PyErr_ChainExceptions1(exc);
2397 Py_CLEAR(ret);
2398 }
2399 return ret;
2400 }
2401
2402 static PyObject *
2403 bufferedrwpair_isatty(rwpair *self, PyObject *Py_UNUSED(ignored))
2404 {
2405 PyObject *ret = _forward_call(self->writer, &_Py_ID(isatty), NULL);
2406
2407 if (ret != Py_False) {
2408 /* either True or exception */
2409 return ret;
2410 }
2411 Py_DECREF(ret);
2412
2413 return _forward_call(self->reader, &_Py_ID(isatty), NULL);
2414 }
2415
2416 static PyObject *
2417 bufferedrwpair_closed_get(rwpair *self, void *context)
2418 {
2419 if (self->writer == NULL) {
2420 PyErr_SetString(PyExc_RuntimeError,
2421 "the BufferedRWPair object is being garbage-collected");
2422 return NULL;
2423 }
2424 return PyObject_GetAttr((PyObject *) self->writer, &_Py_ID(closed));
2425 }
2426
2427
2428 /*
2429 * BufferedRandom
2430 */
2431
2432 /*[clinic input]
2433 _io.BufferedRandom.__init__
2434 raw: object
2435 buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
2436
2437 A buffered interface to random access streams.
2438
2439 The constructor creates a reader and writer for a seekable stream,
2440 raw, given in the first argument. If the buffer_size is omitted it
2441 defaults to DEFAULT_BUFFER_SIZE.
2442 [clinic start generated code]*/
2443
2444 static int
2445 _io_BufferedRandom___init___impl(buffered *self, PyObject *raw,
2446 Py_ssize_t buffer_size)
2447 /*[clinic end generated code: output=d3d64eb0f64e64a3 input=a4e818fb86d0e50c]*/
2448 {
2449 self->ok = 0;
2450 self->detached = 0;
2451
2452 _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
2453 if (_PyIOBase_check_seekable(state, raw, Py_True) == NULL) {
2454 return -1;
2455 }
2456 if (_PyIOBase_check_readable(state, raw, Py_True) == NULL) {
2457 return -1;
2458 }
2459 if (_PyIOBase_check_writable(state, raw, Py_True) == NULL) {
2460 return -1;
2461 }
2462
2463 Py_INCREF(raw);
2464 Py_XSETREF(self->raw, raw);
2465 self->buffer_size = buffer_size;
2466 self->readable = 1;
2467 self->writable = 1;
2468
2469 if (_buffered_init(self) < 0)
2470 return -1;
2471 _bufferedreader_reset_buf(self);
2472 _bufferedwriter_reset_buf(self);
2473 self->pos = 0;
2474
2475 self->fast_closed_checks = (Py_IS_TYPE(self, state->PyBufferedRandom_Type) &&
2476 Py_IS_TYPE(raw, state->PyFileIO_Type));
2477
2478 self->ok = 1;
2479 return 0;
2480 }
2481
2482 #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
2483 #include "clinic/bufferedio.c.h"
2484 #undef clinic_state
2485
2486 static PyMethodDef bufferediobase_methods[] = {
2487 _IO__BUFFEREDIOBASE_DETACH_METHODDEF
2488 _IO__BUFFEREDIOBASE_READ_METHODDEF
2489 _IO__BUFFEREDIOBASE_READ1_METHODDEF
2490 _IO__BUFFEREDIOBASE_READINTO_METHODDEF
2491 _IO__BUFFEREDIOBASE_READINTO1_METHODDEF
2492 _IO__BUFFEREDIOBASE_WRITE_METHODDEF
2493 {NULL, NULL}
2494 };
2495
2496 static PyType_Slot bufferediobase_slots[] = {
2497 {Py_tp_doc, (void *)bufferediobase_doc},
2498 {Py_tp_methods, bufferediobase_methods},
2499 {0, NULL},
2500 };
2501
2502 /* Do not set Py_TPFLAGS_HAVE_GC so that tp_traverse and tp_clear are inherited */
2503 PyType_Spec bufferediobase_spec = {
2504 .name = "_io._BufferedIOBase",
2505 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2506 Py_TPFLAGS_IMMUTABLETYPE),
2507 .slots = bufferediobase_slots,
2508 };
2509
2510 static PyMethodDef bufferedreader_methods[] = {
2511 /* BufferedIOMixin methods */
2512 _IO__BUFFERED_DETACH_METHODDEF
2513 _IO__BUFFERED_SIMPLE_FLUSH_METHODDEF
2514 _IO__BUFFERED_CLOSE_METHODDEF
2515 _IO__BUFFERED_SEEKABLE_METHODDEF
2516 _IO__BUFFERED_READABLE_METHODDEF
2517 _IO__BUFFERED_FILENO_METHODDEF
2518 _IO__BUFFERED_ISATTY_METHODDEF
2519 _IO__BUFFERED__DEALLOC_WARN_METHODDEF
2520
2521 _IO__BUFFERED_READ_METHODDEF
2522 _IO__BUFFERED_PEEK_METHODDEF
2523 _IO__BUFFERED_READ1_METHODDEF
2524 _IO__BUFFERED_READINTO_METHODDEF
2525 _IO__BUFFERED_READINTO1_METHODDEF
2526 _IO__BUFFERED_READLINE_METHODDEF
2527 _IO__BUFFERED_SEEK_METHODDEF
2528 _IO__BUFFERED_TELL_METHODDEF
2529 _IO__BUFFERED_TRUNCATE_METHODDEF
2530 _IO__BUFFERED___SIZEOF___METHODDEF
2531
2532 {"__getstate__", _PyIOBase_cannot_pickle, METH_NOARGS},
2533 {NULL, NULL}
2534 };
2535
2536 static PyMemberDef bufferedreader_members[] = {
2537 {"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
2538 {"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
2539 {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
2540 {"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
2541 {NULL}
2542 };
2543
2544 static PyGetSetDef bufferedreader_getset[] = {
2545 _IO__BUFFERED_CLOSED_GETSETDEF
2546 _IO__BUFFERED_NAME_GETSETDEF
2547 _IO__BUFFERED_MODE_GETSETDEF
2548 {NULL}
2549 };
2550
2551
2552 static PyType_Slot bufferedreader_slots[] = {
2553 {Py_tp_dealloc, buffered_dealloc},
2554 {Py_tp_repr, buffered_repr},
2555 {Py_tp_doc, (void *)_io_BufferedReader___init____doc__},
2556 {Py_tp_traverse, buffered_traverse},
2557 {Py_tp_clear, buffered_clear},
2558 {Py_tp_iternext, buffered_iternext},
2559 {Py_tp_methods, bufferedreader_methods},
2560 {Py_tp_members, bufferedreader_members},
2561 {Py_tp_getset, bufferedreader_getset},
2562 {Py_tp_init, _io_BufferedReader___init__},
2563 {0, NULL},
2564 };
2565
2566 PyType_Spec bufferedreader_spec = {
2567 .name = "_io.BufferedReader",
2568 .basicsize = sizeof(buffered),
2569 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
2570 Py_TPFLAGS_IMMUTABLETYPE),
2571 .slots = bufferedreader_slots,
2572 };
2573
2574 static PyMethodDef bufferedwriter_methods[] = {
2575 /* BufferedIOMixin methods */
2576 _IO__BUFFERED_CLOSE_METHODDEF
2577 _IO__BUFFERED_DETACH_METHODDEF
2578 _IO__BUFFERED_SEEKABLE_METHODDEF
2579 _IO__BUFFERED_WRITABLE_METHODDEF
2580 _IO__BUFFERED_FILENO_METHODDEF
2581 _IO__BUFFERED_ISATTY_METHODDEF
2582 _IO__BUFFERED__DEALLOC_WARN_METHODDEF
2583
2584 _IO_BUFFEREDWRITER_WRITE_METHODDEF
2585 _IO__BUFFERED_TRUNCATE_METHODDEF
2586 _IO__BUFFERED_FLUSH_METHODDEF
2587 _IO__BUFFERED_SEEK_METHODDEF
2588 _IO__BUFFERED_TELL_METHODDEF
2589 _IO__BUFFERED___SIZEOF___METHODDEF
2590
2591 {"__getstate__", _PyIOBase_cannot_pickle, METH_NOARGS},
2592 {NULL, NULL}
2593 };
2594
2595 static PyMemberDef bufferedwriter_members[] = {
2596 {"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
2597 {"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
2598 {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
2599 {"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
2600 {NULL}
2601 };
2602
2603 static PyGetSetDef bufferedwriter_getset[] = {
2604 _IO__BUFFERED_CLOSED_GETSETDEF
2605 _IO__BUFFERED_NAME_GETSETDEF
2606 _IO__BUFFERED_MODE_GETSETDEF
2607 {NULL}
2608 };
2609
2610
2611 static PyType_Slot bufferedwriter_slots[] = {
2612 {Py_tp_dealloc, buffered_dealloc},
2613 {Py_tp_repr, buffered_repr},
2614 {Py_tp_doc, (void *)_io_BufferedWriter___init____doc__},
2615 {Py_tp_traverse, buffered_traverse},
2616 {Py_tp_clear, buffered_clear},
2617 {Py_tp_methods, bufferedwriter_methods},
2618 {Py_tp_members, bufferedwriter_members},
2619 {Py_tp_getset, bufferedwriter_getset},
2620 {Py_tp_init, _io_BufferedWriter___init__},
2621 {0, NULL},
2622 };
2623
2624 PyType_Spec bufferedwriter_spec = {
2625 .name = "_io.BufferedWriter",
2626 .basicsize = sizeof(buffered),
2627 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
2628 Py_TPFLAGS_IMMUTABLETYPE),
2629 .slots = bufferedwriter_slots,
2630 };
2631
2632 static PyMethodDef bufferedrwpair_methods[] = {
2633 {"read", (PyCFunction)bufferedrwpair_read, METH_VARARGS},
2634 {"peek", (PyCFunction)bufferedrwpair_peek, METH_VARARGS},
2635 {"read1", (PyCFunction)bufferedrwpair_read1, METH_VARARGS},
2636 {"readinto", (PyCFunction)bufferedrwpair_readinto, METH_VARARGS},
2637 {"readinto1", (PyCFunction)bufferedrwpair_readinto1, METH_VARARGS},
2638
2639 {"write", (PyCFunction)bufferedrwpair_write, METH_VARARGS},
2640 {"flush", (PyCFunction)bufferedrwpair_flush, METH_NOARGS},
2641
2642 {"readable", (PyCFunction)bufferedrwpair_readable, METH_NOARGS},
2643 {"writable", (PyCFunction)bufferedrwpair_writable, METH_NOARGS},
2644
2645 {"close", (PyCFunction)bufferedrwpair_close, METH_NOARGS},
2646 {"isatty", (PyCFunction)bufferedrwpair_isatty, METH_NOARGS},
2647
2648 {NULL, NULL}
2649 };
2650
2651 static PyMemberDef bufferedrwpair_members[] = {
2652 {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(rwpair, weakreflist), Py_READONLY},
2653 {"__dictoffset__", Py_T_PYSSIZET, offsetof(rwpair, dict), Py_READONLY},
2654 {NULL}
2655 };
2656
2657 static PyGetSetDef bufferedrwpair_getset[] = {
2658 {"closed", (getter)bufferedrwpair_closed_get, NULL, NULL},
2659 {NULL}
2660 };
2661
2662 static PyType_Slot bufferedrwpair_slots[] = {
2663 {Py_tp_dealloc, bufferedrwpair_dealloc},
2664 {Py_tp_doc, (void *)_io_BufferedRWPair___init____doc__},
2665 {Py_tp_traverse, bufferedrwpair_traverse},
2666 {Py_tp_clear, bufferedrwpair_clear},
2667 {Py_tp_methods, bufferedrwpair_methods},
2668 {Py_tp_members, bufferedrwpair_members},
2669 {Py_tp_getset, bufferedrwpair_getset},
2670 {Py_tp_init, _io_BufferedRWPair___init__},
2671 {0, NULL},
2672 };
2673
2674 PyType_Spec bufferedrwpair_spec = {
2675 .name = "_io.BufferedRWPair",
2676 .basicsize = sizeof(rwpair),
2677 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
2678 Py_TPFLAGS_IMMUTABLETYPE),
2679 .slots = bufferedrwpair_slots,
2680 };
2681
2682
2683 static PyMethodDef bufferedrandom_methods[] = {
2684 /* BufferedIOMixin methods */
2685 _IO__BUFFERED_CLOSE_METHODDEF
2686 _IO__BUFFERED_DETACH_METHODDEF
2687 _IO__BUFFERED_SEEKABLE_METHODDEF
2688 _IO__BUFFERED_READABLE_METHODDEF
2689 _IO__BUFFERED_WRITABLE_METHODDEF
2690 _IO__BUFFERED_FILENO_METHODDEF
2691 _IO__BUFFERED_ISATTY_METHODDEF
2692 _IO__BUFFERED__DEALLOC_WARN_METHODDEF
2693
2694 _IO__BUFFERED_FLUSH_METHODDEF
2695
2696 _IO__BUFFERED_SEEK_METHODDEF
2697 _IO__BUFFERED_TELL_METHODDEF
2698 _IO__BUFFERED_TRUNCATE_METHODDEF
2699 _IO__BUFFERED_READ_METHODDEF
2700 _IO__BUFFERED_READ1_METHODDEF
2701 _IO__BUFFERED_READINTO_METHODDEF
2702 _IO__BUFFERED_READINTO1_METHODDEF
2703 _IO__BUFFERED_READLINE_METHODDEF
2704 _IO__BUFFERED_PEEK_METHODDEF
2705 _IO_BUFFEREDWRITER_WRITE_METHODDEF
2706 _IO__BUFFERED___SIZEOF___METHODDEF
2707
2708 {"__getstate__", _PyIOBase_cannot_pickle, METH_NOARGS},
2709 {NULL, NULL}
2710 };
2711
2712 static PyMemberDef bufferedrandom_members[] = {
2713 {"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
2714 {"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
2715 {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
2716 {"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
2717 {NULL}
2718 };
2719
2720 static PyGetSetDef bufferedrandom_getset[] = {
2721 _IO__BUFFERED_CLOSED_GETSETDEF
2722 _IO__BUFFERED_NAME_GETSETDEF
2723 _IO__BUFFERED_MODE_GETSETDEF
2724 {NULL}
2725 };
2726
2727
2728 static PyType_Slot bufferedrandom_slots[] = {
2729 {Py_tp_dealloc, buffered_dealloc},
2730 {Py_tp_repr, buffered_repr},
2731 {Py_tp_doc, (void *)_io_BufferedRandom___init____doc__},
2732 {Py_tp_traverse, buffered_traverse},
2733 {Py_tp_clear, buffered_clear},
2734 {Py_tp_iternext, buffered_iternext},
2735 {Py_tp_methods, bufferedrandom_methods},
2736 {Py_tp_members, bufferedrandom_members},
2737 {Py_tp_getset, bufferedrandom_getset},
2738 {Py_tp_init, _io_BufferedRandom___init__},
2739 {0, NULL},
2740 };
2741
2742 PyType_Spec bufferedrandom_spec = {
2743 .name = "_io.BufferedRandom",
2744 .basicsize = sizeof(buffered),
2745 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
2746 Py_TPFLAGS_IMMUTABLETYPE),
2747 .slots = bufferedrandom_slots,
2748 };