Coverage Report

Created: 2026-11-20 06:19

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