Debian Codegraph @

Modules/_io/stringio.c

raw
1 #include "Python.h"
2 #include <stddef.h> // offsetof()
3 #include "pycore_object.h"
4 #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
5 #include "_iomodule.h"
6
7 /* Implementation note: the buffer is always at least one character longer
8 than the enclosed string, for proper functioning of _PyIO_find_line_ending.
9 */
10
11 #define STATE_REALIZED 1
12 #define STATE_ACCUMULATING 2
13
14 /*[clinic input]
15 module _io
16 class _io.StringIO "stringio *" "clinic_state()->PyStringIO_Type"
17 [clinic start generated code]*/
18 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=2693eada0658d470]*/
19
20 typedef struct {
21 PyObject_HEAD
22 Py_UCS4 *buf;
23 Py_ssize_t pos;
24 Py_ssize_t string_size;
25 size_t buf_size;
26
27 /* The stringio object can be in two states: accumulating or realized.
28 In accumulating state, the internal buffer contains nothing and
29 the contents are given by the embedded _PyUnicodeWriter structure.
30 In realized state, the internal buffer is meaningful and the
31 _PyUnicodeWriter is destroyed.
32 */
33 int state;
34 _PyUnicodeWriter writer;
35
36 char ok; /* initialized? */
37 char closed;
38 char readuniversal;
39 char readtranslate;
40 PyObject *decoder;
41 PyObject *readnl;
42 PyObject *writenl;
43
44 PyObject *dict;
45 PyObject *weakreflist;
46 _PyIO_State *module_state;
47 } stringio;
48
49 #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
50 #include "clinic/stringio.c.h"
51 #undef clinic_state
52
53 static int _io_StringIO___init__(PyObject *self, PyObject *args, PyObject *kwargs);
54
55 #define CHECK_INITIALIZED(self) \
56 if (self->ok <= 0) { \
57 PyErr_SetString(PyExc_ValueError, \
58 "I/O operation on uninitialized object"); \
59 return NULL; \
60 }
61
62 #define CHECK_CLOSED(self) \
63 if (self->closed) { \
64 PyErr_SetString(PyExc_ValueError, \
65 "I/O operation on closed file"); \
66 return NULL; \
67 }
68
69 #define ENSURE_REALIZED(self) \
70 if (realize(self) < 0) { \
71 return NULL; \
72 }
73
74
75 /* Internal routine for changing the size, in terms of characters, of the
76 buffer of StringIO objects. The caller should ensure that the 'size'
77 argument is non-negative. Returns 0 on success, -1 otherwise. */
78 static int
79 resize_buffer(stringio *self, size_t size)
80 {
81 /* Here, unsigned types are used to avoid dealing with signed integer
82 overflow, which is undefined in C. */
83 size_t alloc = self->buf_size;
84 Py_UCS4 *new_buf = NULL;
85
86 assert(self->buf != NULL);
87
88 /* Reserve one more char for line ending detection. */
89 size = size + 1;
90 /* For simplicity, stay in the range of the signed type. Anyway, Python
91 doesn't allow strings to be longer than this. */
92 if (size > PY_SSIZE_T_MAX)
93 goto overflow;
94
95 if (size < alloc / 2) {
96 /* Major downsize; resize down to exact size. */
97 alloc = size + 1;
98 }
99 else if (size < alloc) {
100 /* Within allocated size; quick exit */
101 return 0;
102 }
103 else if (size <= alloc * 1.125) {
104 /* Moderate upsize; overallocate similar to list_resize() */
105 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
106 }
107 else {
108 /* Major upsize; resize up to exact size */
109 alloc = size + 1;
110 }
111
112 if (alloc > PY_SIZE_MAX / sizeof(Py_UCS4))
113 goto overflow;
114 new_buf = (Py_UCS4 *)PyMem_Realloc(self->buf, alloc * sizeof(Py_UCS4));
115 if (new_buf == NULL) {
116 PyErr_NoMemory();
117 return -1;
118 }
119 self->buf_size = alloc;
120 self->buf = new_buf;
121
122 return 0;
123
124 overflow:
125 PyErr_SetString(PyExc_OverflowError,
126 "new buffer size too large");
127 return -1;
128 }
129
130 static PyObject *
131 make_intermediate(stringio *self)
132 {
133 PyObject *intermediate = _PyUnicodeWriter_Finish(&self->writer);
134 self->state = STATE_REALIZED;
135 if (intermediate == NULL)
136 return NULL;
137
138 _PyUnicodeWriter_Init(&self->writer);
139 self->writer.overallocate = 1;
140 if (_PyUnicodeWriter_WriteStr(&self->writer, intermediate)) {
141 Py_DECREF(intermediate);
142 return NULL;
143 }
144 self->state = STATE_ACCUMULATING;
145 return intermediate;
146 }
147
148 static int
149 realize(stringio *self)
150 {
151 Py_ssize_t len;
152 PyObject *intermediate;
153
154 if (self->state == STATE_REALIZED)
155 return 0;
156 assert(self->state == STATE_ACCUMULATING);
157 self->state = STATE_REALIZED;
158
159 intermediate = _PyUnicodeWriter_Finish(&self->writer);
160 if (intermediate == NULL)
161 return -1;
162
163 /* Append the intermediate string to the internal buffer.
164 The length should be equal to the current cursor position.
165 */
166 len = PyUnicode_GET_LENGTH(intermediate);
167 if (resize_buffer(self, len) < 0) {
168 Py_DECREF(intermediate);
169 return -1;
170 }
171 if (!PyUnicode_AsUCS4(intermediate, self->buf, len, 0)) {
172 Py_DECREF(intermediate);
173 return -1;
174 }
175
176 Py_DECREF(intermediate);
177 return 0;
178 }
179
180 /* Internal routine for writing a whole PyUnicode object to the buffer of a
181 StringIO object. Returns 0 on success, or -1 on error. */
182 static Py_ssize_t
183 write_str(stringio *self, PyObject *obj)
184 {
185 Py_ssize_t len;
186 PyObject *decoded = NULL;
187
188 assert(self->buf != NULL);
189 assert(self->pos >= 0);
190
191 if (self->decoder != NULL) {
192 decoded = _PyIncrementalNewlineDecoder_decode(
193 self->decoder, obj, 1 /* always final */);
194 }
195 else {
196 decoded = Py_NewRef(obj);
197 }
198 if (self->writenl) {
199 PyObject *translated = PyUnicode_Replace(
200 decoded, _Py_LATIN1_CHR('\n'), self->writenl, -1);
201 Py_SETREF(decoded, translated);
202 }
203 if (decoded == NULL)
204 return -1;
205
206 assert(PyUnicode_Check(decoded));
207 len = PyUnicode_GET_LENGTH(decoded);
208 assert(len >= 0);
209
210 /* This overflow check is not strictly necessary. However, it avoids us to
211 deal with funky things like comparing an unsigned and a signed
212 integer. */
213 if (self->pos > PY_SSIZE_T_MAX - len) {
214 PyErr_SetString(PyExc_OverflowError,
215 "new position too large");
216 goto fail;
217 }
218
219 if (self->state == STATE_ACCUMULATING) {
220 if (self->string_size == self->pos) {
221 if (_PyUnicodeWriter_WriteStr(&self->writer, decoded))
222 goto fail;
223 goto success;
224 }
225 if (realize(self))
226 goto fail;
227 }
228
229 if (self->pos + len > self->string_size) {
230 if (resize_buffer(self, self->pos + len) < 0)
231 goto fail;
232 }
233
234 if (self->pos > self->string_size) {
235 /* In case of overseek, pad with null bytes the buffer region between
236 the end of stream and the current position.
237
238 0 lo string_size hi
239 | |<---used--->|<----------available----------->|
240 | | <--to pad-->|<---to write---> |
241 0 buf position
242
243 */
244 memset(self->buf + self->string_size, '\0',
245 (self->pos - self->string_size) * sizeof(Py_UCS4));
246 }
247
248 /* Copy the data to the internal buffer, overwriting some of the
249 existing data if self->pos < self->string_size. */
250 if (!PyUnicode_AsUCS4(decoded,
251 self->buf + self->pos,
252 self->buf_size - self->pos,
253 0))
254 goto fail;
255
256 success:
257 /* Set the new length of the internal string if it has changed. */
258 self->pos += len;
259 if (self->string_size < self->pos)
260 self->string_size = self->pos;
261
262 Py_DECREF(decoded);
263 return 0;
264
265 fail:
266 Py_XDECREF(decoded);
267 return -1;
268 }
269
270 /*[clinic input]
271 @critical_section
272 _io.StringIO.getvalue
273
274 Retrieve the entire contents of the object.
275 [clinic start generated code]*/
276
277 static PyObject *
278 _io_StringIO_getvalue_impl(stringio *self)
279 /*[clinic end generated code: output=27b6a7bfeaebce01 input=fb5dee06b8d467f3]*/
280 {
281 CHECK_INITIALIZED(self);
282 CHECK_CLOSED(self);
283 if (self->state == STATE_ACCUMULATING)
284 return make_intermediate(self);
285 return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, self->buf,
286 self->string_size);
287 }
288
289 /*[clinic input]
290 @critical_section
291 _io.StringIO.tell
292
293 Tell the current file position.
294 [clinic start generated code]*/
295
296 static PyObject *
297 _io_StringIO_tell_impl(stringio *self)
298 /*[clinic end generated code: output=2e87ac67b116c77b input=98a08f3e2dae3550]*/
299 {
300 CHECK_INITIALIZED(self);
301 CHECK_CLOSED(self);
302 return PyLong_FromSsize_t(self->pos);
303 }
304
305 /*[clinic input]
306 @critical_section
307 _io.StringIO.read
308 size: Py_ssize_t(accept={int, NoneType}) = -1
309 /
310
311 Read at most size characters, returned as a string.
312
313 If the argument is negative or omitted, read until EOF
314 is reached. Return an empty string at EOF.
315 [clinic start generated code]*/
316
317 static PyObject *
318 _io_StringIO_read_impl(stringio *self, Py_ssize_t size)
319 /*[clinic end generated code: output=ae8cf6002f71626c input=9fbef45d8aece8e7]*/
320 {
321 Py_ssize_t n;
322 Py_UCS4 *output;
323
324 CHECK_INITIALIZED(self);
325 CHECK_CLOSED(self);
326
327 /* adjust invalid sizes */
328 n = self->string_size - self->pos;
329 if (size < 0 || size > n) {
330 size = n;
331 if (size < 0)
332 size = 0;
333 }
334
335 /* Optimization for seek(0); read() */
336 if (self->state == STATE_ACCUMULATING && self->pos == 0 && size == n) {
337 PyObject *result = make_intermediate(self);
338 self->pos = self->string_size;
339 return result;
340 }
341
342 ENSURE_REALIZED(self);
343 output = self->buf + self->pos;
344 self->pos += size;
345 return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, size);
346 }
347
348 /* Internal helper, used by stringio_readline and stringio_iternext */
349 static PyObject *
350 _stringio_readline(stringio *self, Py_ssize_t limit)
351 {
352 Py_UCS4 *start, *end, old_char;
353 Py_ssize_t len, consumed;
354
355 /* In case of overseek, return the empty string */
356 if (self->pos >= self->string_size)
357 return PyUnicode_New(0, 0);
358
359 start = self->buf + self->pos;
360 if (limit < 0 || limit > self->string_size - self->pos)
361 limit = self->string_size - self->pos;
362
363 end = start + limit;
364 old_char = *end;
365 *end = '\0';
366 len = _PyIO_find_line_ending(
367 self->readtranslate, self->readuniversal, self->readnl,
368 PyUnicode_4BYTE_KIND, (char*)start, (char*)end, &consumed);
369 *end = old_char;
370 /* If we haven't found any line ending, we just return everything
371 (`consumed` is ignored). */
372 if (len < 0)
373 len = limit;
374 self->pos += len;
375 return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, start, len);
376 }
377
378 /*[clinic input]
379 @critical_section
380 _io.StringIO.readline
381 size: Py_ssize_t(accept={int, NoneType}) = -1
382 /
383
384 Read until newline or EOF.
385
386 Returns an empty string if EOF is hit immediately.
387 [clinic start generated code]*/
388
389 static PyObject *
390 _io_StringIO_readline_impl(stringio *self, Py_ssize_t size)
391 /*[clinic end generated code: output=cabd6452f1b7e85d input=4d14b8495dea1d98]*/
392 {
393 CHECK_INITIALIZED(self);
394 CHECK_CLOSED(self);
395 ENSURE_REALIZED(self);
396
397 return _stringio_readline(self, size);
398 }
399
400 static PyObject *
401 stringio_iternext(stringio *self)
402 {
403 PyObject *line;
404
405 CHECK_INITIALIZED(self);
406 CHECK_CLOSED(self);
407 ENSURE_REALIZED(self);
408
409 if (Py_IS_TYPE(self, self->module_state->PyStringIO_Type)) {
410 /* Skip method call overhead for speed */
411 line = _stringio_readline(self, -1);
412 }
413 else {
414 /* XXX is subclassing StringIO really supported? */
415 line = PyObject_CallMethodNoArgs((PyObject *)self,
416 &_Py_ID(readline));
417 if (line && !PyUnicode_Check(line)) {
418 PyErr_Format(PyExc_OSError,
419 "readline() should have returned a str object, "
420 "not '%.200s'", Py_TYPE(line)->tp_name);
421 Py_DECREF(line);
422 return NULL;
423 }
424 }
425
426 if (line == NULL)
427 return NULL;
428
429 if (PyUnicode_GET_LENGTH(line) == 0) {
430 /* Reached EOF */
431 Py_DECREF(line);
432 return NULL;
433 }
434
435 return line;
436 }
437
438 /*[clinic input]
439 @critical_section
440 _io.StringIO.truncate
441 pos as size: Py_ssize_t(accept={int, NoneType}, c_default="self->pos") = None
442 /
443
444 Truncate size to pos.
445
446 The pos argument defaults to the current file position, as
447 returned by tell(). The current file position is unchanged.
448 Returns the new absolute position.
449 [clinic start generated code]*/
450
451 static PyObject *
452 _io_StringIO_truncate_impl(stringio *self, Py_ssize_t size)
453 /*[clinic end generated code: output=eb3aef8e06701365 input=461b872dce238452]*/
454 {
455 CHECK_INITIALIZED(self);
456 CHECK_CLOSED(self);
457
458 if (size < 0) {
459 PyErr_Format(PyExc_ValueError,
460 "Negative size value %zd", size);
461 return NULL;
462 }
463
464 if (size < self->string_size) {
465 ENSURE_REALIZED(self);
466 if (resize_buffer(self, size) < 0)
467 return NULL;
468 self->string_size = size;
469 }
470
471 return PyLong_FromSsize_t(size);
472 }
473
474 /*[clinic input]
475 @critical_section
476 _io.StringIO.seek
477 pos: Py_ssize_t
478 whence: int = 0
479 /
480
481 Change stream position.
482
483 Seek to character offset pos relative to position indicated by whence:
484 0 Start of stream (the default). pos should be >= 0;
485 1 Current position - pos must be 0;
486 2 End of stream - pos must be 0.
487 Returns the new absolute position.
488 [clinic start generated code]*/
489
490 static PyObject *
491 _io_StringIO_seek_impl(stringio *self, Py_ssize_t pos, int whence)
492 /*[clinic end generated code: output=e9e0ac9a8ae71c25 input=c75ced09343a00d7]*/
493 {
494 CHECK_INITIALIZED(self);
495 CHECK_CLOSED(self);
496
497 if (whence != 0 && whence != 1 && whence != 2) {
498 PyErr_Format(PyExc_ValueError,
499 "Invalid whence (%i, should be 0, 1 or 2)", whence);
500 return NULL;
501 }
502 else if (pos < 0 && whence == 0) {
503 PyErr_Format(PyExc_ValueError,
504 "Negative seek position %zd", pos);
505 return NULL;
506 }
507 else if (whence != 0 && pos != 0) {
508 PyErr_SetString(PyExc_OSError,
509 "Can't do nonzero cur-relative seeks");
510 return NULL;
511 }
512
513 /* whence = 0: offset relative to beginning of the string.
514 whence = 1: no change to current position.
515 whence = 2: change position to end of file. */
516 if (whence == 1) {
517 pos = self->pos;
518 }
519 else if (whence == 2) {
520 pos = self->string_size;
521 }
522
523 self->pos = pos;
524
525 return PyLong_FromSsize_t(self->pos);
526 }
527
528 /*[clinic input]
529 @critical_section
530 _io.StringIO.write
531 s as obj: object
532 /
533
534 Write string to file.
535
536 Returns the number of characters written, which is always equal to
537 the length of the string.
538 [clinic start generated code]*/
539
540 static PyObject *
541 _io_StringIO_write_impl(stringio *self, PyObject *obj)
542 /*[clinic end generated code: output=d53b1d841d7db288 input=1561272c0da4651f]*/
543 {
544 Py_ssize_t size;
545
546 CHECK_INITIALIZED(self);
547 if (!PyUnicode_Check(obj)) {
548 PyErr_Format(PyExc_TypeError, "string argument expected, got '%s'",
549 Py_TYPE(obj)->tp_name);
550 return NULL;
551 }
552 CHECK_CLOSED(self);
553 size = PyUnicode_GET_LENGTH(obj);
554
555 if (size > 0 && write_str(self, obj) < 0)
556 return NULL;
557
558 return PyLong_FromSsize_t(size);
559 }
560
561 /*[clinic input]
562 @critical_section
563 _io.StringIO.close
564
565 Close the IO object.
566
567 Attempting any further operation after the object is closed
568 will raise a ValueError.
569
570 This method has no effect if the file is already closed.
571 [clinic start generated code]*/
572
573 static PyObject *
574 _io_StringIO_close_impl(stringio *self)
575 /*[clinic end generated code: output=04399355cbe518f1 input=305d19aa29cc40b9]*/
576 {
577 self->closed = 1;
578 /* Free up some memory */
579 if (resize_buffer(self, 0) < 0)
580 return NULL;
581 _PyUnicodeWriter_Dealloc(&self->writer);
582 Py_CLEAR(self->readnl);
583 Py_CLEAR(self->writenl);
584 Py_CLEAR(self->decoder);
585 Py_RETURN_NONE;
586 }
587
588 static int
589 stringio_traverse(stringio *self, visitproc visit, void *arg)
590 {
591 Py_VISIT(Py_TYPE(self));
592 Py_VISIT(self->readnl);
593 Py_VISIT(self->writenl);
594 Py_VISIT(self->decoder);
595 Py_VISIT(self->dict);
596 return 0;
597 }
598
599 static int
600 stringio_clear(stringio *self)
601 {
602 Py_CLEAR(self->readnl);
603 Py_CLEAR(self->writenl);
604 Py_CLEAR(self->decoder);
605 Py_CLEAR(self->dict);
606 return 0;
607 }
608
609 static void
610 stringio_dealloc(stringio *self)
611 {
612 PyTypeObject *tp = Py_TYPE(self);
613 _PyObject_GC_UNTRACK(self);
614 self->ok = 0;
615 if (self->buf) {
616 PyMem_Free(self->buf);
617 self->buf = NULL;
618 }
619 _PyUnicodeWriter_Dealloc(&self->writer);
620 (void)stringio_clear(self);
621 FT_CLEAR_WEAKREFS((PyObject *) self, self->weakreflist);
622 tp->tp_free(self);
623 Py_DECREF(tp);
624 }
625
626 static PyObject *
627 stringio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
628 {
629 stringio *self;
630
631 assert(type != NULL && type->tp_alloc != NULL);
632 self = (stringio *)type->tp_alloc(type, 0);
633 if (self == NULL)
634 return NULL;
635
636 /* tp_alloc initializes all the fields to zero. So we don't have to
637 initialize them here. */
638
639 self->buf = (Py_UCS4 *)PyMem_Malloc(0);
640 if (self->buf == NULL) {
641 Py_DECREF(self);
642 return PyErr_NoMemory();
643 }
644
645 return (PyObject *)self;
646 }
647
648 /*[clinic input]
649 _io.StringIO.__init__
650 initial_value as value: object(c_default="NULL") = ''
651 newline as newline_obj: object(c_default="NULL") = '\n'
652
653 Text I/O implementation using an in-memory buffer.
654
655 The initial_value argument sets the value of object. The newline
656 argument is like the one of TextIOWrapper's constructor.
657 [clinic start generated code]*/
658
659 static int
660 _io_StringIO___init___impl(stringio *self, PyObject *value,
661 PyObject *newline_obj)
662 /*[clinic end generated code: output=a421ea023b22ef4e input=cee2d9181b2577a3]*/
663 {
664 const char *newline = "\n";
665 Py_ssize_t value_len;
666
667 /* Parse the newline argument. We only want to allow unicode objects or
668 None. */
669 if (newline_obj == Py_None) {
670 newline = NULL;
671 }
672 else if (newline_obj) {
673 if (!PyUnicode_Check(newline_obj)) {
674 PyErr_Format(PyExc_TypeError,
675 "newline must be str or None, not %.200s",
676 Py_TYPE(newline_obj)->tp_name);
677 return -1;
678 }
679 newline = PyUnicode_AsUTF8(newline_obj);
680 if (newline == NULL)
681 return -1;
682 }
683
684 if (newline && newline[0] != '\0'
685 && !(newline[0] == '\n' && newline[1] == '\0')
686 && !(newline[0] == '\r' && newline[1] == '\0')
687 && !(newline[0] == '\r' && newline[1] == '\n' && newline[2] == '\0')) {
688 PyErr_Format(PyExc_ValueError,
689 "illegal newline value: %R", newline_obj);
690 return -1;
691 }
692 if (value && value != Py_None && !PyUnicode_Check(value)) {
693 PyErr_Format(PyExc_TypeError,
694 "initial_value must be str or None, not %.200s",
695 Py_TYPE(value)->tp_name);
696 return -1;
697 }
698
699 self->ok = 0;
700
701 _PyUnicodeWriter_Dealloc(&self->writer);
702 Py_CLEAR(self->readnl);
703 Py_CLEAR(self->writenl);
704 Py_CLEAR(self->decoder);
705
706 assert((newline != NULL && newline_obj != Py_None) ||
707 (newline == NULL && newline_obj == Py_None));
708
709 if (newline) {
710 self->readnl = PyUnicode_FromString(newline);
711 if (self->readnl == NULL)
712 return -1;
713 }
714 self->readuniversal = (newline == NULL || newline[0] == '\0');
715 self->readtranslate = (newline == NULL);
716 /* If newline == "", we don't translate anything.
717 If newline == "\n" or newline == None, we translate to "\n", which is
718 a no-op.
719 (for newline == None, TextIOWrapper translates to os.linesep, but it
720 is pointless for StringIO)
721 */
722 if (newline != NULL && newline[0] == '\r') {
723 self->writenl = Py_NewRef(self->readnl);
724 }
725
726 _PyIO_State *module_state = find_io_state_by_def(Py_TYPE(self));
727 if (self->readuniversal) {
728 self->decoder = PyObject_CallFunctionObjArgs(
729 (PyObject *)module_state->PyIncrementalNewlineDecoder_Type,
730 Py_None, self->readtranslate ? Py_True : Py_False, NULL);
731 if (self->decoder == NULL)
732 return -1;
733 }
734
735 /* Now everything is set up, resize buffer to size of initial value,
736 and copy it */
737 self->string_size = 0;
738 if (value && value != Py_None)
739 value_len = PyUnicode_GetLength(value);
740 else
741 value_len = 0;
742 if (value_len > 0) {
743 /* This is a heuristic, for newline translation might change
744 the string length. */
745 if (resize_buffer(self, 0) < 0)
746 return -1;
747 self->state = STATE_REALIZED;
748 self->pos = 0;
749 if (write_str(self, value) < 0)
750 return -1;
751 }
752 else {
753 /* Empty stringio object, we can start by accumulating */
754 if (resize_buffer(self, 0) < 0)
755 return -1;
756 _PyUnicodeWriter_Init(&self->writer);
757 self->writer.overallocate = 1;
758 self->state = STATE_ACCUMULATING;
759 }
760 self->pos = 0;
761 self->module_state = module_state;
762 self->closed = 0;
763 self->ok = 1;
764 return 0;
765 }
766
767 /* Properties and pseudo-properties */
768
769 /*[clinic input]
770 @critical_section
771 _io.StringIO.readable
772
773 Returns True if the IO object can be read.
774 [clinic start generated code]*/
775
776 static PyObject *
777 _io_StringIO_readable_impl(stringio *self)
778 /*[clinic end generated code: output=b19d44dd8b1ceb99 input=6cd2ffd65a8e8763]*/
779 {
780 CHECK_INITIALIZED(self);
781 CHECK_CLOSED(self);
782 Py_RETURN_TRUE;
783 }
784
785 /*[clinic input]
786 @critical_section
787 _io.StringIO.writable
788
789 Returns True if the IO object can be written.
790 [clinic start generated code]*/
791
792 static PyObject *
793 _io_StringIO_writable_impl(stringio *self)
794 /*[clinic end generated code: output=13e4dd77187074ca input=1b3c63dbaa761c69]*/
795 {
796 CHECK_INITIALIZED(self);
797 CHECK_CLOSED(self);
798 Py_RETURN_TRUE;
799 }
800
801 /*[clinic input]
802 @critical_section
803 _io.StringIO.seekable
804
805 Returns True if the IO object can be seeked.
806 [clinic start generated code]*/
807
808 static PyObject *
809 _io_StringIO_seekable_impl(stringio *self)
810 /*[clinic end generated code: output=4d20b4641c756879 input=a820fad2cf085fc3]*/
811 {
812 CHECK_INITIALIZED(self);
813 CHECK_CLOSED(self);
814 Py_RETURN_TRUE;
815 }
816
817 /* Pickling support.
818
819 The implementation of __getstate__ is similar to the one for BytesIO,
820 except that we also save the newline parameter. For __setstate__ and unlike
821 BytesIO, we call __init__ to restore the object's state. Doing so allows us
822 to avoid decoding the complex newline state while keeping the object
823 representation compact.
824
825 See comment in bytesio.c regarding why only pickle protocols and onward are
826 supported.
827 */
828
829 /*[clinic input]
830 @critical_section
831 _io.StringIO.__getstate__
832
833 [clinic start generated code]*/
834
835 static PyObject *
836 _io_StringIO___getstate___impl(stringio *self)
837 /*[clinic end generated code: output=780be4a996410199 input=76f27255ef83bb92]*/
838 {
839 PyObject *initvalue = _io_StringIO_getvalue_impl(self);
840 PyObject *dict;
841 PyObject *state;
842
843 if (initvalue == NULL)
844 return NULL;
845 if (self->dict == NULL) {
846 dict = Py_NewRef(Py_None);
847 }
848 else {
849 dict = PyDict_Copy(self->dict);
850 if (dict == NULL) {
851 Py_DECREF(initvalue);
852 return NULL;
853 }
854 }
855
856 state = Py_BuildValue("(OOnN)", initvalue,
857 self->readnl ? self->readnl : Py_None,
858 self->pos, dict);
859 Py_DECREF(initvalue);
860 return state;
861 }
862
863 /*[clinic input]
864 @critical_section
865 _io.StringIO.__setstate__
866
867 state: object
868 /
869 [clinic start generated code]*/
870
871 static PyObject *
872 _io_StringIO___setstate___impl(stringio *self, PyObject *state)
873 /*[clinic end generated code: output=cb3962bc6d5c5609 input=8a27784b11b82e47]*/
874 {
875 PyObject *initarg;
876 PyObject *position_obj;
877 PyObject *dict;
878 Py_ssize_t pos;
879
880 assert(state != NULL);
881 CHECK_CLOSED(self);
882
883 /* We allow the state tuple to be longer than 4, because we may need
884 someday to extend the object's state without breaking
885 backward-compatibility. */
886 if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) < 4) {
887 PyErr_Format(PyExc_TypeError,
888 "%.200s.__setstate__ argument should be 4-tuple, got %.200s",
889 Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
890 return NULL;
891 }
892
893 /* Initialize the object's state. */
894 initarg = PyTuple_GetSlice(state, 0, 2);
895 if (initarg == NULL)
896 return NULL;
897 if (_io_StringIO___init__((PyObject *)self, initarg, NULL) < 0) {
898 Py_DECREF(initarg);
899 return NULL;
900 }
901 Py_DECREF(initarg);
902
903 /* Restore the buffer state. Even if __init__ did initialize the buffer,
904 we have to initialize it again since __init__ may translate the
905 newlines in the initial_value string. We clearly do not want that
906 because the string value in the state tuple has already been translated
907 once by __init__. So we do not take any chance and replace object's
908 buffer completely. */
909 {
910 PyObject *item = PyTuple_GET_ITEM(state, 0);
911 if (PyUnicode_Check(item)) {
912 Py_UCS4 *buf = PyUnicode_AsUCS4Copy(item);
913 if (buf == NULL)
914 return NULL;
915 Py_ssize_t bufsize = PyUnicode_GET_LENGTH(item);
916
917 if (resize_buffer(self, bufsize) < 0) {
918 PyMem_Free(buf);
919 return NULL;
920 }
921 memcpy(self->buf, buf, bufsize * sizeof(Py_UCS4));
922 PyMem_Free(buf);
923 self->string_size = bufsize;
924 }
925 else {
926 assert(item == Py_None);
927 self->string_size = 0;
928 }
929 }
930
931 /* Set carefully the position value. Alternatively, we could use the seek
932 method instead of modifying self->pos directly to better protect the
933 object internal state against erroneous (or malicious) inputs. */
934 position_obj = PyTuple_GET_ITEM(state, 2);
935 if (!PyLong_Check(position_obj)) {
936 PyErr_Format(PyExc_TypeError,
937 "third item of state must be an integer, got %.200s",
938 Py_TYPE(position_obj)->tp_name);
939 return NULL;
940 }
941 pos = PyLong_AsSsize_t(position_obj);
942 if (pos == -1 && PyErr_Occurred())
943 return NULL;
944 if (pos < 0) {
945 PyErr_SetString(PyExc_ValueError,
946 "position value cannot be negative");
947 return NULL;
948 }
949 self->pos = pos;
950
951 /* Set the dictionary of the instance variables. */
952 dict = PyTuple_GET_ITEM(state, 3);
953 if (dict != Py_None) {
954 if (!PyDict_Check(dict)) {
955 PyErr_Format(PyExc_TypeError,
956 "fourth item of state should be a dict, got a %.200s",
957 Py_TYPE(dict)->tp_name);
958 return NULL;
959 }
960 if (self->dict) {
961 /* Alternatively, we could replace the internal dictionary
962 completely. However, it seems more practical to just update it. */
963 if (PyDict_Update(self->dict, dict) < 0)
964 return NULL;
965 }
966 else {
967 self->dict = Py_NewRef(dict);
968 }
969 }
970
971 Py_RETURN_NONE;
972 }
973
974 /*[clinic input]
975 @critical_section
976 @getter
977 _io.StringIO.closed
978 [clinic start generated code]*/
979
980 static PyObject *
981 _io_StringIO_closed_get_impl(stringio *self)
982 /*[clinic end generated code: output=531ddca7954331d6 input=178d2ef24395fd49]*/
983 {
984 CHECK_INITIALIZED(self);
985 return PyBool_FromLong(self->closed);
986 }
987
988 /*[clinic input]
989 @critical_section
990 @getter
991 _io.StringIO.line_buffering
992 [clinic start generated code]*/
993
994 static PyObject *
995 _io_StringIO_line_buffering_get_impl(stringio *self)
996 /*[clinic end generated code: output=360710e0112966ae input=6a7634e7f890745e]*/
997 {
998 CHECK_INITIALIZED(self);
999 CHECK_CLOSED(self);
1000 Py_RETURN_FALSE;
1001 }
1002
1003 /*[clinic input]
1004 @critical_section
1005 @getter
1006 _io.StringIO.newlines
1007 [clinic start generated code]*/
1008
1009 static PyObject *
1010 _io_StringIO_newlines_get_impl(stringio *self)
1011 /*[clinic end generated code: output=35d7c0b66d7e0160 input=092a14586718244b]*/
1012 {
1013 CHECK_INITIALIZED(self);
1014 CHECK_CLOSED(self);
1015 if (self->decoder == NULL) {
1016 Py_RETURN_NONE;
1017 }
1018 return PyObject_GetAttr(self->decoder, &_Py_ID(newlines));
1019 }
1020
1021 static struct PyMethodDef stringio_methods[] = {
1022 _IO_STRINGIO_CLOSE_METHODDEF
1023 _IO_STRINGIO_GETVALUE_METHODDEF
1024 _IO_STRINGIO_READ_METHODDEF
1025 _IO_STRINGIO_READLINE_METHODDEF
1026 _IO_STRINGIO_TELL_METHODDEF
1027 _IO_STRINGIO_TRUNCATE_METHODDEF
1028 _IO_STRINGIO_SEEK_METHODDEF
1029 _IO_STRINGIO_WRITE_METHODDEF
1030
1031 _IO_STRINGIO_SEEKABLE_METHODDEF
1032 _IO_STRINGIO_READABLE_METHODDEF
1033 _IO_STRINGIO_WRITABLE_METHODDEF
1034
1035 _IO_STRINGIO___GETSTATE___METHODDEF
1036 _IO_STRINGIO___SETSTATE___METHODDEF
1037 {NULL, NULL} /* sentinel */
1038 };
1039
1040 static PyGetSetDef stringio_getset[] = {
1041 _IO_STRINGIO_CLOSED_GETSETDEF
1042 _IO_STRINGIO_NEWLINES_GETSETDEF
1043 /* (following comments straight off of the original Python wrapper:)
1044 XXX Cruft to support the TextIOWrapper API. This would only
1045 be meaningful if StringIO supported the buffer attribute.
1046 Hopefully, a better solution, than adding these pseudo-attributes,
1047 will be found.
1048 */
1049 _IO_STRINGIO_LINE_BUFFERING_GETSETDEF
1050 {NULL}
1051 };
1052
1053 static struct PyMemberDef stringio_members[] = {
1054 {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(stringio, weakreflist), Py_READONLY},
1055 {"__dictoffset__", Py_T_PYSSIZET, offsetof(stringio, dict), Py_READONLY},
1056 {NULL},
1057 };
1058
1059 static PyType_Slot stringio_slots[] = {
1060 {Py_tp_dealloc, stringio_dealloc},
1061 {Py_tp_doc, (void *)_io_StringIO___init____doc__},
1062 {Py_tp_traverse, stringio_traverse},
1063 {Py_tp_clear, stringio_clear},
1064 {Py_tp_iternext, stringio_iternext},
1065 {Py_tp_methods, stringio_methods},
1066 {Py_tp_members, stringio_members},
1067 {Py_tp_getset, stringio_getset},
1068 {Py_tp_init, _io_StringIO___init__},
1069 {Py_tp_new, stringio_new},
1070 {0, NULL},
1071 };
1072
1073 PyType_Spec stringio_spec = {
1074 .name = "_io.StringIO",
1075 .basicsize = sizeof(stringio),
1076 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1077 Py_TPFLAGS_IMMUTABLETYPE),
1078 .slots = stringio_slots,
1079 };