Coverage Report

Created: 2026-12-01 06:09

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