Debian Codegraph @

Modules/_io/bytesio.c

raw
1 #include "Python.h"
2 #include "pycore_object.h"
3 #include "pycore_sysmodule.h" // _PySys_GetSizeOf()
4 #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
5
6 #include <stddef.h> // offsetof()
7 #include "_iomodule.h"
8
9 /*[clinic input]
10 module _io
11 class _io.BytesIO "bytesio *" "clinic_state()->PyBytesIO_Type"
12 [clinic start generated code]*/
13 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=48ede2f330f847c3]*/
14
15 typedef struct {
16 PyObject_HEAD
17 PyObject *buf;
18 Py_ssize_t pos;
19 Py_ssize_t string_size;
20 PyObject *dict;
21 PyObject *weakreflist;
22 Py_ssize_t exports;
23 } bytesio;
24
25 typedef struct {
26 PyObject_HEAD
27 bytesio *source;
28 } bytesiobuf;
29
30 /* The bytesio object can be in three states:
31 * Py_REFCNT(buf) == 1, exports == 0.
32 * Py_REFCNT(buf) > 1. exports == 0,
33 first modification or export causes the internal buffer copying.
34 * exports > 0. Py_REFCNT(buf) == 1, any modifications are forbidden.
35 */
36
37 static int
38 check_closed(bytesio *self)
39 {
40 if (self->buf == NULL) {
41 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
42 return 1;
43 }
44 return 0;
45 }
46
47 static int
48 check_exports(bytesio *self)
49 {
50 if (self->exports > 0) {
51 PyErr_SetString(PyExc_BufferError,
52 "Existing exports of data: object cannot be re-sized");
53 return 1;
54 }
55 return 0;
56 }
57
58 #define CHECK_CLOSED(self) \
59 if (check_closed(self)) { \
60 return NULL; \
61 }
62
63 #define CHECK_EXPORTS(self) \
64 if (check_exports(self)) { \
65 return NULL; \
66 }
67
68 #define SHARED_BUF(self) (Py_REFCNT((self)->buf) > 1)
69
70
71 /* Internal routine to get a line from the buffer of a BytesIO
72 object. Returns the length between the current position to the
73 next newline character. */
74 static Py_ssize_t
75 scan_eol(bytesio *self, Py_ssize_t len)
76 {
77 const char *start, *n;
78 Py_ssize_t maxlen;
79
80 assert(self->buf != NULL);
81 assert(self->pos >= 0);
82
83 if (self->pos >= self->string_size)
84 return 0;
85
86 /* Move to the end of the line, up to the end of the string, s. */
87 maxlen = self->string_size - self->pos;
88 if (len < 0 || len > maxlen)
89 len = maxlen;
90
91 if (len) {
92 start = PyBytes_AS_STRING(self->buf) + self->pos;
93 n = memchr(start, '\n', len);
94 if (n)
95 /* Get the length from the current position to the end of
96 the line. */
97 len = n - start + 1;
98 }
99 assert(len >= 0);
100 assert(self->pos < PY_SSIZE_T_MAX - len);
101
102 return len;
103 }
104
105 /* Internal routine for detaching the shared buffer of BytesIO objects.
106 The caller should ensure that the 'size' argument is non-negative and
107 not lesser than self->string_size. Returns 0 on success, -1 otherwise. */
108 static int
109 unshare_buffer(bytesio *self, size_t size)
110 {
111 PyObject *new_buf;
112 assert(SHARED_BUF(self));
113 assert(self->exports == 0);
114 assert(size >= (size_t)self->string_size);
115 new_buf = PyBytes_FromStringAndSize(NULL, size);
116 if (new_buf == NULL)
117 return -1;
118 memcpy(PyBytes_AS_STRING(new_buf), PyBytes_AS_STRING(self->buf),
119 self->string_size);
120 Py_SETREF(self->buf, new_buf);
121 return 0;
122 }
123
124 /* Internal routine for changing the size of the buffer of BytesIO objects.
125 The caller should ensure that the 'size' argument is non-negative. Returns
126 0 on success, -1 otherwise. */
127 static int
128 resize_buffer(bytesio *self, size_t size)
129 {
130 assert(self->buf != NULL);
131 assert(self->exports == 0);
132
133 /* Here, unsigned types are used to avoid dealing with signed integer
134 overflow, which is undefined in C. */
135 size_t alloc = PyBytes_GET_SIZE(self->buf);
136
137 /* For simplicity, stay in the range of the signed type. Anyway, Python
138 doesn't allow strings to be longer than this. */
139 if (size > PY_SSIZE_T_MAX)
140 goto overflow;
141
142 if (size < alloc / 2) {
143 /* Major downsize; resize down to exact size. */
144 alloc = size + 1;
145 }
146 else if (size < alloc) {
147 /* Within allocated size; quick exit */
148 return 0;
149 }
150 else if (size <= alloc * 1.125) {
151 /* Moderate upsize; overallocate similar to list_resize() */
152 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
153 }
154 else {
155 /* Major upsize; resize up to exact size */
156 alloc = size + 1;
157 }
158
159 if (SHARED_BUF(self)) {
160 if (unshare_buffer(self, alloc) < 0)
161 return -1;
162 }
163 else {
164 if (_PyBytes_Resize(&self->buf, alloc) < 0)
165 return -1;
166 }
167
168 return 0;
169
170 overflow:
171 PyErr_SetString(PyExc_OverflowError,
172 "new buffer size too large");
173 return -1;
174 }
175
176 /* Internal routine for writing a string of bytes to the buffer of a BytesIO
177 object. Returns the number of bytes written, or -1 on error.
178 Inlining is disabled because it's significantly decreases performance
179 of writelines() in PGO build. */
180 Py_NO_INLINE static Py_ssize_t
181 write_bytes(bytesio *self, PyObject *b)
182 {
183 Py_buffer buf;
184 Py_ssize_t len;
185 if (PyObject_GetBuffer(b, &buf, PyBUF_CONTIG_RO) < 0) {
186 return -1;
187 }
188
189 if (check_closed(self) || check_exports(self)) {
190 len = -1;
191 goto done;
192 }
193
194 len = buf.len;
195 if (len == 0) {
196 goto done;
197 }
198
199 assert(self->pos >= 0);
200 size_t endpos = (size_t)self->pos + len;
201 if (endpos > (size_t)PyBytes_GET_SIZE(self->buf)) {
202 if (resize_buffer(self, endpos) < 0) {
203 len = -1;
204 goto done;
205 }
206 }
207 else if (SHARED_BUF(self)) {
208 if (unshare_buffer(self, Py_MAX(endpos, (size_t)self->string_size)) < 0) {
209 len = -1;
210 goto done;
211 }
212 }
213
214 if (self->pos > self->string_size) {
215 /* In case of overseek, pad with null bytes the buffer region between
216 the end of stream and the current position.
217
218 0 lo string_size hi
219 | |<---used--->|<----------available----------->|
220 | | <--to pad-->|<---to write---> |
221 0 buf position
222 */
223 memset(PyBytes_AS_STRING(self->buf) + self->string_size, '\0',
224 (self->pos - self->string_size) * sizeof(char));
225 }
226
227 /* Copy the data to the internal buffer, overwriting some of the existing
228 data if self->pos < self->string_size. */
229 memcpy(PyBytes_AS_STRING(self->buf) + self->pos, buf.buf, len);
230 self->pos = endpos;
231
232 /* Set the new length of the internal string if it has changed. */
233 if ((size_t)self->string_size < endpos) {
234 self->string_size = endpos;
235 }
236
237 done:
238 PyBuffer_Release(&buf);
239 return len;
240 }
241
242 static PyObject *
243 bytesio_get_closed(bytesio *self, void *Py_UNUSED(ignored))
244 {
245 if (self->buf == NULL) {
246 Py_RETURN_TRUE;
247 }
248 else {
249 Py_RETURN_FALSE;
250 }
251 }
252
253 /*[clinic input]
254 _io.BytesIO.readable
255
256 Returns True if the IO object can be read.
257 [clinic start generated code]*/
258
259 static PyObject *
260 _io_BytesIO_readable_impl(bytesio *self)
261 /*[clinic end generated code: output=4e93822ad5b62263 input=96c5d0cccfb29f5c]*/
262 {
263 CHECK_CLOSED(self);
264 Py_RETURN_TRUE;
265 }
266
267 /*[clinic input]
268 _io.BytesIO.writable
269
270 Returns True if the IO object can be written.
271 [clinic start generated code]*/
272
273 static PyObject *
274 _io_BytesIO_writable_impl(bytesio *self)
275 /*[clinic end generated code: output=64ff6a254b1150b8 input=700eed808277560a]*/
276 {
277 CHECK_CLOSED(self);
278 Py_RETURN_TRUE;
279 }
280
281 /*[clinic input]
282 _io.BytesIO.seekable
283
284 Returns True if the IO object can be seeked.
285 [clinic start generated code]*/
286
287 static PyObject *
288 _io_BytesIO_seekable_impl(bytesio *self)
289 /*[clinic end generated code: output=6b417f46dcc09b56 input=9421f65627a344dd]*/
290 {
291 CHECK_CLOSED(self);
292 Py_RETURN_TRUE;
293 }
294
295 /*[clinic input]
296 _io.BytesIO.flush
297
298 Does nothing.
299 [clinic start generated code]*/
300
301 static PyObject *
302 _io_BytesIO_flush_impl(bytesio *self)
303 /*[clinic end generated code: output=187e3d781ca134a0 input=561ea490be4581a7]*/
304 {
305 CHECK_CLOSED(self);
306 Py_RETURN_NONE;
307 }
308
309 /*[clinic input]
310 _io.BytesIO.getbuffer
311
312 cls: defining_class
313 /
314
315 Get a read-write view over the contents of the BytesIO object.
316 [clinic start generated code]*/
317
318 static PyObject *
319 _io_BytesIO_getbuffer_impl(bytesio *self, PyTypeObject *cls)
320 /*[clinic end generated code: output=045091d7ce87fe4e input=0668fbb48f95dffa]*/
321 {
322 _PyIO_State *state = get_io_state_by_cls(cls);
323 PyTypeObject *type = state->PyBytesIOBuffer_Type;
324 bytesiobuf *buf;
325 PyObject *view;
326
327 CHECK_CLOSED(self);
328
329 buf = (bytesiobuf *) type->tp_alloc(type, 0);
330 if (buf == NULL)
331 return NULL;
332 buf->source = (bytesio*)Py_NewRef(self);
333 view = PyMemoryView_FromObject((PyObject *) buf);
334 Py_DECREF(buf);
335 return view;
336 }
337
338 /*[clinic input]
339 _io.BytesIO.getvalue
340
341 Retrieve the entire contents of the BytesIO object.
342 [clinic start generated code]*/
343
344 static PyObject *
345 _io_BytesIO_getvalue_impl(bytesio *self)
346 /*[clinic end generated code: output=b3f6a3233c8fd628 input=4b403ac0af3973ed]*/
347 {
348 CHECK_CLOSED(self);
349 if (self->string_size <= 1 || self->exports > 0)
350 return PyBytes_FromStringAndSize(PyBytes_AS_STRING(self->buf),
351 self->string_size);
352
353 if (self->string_size != PyBytes_GET_SIZE(self->buf)) {
354 if (SHARED_BUF(self)) {
355 if (unshare_buffer(self, self->string_size) < 0)
356 return NULL;
357 }
358 else {
359 if (_PyBytes_Resize(&self->buf, self->string_size) < 0)
360 return NULL;
361 }
362 }
363 return Py_NewRef(self->buf);
364 }
365
366 /*[clinic input]
367 _io.BytesIO.isatty
368
369 Always returns False.
370
371 BytesIO objects are not connected to a TTY-like device.
372 [clinic start generated code]*/
373
374 static PyObject *
375 _io_BytesIO_isatty_impl(bytesio *self)
376 /*[clinic end generated code: output=df67712e669f6c8f input=6f97f0985d13f827]*/
377 {
378 CHECK_CLOSED(self);
379 Py_RETURN_FALSE;
380 }
381
382 /*[clinic input]
383 _io.BytesIO.tell
384
385 Current file position, an integer.
386 [clinic start generated code]*/
387
388 static PyObject *
389 _io_BytesIO_tell_impl(bytesio *self)
390 /*[clinic end generated code: output=b54b0f93cd0e5e1d input=b106adf099cb3657]*/
391 {
392 CHECK_CLOSED(self);
393 return PyLong_FromSsize_t(self->pos);
394 }
395
396 static PyObject *
397 read_bytes(bytesio *self, Py_ssize_t size)
398 {
399 const char *output;
400
401 assert(self->buf != NULL);
402 assert(size <= self->string_size);
403 if (size > 1 &&
404 self->pos == 0 && size == PyBytes_GET_SIZE(self->buf) &&
405 self->exports == 0) {
406 self->pos += size;
407 return Py_NewRef(self->buf);
408 }
409
410 /* gh-141311: Avoid undefined behavior when self->pos (limit PY_SSIZE_T_MAX)
411 is beyond the size of self->buf. Assert above validates size is always in
412 bounds. When self->pos is out of bounds calling code sets size to 0. */
413 if (size == 0) {
414 return PyBytes_FromStringAndSize(NULL, 0);
415 }
416
417 output = PyBytes_AS_STRING(self->buf) + self->pos;
418 self->pos += size;
419 return PyBytes_FromStringAndSize(output, size);
420 }
421
422 /*[clinic input]
423 _io.BytesIO.read
424 size: Py_ssize_t(accept={int, NoneType}) = -1
425 /
426
427 Read at most size bytes, returned as a bytes object.
428
429 If the size argument is negative, read until EOF is reached.
430 Return an empty bytes object at EOF.
431 [clinic start generated code]*/
432
433 static PyObject *
434 _io_BytesIO_read_impl(bytesio *self, Py_ssize_t size)
435 /*[clinic end generated code: output=9cc025f21c75bdd2 input=74344a39f431c3d7]*/
436 {
437 Py_ssize_t n;
438
439 CHECK_CLOSED(self);
440
441 /* adjust invalid sizes */
442 n = self->string_size - self->pos;
443 if (size < 0 || size > n) {
444 size = n;
445 if (size < 0)
446 size = 0;
447 }
448
449 return read_bytes(self, size);
450 }
451
452
453 /*[clinic input]
454 _io.BytesIO.read1
455 size: Py_ssize_t(accept={int, NoneType}) = -1
456 /
457
458 Read at most size bytes, returned as a bytes object.
459
460 If the size argument is negative or omitted, read until EOF is reached.
461 Return an empty bytes object at EOF.
462 [clinic start generated code]*/
463
464 static PyObject *
465 _io_BytesIO_read1_impl(bytesio *self, Py_ssize_t size)
466 /*[clinic end generated code: output=d0f843285aa95f1c input=440a395bf9129ef5]*/
467 {
468 return _io_BytesIO_read_impl(self, size);
469 }
470
471 /*[clinic input]
472 _io.BytesIO.readline
473 size: Py_ssize_t(accept={int, NoneType}) = -1
474 /
475
476 Next line from the file, as a bytes object.
477
478 Retain newline. A non-negative size argument limits the maximum
479 number of bytes to return (an incomplete line may be returned then).
480 Return an empty bytes object at EOF.
481 [clinic start generated code]*/
482
483 static PyObject *
484 _io_BytesIO_readline_impl(bytesio *self, Py_ssize_t size)
485 /*[clinic end generated code: output=4bff3c251df8ffcd input=e7c3fbd1744e2783]*/
486 {
487 Py_ssize_t n;
488
489 CHECK_CLOSED(self);
490
491 n = scan_eol(self, size);
492
493 return read_bytes(self, n);
494 }
495
496 /*[clinic input]
497 _io.BytesIO.readlines
498 size as arg: object = None
499 /
500
501 List of bytes objects, each a line from the file.
502
503 Call readline() repeatedly and return a list of the lines so read.
504 The optional size argument, if given, is an approximate bound on the
505 total number of bytes in the lines returned.
506 [clinic start generated code]*/
507
508 static PyObject *
509 _io_BytesIO_readlines_impl(bytesio *self, PyObject *arg)
510 /*[clinic end generated code: output=09b8e34c880808ff input=691aa1314f2c2a87]*/
511 {
512 Py_ssize_t maxsize, size, n;
513 PyObject *result, *line;
514 const char *output;
515
516 CHECK_CLOSED(self);
517
518 if (PyLong_Check(arg)) {
519 maxsize = PyLong_AsSsize_t(arg);
520 if (maxsize == -1 && PyErr_Occurred())
521 return NULL;
522 }
523 else if (arg == Py_None) {
524 /* No size limit, by default. */
525 maxsize = -1;
526 }
527 else {
528 PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
529 Py_TYPE(arg)->tp_name);
530 return NULL;
531 }
532
533 size = 0;
534 result = PyList_New(0);
535 if (!result)
536 return NULL;
537
538 output = PyBytes_AS_STRING(self->buf) + self->pos;
539 while ((n = scan_eol(self, -1)) != 0) {
540 self->pos += n;
541 line = PyBytes_FromStringAndSize(output, n);
542 if (!line)
543 goto on_error;
544 if (PyList_Append(result, line) == -1) {
545 Py_DECREF(line);
546 goto on_error;
547 }
548 Py_DECREF(line);
549 size += n;
550 if (maxsize > 0 && size >= maxsize)
551 break;
552 output += n;
553 }
554 return result;
555
556 on_error:
557 Py_DECREF(result);
558 return NULL;
559 }
560
561 /*[clinic input]
562 _io.BytesIO.readinto
563 buffer: Py_buffer(accept={rwbuffer})
564 /
565
566 Read bytes into buffer.
567
568 Returns number of bytes read (0 for EOF), or None if the object
569 is set not to block and has no data to read.
570 [clinic start generated code]*/
571
572 static PyObject *
573 _io_BytesIO_readinto_impl(bytesio *self, Py_buffer *buffer)
574 /*[clinic end generated code: output=a5d407217dcf0639 input=1424d0fdce857919]*/
575 {
576 Py_ssize_t len, n;
577
578 CHECK_CLOSED(self);
579
580 /* adjust invalid sizes */
581 len = buffer->len;
582 n = self->string_size - self->pos;
583 if (len > n) {
584 len = n;
585 if (len < 0) {
586 /* gh-141311: Avoid undefined behavior when self->pos (limit
587 PY_SSIZE_T_MAX) points beyond the size of self->buf. */
588 return PyLong_FromSsize_t(0);
589 }
590 }
591
592 assert(self->pos + len <= PY_SSIZE_T_MAX);
593 assert(len >= 0);
594 memcpy(buffer->buf, PyBytes_AS_STRING(self->buf) + self->pos, len);
595 self->pos += len;
596
597 return PyLong_FromSsize_t(len);
598 }
599
600 /*[clinic input]
601 _io.BytesIO.truncate
602 size: Py_ssize_t(accept={int, NoneType}, c_default="self->pos") = None
603 /
604
605 Truncate the file to at most size bytes.
606
607 Size defaults to the current file position, as returned by tell().
608 The current file position is unchanged. Returns the new size.
609 [clinic start generated code]*/
610
611 static PyObject *
612 _io_BytesIO_truncate_impl(bytesio *self, Py_ssize_t size)
613 /*[clinic end generated code: output=9ad17650c15fa09b input=423759dd42d2f7c1]*/
614 {
615 CHECK_CLOSED(self);
616 CHECK_EXPORTS(self);
617
618 if (size < 0) {
619 PyErr_Format(PyExc_ValueError,
620 "negative size value %zd", size);
621 return NULL;
622 }
623
624 if (size < self->string_size) {
625 self->string_size = size;
626 if (resize_buffer(self, size) < 0)
627 return NULL;
628 }
629
630 return PyLong_FromSsize_t(size);
631 }
632
633 static PyObject *
634 bytesio_iternext(bytesio *self)
635 {
636 Py_ssize_t n;
637
638 CHECK_CLOSED(self);
639
640 n = scan_eol(self, -1);
641
642 if (n == 0)
643 return NULL;
644
645 return read_bytes(self, n);
646 }
647
648 /*[clinic input]
649 _io.BytesIO.seek
650 pos: Py_ssize_t
651 whence: int = 0
652 /
653
654 Change stream position.
655
656 Seek to byte offset pos relative to position indicated by whence:
657 0 Start of stream (the default). pos should be >= 0;
658 1 Current position - pos may be negative;
659 2 End of stream - pos usually negative.
660 Returns the new absolute position.
661 [clinic start generated code]*/
662
663 static PyObject *
664 _io_BytesIO_seek_impl(bytesio *self, Py_ssize_t pos, int whence)
665 /*[clinic end generated code: output=c26204a68e9190e4 input=1e875e6ebc652948]*/
666 {
667 CHECK_CLOSED(self);
668
669 if (pos < 0 && whence == 0) {
670 PyErr_Format(PyExc_ValueError,
671 "negative seek value %zd", pos);
672 return NULL;
673 }
674
675 /* whence = 0: offset relative to beginning of the string.
676 whence = 1: offset relative to current position.
677 whence = 2: offset relative the end of the string. */
678 if (whence == 1) {
679 if (pos > PY_SSIZE_T_MAX - self->pos) {
680 PyErr_SetString(PyExc_OverflowError,
681 "new position too large");
682 return NULL;
683 }
684 pos += self->pos;
685 }
686 else if (whence == 2) {
687 if (pos > PY_SSIZE_T_MAX - self->string_size) {
688 PyErr_SetString(PyExc_OverflowError,
689 "new position too large");
690 return NULL;
691 }
692 pos += self->string_size;
693 }
694 else if (whence != 0) {
695 PyErr_Format(PyExc_ValueError,
696 "invalid whence (%i, should be 0, 1 or 2)", whence);
697 return NULL;
698 }
699
700 if (pos < 0)
701 pos = 0;
702 self->pos = pos;
703
704 return PyLong_FromSsize_t(self->pos);
705 }
706
707 /*[clinic input]
708 _io.BytesIO.write
709 b: object
710 /
711
712 Write bytes to file.
713
714 Return the number of bytes written.
715 [clinic start generated code]*/
716
717 static PyObject *
718 _io_BytesIO_write(bytesio *self, PyObject *b)
719 /*[clinic end generated code: output=53316d99800a0b95 input=f5ec7c8c64ed720a]*/
720 {
721 Py_ssize_t n = write_bytes(self, b);
722 return n >= 0 ? PyLong_FromSsize_t(n) : NULL;
723 }
724
725 /*[clinic input]
726 _io.BytesIO.writelines
727 lines: object
728 /
729
730 Write lines to the file.
731
732 Note that newlines are not added. lines can be any iterable object
733 producing bytes-like objects. This is equivalent to calling write() for
734 each element.
735 [clinic start generated code]*/
736
737 static PyObject *
738 _io_BytesIO_writelines(bytesio *self, PyObject *lines)
739 /*[clinic end generated code: output=7f33aa3271c91752 input=e972539176fc8fc1]*/
740 {
741 PyObject *it, *item;
742
743 CHECK_CLOSED(self);
744
745 it = PyObject_GetIter(lines);
746 if (it == NULL)
747 return NULL;
748
749 while ((item = PyIter_Next(it)) != NULL) {
750 Py_ssize_t ret = write_bytes(self, item);
751 Py_DECREF(item);
752 if (ret < 0) {
753 Py_DECREF(it);
754 return NULL;
755 }
756 }
757 Py_DECREF(it);
758
759 /* See if PyIter_Next failed */
760 if (PyErr_Occurred())
761 return NULL;
762
763 Py_RETURN_NONE;
764 }
765
766 /*[clinic input]
767 _io.BytesIO.close
768
769 Disable all I/O operations.
770 [clinic start generated code]*/
771
772 static PyObject *
773 _io_BytesIO_close_impl(bytesio *self)
774 /*[clinic end generated code: output=1471bb9411af84a0 input=37e1f55556e61f60]*/
775 {
776 CHECK_EXPORTS(self);
777 Py_CLEAR(self->buf);
778 Py_RETURN_NONE;
779 }
780
781 /* Pickling support.
782
783 Note that only pickle protocol 2 and onward are supported since we use
784 extended __reduce__ API of PEP 307 to make BytesIO instances picklable.
785
786 Providing support for protocol < 2 would require the __reduce_ex__ method
787 which is notably long-winded when defined properly.
788
789 For BytesIO, the implementation would similar to one coded for
790 object.__reduce_ex__, but slightly less general. To be more specific, we
791 could call bytesio_getstate directly and avoid checking for the presence of
792 a fallback __reduce__ method. However, we would still need a __newobj__
793 function to use the efficient instance representation of PEP 307.
794 */
795
796 static PyObject *
797 bytesio_getstate(bytesio *self, PyObject *Py_UNUSED(ignored))
798 {
799 PyObject *initvalue = _io_BytesIO_getvalue_impl(self);
800 PyObject *dict;
801 PyObject *state;
802
803 if (initvalue == NULL)
804 return NULL;
805 if (self->dict == NULL) {
806 dict = Py_NewRef(Py_None);
807 }
808 else {
809 dict = PyDict_Copy(self->dict);
810 if (dict == NULL) {
811 Py_DECREF(initvalue);
812 return NULL;
813 }
814 }
815
816 state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);
817 Py_DECREF(initvalue);
818 return state;
819 }
820
821 static PyObject *
822 bytesio_setstate(bytesio *self, PyObject *state)
823 {
824 PyObject *result;
825 PyObject *position_obj;
826 PyObject *dict;
827 Py_ssize_t pos;
828
829 assert(state != NULL);
830
831 /* We allow the state tuple to be longer than 3, because we may need
832 someday to extend the object's state without breaking
833 backward-compatibility. */
834 if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) < 3) {
835 PyErr_Format(PyExc_TypeError,
836 "%.200s.__setstate__ argument should be 3-tuple, got %.200s",
837 Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
838 return NULL;
839 }
840 CHECK_EXPORTS(self);
841 /* Reset the object to its default state. This is only needed to handle
842 the case of repeated calls to __setstate__. */
843 self->string_size = 0;
844 self->pos = 0;
845
846 /* Set the value of the internal buffer. If state[0] does not support the
847 buffer protocol, bytesio_write will raise the appropriate TypeError. */
848 result = _io_BytesIO_write(self, PyTuple_GET_ITEM(state, 0));
849 if (result == NULL)
850 return NULL;
851 Py_DECREF(result);
852
853 /* Set carefully the position value. Alternatively, we could use the seek
854 method instead of modifying self->pos directly to better protect the
855 object internal state against erroneous (or malicious) inputs. */
856 position_obj = PyTuple_GET_ITEM(state, 1);
857 if (!PyLong_Check(position_obj)) {
858 PyErr_Format(PyExc_TypeError,
859 "second item of state must be an integer, not %.200s",
860 Py_TYPE(position_obj)->tp_name);
861 return NULL;
862 }
863 pos = PyLong_AsSsize_t(position_obj);
864 if (pos == -1 && PyErr_Occurred())
865 return NULL;
866 if (pos < 0) {
867 PyErr_SetString(PyExc_ValueError,
868 "position value cannot be negative");
869 return NULL;
870 }
871 self->pos = pos;
872
873 /* Set the dictionary of the instance variables. */
874 dict = PyTuple_GET_ITEM(state, 2);
875 if (dict != Py_None) {
876 if (!PyDict_Check(dict)) {
877 PyErr_Format(PyExc_TypeError,
878 "third item of state should be a dict, got a %.200s",
879 Py_TYPE(dict)->tp_name);
880 return NULL;
881 }
882 if (self->dict) {
883 /* Alternatively, we could replace the internal dictionary
884 completely. However, it seems more practical to just update it. */
885 if (PyDict_Update(self->dict, dict) < 0)
886 return NULL;
887 }
888 else {
889 self->dict = Py_NewRef(dict);
890 }
891 }
892
893 Py_RETURN_NONE;
894 }
895
896 static void
897 bytesio_dealloc(bytesio *self)
898 {
899 PyTypeObject *tp = Py_TYPE(self);
900 _PyObject_GC_UNTRACK(self);
901 if (self->exports > 0) {
902 PyErr_SetString(PyExc_SystemError,
903 "deallocated BytesIO object has exported buffers");
904 PyErr_Print();
905 }
906 Py_CLEAR(self->buf);
907 Py_CLEAR(self->dict);
908 FT_CLEAR_WEAKREFS((PyObject *) self, self->weakreflist);
909 tp->tp_free(self);
910 Py_DECREF(tp);
911 }
912
913 static PyObject *
914 bytesio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
915 {
916 bytesio *self;
917
918 assert(type != NULL && type->tp_alloc != NULL);
919 self = (bytesio *)type->tp_alloc(type, 0);
920 if (self == NULL)
921 return NULL;
922
923 /* tp_alloc initializes all the fields to zero. So we don't have to
924 initialize them here. */
925
926 self->buf = PyBytes_FromStringAndSize(NULL, 0);
927 if (self->buf == NULL) {
928 Py_DECREF(self);
929 return PyErr_NoMemory();
930 }
931
932 return (PyObject *)self;
933 }
934
935 /*[clinic input]
936 _io.BytesIO.__init__
937 initial_bytes as initvalue: object(c_default="NULL") = b''
938
939 Buffered I/O implementation using an in-memory bytes buffer.
940 [clinic start generated code]*/
941
942 static int
943 _io_BytesIO___init___impl(bytesio *self, PyObject *initvalue)
944 /*[clinic end generated code: output=65c0c51e24c5b621 input=aac7f31b67bf0fb6]*/
945 {
946 /* In case, __init__ is called multiple times. */
947 self->string_size = 0;
948 self->pos = 0;
949
950 if (self->exports > 0) {
951 PyErr_SetString(PyExc_BufferError,
952 "Existing exports of data: object cannot be re-sized");
953 return -1;
954 }
955 if (initvalue && initvalue != Py_None) {
956 if (PyBytes_CheckExact(initvalue)) {
957 Py_XSETREF(self->buf, Py_NewRef(initvalue));
958 self->string_size = PyBytes_GET_SIZE(initvalue);
959 }
960 else {
961 PyObject *res;
962 res = _io_BytesIO_write(self, initvalue);
963 if (res == NULL)
964 return -1;
965 Py_DECREF(res);
966 self->pos = 0;
967 }
968 }
969
970 return 0;
971 }
972
973 static PyObject *
974 bytesio_sizeof(bytesio *self, void *unused)
975 {
976 size_t res = _PyObject_SIZE(Py_TYPE(self));
977 if (self->buf && !SHARED_BUF(self)) {
978 size_t s = _PySys_GetSizeOf(self->buf);
979 if (s == (size_t)-1) {
980 return NULL;
981 }
982 res += s;
983 }
984 return PyLong_FromSize_t(res);
985 }
986
987 static int
988 bytesio_traverse(bytesio *self, visitproc visit, void *arg)
989 {
990 Py_VISIT(Py_TYPE(self));
991 Py_VISIT(self->dict);
992 Py_VISIT(self->buf);
993 return 0;
994 }
995
996 static int
997 bytesio_clear(bytesio *self)
998 {
999 Py_CLEAR(self->dict);
1000 if (self->exports == 0) {
1001 Py_CLEAR(self->buf);
1002 }
1003 return 0;
1004 }
1005
1006
1007 #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
1008 #include "clinic/bytesio.c.h"
1009 #undef clinic_state
1010
1011 static PyGetSetDef bytesio_getsetlist[] = {
1012 {"closed", (getter)bytesio_get_closed, NULL,
1013 "True if the file is closed."},
1014 {NULL}, /* sentinel */
1015 };
1016
1017 static struct PyMethodDef bytesio_methods[] = {
1018 _IO_BYTESIO_READABLE_METHODDEF
1019 _IO_BYTESIO_SEEKABLE_METHODDEF
1020 _IO_BYTESIO_WRITABLE_METHODDEF
1021 _IO_BYTESIO_CLOSE_METHODDEF
1022 _IO_BYTESIO_FLUSH_METHODDEF
1023 _IO_BYTESIO_ISATTY_METHODDEF
1024 _IO_BYTESIO_TELL_METHODDEF
1025 _IO_BYTESIO_WRITE_METHODDEF
1026 _IO_BYTESIO_WRITELINES_METHODDEF
1027 _IO_BYTESIO_READ1_METHODDEF
1028 _IO_BYTESIO_READINTO_METHODDEF
1029 _IO_BYTESIO_READLINE_METHODDEF
1030 _IO_BYTESIO_READLINES_METHODDEF
1031 _IO_BYTESIO_READ_METHODDEF
1032 _IO_BYTESIO_GETBUFFER_METHODDEF
1033 _IO_BYTESIO_GETVALUE_METHODDEF
1034 _IO_BYTESIO_SEEK_METHODDEF
1035 _IO_BYTESIO_TRUNCATE_METHODDEF
1036 {"__getstate__", (PyCFunction)bytesio_getstate, METH_NOARGS, NULL},
1037 {"__setstate__", (PyCFunction)bytesio_setstate, METH_O, NULL},
1038 {"__sizeof__", (PyCFunction)bytesio_sizeof, METH_NOARGS, NULL},
1039 {NULL, NULL} /* sentinel */
1040 };
1041
1042 static PyMemberDef bytesio_members[] = {
1043 {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(bytesio, weakreflist), Py_READONLY},
1044 {"__dictoffset__", Py_T_PYSSIZET, offsetof(bytesio, dict), Py_READONLY},
1045 {NULL}
1046 };
1047
1048 static PyType_Slot bytesio_slots[] = {
1049 {Py_tp_dealloc, bytesio_dealloc},
1050 {Py_tp_doc, (void *)_io_BytesIO___init____doc__},
1051 {Py_tp_traverse, bytesio_traverse},
1052 {Py_tp_clear, bytesio_clear},
1053 {Py_tp_iter, PyObject_SelfIter},
1054 {Py_tp_iternext, bytesio_iternext},
1055 {Py_tp_methods, bytesio_methods},
1056 {Py_tp_members, bytesio_members},
1057 {Py_tp_getset, bytesio_getsetlist},
1058 {Py_tp_init, _io_BytesIO___init__},
1059 {Py_tp_new, bytesio_new},
1060 {0, NULL},
1061 };
1062
1063 PyType_Spec bytesio_spec = {
1064 .name = "_io.BytesIO",
1065 .basicsize = sizeof(bytesio),
1066 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1067 Py_TPFLAGS_IMMUTABLETYPE),
1068 .slots = bytesio_slots,
1069 };
1070
1071 /*
1072 * Implementation of the small intermediate object used by getbuffer().
1073 * getbuffer() returns a memoryview over this object, which should make it
1074 * invisible from Python code.
1075 */
1076
1077 static int
1078 bytesiobuf_getbuffer(bytesiobuf *obj, Py_buffer *view, int flags)
1079 {
1080 bytesio *b = (bytesio *) obj->source;
1081
1082 if (view == NULL) {
1083 PyErr_SetString(PyExc_BufferError,
1084 "bytesiobuf_getbuffer: view==NULL argument is obsolete");
1085 return -1;
1086 }
1087 if (b->exports == 0 && SHARED_BUF(b)) {
1088 if (unshare_buffer(b, b->string_size) < 0)
1089 return -1;
1090 }
1091
1092 /* cannot fail if view != NULL and readonly == 0 */
1093 (void)PyBuffer_FillInfo(view, (PyObject*)obj,
1094 PyBytes_AS_STRING(b->buf), b->string_size,
1095 0, flags);
1096 b->exports++;
1097 return 0;
1098 }
1099
1100 static void
1101 bytesiobuf_releasebuffer(bytesiobuf *obj, Py_buffer *view)
1102 {
1103 bytesio *b = (bytesio *) obj->source;
1104 b->exports--;
1105 }
1106
1107 static int
1108 bytesiobuf_traverse(bytesiobuf *self, visitproc visit, void *arg)
1109 {
1110 Py_VISIT(Py_TYPE(self));
1111 Py_VISIT(self->source);
1112 return 0;
1113 }
1114
1115 static void
1116 bytesiobuf_dealloc(bytesiobuf *self)
1117 {
1118 PyTypeObject *tp = Py_TYPE(self);
1119 /* bpo-31095: UnTrack is needed before calling any callbacks */
1120 PyObject_GC_UnTrack(self);
1121 Py_CLEAR(self->source);
1122 tp->tp_free(self);
1123 Py_DECREF(tp);
1124 }
1125
1126 static PyType_Slot bytesiobuf_slots[] = {
1127 {Py_tp_dealloc, bytesiobuf_dealloc},
1128 {Py_tp_traverse, bytesiobuf_traverse},
1129
1130 // Buffer protocol
1131 {Py_bf_getbuffer, bytesiobuf_getbuffer},
1132 {Py_bf_releasebuffer, bytesiobuf_releasebuffer},
1133 {0, NULL},
1134 };
1135
1136 PyType_Spec bytesiobuf_spec = {
1137 .name = "_io._BytesIOBuffer",
1138 .basicsize = sizeof(bytesiobuf),
1139 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1140 Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
1141 .slots = bytesiobuf_slots,
1142 };