-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
bufferedio.c
2752 lines (2397 loc) · 76.6 KB
/
bufferedio.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
An implementation of Buffered I/O as defined by PEP 3116 - "New I/O"
Classes defined here: BufferedIOBase, BufferedReader, BufferedWriter,
BufferedRandom.
Written by Amaury Forgeot d'Arc and Antoine Pitrou
*/
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h" // _Py_FatalErrorFormat()
#include "pycore_pylifecycle.h" // _Py_IsInterpreterFinalizing()
#include "_iomodule.h"
/*[clinic input]
module _io
class _io._BufferedIOBase "PyObject *" "clinic_state()->PyBufferedIOBase_Type"
class _io._Buffered "buffered *" "clinic_state()->PyBufferedIOBase_Type"
class _io.BufferedReader "buffered *" "clinic_state()->PyBufferedReader_Type"
class _io.BufferedWriter "buffered *" "clinic_state()->PyBufferedWriter_Type"
class _io.BufferedRWPair "rwpair *" "clinic_state()->PyBufferedRWPair_Type"
class _io.BufferedRandom "buffered *" "clinic_state()->PyBufferedRandom_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3b3ef9cbbbad4590]*/
/*
* BufferedIOBase class, inherits from IOBase.
*/
PyDoc_STRVAR(bufferediobase_doc,
"Base class for buffered IO objects.\n"
"\n"
"The main difference with RawIOBase is that the read() method\n"
"supports omitting the size argument, and does not have a default\n"
"implementation that defers to readinto().\n"
"\n"
"In addition, read(), readinto() and write() may raise\n"
"BlockingIOError if the underlying raw stream is in non-blocking\n"
"mode and not ready; unlike their raw counterparts, they will never\n"
"return None.\n"
"\n"
"A typical implementation should not inherit from a RawIOBase\n"
"implementation, but wrap one.\n"
);
static PyObject *
_bufferediobase_readinto_generic(PyObject *self, Py_buffer *buffer, char readinto1)
{
Py_ssize_t len;
PyObject *data;
PyObject *attr = readinto1
? &_Py_ID(read1)
: &_Py_ID(read);
data = _PyObject_CallMethod(self, attr, "n", buffer->len);
if (data == NULL)
return NULL;
if (!PyBytes_Check(data)) {
Py_DECREF(data);
PyErr_SetString(PyExc_TypeError, "read() should return bytes");
return NULL;
}
len = PyBytes_GET_SIZE(data);
if (len > buffer->len) {
PyErr_Format(PyExc_ValueError,
"read() returned too much data: "
"%zd bytes requested, %zd returned",
buffer->len, len);
Py_DECREF(data);
return NULL;
}
memcpy(buffer->buf, PyBytes_AS_STRING(data), len);
Py_DECREF(data);
return PyLong_FromSsize_t(len);
}
/*[clinic input]
@critical_section
_io._BufferedIOBase.readinto
buffer: Py_buffer(accept={rwbuffer})
/
[clinic start generated code]*/
static PyObject *
_io__BufferedIOBase_readinto_impl(PyObject *self, Py_buffer *buffer)
/*[clinic end generated code: output=8c8cda6684af8038 input=5273d20db7f56e1a]*/
{
return _bufferediobase_readinto_generic(self, buffer, 0);
}
/*[clinic input]
@critical_section
_io._BufferedIOBase.readinto1
buffer: Py_buffer(accept={rwbuffer})
/
[clinic start generated code]*/
static PyObject *
_io__BufferedIOBase_readinto1_impl(PyObject *self, Py_buffer *buffer)
/*[clinic end generated code: output=358623e4fd2b69d3 input=d6eb723dedcee654]*/
{
return _bufferediobase_readinto_generic(self, buffer, 1);
}
static PyObject *
bufferediobase_unsupported(_PyIO_State *state, const char *message)
{
PyErr_SetString(state->unsupported_operation, message);
return NULL;
}
/*[clinic input]
_io._BufferedIOBase.detach
cls: defining_class
/
Disconnect this buffer from its underlying raw stream and return it.
After the raw stream has been detached, the buffer is in an unusable
state.
[clinic start generated code]*/
static PyObject *
_io__BufferedIOBase_detach_impl(PyObject *self, PyTypeObject *cls)
/*[clinic end generated code: output=b87b135d67cd4448 input=0b61a7b4357c1ea7]*/
{
_PyIO_State *state = get_io_state_by_cls(cls);
return bufferediobase_unsupported(state, "detach");
}
/*[clinic input]
_io._BufferedIOBase.read
cls: defining_class
size: int(unused=True) = -1
/
Read and return up to n bytes.
If the size argument is omitted, None, or negative, read and
return all data until EOF.
If the size argument is positive, and the underlying raw stream is
not 'interactive', multiple raw reads may be issued to satisfy
the byte count (unless EOF is reached first).
However, for interactive raw streams (as well as sockets and pipes),
at most one raw read will be issued, and a short result does not
imply that EOF is imminent.
Return an empty bytes object on EOF.
Return None if the underlying raw stream was open in non-blocking
mode and no data is available at the moment.
[clinic start generated code]*/
static PyObject *
_io__BufferedIOBase_read_impl(PyObject *self, PyTypeObject *cls,
int Py_UNUSED(size))
/*[clinic end generated code: output=aceb2765587b0a29 input=824f6f910465e61a]*/
{
_PyIO_State *state = get_io_state_by_cls(cls);
return bufferediobase_unsupported(state, "read");
}
/*[clinic input]
_io._BufferedIOBase.read1
cls: defining_class
size: int(unused=True) = -1
/
Read and return up to size bytes, with at most one read() call to the underlying raw stream.
Return an empty bytes object on EOF.
A short result does not imply that EOF is imminent.
[clinic start generated code]*/
static PyObject *
_io__BufferedIOBase_read1_impl(PyObject *self, PyTypeObject *cls,
int Py_UNUSED(size))
/*[clinic end generated code: output=2e7fc62972487eaa input=af76380e020fd9e6]*/
{
_PyIO_State *state = get_io_state_by_cls(cls);
return bufferediobase_unsupported(state, "read1");
}
/*[clinic input]
_io._BufferedIOBase.write
cls: defining_class
b: object(unused=True)
/
Write buffer b to the IO stream.
Return the number of bytes written, which is always
the length of b in bytes.
Raise BlockingIOError if the buffer is full and the
underlying raw stream cannot accept more data at the moment.
[clinic start generated code]*/
static PyObject *
_io__BufferedIOBase_write_impl(PyObject *self, PyTypeObject *cls,
PyObject *Py_UNUSED(b))
/*[clinic end generated code: output=712c635246bf2306 input=9793f5c8f71029ad]*/
{
_PyIO_State *state = get_io_state_by_cls(cls);
return bufferediobase_unsupported(state, "write");
}
typedef struct {
PyObject_HEAD
PyObject *raw;
int ok; /* Initialized? */
int detached;
int readable;
int writable;
char finalizing;
/* True if this is a vanilla Buffered object (rather than a user derived
class) *and* the raw stream is a vanilla FileIO object. */
int fast_closed_checks;
/* Absolute position inside the raw stream (-1 if unknown). */
Py_off_t abs_pos;
/* A static buffer of size `buffer_size` */
char *buffer;
/* Current logical position in the buffer. */
Py_off_t pos;
/* Position of the raw stream in the buffer. */
Py_off_t raw_pos;
/* Just after the last buffered byte in the buffer, or -1 if the buffer
isn't ready for reading. */
Py_off_t read_end;
/* Just after the last byte actually written */
Py_off_t write_pos;
/* Just after the last byte waiting to be written, or -1 if the buffer
isn't ready for writing. */
Py_off_t write_end;
PyThread_type_lock lock;
volatile unsigned long owner;
Py_ssize_t buffer_size;
Py_ssize_t buffer_mask;
PyObject *dict;
PyObject *weakreflist;
} buffered;
/*
Implementation notes:
* BufferedReader, BufferedWriter and BufferedRandom try to share most
methods (this is helped by the members `readable` and `writable`, which
are initialized in the respective constructors)
* They also share a single buffer for reading and writing. This enables
interleaved reads and writes without flushing. It also makes the logic
a bit trickier to get right.
* The absolute position of the raw stream is cached, if possible, in the
`abs_pos` member. It must be updated every time an operation is done
on the raw stream. If not sure, it can be reinitialized by calling
_buffered_raw_tell(), which queries the raw stream (_buffered_raw_seek()
also does it). To read it, use RAW_TELL().
* Three helpers, _bufferedreader_raw_read, _bufferedwriter_raw_write and
_bufferedwriter_flush_unlocked do a lot of useful housekeeping.
NOTE: we should try to maintain block alignment of reads and writes to the
raw stream (according to the buffer size), but for now it is only done
in read() and friends.
*/
/* These macros protect the buffered object against concurrent operations. */
static int
_enter_buffered_busy(buffered *self)
{
int relax_locking;
PyLockStatus st;
if (self->owner == PyThread_get_thread_ident()) {
PyErr_Format(PyExc_RuntimeError,
"reentrant call inside %R", self);
return 0;
}
PyInterpreterState *interp = _PyInterpreterState_GET();
relax_locking = _Py_IsInterpreterFinalizing(interp);
Py_BEGIN_ALLOW_THREADS
if (!relax_locking)
st = PyThread_acquire_lock(self->lock, 1);
else {
/* When finalizing, we don't want a deadlock to happen with daemon
* threads abruptly shut down while they owned the lock.
* Therefore, only wait for a grace period (1 s.).
* Note that non-daemon threads have already exited here, so this
* shouldn't affect carefully written threaded I/O code.
*/
st = PyThread_acquire_lock_timed(self->lock, (PY_TIMEOUT_T)1e6, 0);
}
Py_END_ALLOW_THREADS
if (relax_locking && st != PY_LOCK_ACQUIRED) {
PyObject *ascii = PyObject_ASCII((PyObject*)self);
_Py_FatalErrorFormat(__func__,
"could not acquire lock for %s at interpreter "
"shutdown, possibly due to daemon threads",
ascii ? PyUnicode_AsUTF8(ascii) : "<ascii(self) failed>");
}
return 1;
}
#define ENTER_BUFFERED(self) \
( (PyThread_acquire_lock(self->lock, 0) ? \
1 : _enter_buffered_busy(self)) \
&& (self->owner = PyThread_get_thread_ident(), 1) )
#define LEAVE_BUFFERED(self) \
do { \
self->owner = 0; \
PyThread_release_lock(self->lock); \
} while(0);
#define CHECK_INITIALIZED(self) \
if (self->ok <= 0) { \
if (self->detached) { \
PyErr_SetString(PyExc_ValueError, \
"raw stream has been detached"); \
} else { \
PyErr_SetString(PyExc_ValueError, \
"I/O operation on uninitialized object"); \
} \
return NULL; \
}
#define CHECK_INITIALIZED_INT(self) \
if (self->ok <= 0) { \
if (self->detached) { \
PyErr_SetString(PyExc_ValueError, \
"raw stream has been detached"); \
} else { \
PyErr_SetString(PyExc_ValueError, \
"I/O operation on uninitialized object"); \
} \
return -1; \
}
#define IS_CLOSED(self) \
(!self->buffer || \
(self->fast_closed_checks \
? _PyFileIO_closed(self->raw) \
: buffered_closed(self)))
#define CHECK_CLOSED(self, error_msg) \
if (IS_CLOSED(self) && (Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t) == 0)) { \
PyErr_SetString(PyExc_ValueError, error_msg); \
return NULL; \
} \
#define VALID_READ_BUFFER(self) \
(self->readable && self->read_end != -1)
#define VALID_WRITE_BUFFER(self) \
(self->writable && self->write_end != -1)
#define ADJUST_POSITION(self, _new_pos) \
do { \
self->pos = _new_pos; \
if (VALID_READ_BUFFER(self) && self->read_end < self->pos) \
self->read_end = self->pos; \
} while(0)
#define READAHEAD(self) \
((self->readable && VALID_READ_BUFFER(self)) \
? (self->read_end - self->pos) : 0)
#define RAW_OFFSET(self) \
(((VALID_READ_BUFFER(self) || VALID_WRITE_BUFFER(self)) \
&& self->raw_pos >= 0) ? self->raw_pos - self->pos : 0)
#define RAW_TELL(self) \
(self->abs_pos != -1 ? self->abs_pos : _buffered_raw_tell(self))
#define MINUS_LAST_BLOCK(self, size) \
(self->buffer_mask ? \
(size & ~self->buffer_mask) : \
(self->buffer_size * (size / self->buffer_size)))
static int
buffered_clear(buffered *self)
{
self->ok = 0;
Py_CLEAR(self->raw);
Py_CLEAR(self->dict);
return 0;
}
static void
buffered_dealloc(buffered *self)
{
PyTypeObject *tp = Py_TYPE(self);
self->finalizing = 1;
if (_PyIOBase_finalize((PyObject *) self) < 0)
return;
_PyObject_GC_UNTRACK(self);
self->ok = 0;
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *)self);
if (self->buffer) {
PyMem_Free(self->buffer);
self->buffer = NULL;
}
if (self->lock) {
PyThread_free_lock(self->lock);
self->lock = NULL;
}
(void)buffered_clear(self);
tp->tp_free((PyObject *)self);
Py_DECREF(tp);
}
/*[clinic input]
@critical_section
_io._Buffered.__sizeof__
[clinic start generated code]*/
static PyObject *
_io__Buffered___sizeof___impl(buffered *self)
/*[clinic end generated code: output=0231ef7f5053134e input=07a32d578073ea64]*/
{
size_t res = _PyObject_SIZE(Py_TYPE(self));
if (self->buffer) {
res += (size_t)self->buffer_size;
}
return PyLong_FromSize_t(res);
}
static int
buffered_traverse(buffered *self, visitproc visit, void *arg)
{
Py_VISIT(Py_TYPE(self));
Py_VISIT(self->raw);
Py_VISIT(self->dict);
return 0;
}
/* Because this can call arbitrary code, it shouldn't be called when
the refcount is 0 (that is, not directly from tp_dealloc unless
the refcount has been temporarily re-incremented). */
/*[clinic input]
_io._Buffered._dealloc_warn
source: object
/
[clinic start generated code]*/
static PyObject *
_io__Buffered__dealloc_warn(buffered *self, PyObject *source)
/*[clinic end generated code: output=690dcc3df8967162 input=8f845f2a4786391c]*/
{
if (self->ok && self->raw) {
PyObject *r;
r = PyObject_CallMethodOneArg(self->raw, &_Py_ID(_dealloc_warn), source);
if (r)
Py_DECREF(r);
else
PyErr_Clear();
}
Py_RETURN_NONE;
}
/*
* _BufferedIOMixin methods
* This is not a class, just a collection of methods that will be reused
* by BufferedReader and BufferedWriter
*/
/* Flush and close */
/*[clinic input]
@critical_section
_io._Buffered.flush as _io__Buffered_simple_flush
[clinic start generated code]*/
static PyObject *
_io__Buffered_simple_flush_impl(buffered *self)
/*[clinic end generated code: output=29ebb3820db1bdfd input=5248cb84a65f80bd]*/
{
CHECK_INITIALIZED(self)
return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(flush));
}
static int
buffered_closed(buffered *self)
{
int closed;
PyObject *res;
CHECK_INITIALIZED_INT(self)
res = PyObject_GetAttr(self->raw, &_Py_ID(closed));
if (res == NULL)
return -1;
closed = PyObject_IsTrue(res);
Py_DECREF(res);
return closed;
}
/*[clinic input]
@critical_section
@getter
_io._Buffered.closed
[clinic start generated code]*/
static PyObject *
_io__Buffered_closed_get_impl(buffered *self)
/*[clinic end generated code: output=f08ce57290703a1a input=18eddefdfe4a3d2f]*/
{
CHECK_INITIALIZED(self)
return PyObject_GetAttr(self->raw, &_Py_ID(closed));
}
/*[clinic input]
@critical_section
_io._Buffered.close
[clinic start generated code]*/
static PyObject *
_io__Buffered_close_impl(buffered *self)
/*[clinic end generated code: output=7280b7b42033be0c input=56d95935b03fd326]*/
{
PyObject *res = NULL;
int r;
CHECK_INITIALIZED(self)
if (!ENTER_BUFFERED(self)) {
return NULL;
}
r = buffered_closed(self);
if (r < 0)
goto end;
if (r > 0) {
res = Py_NewRef(Py_None);
goto end;
}
if (self->finalizing) {
PyObject *r = _io__Buffered__dealloc_warn(self, (PyObject *) self);
if (r)
Py_DECREF(r);
else
PyErr_Clear();
}
/* flush() will most probably re-take the lock, so drop it first */
LEAVE_BUFFERED(self)
r = _PyFile_Flush((PyObject *)self);
if (!ENTER_BUFFERED(self)) {
return NULL;
}
PyObject *exc = NULL;
if (r < 0) {
exc = PyErr_GetRaisedException();
}
res = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(close));
if (self->buffer) {
PyMem_Free(self->buffer);
self->buffer = NULL;
}
if (exc != NULL) {
_PyErr_ChainExceptions1(exc);
Py_CLEAR(res);
}
self->read_end = 0;
self->pos = 0;
end:
LEAVE_BUFFERED(self)
return res;
}
/*[clinic input]
@critical_section
_io._Buffered.detach
[clinic start generated code]*/
static PyObject *
_io__Buffered_detach_impl(buffered *self)
/*[clinic end generated code: output=dd0fc057b8b779f7 input=d4ef1828a678be37]*/
{
PyObject *raw;
CHECK_INITIALIZED(self)
if (_PyFile_Flush((PyObject *)self) < 0) {
return NULL;
}
raw = self->raw;
self->raw = NULL;
self->detached = 1;
self->ok = 0;
return raw;
}
/* Inquiries */
/*[clinic input]
@critical_section
_io._Buffered.seekable
[clinic start generated code]*/
static PyObject *
_io__Buffered_seekable_impl(buffered *self)
/*[clinic end generated code: output=90172abb5ceb6e8f input=e3a4fc1d297b2fd3]*/
{
CHECK_INITIALIZED(self)
return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(seekable));
}
/*[clinic input]
@critical_section
_io._Buffered.readable
[clinic start generated code]*/
static PyObject *
_io__Buffered_readable_impl(buffered *self)
/*[clinic end generated code: output=92afa07661ecb698 input=abe54107d59bca9a]*/
{
CHECK_INITIALIZED(self)
return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(readable));
}
/*[clinic input]
@critical_section
_io._Buffered.writable
[clinic start generated code]*/
static PyObject *
_io__Buffered_writable_impl(buffered *self)
/*[clinic end generated code: output=4e3eee8d6f9d8552 input=45eb76bf6a10e6f7]*/
{
CHECK_INITIALIZED(self)
return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(writable));
}
/*[clinic input]
@critical_section
@getter
_io._Buffered.name
[clinic start generated code]*/
static PyObject *
_io__Buffered_name_get_impl(buffered *self)
/*[clinic end generated code: output=d2adf384051d3d10 input=6b84a0e6126f545e]*/
{
CHECK_INITIALIZED(self)
return PyObject_GetAttr(self->raw, &_Py_ID(name));
}
/*[clinic input]
@critical_section
@getter
_io._Buffered.mode
[clinic start generated code]*/
static PyObject *
_io__Buffered_mode_get_impl(buffered *self)
/*[clinic end generated code: output=0feb205748892fa4 input=0762d5e28542fd8c]*/
{
CHECK_INITIALIZED(self)
return PyObject_GetAttr(self->raw, &_Py_ID(mode));
}
/* Lower-level APIs */
/*[clinic input]
@critical_section
_io._Buffered.fileno
[clinic start generated code]*/
static PyObject *
_io__Buffered_fileno_impl(buffered *self)
/*[clinic end generated code: output=b717648d58a95ee3 input=1c4fead777bae20a]*/
{
CHECK_INITIALIZED(self)
return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(fileno));
}
/*[clinic input]
@critical_section
_io._Buffered.isatty
[clinic start generated code]*/
static PyObject *
_io__Buffered_isatty_impl(buffered *self)
/*[clinic end generated code: output=c20e55caae67baea input=e53d182d7e490e3a]*/
{
CHECK_INITIALIZED(self)
return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(isatty));
}
/* Forward decls */
static PyObject *
_bufferedwriter_flush_unlocked(buffered *);
static Py_ssize_t
_bufferedreader_fill_buffer(buffered *self);
static void
_bufferedreader_reset_buf(buffered *self);
static void
_bufferedwriter_reset_buf(buffered *self);
static PyObject *
_bufferedreader_peek_unlocked(buffered *self);
static PyObject *
_bufferedreader_read_all(buffered *self);
static PyObject *
_bufferedreader_read_fast(buffered *self, Py_ssize_t);
static PyObject *
_bufferedreader_read_generic(buffered *self, Py_ssize_t);
static Py_ssize_t
_bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len);
/*
* Helpers
*/
/* Sets the current error to BlockingIOError */
static void
_set_BlockingIOError(const char *msg, Py_ssize_t written)
{
PyObject *err;
PyErr_Clear();
err = PyObject_CallFunction(PyExc_BlockingIOError, "isn",
errno, msg, written);
if (err)
PyErr_SetObject(PyExc_BlockingIOError, err);
Py_XDECREF(err);
}
/* Returns the address of the `written` member if a BlockingIOError was
raised, NULL otherwise. The error is always re-raised. */
static Py_ssize_t *
_buffered_check_blocking_error(void)
{
PyObject *exc = PyErr_GetRaisedException();
if (exc == NULL || !PyErr_GivenExceptionMatches(exc, PyExc_BlockingIOError)) {
PyErr_SetRaisedException(exc);
return NULL;
}
PyOSErrorObject *err = (PyOSErrorObject *)exc;
/* TODO: sanity check (err->written >= 0) */
PyErr_SetRaisedException(exc);
return &err->written;
}
static Py_off_t
_buffered_raw_tell(buffered *self)
{
Py_off_t n;
PyObject *res;
res = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(tell));
if (res == NULL)
return -1;
n = PyNumber_AsOff_t(res, PyExc_ValueError);
Py_DECREF(res);
if (n < 0) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_OSError,
"Raw stream returned invalid position %" PY_PRIdOFF,
(PY_OFF_T_COMPAT)n);
return -1;
}
self->abs_pos = n;
return n;
}
static Py_off_t
_buffered_raw_seek(buffered *self, Py_off_t target, int whence)
{
PyObject *res, *posobj, *whenceobj;
Py_off_t n;
posobj = PyLong_FromOff_t(target);
if (posobj == NULL)
return -1;
whenceobj = PyLong_FromLong(whence);
if (whenceobj == NULL) {
Py_DECREF(posobj);
return -1;
}
res = PyObject_CallMethodObjArgs(self->raw, &_Py_ID(seek),
posobj, whenceobj, NULL);
Py_DECREF(posobj);
Py_DECREF(whenceobj);
if (res == NULL)
return -1;
n = PyNumber_AsOff_t(res, PyExc_ValueError);
Py_DECREF(res);
if (n < 0) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_OSError,
"Raw stream returned invalid position %" PY_PRIdOFF,
(PY_OFF_T_COMPAT)n);
return -1;
}
self->abs_pos = n;
return n;
}
static int
_buffered_init(buffered *self)
{
Py_ssize_t n;
if (self->buffer_size <= 0) {
PyErr_SetString(PyExc_ValueError,
"buffer size must be strictly positive");
return -1;
}
if (self->buffer)
PyMem_Free(self->buffer);
self->buffer = PyMem_Malloc(self->buffer_size);
if (self->buffer == NULL) {
PyErr_NoMemory();
return -1;
}
if (self->lock)
PyThread_free_lock(self->lock);
self->lock = PyThread_allocate_lock();
if (self->lock == NULL) {
PyErr_SetString(PyExc_RuntimeError, "can't allocate read lock");
return -1;
}
self->owner = 0;
/* Find out whether buffer_size is a power of 2 */
/* XXX is this optimization useful? */
for (n = self->buffer_size - 1; n & 1; n >>= 1)
;
if (n == 0)
self->buffer_mask = self->buffer_size - 1;
else
self->buffer_mask = 0;
if (_buffered_raw_tell(self) == -1)
PyErr_Clear();
return 0;
}
/* Return 1 if an OSError with errno == EINTR is set (and then
clears the error indicator), 0 otherwise.
Should only be called when PyErr_Occurred() is true.
*/
int
_PyIO_trap_eintr(void)
{
if (!PyErr_ExceptionMatches(PyExc_OSError)) {
return 0;
}
PyObject *exc = PyErr_GetRaisedException();
PyOSErrorObject *env_err = (PyOSErrorObject *)exc;
assert(env_err != NULL);
if (env_err->myerrno != NULL) {
assert(EINTR > 0 && EINTR < INT_MAX);
assert(PyLong_CheckExact(env_err->myerrno));
int overflow;
int myerrno = PyLong_AsLongAndOverflow(env_err->myerrno, &overflow);
PyErr_Clear();
if (myerrno == EINTR) {
Py_DECREF(exc);
return 1;
}
}
/* This silences any error set by PyObject_RichCompareBool() */
PyErr_SetRaisedException(exc);
return 0;
}
/*
* Shared methods and wrappers
*/
static PyObject *
buffered_flush_and_rewind_unlocked(buffered *self)
{
PyObject *res;
res = _bufferedwriter_flush_unlocked(self);
if (res == NULL)
return NULL;
Py_DECREF(res);
if (self->readable) {
/* Rewind the raw stream so that its position corresponds to
the current logical position. */
Py_off_t n;
n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1);
_bufferedreader_reset_buf(self);
if (n == -1)
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
@critical_section
_io._Buffered.flush
[clinic start generated code]*/
static PyObject *
_io__Buffered_flush_impl(buffered *self)
/*[clinic end generated code: output=da2674ef1ce71f3a input=6b30de9f083419c2]*/
{
PyObject *res;
CHECK_INITIALIZED(self)
CHECK_CLOSED(self, "flush of closed file")
if (!ENTER_BUFFERED(self))
return NULL;
res = buffered_flush_and_rewind_unlocked(self);
LEAVE_BUFFERED(self)
return res;
}
/*[clinic input]
@critical_section
_io._Buffered.peek
size: Py_ssize_t = 0
/
[clinic start generated code]*/
static PyObject *
_io__Buffered_peek_impl(buffered *self, Py_ssize_t size)
/*[clinic end generated code: output=ba7a097ca230102b input=56733376f926d982]*/
{
PyObject *res = NULL;
CHECK_INITIALIZED(self)
CHECK_CLOSED(self, "peek of closed file")
if (!ENTER_BUFFERED(self))
return NULL;
if (self->writable) {
res = buffered_flush_and_rewind_unlocked(self);
if (res == NULL)
goto end;
Py_CLEAR(res);
}
res = _bufferedreader_peek_unlocked(self);
end:
LEAVE_BUFFERED(self)
return res;
}
/*[clinic input]
@critical_section
_io._Buffered.read
size as n: Py_ssize_t(accept={int, NoneType}) = -1
/
[clinic start generated code]*/
static PyObject *
_io__Buffered_read_impl(buffered *self, Py_ssize_t n)
/*[clinic end generated code: output=f41c78bb15b9bbe9 input=bdb4b0425b295472]*/
{
PyObject *res;
CHECK_INITIALIZED(self)
if (n < -1) {
PyErr_SetString(PyExc_ValueError,
"read length must be non-negative or -1");
return NULL;
}
CHECK_CLOSED(self, "read of closed file")
if (n == -1) {
/* The number of bytes is unspecified, read until the end of stream */
if (!ENTER_BUFFERED(self))
return NULL;
res = _bufferedreader_read_all(self);
}
else {
res = _bufferedreader_read_fast(self, n);
if (res != Py_None)
return res;