blob: ad9730d67ae6e5c7d92acdd9d6168de0a649a21d [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001#define PY_SSIZE_T_CLEAN
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002#include "Python.h"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00003#include "structmember.h"
4#include "_iomodule.h"
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00005
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00006/* Implementation note: the buffer is always at least one character longer
7 than the enclosed string, for proper functioning of _PyIO_find_line_ending.
8*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00009
10typedef struct {
11 PyObject_HEAD
12 Py_UNICODE *buf;
13 Py_ssize_t pos;
14 Py_ssize_t string_size;
15 size_t buf_size;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016
17 char ok; /* initialized? */
18 char closed;
19 char readuniversal;
20 char readtranslate;
21 PyObject *decoder;
22 PyObject *readnl;
23 PyObject *writenl;
24
25 PyObject *dict;
26 PyObject *weakreflist;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000027} stringio;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000028
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000029#define CHECK_INITIALIZED(self) \
30 if (self->ok <= 0) { \
31 PyErr_SetString(PyExc_ValueError, \
32 "I/O operation on uninitialized object"); \
33 return NULL; \
34 }
35
36#define CHECK_CLOSED(self) \
37 if (self->closed) { \
38 PyErr_SetString(PyExc_ValueError, \
39 "I/O operation on closed file"); \
40 return NULL; \
41 }
42
43PyDoc_STRVAR(stringio_doc,
44 "Text I/O implementation using an in-memory buffer.\n"
45 "\n"
46 "The initial_value argument sets the value of object. The newline\n"
47 "argument is like the one of TextIOWrapper's constructor.");
48
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000049
50/* Internal routine for changing the size, in terms of characters, of the
51 buffer of StringIO objects. The caller should ensure that the 'size'
52 argument is non-negative. Returns 0 on success, -1 otherwise. */
53static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000054resize_buffer(stringio *self, size_t size)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000055{
56 /* Here, unsigned types are used to avoid dealing with signed integer
57 overflow, which is undefined in C. */
58 size_t alloc = self->buf_size;
59 Py_UNICODE *new_buf = NULL;
60
61 assert(self->buf != NULL);
62
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000063 /* Reserve one more char for line ending detection. */
64 size = size + 1;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000065 /* For simplicity, stay in the range of the signed type. Anyway, Python
66 doesn't allow strings to be longer than this. */
67 if (size > PY_SSIZE_T_MAX)
68 goto overflow;
69
70 if (size < alloc / 2) {
71 /* Major downsize; resize down to exact size. */
72 alloc = size + 1;
73 }
74 else if (size < alloc) {
75 /* Within allocated size; quick exit */
76 return 0;
77 }
78 else if (size <= alloc * 1.125) {
79 /* Moderate upsize; overallocate similar to list_resize() */
80 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
81 }
82 else {
83 /* Major upsize; resize up to exact size */
84 alloc = size + 1;
85 }
86
87 if (alloc > ((size_t)-1) / sizeof(Py_UNICODE))
88 goto overflow;
89 new_buf = (Py_UNICODE *)PyMem_Realloc(self->buf,
90 alloc * sizeof(Py_UNICODE));
91 if (new_buf == NULL) {
92 PyErr_NoMemory();
93 return -1;
94 }
95 self->buf_size = alloc;
96 self->buf = new_buf;
97
98 return 0;
99
100 overflow:
101 PyErr_SetString(PyExc_OverflowError,
102 "new buffer size too large");
103 return -1;
104}
105
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000106/* Internal routine for writing a whole PyUnicode object to the buffer of a
107 StringIO object. Returns 0 on success, or -1 on error. */
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000108static Py_ssize_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000109write_str(stringio *self, PyObject *obj)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000110{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000111 Py_UNICODE *str;
112 Py_ssize_t len;
113 PyObject *decoded = NULL;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000114 assert(self->buf != NULL);
115 assert(self->pos >= 0);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000116
117 if (self->decoder != NULL) {
118 decoded = _PyIncrementalNewlineDecoder_decode(
119 self->decoder, obj, 1 /* always final */);
120 }
121 else {
122 decoded = obj;
123 Py_INCREF(decoded);
124 }
125 if (self->writenl) {
126 PyObject *translated = PyUnicode_Replace(
127 decoded, _PyIO_str_nl, self->writenl, -1);
128 Py_DECREF(decoded);
129 decoded = translated;
130 }
131 if (decoded == NULL)
132 return -1;
133
134 assert(PyUnicode_Check(decoded));
135 str = PyUnicode_AS_UNICODE(decoded);
136 len = PyUnicode_GET_SIZE(decoded);
137
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000138 assert(len >= 0);
139
140 /* This overflow check is not strictly necessary. However, it avoids us to
141 deal with funky things like comparing an unsigned and a signed
142 integer. */
143 if (self->pos > PY_SSIZE_T_MAX - len) {
144 PyErr_SetString(PyExc_OverflowError,
145 "new position too large");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000146 goto fail;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000147 }
148 if (self->pos + len > self->string_size) {
149 if (resize_buffer(self, self->pos + len) < 0)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000150 goto fail;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000151 }
152
153 if (self->pos > self->string_size) {
154 /* In case of overseek, pad with null bytes the buffer region between
155 the end of stream and the current position.
156
157 0 lo string_size hi
158 | |<---used--->|<----------available----------->|
159 | | <--to pad-->|<---to write---> |
160 0 buf positon
161
162 */
163 memset(self->buf + self->string_size, '\0',
164 (self->pos - self->string_size) * sizeof(Py_UNICODE));
165 }
166
167 /* Copy the data to the internal buffer, overwriting some of the
168 existing data if self->pos < self->string_size. */
169 memcpy(self->buf + self->pos, str, len * sizeof(Py_UNICODE));
170 self->pos += len;
171
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000172 /* Set the new length of the internal string if it has changed. */
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000173 if (self->string_size < self->pos) {
174 self->string_size = self->pos;
175 }
176
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000177 Py_DECREF(decoded);
178 return 0;
179
180fail:
181 Py_XDECREF(decoded);
182 return -1;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000183}
184
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000185PyDoc_STRVAR(stringio_getvalue_doc,
186 "Retrieve the entire contents of the object.");
187
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000188static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000189stringio_getvalue(stringio *self)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000190{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000191 CHECK_INITIALIZED(self);
192 CHECK_CLOSED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000193 return PyUnicode_FromUnicode(self->buf, self->string_size);
194}
195
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000196PyDoc_STRVAR(stringio_tell_doc,
197 "Tell the current file position.");
198
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000199static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000200stringio_tell(stringio *self)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000201{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000202 CHECK_INITIALIZED(self);
203 CHECK_CLOSED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000204 return PyLong_FromSsize_t(self->pos);
205}
206
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000207PyDoc_STRVAR(stringio_read_doc,
208 "Read at most n characters, returned as a string.\n"
209 "\n"
210 "If the argument is negative or omitted, read until EOF\n"
211 "is reached. Return an empty string at EOF.\n");
212
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000213static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000214stringio_read(stringio *self, PyObject *args)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000215{
216 Py_ssize_t size, n;
217 Py_UNICODE *output;
218 PyObject *arg = Py_None;
219
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000220 CHECK_INITIALIZED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000221 if (!PyArg_ParseTuple(args, "|O:read", &arg))
222 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000223 CHECK_CLOSED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000224
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000225 if (PyNumber_Check(arg)) {
226 size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Amaury Forgeot d'Arc58fb9052008-09-30 20:22:44 +0000227 if (size == -1 && PyErr_Occurred())
228 return NULL;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000229 }
230 else if (arg == Py_None) {
231 /* Read until EOF is reached, by default. */
232 size = -1;
233 }
234 else {
235 PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
236 Py_TYPE(arg)->tp_name);
237 return NULL;
238 }
239
240 /* adjust invalid sizes */
241 n = self->string_size - self->pos;
242 if (size < 0 || size > n) {
243 size = n;
244 if (size < 0)
245 size = 0;
246 }
247
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000248 output = self->buf + self->pos;
249 self->pos += size;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000250 return PyUnicode_FromUnicode(output, size);
251}
252
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000253/* Internal helper, used by stringio_readline and stringio_iternext */
254static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000255_stringio_readline(stringio *self, Py_ssize_t limit)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000256{
257 Py_UNICODE *start, *end, old_char;
258 Py_ssize_t len, consumed;
259
260 /* In case of overseek, return the empty string */
261 if (self->pos >= self->string_size)
262 return PyUnicode_FromString("");
263
264 start = self->buf + self->pos;
265 if (limit < 0 || limit > self->string_size - self->pos)
266 limit = self->string_size - self->pos;
267
268 end = start + limit;
269 old_char = *end;
270 *end = '\0';
271 len = _PyIO_find_line_ending(
272 self->readtranslate, self->readuniversal, self->readnl,
273 start, end, &consumed);
274 *end = old_char;
275 /* If we haven't found any line ending, we just return everything
276 (`consumed` is ignored). */
277 if (len < 0)
278 len = limit;
279 self->pos += len;
280 return PyUnicode_FromUnicode(start, len);
281}
282
283PyDoc_STRVAR(stringio_readline_doc,
284 "Read until newline or EOF.\n"
285 "\n"
286 "Returns an empty string if EOF is hit immediately.\n");
287
288static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000289stringio_readline(stringio *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000290{
291 PyObject *arg = Py_None;
292 Py_ssize_t limit = -1;
293
294 CHECK_INITIALIZED(self);
295 if (!PyArg_ParseTuple(args, "|O:readline", &arg))
296 return NULL;
297 CHECK_CLOSED(self);
298
299 if (PyNumber_Check(arg)) {
300 limit = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
301 if (limit == -1 && PyErr_Occurred())
302 return NULL;
303 }
304 else if (arg != Py_None) {
305 PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
306 Py_TYPE(arg)->tp_name);
307 return NULL;
308 }
309 return _stringio_readline(self, limit);
310}
311
312static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000313stringio_iternext(stringio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000314{
315 PyObject *line;
316
317 CHECK_INITIALIZED(self);
318 CHECK_CLOSED(self);
319
320 if (Py_TYPE(self) == &PyStringIO_Type) {
321 /* Skip method call overhead for speed */
322 line = _stringio_readline(self, -1);
323 }
324 else {
325 /* XXX is subclassing StringIO really supported? */
326 line = PyObject_CallMethodObjArgs((PyObject *)self,
327 _PyIO_str_readline, NULL);
328 if (line && !PyUnicode_Check(line)) {
329 PyErr_Format(PyExc_IOError,
330 "readline() should have returned an str object, "
331 "not '%.200s'", Py_TYPE(line)->tp_name);
332 Py_DECREF(line);
333 return NULL;
334 }
335 }
336
337 if (line == NULL)
338 return NULL;
339
340 if (PyUnicode_GET_SIZE(line) == 0) {
341 /* Reached EOF */
342 Py_DECREF(line);
343 return NULL;
344 }
345
346 return line;
347}
348
349PyDoc_STRVAR(stringio_truncate_doc,
350 "Truncate size to pos.\n"
351 "\n"
352 "The pos argument defaults to the current file position, as\n"
353 "returned by tell(). Imply an absolute seek to pos.\n"
354 "Returns the new absolute position.\n");
355
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000356static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000357stringio_truncate(stringio *self, PyObject *args)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000358{
359 Py_ssize_t size;
360 PyObject *arg = Py_None;
361
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000362 CHECK_INITIALIZED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000363 if (!PyArg_ParseTuple(args, "|O:truncate", &arg))
364 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000365 CHECK_CLOSED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000366
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000367 if (PyNumber_Check(arg)) {
368 size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Benjamin Petersonc9e435e2008-09-30 02:22:04 +0000369 if (size == -1 && PyErr_Occurred())
370 return NULL;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000371 }
372 else if (arg == Py_None) {
373 /* Truncate to current position if no argument is passed. */
374 size = self->pos;
375 }
376 else {
377 PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
378 Py_TYPE(arg)->tp_name);
379 return NULL;
380 }
381
382 if (size < 0) {
383 PyErr_Format(PyExc_ValueError,
384 "Negative size value %zd", size);
385 return NULL;
386 }
387
388 if (size < self->string_size) {
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000389 if (resize_buffer(self, size) < 0)
390 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000391 self->string_size = size;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000392 }
393 self->pos = size;
394
395 return PyLong_FromSsize_t(size);
396}
397
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000398PyDoc_STRVAR(stringio_seek_doc,
399 "Change stream position.\n"
400 "\n"
401 "Seek to character offset pos relative to position indicated by whence:\n"
402 " 0 Start of stream (the default). pos should be >= 0;\n"
403 " 1 Current position - pos must be 0;\n"
404 " 2 End of stream - pos must be 0.\n"
405 "Returns the new absolute position.\n");
406
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000407static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000408stringio_seek(stringio *self, PyObject *args)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000409{
410 Py_ssize_t pos;
411 int mode = 0;
412
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000413 CHECK_INITIALIZED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000414 if (!PyArg_ParseTuple(args, "n|i:seek", &pos, &mode))
415 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000416 CHECK_CLOSED(self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000417
418 if (mode != 0 && mode != 1 && mode != 2) {
419 PyErr_Format(PyExc_ValueError,
420 "Invalid whence (%i, should be 0, 1 or 2)", mode);
421 return NULL;
422 }
423 else if (pos < 0 && mode == 0) {
424 PyErr_Format(PyExc_ValueError,
425 "Negative seek position %zd", pos);
426 return NULL;
427 }
428 else if (mode != 0 && pos != 0) {
429 PyErr_SetString(PyExc_IOError,
430 "Can't do nonzero cur-relative seeks");
431 return NULL;
432 }
433
434 /* mode 0: offset relative to beginning of the string.
435 mode 1: no change to current position.
436 mode 2: change position to end of file. */
437 if (mode == 1) {
438 pos = self->pos;
439 }
440 else if (mode == 2) {
441 pos = self->string_size;
442 }
443
444 self->pos = pos;
445
446 return PyLong_FromSsize_t(self->pos);
447}
448
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000449PyDoc_STRVAR(stringio_write_doc,
450 "Write string to file.\n"
451 "\n"
452 "Returns the number of characters written, which is always equal to\n"
453 "the length of the string.\n");
454
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000455static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000456stringio_write(stringio *self, PyObject *obj)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000457{
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000458 Py_ssize_t size;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000459
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000460 CHECK_INITIALIZED(self);
461 if (!PyUnicode_Check(obj)) {
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000462 PyErr_Format(PyExc_TypeError, "string argument expected, got '%s'",
463 Py_TYPE(obj)->tp_name);
464 return NULL;
465 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000466 CHECK_CLOSED(self);
467 size = PyUnicode_GET_SIZE(obj);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000468
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000469 if (size > 0 && write_str(self, obj) < 0)
470 return NULL;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000471
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000472 return PyLong_FromSsize_t(size);
473}
474
475PyDoc_STRVAR(stringio_close_doc,
476 "Close the IO object. Attempting any further operation after the\n"
477 "object is closed will raise a ValueError.\n"
478 "\n"
479 "This method has no effect if the file is already closed.\n");
480
481static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000482stringio_close(stringio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000483{
484 self->closed = 1;
485 /* Free up some memory */
486 if (resize_buffer(self, 0) < 0)
487 return NULL;
488 Py_CLEAR(self->readnl);
489 Py_CLEAR(self->writenl);
490 Py_CLEAR(self->decoder);
491 Py_RETURN_NONE;
492}
493
494static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000495stringio_traverse(stringio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000496{
497 Py_VISIT(self->dict);
498 return 0;
499}
500
501static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000502stringio_clear(stringio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000503{
504 Py_CLEAR(self->dict);
505 return 0;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000506}
507
508static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000509stringio_dealloc(stringio *self)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000510{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000511 _PyObject_GC_UNTRACK(self);
Alexandre Vassalottifc477042009-07-22 02:24:49 +0000512 self->ok = 0;
513 if (self->buf) {
514 PyMem_Free(self->buf);
515 self->buf = NULL;
516 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000517 Py_CLEAR(self->readnl);
518 Py_CLEAR(self->writenl);
519 Py_CLEAR(self->decoder);
Alexandre Vassalottifc477042009-07-22 02:24:49 +0000520 Py_CLEAR(self->dict);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000521 if (self->weakreflist != NULL)
522 PyObject_ClearWeakRefs((PyObject *) self);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000523 Py_TYPE(self)->tp_free(self);
524}
525
526static PyObject *
527stringio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
528{
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000529 stringio *self;
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000530
531 assert(type != NULL && type->tp_alloc != NULL);
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000532 self = (stringio *)type->tp_alloc(type, 0);
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000533 if (self == NULL)
534 return NULL;
535
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000536 /* tp_alloc initializes all the fields to zero. So we don't have to
537 initialize them here. */
538
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000539 self->buf = (Py_UNICODE *)PyMem_Malloc(0);
540 if (self->buf == NULL) {
541 Py_DECREF(self);
542 return PyErr_NoMemory();
543 }
544
545 return (PyObject *)self;
546}
547
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000548static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000549stringio_init(stringio *self, PyObject *args, PyObject *kwds)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000550{
551 char *kwlist[] = {"initial_value", "newline", NULL};
552 PyObject *value = NULL;
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +0000553 PyObject *newline_obj = NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000554 char *newline = "\n";
555
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +0000556 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:__init__", kwlist,
557 &value, &newline_obj))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000558 return -1;
559
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +0000560 /* Parse the newline argument. This used to be done with the 'z'
561 specifier, however this allowed any object with the buffer interface to
562 be converted. Thus we have to parse it manually since we only want to
563 allow unicode objects or None. */
564 if (newline_obj == Py_None) {
565 newline = NULL;
566 }
567 else if (newline_obj) {
568 if (!PyUnicode_Check(newline_obj)) {
569 PyErr_Format(PyExc_TypeError,
570 "newline must be str or None, not %.200s",
571 Py_TYPE(newline_obj)->tp_name);
572 return -1;
573 }
574 newline = _PyUnicode_AsString(newline_obj);
575 if (newline == NULL)
576 return -1;
577 }
578
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000579 if (newline && newline[0] != '\0'
580 && !(newline[0] == '\n' && newline[1] == '\0')
581 && !(newline[0] == '\r' && newline[1] == '\0')
582 && !(newline[0] == '\r' && newline[1] == '\n' && newline[2] == '\0')) {
583 PyErr_Format(PyExc_ValueError,
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +0000584 "illegal newline value: %R", newline_obj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000585 return -1;
586 }
587 if (value && value != Py_None && !PyUnicode_Check(value)) {
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +0000588 PyErr_Format(PyExc_TypeError,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000589 "initial_value must be str or None, not %.200s",
590 Py_TYPE(value)->tp_name);
591 return -1;
592 }
593
594 self->ok = 0;
595
596 Py_CLEAR(self->readnl);
597 Py_CLEAR(self->writenl);
598 Py_CLEAR(self->decoder);
599
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +0000600 assert((newline != NULL && newline_obj != Py_None) ||
601 (newline == NULL && newline_obj == Py_None));
602
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000603 assert((newline != NULL && newline_obj != Py_None) ||
604 (newline == NULL && newline_obj == Py_None));
605
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000606 if (newline) {
607 self->readnl = PyUnicode_FromString(newline);
608 if (self->readnl == NULL)
609 return -1;
610 }
611 self->readuniversal = (newline == NULL || newline[0] == '\0');
612 self->readtranslate = (newline == NULL);
613 /* If newline == "", we don't translate anything.
614 If newline == "\n" or newline == None, we translate to "\n", which is
615 a no-op.
616 (for newline == None, TextIOWrapper translates to os.sepline, but it
617 is pointless for StringIO)
618 */
619 if (newline != NULL && newline[0] == '\r') {
620 self->writenl = self->readnl;
621 Py_INCREF(self->writenl);
622 }
623
624 if (self->readuniversal) {
625 self->decoder = PyObject_CallFunction(
626 (PyObject *)&PyIncrementalNewlineDecoder_Type,
627 "Oi", Py_None, (int) self->readtranslate);
628 if (self->decoder == NULL)
629 return -1;
630 }
631
632 /* Now everything is set up, resize buffer to size of initial value,
633 and copy it */
634 self->string_size = 0;
635 if (value && value != Py_None) {
636 Py_ssize_t len = PyUnicode_GetSize(value);
637 /* This is a heuristic, for newline translation might change
638 the string length. */
639 if (resize_buffer(self, len) < 0)
640 return -1;
641 self->pos = 0;
642 if (write_str(self, value) < 0)
643 return -1;
644 }
645 else {
646 if (resize_buffer(self, 0) < 0)
647 return -1;
648 }
649 self->pos = 0;
650
651 self->closed = 0;
652 self->ok = 1;
653 return 0;
654}
655
656/* Properties and pseudo-properties */
657static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000658stringio_seekable(stringio *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000659{
660 CHECK_INITIALIZED(self);
661 Py_RETURN_TRUE;
662}
663
664static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000665stringio_readable(stringio *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000666{
667 CHECK_INITIALIZED(self);
668 Py_RETURN_TRUE;
669}
670
671static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000672stringio_writable(stringio *self, PyObject *args)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000673{
674 CHECK_INITIALIZED(self);
675 Py_RETURN_TRUE;
676}
677
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000678/* Pickling support.
679
680 The implementation of __getstate__ is similar to the one for BytesIO,
681 except that we also save the newline parameter. For __setstate__ and unlike
682 BytesIO, we call __init__ to restore the object's state. Doing so allows us
683 to avoid decoding the complex newline state while keeping the object
684 representation compact.
685
686 See comment in bytesio.c regarding why only pickle protocols and onward are
687 supported.
688*/
689
690static PyObject *
691stringio_getstate(stringio *self)
692{
693 PyObject *initvalue = stringio_getvalue(self);
694 PyObject *dict;
695 PyObject *state;
696
697 if (initvalue == NULL)
698 return NULL;
699 if (self->dict == NULL) {
700 Py_INCREF(Py_None);
701 dict = Py_None;
702 }
703 else {
704 dict = PyDict_Copy(self->dict);
705 if (dict == NULL)
706 return NULL;
707 }
708
709 state = Py_BuildValue("(OOnN)", initvalue,
710 self->readnl ? self->readnl : Py_None,
711 self->pos, dict);
712 Py_DECREF(initvalue);
713 return state;
714}
715
716static PyObject *
717stringio_setstate(stringio *self, PyObject *state)
718{
719 PyObject *initarg;
720 PyObject *position_obj;
721 PyObject *dict;
722 Py_ssize_t pos;
723
724 assert(state != NULL);
725 CHECK_CLOSED(self);
726
727 /* We allow the state tuple to be longer than 4, because we may need
728 someday to extend the object's state without breaking
729 backward-compatibility. */
730 if (!PyTuple_Check(state) || Py_SIZE(state) < 4) {
731 PyErr_Format(PyExc_TypeError,
732 "%.200s.__setstate__ argument should be 4-tuple, got %.200s",
733 Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
734 return NULL;
735 }
736
737 /* Initialize the object's state. */
738 initarg = PyTuple_GetSlice(state, 0, 2);
739 if (initarg == NULL)
740 return NULL;
741 if (stringio_init(self, initarg, NULL) < 0) {
742 Py_DECREF(initarg);
743 return NULL;
744 }
745 Py_DECREF(initarg);
746
747 /* Restore the buffer state. Even if __init__ did initialize the buffer,
748 we have to initialize it again since __init__ may translates the
749 newlines in the inital_value string. We clearly do not want that
750 because the string value in the state tuple has already been translated
751 once by __init__. So we do not take any chance and replace object's
752 buffer completely. */
753 {
754 Py_UNICODE *buf = PyUnicode_AS_UNICODE(PyTuple_GET_ITEM(state, 0));
755 Py_ssize_t bufsize = PyUnicode_GET_SIZE(PyTuple_GET_ITEM(state, 0));
756 if (resize_buffer(self, bufsize) < 0)
757 return NULL;
758 memcpy(self->buf, buf, bufsize * sizeof(Py_UNICODE));
759 self->string_size = bufsize;
760 }
761
762 /* Set carefully the position value. Alternatively, we could use the seek
763 method instead of modifying self->pos directly to better protect the
764 object internal state against errneous (or malicious) inputs. */
765 position_obj = PyTuple_GET_ITEM(state, 2);
766 if (!PyLong_Check(position_obj)) {
767 PyErr_Format(PyExc_TypeError,
768 "third item of state must be an integer, got %.200s",
769 Py_TYPE(position_obj)->tp_name);
770 return NULL;
771 }
772 pos = PyLong_AsSsize_t(position_obj);
773 if (pos == -1 && PyErr_Occurred())
774 return NULL;
775 if (pos < 0) {
776 PyErr_SetString(PyExc_ValueError,
777 "position value cannot be negative");
778 return NULL;
779 }
780 self->pos = pos;
781
782 /* Set the dictionary of the instance variables. */
783 dict = PyTuple_GET_ITEM(state, 3);
784 if (dict != Py_None) {
785 if (!PyDict_Check(dict)) {
786 PyErr_Format(PyExc_TypeError,
787 "fourth item of state should be a dict, got a %.200s",
788 Py_TYPE(dict)->tp_name);
789 return NULL;
790 }
791 if (self->dict) {
792 /* Alternatively, we could replace the internal dictionary
793 completely. However, it seems more practical to just update it. */
794 if (PyDict_Update(self->dict, dict) < 0)
795 return NULL;
796 }
797 else {
798 Py_INCREF(dict);
799 self->dict = dict;
800 }
801 }
802
803 Py_RETURN_NONE;
804}
805
806
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000807static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000808stringio_closed(stringio *self, void *context)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000809{
810 CHECK_INITIALIZED(self);
811 return PyBool_FromLong(self->closed);
812}
813
814static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000815stringio_line_buffering(stringio *self, void *context)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000816{
817 CHECK_INITIALIZED(self);
818 CHECK_CLOSED(self);
819 Py_RETURN_FALSE;
820}
821
822static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000823stringio_newlines(stringio *self, void *context)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000824{
825 CHECK_INITIALIZED(self);
826 CHECK_CLOSED(self);
827 if (self->decoder == NULL)
828 Py_RETURN_NONE;
829 return PyObject_GetAttr(self->decoder, _PyIO_str_newlines);
830}
831
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000832static struct PyMethodDef stringio_methods[] = {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000833 {"close", (PyCFunction)stringio_close, METH_NOARGS, stringio_close_doc},
834 {"getvalue", (PyCFunction)stringio_getvalue, METH_VARARGS, stringio_getvalue_doc},
835 {"read", (PyCFunction)stringio_read, METH_VARARGS, stringio_read_doc},
836 {"readline", (PyCFunction)stringio_readline, METH_VARARGS, stringio_readline_doc},
837 {"tell", (PyCFunction)stringio_tell, METH_NOARGS, stringio_tell_doc},
838 {"truncate", (PyCFunction)stringio_truncate, METH_VARARGS, stringio_truncate_doc},
839 {"seek", (PyCFunction)stringio_seek, METH_VARARGS, stringio_seek_doc},
840 {"write", (PyCFunction)stringio_write, METH_O, stringio_write_doc},
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000841
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000842 {"seekable", (PyCFunction)stringio_seekable, METH_NOARGS},
843 {"readable", (PyCFunction)stringio_readable, METH_NOARGS},
844 {"writable", (PyCFunction)stringio_writable, METH_NOARGS},
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000845
846 {"__getstate__", (PyCFunction)stringio_getstate, METH_NOARGS},
847 {"__setstate__", (PyCFunction)stringio_setstate, METH_O},
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000848 {NULL, NULL} /* sentinel */
849};
850
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000851static PyGetSetDef stringio_getset[] = {
852 {"closed", (getter)stringio_closed, NULL, NULL},
853 {"newlines", (getter)stringio_newlines, NULL, NULL},
854 /* (following comments straight off of the original Python wrapper:)
855 XXX Cruft to support the TextIOWrapper API. This would only
856 be meaningful if StringIO supported the buffer attribute.
857 Hopefully, a better solution, than adding these pseudo-attributes,
858 will be found.
859 */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000860 {"line_buffering", (getter)stringio_line_buffering, NULL, NULL},
Benjamin Peterson1fea3212009-04-19 03:15:20 +0000861 {NULL}
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000862};
863
864PyTypeObject PyStringIO_Type = {
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000865 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000866 "_io.StringIO", /*tp_name*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000867 sizeof(stringio), /*tp_basicsize*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000868 0, /*tp_itemsize*/
869 (destructor)stringio_dealloc, /*tp_dealloc*/
870 0, /*tp_print*/
871 0, /*tp_getattr*/
872 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000873 0, /*tp_reserved*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000874 0, /*tp_repr*/
875 0, /*tp_as_number*/
876 0, /*tp_as_sequence*/
877 0, /*tp_as_mapping*/
878 0, /*tp_hash*/
879 0, /*tp_call*/
880 0, /*tp_str*/
881 0, /*tp_getattro*/
882 0, /*tp_setattro*/
883 0, /*tp_as_buffer*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000884 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
885 | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
886 stringio_doc, /*tp_doc*/
887 (traverseproc)stringio_traverse, /*tp_traverse*/
888 (inquiry)stringio_clear, /*tp_clear*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000889 0, /*tp_richcompare*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000890 offsetof(stringio, weakreflist), /*tp_weaklistoffset*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000891 0, /*tp_iter*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000892 (iternextfunc)stringio_iternext, /*tp_iternext*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000893 stringio_methods, /*tp_methods*/
894 0, /*tp_members*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000895 stringio_getset, /*tp_getset*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000896 0, /*tp_base*/
897 0, /*tp_dict*/
898 0, /*tp_descr_get*/
899 0, /*tp_descr_set*/
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000900 offsetof(stringio, dict), /*tp_dictoffset*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000901 (initproc)stringio_init, /*tp_init*/
Alexandre Vassalotti794652d2008-06-11 22:58:36 +0000902 0, /*tp_alloc*/
903 stringio_new, /*tp_new*/
904};