blob: 83fc79ef30ca5f6b365e195abb43b737a65d5c9f [file] [log] [blame]
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001#include "Python.h"
2
3/* This module is a stripped down version of _bytesio.c with a Py_UNICODE
4 buffer. Most of the functionality is provided by subclassing _StringIO. */
5
6
7typedef struct {
8 PyObject_HEAD
9 Py_UNICODE *buf;
10 Py_ssize_t pos;
11 Py_ssize_t string_size;
12 size_t buf_size;
13} StringIOObject;
14
15
16/* Internal routine for changing the size, in terms of characters, of the
17 buffer of StringIO objects. The caller should ensure that the 'size'
18 argument is non-negative. Returns 0 on success, -1 otherwise. */
19static int
20resize_buffer(StringIOObject *self, size_t size)
21{
22 /* Here, unsigned types are used to avoid dealing with signed integer
23 overflow, which is undefined in C. */
24 size_t alloc = self->buf_size;
25 Py_UNICODE *new_buf = NULL;
26
27 assert(self->buf != NULL);
28
29 /* For simplicity, stay in the range of the signed type. Anyway, Python
30 doesn't allow strings to be longer than this. */
31 if (size > PY_SSIZE_T_MAX)
32 goto overflow;
33
34 if (size < alloc / 2) {
35 /* Major downsize; resize down to exact size. */
36 alloc = size + 1;
37 }
38 else if (size < alloc) {
39 /* Within allocated size; quick exit */
40 return 0;
41 }
42 else if (size <= alloc * 1.125) {
43 /* Moderate upsize; overallocate similar to list_resize() */
44 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
45 }
46 else {
47 /* Major upsize; resize up to exact size */
48 alloc = size + 1;
49 }
50
51 if (alloc > ((size_t)-1) / sizeof(Py_UNICODE))
52 goto overflow;
53 new_buf = (Py_UNICODE *)PyMem_Realloc(self->buf,
54 alloc * sizeof(Py_UNICODE));
55 if (new_buf == NULL) {
56 PyErr_NoMemory();
57 return -1;
58 }
59 self->buf_size = alloc;
60 self->buf = new_buf;
61
62 return 0;
63
64 overflow:
65 PyErr_SetString(PyExc_OverflowError,
66 "new buffer size too large");
67 return -1;
68}
69
70/* Internal routine for writing a string of characters to the buffer of a
71 StringIO object. Returns the number of bytes wrote, or -1 on error. */
72static Py_ssize_t
73write_str(StringIOObject *self, const Py_UNICODE *str, Py_ssize_t len)
74{
75 assert(self->buf != NULL);
76 assert(self->pos >= 0);
77 assert(len >= 0);
78
79 /* This overflow check is not strictly necessary. However, it avoids us to
80 deal with funky things like comparing an unsigned and a signed
81 integer. */
82 if (self->pos > PY_SSIZE_T_MAX - len) {
83 PyErr_SetString(PyExc_OverflowError,
84 "new position too large");
85 return -1;
86 }
87 if (self->pos + len > self->string_size) {
88 if (resize_buffer(self, self->pos + len) < 0)
89 return -1;
90 }
91
92 if (self->pos > self->string_size) {
93 /* In case of overseek, pad with null bytes the buffer region between
94 the end of stream and the current position.
95
96 0 lo string_size hi
97 | |<---used--->|<----------available----------->|
98 | | <--to pad-->|<---to write---> |
99 0 buf positon
100
101 */
102 memset(self->buf + self->string_size, '\0',
103 (self->pos - self->string_size) * sizeof(Py_UNICODE));
104 }
105
106 /* Copy the data to the internal buffer, overwriting some of the
107 existing data if self->pos < self->string_size. */
108 memcpy(self->buf + self->pos, str, len * sizeof(Py_UNICODE));
109 self->pos += len;
110
111 /* Set the new length of the internal string if it has changed */
112 if (self->string_size < self->pos) {
113 self->string_size = self->pos;
114 }
115
116 return len;
117}
118
119static PyObject *
120stringio_getvalue(StringIOObject *self)
121{
122 return PyUnicode_FromUnicode(self->buf, self->string_size);
123}
124
125static PyObject *
126stringio_tell(StringIOObject *self)
127{
128 return PyLong_FromSsize_t(self->pos);
129}
130
131static PyObject *
132stringio_read(StringIOObject *self, PyObject *args)
133{
134 Py_ssize_t size, n;
135 Py_UNICODE *output;
136 PyObject *arg = Py_None;
137
138 if (!PyArg_ParseTuple(args, "|O:read", &arg))
139 return NULL;
140
141 if (PyLong_Check(arg)) {
142 size = PyLong_AsSsize_t(arg);
143 }
144 else if (arg == Py_None) {
145 /* Read until EOF is reached, by default. */
146 size = -1;
147 }
148 else {
149 PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
150 Py_TYPE(arg)->tp_name);
151 return NULL;
152 }
153
154 /* adjust invalid sizes */
155 n = self->string_size - self->pos;
156 if (size < 0 || size > n) {
157 size = n;
158 if (size < 0)
159 size = 0;
160 }
161
162 assert(self->buf != NULL);
163 output = self->buf + self->pos;
164 self->pos += size;
165
166 return PyUnicode_FromUnicode(output, size);
167}
168
169static PyObject *
170stringio_truncate(StringIOObject *self, PyObject *args)
171{
172 Py_ssize_t size;
173 PyObject *arg = Py_None;
174
175 if (!PyArg_ParseTuple(args, "|O:truncate", &arg))
176 return NULL;
177
178 if (PyLong_Check(arg)) {
179 size = PyLong_AsSsize_t(arg);
180 }
181 else if (arg == Py_None) {
182 /* Truncate to current position if no argument is passed. */
183 size = self->pos;
184 }
185 else {
186 PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
187 Py_TYPE(arg)->tp_name);
188 return NULL;
189 }
190
191 if (size < 0) {
192 PyErr_Format(PyExc_ValueError,
193 "Negative size value %zd", size);
194 return NULL;
195 }
196
197 if (size < self->string_size) {
198 self->string_size = size;
199 if (resize_buffer(self, size) < 0)
200 return NULL;
201 }
202 self->pos = size;
203
204 return PyLong_FromSsize_t(size);
205}
206
207static PyObject *
208stringio_seek(StringIOObject *self, PyObject *args)
209{
210 Py_ssize_t pos;
211 int mode = 0;
212
213 if (!PyArg_ParseTuple(args, "n|i:seek", &pos, &mode))
214 return NULL;
215
216 if (mode != 0 && mode != 1 && mode != 2) {
217 PyErr_Format(PyExc_ValueError,
218 "Invalid whence (%i, should be 0, 1 or 2)", mode);
219 return NULL;
220 }
221 else if (pos < 0 && mode == 0) {
222 PyErr_Format(PyExc_ValueError,
223 "Negative seek position %zd", pos);
224 return NULL;
225 }
226 else if (mode != 0 && pos != 0) {
227 PyErr_SetString(PyExc_IOError,
228 "Can't do nonzero cur-relative seeks");
229 return NULL;
230 }
231
232 /* mode 0: offset relative to beginning of the string.
233 mode 1: no change to current position.
234 mode 2: change position to end of file. */
235 if (mode == 1) {
236 pos = self->pos;
237 }
238 else if (mode == 2) {
239 pos = self->string_size;
240 }
241
242 self->pos = pos;
243
244 return PyLong_FromSsize_t(self->pos);
245}
246
247static PyObject *
248stringio_write(StringIOObject *self, PyObject *obj)
249{
250 const Py_UNICODE *str;
251 Py_ssize_t size;
252 Py_ssize_t n = 0;
253
254 if (PyUnicode_Check(obj)) {
255 str = PyUnicode_AsUnicode(obj);
256 size = PyUnicode_GetSize(obj);
257 }
258 else {
259 PyErr_Format(PyExc_TypeError, "string argument expected, got '%s'",
260 Py_TYPE(obj)->tp_name);
261 return NULL;
262 }
263
264 if (size != 0) {
265 n = write_str(self, str, size);
266 if (n < 0)
267 return NULL;
268 }
269
270 return PyLong_FromSsize_t(n);
271}
272
273static void
274stringio_dealloc(StringIOObject *self)
275{
276 PyMem_Free(self->buf);
277 Py_TYPE(self)->tp_free(self);
278}
279
280static PyObject *
281stringio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
282{
283 StringIOObject *self;
284
285 assert(type != NULL && type->tp_alloc != NULL);
286 self = (StringIOObject *)type->tp_alloc(type, 0);
287 if (self == NULL)
288 return NULL;
289
290 self->string_size = 0;
291 self->pos = 0;
292 self->buf_size = 0;
293 self->buf = (Py_UNICODE *)PyMem_Malloc(0);
294 if (self->buf == NULL) {
295 Py_DECREF(self);
296 return PyErr_NoMemory();
297 }
298
299 return (PyObject *)self;
300}
301
302static struct PyMethodDef stringio_methods[] = {
303 {"getvalue", (PyCFunction)stringio_getvalue, METH_VARARGS, NULL},
304 {"read", (PyCFunction)stringio_read, METH_VARARGS, NULL},
305 {"tell", (PyCFunction)stringio_tell, METH_NOARGS, NULL},
306 {"truncate", (PyCFunction)stringio_truncate, METH_VARARGS, NULL},
307 {"seek", (PyCFunction)stringio_seek, METH_VARARGS, NULL},
308 {"write", (PyCFunction)stringio_write, METH_O, NULL},
309 {NULL, NULL} /* sentinel */
310};
311
312static PyTypeObject StringIO_Type = {
313 PyVarObject_HEAD_INIT(NULL, 0)
314 "_stringio._StringIO", /*tp_name*/
315 sizeof(StringIOObject), /*tp_basicsize*/
316 0, /*tp_itemsize*/
317 (destructor)stringio_dealloc, /*tp_dealloc*/
318 0, /*tp_print*/
319 0, /*tp_getattr*/
320 0, /*tp_setattr*/
321 0, /*tp_compare*/
322 0, /*tp_repr*/
323 0, /*tp_as_number*/
324 0, /*tp_as_sequence*/
325 0, /*tp_as_mapping*/
326 0, /*tp_hash*/
327 0, /*tp_call*/
328 0, /*tp_str*/
329 0, /*tp_getattro*/
330 0, /*tp_setattro*/
331 0, /*tp_as_buffer*/
332 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
333 0, /*tp_doc*/
334 0, /*tp_traverse*/
335 0, /*tp_clear*/
336 0, /*tp_richcompare*/
337 0, /*tp_weaklistoffset*/
338 0, /*tp_iter*/
339 0, /*tp_iternext*/
340 stringio_methods, /*tp_methods*/
341 0, /*tp_members*/
342 0, /*tp_getset*/
343 0, /*tp_base*/
344 0, /*tp_dict*/
345 0, /*tp_descr_get*/
346 0, /*tp_descr_set*/
347 0, /*tp_dictoffset*/
348 0, /*tp_init*/
349 0, /*tp_alloc*/
350 stringio_new, /*tp_new*/
351};
352
353static struct PyModuleDef _stringiomodule = {
354 PyModuleDef_HEAD_INIT,
355 "_stringio",
356 NULL,
357 -1,
358 NULL,
359 NULL,
360 NULL,
361 NULL,
362 NULL
363};
364
365PyMODINIT_FUNC
366PyInit__stringio(void)
367{
368 PyObject *m;
369
370 if (PyType_Ready(&StringIO_Type) < 0)
371 return NULL;
372 m = PyModule_Create(&_stringiomodule);
373 if (m == NULL)
374 return NULL;
375 Py_INCREF(&StringIO_Type);
376 if (PyModule_AddObject(m, "_StringIO", (PyObject *)&StringIO_Type) < 0)
377 return NULL;
378 return m;
379}