Debian Codegraph @

cpython27/Modules/cjkcodecs/multibytecodec.c

raw symbols SCIP
1 /*
2 * multibytecodec.c: Common Multibyte Codec Implementation
3 *
4 * Written by Hye-Shik Chang <[email protected]>
5 */
6
7 #define PY_SSIZE_T_CLEAN
8 #include "Python.h"
9 #include "structmember.h"
10 #include "multibytecodec.h"
11
12 typedef struct {
13 const Py_UNICODE *inbuf, *inbuf_top, *inbuf_end;
14 unsigned char *outbuf, *outbuf_end;
15 PyObject *excobj, *outobj;
16 } MultibyteEncodeBuffer;
17
18 typedef struct {
19 const unsigned char *inbuf, *inbuf_top, *inbuf_end;
20 Py_UNICODE *outbuf, *outbuf_end;
21 PyObject *excobj, *outobj;
22 } MultibyteDecodeBuffer;
23
24 PyDoc_STRVAR(MultibyteCodec_Encode__doc__,
25 "I.encode(unicode[, errors]) -> (string, length consumed)\n\
26 \n\
27 Return an encoded string version of `unicode'. errors may be given to\n\
28 set a different error handling scheme. Default is 'strict' meaning that\n\
29 encoding errors raise a UnicodeEncodeError. Other possible values are\n\
30 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name\n\
31 registered with codecs.register_error that can handle UnicodeEncodeErrors.");
32
33 PyDoc_STRVAR(MultibyteCodec_Decode__doc__,
34 "I.decode(string[, errors]) -> (unicodeobject, length consumed)\n\
35 \n\
36 Decodes `string' using I, an MultibyteCodec instance. errors may be given\n\
37 to set a different error handling scheme. Default is 'strict' meaning\n\
38 that encoding errors raise a UnicodeDecodeError. Other possible values\n\
39 are 'ignore' and 'replace' as well as any other name registered with\n\
40 codecs.register_error that is able to handle UnicodeDecodeErrors.");
41
42 static char *codeckwarglist[] = {"input", "errors", NULL};
43 static char *incnewkwarglist[] = {"errors", NULL};
44 static char *incrementalkwarglist[] = {"input", "final", NULL};
45 static char *streamkwarglist[] = {"stream", "errors", NULL};
46
47 static PyObject *multibytecodec_encode(MultibyteCodec *,
48 MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t,
49 PyObject *, int);
50
51 #define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */
52
53 static PyObject *
54 make_tuple(PyObject *object, Py_ssize_t len)
55 {
56 PyObject *v, *w;
57
58 if (object == NULL)
59 return NULL;
60
61 v = PyTuple_New(2);
62 if (v == NULL) {
63 Py_DECREF(object);
64 return NULL;
65 }
66 PyTuple_SET_ITEM(v, 0, object);
67
68 w = PyInt_FromSsize_t(len);
69 if (w == NULL) {
70 Py_DECREF(v);
71 return NULL;
72 }
73 PyTuple_SET_ITEM(v, 1, w);
74
75 return v;
76 }
77
78 static PyObject *
79 internal_error_callback(const char *errors)
80 {
81 if (errors == NULL || strcmp(errors, "strict") == 0)
82 return ERROR_STRICT;
83 else if (strcmp(errors, "ignore") == 0)
84 return ERROR_IGNORE;
85 else if (strcmp(errors, "replace") == 0)
86 return ERROR_REPLACE;
87 else
88 return PyString_FromString(errors);
89 }
90
91 static PyObject *
92 call_error_callback(PyObject *errors, PyObject *exc)
93 {
94 PyObject *args, *cb, *r;
95
96 assert(PyString_Check(errors));
97 cb = PyCodec_LookupError(PyString_AS_STRING(errors));
98 if (cb == NULL)
99 return NULL;
100
101 args = PyTuple_New(1);
102 if (args == NULL) {
103 Py_DECREF(cb);
104 return NULL;
105 }
106
107 PyTuple_SET_ITEM(args, 0, exc);
108 Py_INCREF(exc);
109
110 r = PyObject_CallObject(cb, args);
111 Py_DECREF(args);
112 Py_DECREF(cb);
113 return r;
114 }
115
116 static PyObject *
117 codecctx_errors_get(MultibyteStatefulCodecContext *self)
118 {
119 const char *errors;
120
121 if (self->errors == ERROR_STRICT)
122 errors = "strict";
123 else if (self->errors == ERROR_IGNORE)
124 errors = "ignore";
125 else if (self->errors == ERROR_REPLACE)
126 errors = "replace";
127 else {
128 Py_INCREF(self->errors);
129 return self->errors;
130 }
131
132 return PyString_FromString(errors);
133 }
134
135 static int
136 codecctx_errors_set(MultibyteStatefulCodecContext *self, PyObject *value,
137 void *closure)
138 {
139 PyObject *cb;
140
141 if (value == NULL) {
142 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
143 return -1;
144 }
145 if (!PyString_Check(value)) {
146 PyErr_SetString(PyExc_TypeError, "errors must be a string");
147 return -1;
148 }
149
150 cb = internal_error_callback(PyString_AS_STRING(value));
151 if (cb == NULL)
152 return -1;
153
154 ERROR_DECREF(self->errors);
155 self->errors = cb;
156 return 0;
157 }
158
159 /* This getset handlers list is used by all the stateful codec objects */
160 static PyGetSetDef codecctx_getsets[] = {
161 {"errors", (getter)codecctx_errors_get,
162 (setter)codecctx_errors_set,
163 PyDoc_STR("how to treat errors")},
164 {NULL,}
165 };
166
167 static int
168 expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize)
169 {
170 Py_ssize_t orgpos, orgsize, incsize;
171
172 orgpos = (Py_ssize_t)((char *)buf->outbuf -
173 PyString_AS_STRING(buf->outobj));
174 orgsize = PyString_GET_SIZE(buf->outobj);
175 incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize);
176
177 if (orgsize > PY_SSIZE_T_MAX - incsize) {
178 PyErr_NoMemory();
179 return -1;
180 }
181
182 if (_PyString_Resize(&buf->outobj, orgsize + incsize) == -1)
183 return -1;
184
185 buf->outbuf = (unsigned char *)PyString_AS_STRING(buf->outobj) +orgpos;
186 buf->outbuf_end = (unsigned char *)PyString_AS_STRING(buf->outobj)
187 + PyString_GET_SIZE(buf->outobj);
188
189 return 0;
190 }
191 #define REQUIRE_ENCODEBUFFER(buf, s) do { \
192 if ((s) < 0 || (s) > (buf)->outbuf_end - (buf)->outbuf) \
193 if (expand_encodebuffer(buf, s) == -1) \
194 goto errorexit; \
195 } while(0)
196
197 static int
198 expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize)
199 {
200 Py_ssize_t orgpos, orgsize;
201
202 orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj));
203 orgsize = PyUnicode_GET_SIZE(buf->outobj);
204 if (PyUnicode_Resize(&buf->outobj, orgsize + (
205 esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1)
206 return -1;
207
208 buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos;
209 buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj)
210 + PyUnicode_GET_SIZE(buf->outobj);
211
212 return 0;
213 }
214 #define REQUIRE_DECODEBUFFER(buf, s) do { \
215 if ((s) < 0 || (s) > (buf)->outbuf_end - (buf)->outbuf) \
216 if (expand_decodebuffer(buf, s) == -1) \
217 goto errorexit; \
218 } while(0)
219
220
221 /**
222 * MultibyteCodec object
223 */
224
225 static int
226 multibytecodec_encerror(MultibyteCodec *codec,
227 MultibyteCodec_State *state,
228 MultibyteEncodeBuffer *buf,
229 PyObject *errors, Py_ssize_t e)
230 {
231 PyObject *retobj = NULL, *retstr = NULL, *tobj;
232 Py_ssize_t retstrsize, newpos;
233 Py_ssize_t esize, start, end;
234 const char *reason;
235
236 if (e > 0) {
237 reason = "illegal multibyte sequence";
238 esize = e;
239 }
240 else {
241 switch (e) {
242 case MBERR_TOOSMALL:
243 REQUIRE_ENCODEBUFFER(buf, -1);
244 return 0; /* retry it */
245 case MBERR_TOOFEW:
246 reason = "incomplete multibyte sequence";
247 esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
248 break;
249 case MBERR_INTERNAL:
250 PyErr_SetString(PyExc_RuntimeError,
251 "internal codec error");
252 return -1;
253 default:
254 PyErr_SetString(PyExc_RuntimeError,
255 "unknown runtime error");
256 return -1;
257 }
258 }
259
260 if (errors == ERROR_REPLACE) {
261 const Py_UNICODE replchar = '?', *inbuf = &replchar;
262 Py_ssize_t r;
263
264 for (;;) {
265 Py_ssize_t outleft;
266
267 outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
268 r = codec->encode(state, codec->config, &inbuf, 1,
269 &buf->outbuf, outleft, 0);
270 if (r == MBERR_TOOSMALL) {
271 REQUIRE_ENCODEBUFFER(buf, -1);
272 continue;
273 }
274 else
275 break;
276 }
277
278 if (r != 0) {
279 REQUIRE_ENCODEBUFFER(buf, 1);
280 *buf->outbuf++ = '?';
281 }
282 }
283 if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
284 buf->inbuf += esize;
285 return 0;
286 }
287
288 start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
289 end = start + esize;
290
291 /* use cached exception object if available */
292 if (buf->excobj == NULL) {
293 buf->excobj = PyUnicodeEncodeError_Create(codec->encoding,
294 buf->inbuf_top,
295 buf->inbuf_end - buf->inbuf_top,
296 start, end, reason);
297 if (buf->excobj == NULL)
298 goto errorexit;
299 }
300 else
301 if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 ||
302 PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 ||
303 PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0)
304 goto errorexit;
305
306 if (errors == ERROR_STRICT) {
307 PyCodec_StrictErrors(buf->excobj);
308 goto errorexit;
309 }
310
311 retobj = call_error_callback(errors, buf->excobj);
312 if (retobj == NULL)
313 goto errorexit;
314
315 if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
316 !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) ||
317 !_PyAnyInt_Check(PyTuple_GET_ITEM(retobj, 1))) {
318 PyErr_SetString(PyExc_TypeError,
319 "encoding error handler must return "
320 "(unicode, int) tuple");
321 goto errorexit;
322 }
323
324 {
325 const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj);
326
327 retstr = multibytecodec_encode(codec, state, &uraw,
328 PyUnicode_GET_SIZE(tobj), ERROR_STRICT,
329 MBENC_FLUSH);
330 if (retstr == NULL)
331 goto errorexit;
332 }
333
334 retstrsize = PyString_GET_SIZE(retstr);
335 if (retstrsize > 0) {
336 REQUIRE_ENCODEBUFFER(buf, retstrsize);
337 memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
338 buf->outbuf += retstrsize;
339 }
340
341 newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
342 if (newpos < 0 && !PyErr_Occurred())
343 newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
344 if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
345 PyErr_Clear();
346 PyErr_Format(PyExc_IndexError,
347 "position %zd from error handler out of bounds",
348 newpos);
349 goto errorexit;
350 }
351 buf->inbuf = buf->inbuf_top + newpos;
352
353 Py_DECREF(retobj);
354 Py_DECREF(retstr);
355 return 0;
356
357 errorexit:
358 Py_XDECREF(retobj);
359 Py_XDECREF(retstr);
360 return -1;
361 }
362
363 static int
364 multibytecodec_decerror(MultibyteCodec *codec,
365 MultibyteCodec_State *state,
366 MultibyteDecodeBuffer *buf,
367 PyObject *errors, Py_ssize_t e)
368 {
369 PyObject *retobj = NULL, *retuni = NULL;
370 Py_ssize_t retunisize, newpos;
371 const char *reason;
372 Py_ssize_t esize, start, end;
373
374 if (e > 0) {
375 reason = "illegal multibyte sequence";
376 esize = e;
377 }
378 else {
379 switch (e) {
380 case MBERR_TOOSMALL:
381 REQUIRE_DECODEBUFFER(buf, -1);
382 return 0; /* retry it */
383 case MBERR_TOOFEW:
384 reason = "incomplete multibyte sequence";
385 esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
386 break;
387 case MBERR_INTERNAL:
388 PyErr_SetString(PyExc_RuntimeError,
389 "internal codec error");
390 return -1;
391 default:
392 PyErr_SetString(PyExc_RuntimeError,
393 "unknown runtime error");
394 return -1;
395 }
396 }
397
398 if (errors == ERROR_REPLACE) {
399 REQUIRE_DECODEBUFFER(buf, 1);
400 *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER;
401 }
402 if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
403 buf->inbuf += esize;
404 return 0;
405 }
406
407 start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
408 end = start + esize;
409
410 /* use cached exception object if available */
411 if (buf->excobj == NULL) {
412 buf->excobj = PyUnicodeDecodeError_Create(codec->encoding,
413 (const char *)buf->inbuf_top,
414 (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top),
415 start, end, reason);
416 if (buf->excobj == NULL)
417 goto errorexit;
418 }
419 else
420 if (PyUnicodeDecodeError_SetStart(buf->excobj, start) ||
421 PyUnicodeDecodeError_SetEnd(buf->excobj, end) ||
422 PyUnicodeDecodeError_SetReason(buf->excobj, reason))
423 goto errorexit;
424
425 if (errors == ERROR_STRICT) {
426 PyCodec_StrictErrors(buf->excobj);
427 goto errorexit;
428 }
429
430 retobj = call_error_callback(errors, buf->excobj);
431 if (retobj == NULL)
432 goto errorexit;
433
434 if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
435 !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) ||
436 !_PyAnyInt_Check(PyTuple_GET_ITEM(retobj, 1))) {
437 PyErr_SetString(PyExc_TypeError,
438 "decoding error handler must return "
439 "(unicode, int) tuple");
440 goto errorexit;
441 }
442
443 retunisize = PyUnicode_GET_SIZE(retuni);
444 if (retunisize > 0) {
445 REQUIRE_DECODEBUFFER(buf, retunisize);
446 memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni),
447 retunisize * Py_UNICODE_SIZE);
448 buf->outbuf += retunisize;
449 }
450
451 newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
452 if (newpos < 0 && !PyErr_Occurred())
453 newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
454 if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
455 PyErr_Clear();
456 PyErr_Format(PyExc_IndexError,
457 "position %zd from error handler out of bounds",
458 newpos);
459 goto errorexit;
460 }
461 buf->inbuf = buf->inbuf_top + newpos;
462 Py_DECREF(retobj);
463 return 0;
464
465 errorexit:
466 Py_XDECREF(retobj);
467 return -1;
468 }
469
470 static PyObject *
471 multibytecodec_encode(MultibyteCodec *codec,
472 MultibyteCodec_State *state,
473 const Py_UNICODE **data, Py_ssize_t datalen,
474 PyObject *errors, int flags)
475 {
476 MultibyteEncodeBuffer buf;
477 Py_ssize_t finalsize, r = 0;
478
479 if (datalen == 0 && !(flags & MBENC_RESET))
480 return PyString_FromString("");
481
482 buf.excobj = NULL;
483 buf.outobj = NULL;
484 buf.inbuf = buf.inbuf_top = *data;
485 buf.inbuf_end = buf.inbuf_top + datalen;
486
487 if (datalen > (PY_SSIZE_T_MAX - 16) / 2) {
488 PyErr_NoMemory();
489 goto errorexit;
490 }
491
492 buf.outobj = PyString_FromStringAndSize(NULL, datalen * 2 + 16);
493 if (buf.outobj == NULL)
494 goto errorexit;
495 buf.outbuf = (unsigned char *)PyString_AS_STRING(buf.outobj);
496 buf.outbuf_end = buf.outbuf + PyString_GET_SIZE(buf.outobj);
497
498 while (buf.inbuf < buf.inbuf_end) {
499 Py_ssize_t inleft, outleft;
500
501 /* we don't reuse inleft and outleft here.
502 * error callbacks can relocate the cursor anywhere on buffer*/
503 inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
504 outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
505 r = codec->encode(state, codec->config, &buf.inbuf, inleft,
506 &buf.outbuf, outleft, flags);
507 if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH)))
508 break;
509 else if (multibytecodec_encerror(codec, state, &buf, errors,r))
510 goto errorexit;
511 else if (r == MBERR_TOOFEW)
512 break;
513 }
514
515 if (codec->encreset != NULL && (flags & MBENC_RESET))
516 for (;;) {
517 Py_ssize_t outleft;
518
519 outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
520 r = codec->encreset(state, codec->config, &buf.outbuf,
521 outleft);
522 if (r == 0)
523 break;
524 else if (multibytecodec_encerror(codec, state,
525 &buf, errors, r))
526 goto errorexit;
527 }
528
529 finalsize = (Py_ssize_t)((char *)buf.outbuf -
530 PyString_AS_STRING(buf.outobj));
531
532 if (finalsize != PyString_GET_SIZE(buf.outobj))
533 if (_PyString_Resize(&buf.outobj, finalsize) == -1)
534 goto errorexit;
535
536 *data = buf.inbuf;
537 Py_XDECREF(buf.excobj);
538 return buf.outobj;
539
540 errorexit:
541 Py_XDECREF(buf.excobj);
542 Py_XDECREF(buf.outobj);
543 return NULL;
544 }
545
546 static PyObject *
547 MultibyteCodec_Encode(MultibyteCodecObject *self,
548 PyObject *args, PyObject *kwargs)
549 {
550 MultibyteCodec_State state;
551 Py_UNICODE *data;
552 PyObject *errorcb, *r, *arg, *ucvt;
553 const char *errors = NULL;
554 Py_ssize_t datalen;
555
556 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode",
557 codeckwarglist, &arg, &errors))
558 return NULL;
559
560 if (PyUnicode_Check(arg))
561 ucvt = NULL;
562 else {
563 arg = ucvt = PyObject_Unicode(arg);
564 if (arg == NULL)
565 return NULL;
566 else if (!PyUnicode_Check(arg)) {
567 PyErr_SetString(PyExc_TypeError,
568 "couldn't convert the object to unicode.");
569 Py_DECREF(ucvt);
570 return NULL;
571 }
572 }
573
574 data = PyUnicode_AS_UNICODE(arg);
575 datalen = PyUnicode_GET_SIZE(arg);
576
577 errorcb = internal_error_callback(errors);
578 if (errorcb == NULL) {
579 Py_XDECREF(ucvt);
580 return NULL;
581 }
582
583 if (self->codec->encinit != NULL &&
584 self->codec->encinit(&state, self->codec->config) != 0)
585 goto errorexit;
586 r = multibytecodec_encode(self->codec, &state,
587 (const Py_UNICODE **)&data, datalen, errorcb,
588 MBENC_FLUSH | MBENC_RESET);
589 if (r == NULL)
590 goto errorexit;
591
592 ERROR_DECREF(errorcb);
593 Py_XDECREF(ucvt);
594 return make_tuple(r, datalen);
595
596 errorexit:
597 ERROR_DECREF(errorcb);
598 Py_XDECREF(ucvt);
599 return NULL;
600 }
601
602 static PyObject *
603 MultibyteCodec_Decode(MultibyteCodecObject *self,
604 PyObject *args, PyObject *kwargs)
605 {
606 MultibyteCodec_State state;
607 MultibyteDecodeBuffer buf;
608 PyObject *errorcb;
609 Py_buffer pdata;
610 const char *data, *errors = NULL;
611 Py_ssize_t datalen, finalsize;
612
613 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|z:decode",
614 codeckwarglist, &pdata, &errors))
615 return NULL;
616 data = pdata.buf;
617 datalen = pdata.len;
618
619 errorcb = internal_error_callback(errors);
620 if (errorcb == NULL) {
621 PyBuffer_Release(&pdata);
622 return NULL;
623 }
624
625 if (datalen == 0) {
626 PyBuffer_Release(&pdata);
627 ERROR_DECREF(errorcb);
628 return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0);
629 }
630
631 buf.excobj = NULL;
632 buf.inbuf = buf.inbuf_top = (unsigned char *)data;
633 buf.inbuf_end = buf.inbuf_top + datalen;
634 buf.outobj = PyUnicode_FromUnicode(NULL, datalen);
635 if (buf.outobj == NULL)
636 goto errorexit;
637 buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj);
638 buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj);
639
640 if (self->codec->decinit != NULL &&
641 self->codec->decinit(&state, self->codec->config) != 0)
642 goto errorexit;
643
644 while (buf.inbuf < buf.inbuf_end) {
645 Py_ssize_t inleft, outleft, r;
646
647 inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
648 outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
649
650 r = self->codec->decode(&state, self->codec->config,
651 &buf.inbuf, inleft, &buf.outbuf, outleft);
652 if (r == 0)
653 break;
654 else if (multibytecodec_decerror(self->codec, &state,
655 &buf, errorcb, r))
656 goto errorexit;
657 }
658
659 finalsize = (Py_ssize_t)(buf.outbuf -
660 PyUnicode_AS_UNICODE(buf.outobj));
661
662 if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
663 if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
664 goto errorexit;
665
666 PyBuffer_Release(&pdata);
667 Py_XDECREF(buf.excobj);
668 ERROR_DECREF(errorcb);
669 return make_tuple(buf.outobj, datalen);
670
671 errorexit:
672 PyBuffer_Release(&pdata);
673 ERROR_DECREF(errorcb);
674 Py_XDECREF(buf.excobj);
675 Py_XDECREF(buf.outobj);
676
677 return NULL;
678 }
679
680 static struct PyMethodDef multibytecodec_methods[] = {
681 {"encode", (PyCFunction)MultibyteCodec_Encode,
682 METH_VARARGS | METH_KEYWORDS,
683 MultibyteCodec_Encode__doc__},
684 {"decode", (PyCFunction)MultibyteCodec_Decode,
685 METH_VARARGS | METH_KEYWORDS,
686 MultibyteCodec_Decode__doc__},
687 {NULL, NULL},
688 };
689
690 static void
691 multibytecodec_dealloc(MultibyteCodecObject *self)
692 {
693 PyObject_Del(self);
694 }
695
696 static PyTypeObject MultibyteCodec_Type = {
697 PyVarObject_HEAD_INIT(NULL, 0)
698 "MultibyteCodec", /* tp_name */
699 sizeof(MultibyteCodecObject), /* tp_basicsize */
700 0, /* tp_itemsize */
701 /* methods */
702 (destructor)multibytecodec_dealloc, /* tp_dealloc */
703 0, /* tp_print */
704 0, /* tp_getattr */
705 0, /* tp_setattr */
706 0, /* tp_compare */
707 0, /* tp_repr */
708 0, /* tp_as_number */
709 0, /* tp_as_sequence */
710 0, /* tp_as_mapping */
711 0, /* tp_hash */
712 0, /* tp_call */
713 0, /* tp_str */
714 PyObject_GenericGetAttr, /* tp_getattro */
715 0, /* tp_setattro */
716 0, /* tp_as_buffer */
717 Py_TPFLAGS_DEFAULT, /* tp_flags */
718 0, /* tp_doc */
719 0, /* tp_traverse */
720 0, /* tp_clear */
721 0, /* tp_richcompare */
722 0, /* tp_weaklistoffset */
723 0, /* tp_iter */
724 0, /* tp_iterext */
725 multibytecodec_methods, /* tp_methods */
726 };
727
728
729 /**
730 * Utility functions for stateful codec mechanism
731 */
732
733 #define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o))
734 #define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o))
735
736 static PyObject *
737 encoder_encode_stateful(MultibyteStatefulEncoderContext *ctx,
738 PyObject *unistr, int final)
739 {
740 PyObject *ucvt, *r = NULL;
741 Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL;
742 Py_ssize_t datalen, origpending;
743
744 if (PyUnicode_Check(unistr))
745 ucvt = NULL;
746 else {
747 unistr = ucvt = PyObject_Unicode(unistr);
748 if (unistr == NULL)
749 return NULL;
750 else if (!PyUnicode_Check(unistr)) {
751 PyErr_SetString(PyExc_TypeError,
752 "couldn't convert the object to unicode.");
753 Py_DECREF(ucvt);
754 return NULL;
755 }
756 }
757
758 datalen = PyUnicode_GET_SIZE(unistr);
759 origpending = ctx->pendingsize;
760
761 if (origpending > 0) {
762 if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) {
763 PyErr_NoMemory();
764 /* inbuf_tmp == NULL */
765 goto errorexit;
766 }
767 inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize);
768 if (inbuf_tmp == NULL)
769 goto errorexit;
770 memcpy(inbuf_tmp, ctx->pending,
771 Py_UNICODE_SIZE * ctx->pendingsize);
772 memcpy(inbuf_tmp + ctx->pendingsize,
773 PyUnicode_AS_UNICODE(unistr),
774 Py_UNICODE_SIZE * datalen);
775 datalen += ctx->pendingsize;
776 ctx->pendingsize = 0;
777 inbuf = inbuf_tmp;
778 }
779 else
780 inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr);
781
782 inbuf_end = inbuf + datalen;
783
784 r = multibytecodec_encode(ctx->codec, &ctx->state,
785 (const Py_UNICODE **)&inbuf, datalen,
786 ctx->errors, final ? MBENC_FLUSH | MBENC_RESET : 0);
787 if (r == NULL) {
788 /* recover the original pending buffer */
789 if (origpending > 0)
790 memcpy(ctx->pending, inbuf_tmp,
791 Py_UNICODE_SIZE * origpending);
792 ctx->pendingsize = origpending;
793 goto errorexit;
794 }
795
796 if (inbuf < inbuf_end) {
797 ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf);
798 if (ctx->pendingsize > MAXENCPENDING) {
799 /* normal codecs can't reach here */
800 ctx->pendingsize = 0;
801 PyErr_SetString(PyExc_UnicodeError,
802 "pending buffer overflow");
803 goto errorexit;
804 }
805 memcpy(ctx->pending, inbuf,
806 ctx->pendingsize * Py_UNICODE_SIZE);
807 }
808
809 if (inbuf_tmp != NULL)
810 PyMem_Del(inbuf_tmp);
811 Py_XDECREF(ucvt);
812 return r;
813
814 errorexit:
815 if (inbuf_tmp != NULL)
816 PyMem_Del(inbuf_tmp);
817 Py_XDECREF(r);
818 Py_XDECREF(ucvt);
819 return NULL;
820 }
821
822 static int
823 decoder_append_pending(MultibyteStatefulDecoderContext *ctx,
824 MultibyteDecodeBuffer *buf)
825 {
826 Py_ssize_t npendings;
827
828 npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
829 if (npendings + ctx->pendingsize > MAXDECPENDING ||
830 npendings > PY_SSIZE_T_MAX - ctx->pendingsize) {
831 PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow");
832 return -1;
833 }
834 memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings);
835 ctx->pendingsize += npendings;
836 return 0;
837 }
838
839 static int
840 decoder_prepare_buffer(MultibyteDecodeBuffer *buf, const char *data,
841 Py_ssize_t size)
842 {
843 buf->inbuf = buf->inbuf_top = (const unsigned char *)data;
844 buf->inbuf_end = buf->inbuf_top + size;
845 if (buf->outobj == NULL) { /* only if outobj is not allocated yet */
846 buf->outobj = PyUnicode_FromUnicode(NULL, size);
847 if (buf->outobj == NULL)
848 return -1;
849 buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj);
850 buf->outbuf_end = buf->outbuf +
851 PyUnicode_GET_SIZE(buf->outobj);
852 }
853
854 return 0;
855 }
856
857 static int
858 decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx,
859 MultibyteDecodeBuffer *buf)
860 {
861 while (buf->inbuf < buf->inbuf_end) {
862 Py_ssize_t inleft, outleft;
863 Py_ssize_t r;
864
865 inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
866 outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
867
868 r = ctx->codec->decode(&ctx->state, ctx->codec->config,
869 &buf->inbuf, inleft, &buf->outbuf, outleft);
870 if (r == 0 || r == MBERR_TOOFEW)
871 break;
872 else if (multibytecodec_decerror(ctx->codec, &ctx->state,
873 buf, ctx->errors, r))
874 return -1;
875 }
876 return 0;
877 }
878
879
880 /**
881 * MultibyteIncrementalEncoder object
882 */
883
884 static PyObject *
885 mbiencoder_encode(MultibyteIncrementalEncoderObject *self,
886 PyObject *args, PyObject *kwargs)
887 {
888 PyObject *data;
889 int final = 0;
890
891 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode",
892 incrementalkwarglist, &data, &final))
893 return NULL;
894
895 return encoder_encode_stateful(STATEFUL_ECTX(self), data, final);
896 }
897
898 static PyObject *
899 mbiencoder_reset(MultibyteIncrementalEncoderObject *self)
900 {
901 if (self->codec->decreset != NULL &&
902 self->codec->decreset(&self->state, self->codec->config) != 0)
903 return NULL;
904 self->pendingsize = 0;
905
906 Py_RETURN_NONE;
907 }
908
909 static struct PyMethodDef mbiencoder_methods[] = {
910 {"encode", (PyCFunction)mbiencoder_encode,
911 METH_VARARGS | METH_KEYWORDS, NULL},
912 {"reset", (PyCFunction)mbiencoder_reset,
913 METH_NOARGS, NULL},
914 {NULL, NULL},
915 };
916
917 static PyObject *
918 mbiencoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
919 {
920 MultibyteIncrementalEncoderObject *self;
921 PyObject *codec = NULL;
922 char *errors = NULL;
923
924 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder",
925 incnewkwarglist, &errors))
926 return NULL;
927
928 self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0);
929 if (self == NULL)
930 return NULL;
931
932 codec = PyObject_GetAttrString((PyObject *)type, "codec");
933 if (codec == NULL)
934 goto errorexit;
935 if (!MultibyteCodec_Check(codec)) {
936 PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
937 goto errorexit;
938 }
939
940 self->codec = ((MultibyteCodecObject *)codec)->codec;
941 self->pendingsize = 0;
942 self->errors = internal_error_callback(errors);
943 if (self->errors == NULL)
944 goto errorexit;
945 if (self->codec->encinit != NULL &&
946 self->codec->encinit(&self->state, self->codec->config) != 0)
947 goto errorexit;
948
949 Py_DECREF(codec);
950 return (PyObject *)self;
951
952 errorexit:
953 Py_XDECREF(self);
954 Py_XDECREF(codec);
955 return NULL;
956 }
957
958 static int
959 mbiencoder_init(PyObject *self, PyObject *args, PyObject *kwds)
960 {
961 return 0;
962 }
963
964 static int
965 mbiencoder_traverse(MultibyteIncrementalEncoderObject *self,
966 visitproc visit, void *arg)
967 {
968 if (ERROR_ISCUSTOM(self->errors))
969 Py_VISIT(self->errors);
970 return 0;
971 }
972
973 static void
974 mbiencoder_dealloc(MultibyteIncrementalEncoderObject *self)
975 {
976 PyObject_GC_UnTrack(self);
977 ERROR_DECREF(self->errors);
978 Py_TYPE(self)->tp_free(self);
979 }
980
981 static PyTypeObject MultibyteIncrementalEncoder_Type = {
982 PyVarObject_HEAD_INIT(NULL, 0)
983 "MultibyteIncrementalEncoder", /* tp_name */
984 sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */
985 0, /* tp_itemsize */
986 /* methods */
987 (destructor)mbiencoder_dealloc, /* tp_dealloc */
988 0, /* tp_print */
989 0, /* tp_getattr */
990 0, /* tp_setattr */
991 0, /* tp_compare */
992 0, /* tp_repr */
993 0, /* tp_as_number */
994 0, /* tp_as_sequence */
995 0, /* tp_as_mapping */
996 0, /* tp_hash */
997 0, /* tp_call */
998 0, /* tp_str */
999 PyObject_GenericGetAttr, /* tp_getattro */
1000 0, /* tp_setattro */
1001 0, /* tp_as_buffer */
1002 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
1003 | Py_TPFLAGS_BASETYPE, /* tp_flags */
1004 0, /* tp_doc */
1005 (traverseproc)mbiencoder_traverse, /* tp_traverse */
1006 0, /* tp_clear */
1007 0, /* tp_richcompare */
1008 0, /* tp_weaklistoffset */
1009 0, /* tp_iter */
1010 0, /* tp_iterext */
1011 mbiencoder_methods, /* tp_methods */
1012 0, /* tp_members */
1013 codecctx_getsets, /* tp_getset */
1014 0, /* tp_base */
1015 0, /* tp_dict */
1016 0, /* tp_descr_get */
1017 0, /* tp_descr_set */
1018 0, /* tp_dictoffset */
1019 mbiencoder_init, /* tp_init */
1020 0, /* tp_alloc */
1021 mbiencoder_new, /* tp_new */
1022 };
1023
1024
1025 /**
1026 * MultibyteIncrementalDecoder object
1027 */
1028
1029 static PyObject *
1030 mbidecoder_decode(MultibyteIncrementalDecoderObject *self,
1031 PyObject *args, PyObject *kwargs)
1032 {
1033 MultibyteDecodeBuffer buf;
1034 char *data, *wdata = NULL;
1035 Py_buffer pdata;
1036 Py_ssize_t wsize, finalsize = 0, size, origpending;
1037 int final = 0;
1038
1039 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i:decode",
1040 incrementalkwarglist, &pdata, &final))
1041 return NULL;
1042 data = pdata.buf;
1043 size = pdata.len;
1044
1045 buf.outobj = buf.excobj = NULL;
1046 origpending = self->pendingsize;
1047
1048 if (self->pendingsize == 0) {
1049 wsize = size;
1050 wdata = data;
1051 }
1052 else {
1053 if (size > PY_SSIZE_T_MAX - self->pendingsize) {
1054 PyErr_NoMemory();
1055 goto errorexit;
1056 }
1057 wsize = size + self->pendingsize;
1058 wdata = PyMem_Malloc(wsize);
1059 if (wdata == NULL)
1060 goto errorexit;
1061 memcpy(wdata, self->pending, self->pendingsize);
1062 memcpy(wdata + self->pendingsize, data, size);
1063 self->pendingsize = 0;
1064 }
1065
1066 if (decoder_prepare_buffer(&buf, wdata, wsize) != 0)
1067 goto errorexit;
1068
1069 if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf))
1070 goto errorexit;
1071
1072 if (final && buf.inbuf < buf.inbuf_end) {
1073 if (multibytecodec_decerror(self->codec, &self->state,
1074 &buf, self->errors, MBERR_TOOFEW)) {
1075 /* recover the original pending buffer */
1076 memcpy(self->pending, wdata, origpending);
1077 self->pendingsize = origpending;
1078 goto errorexit;
1079 }
1080 }
1081
1082 if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */
1083 if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0)
1084 goto errorexit;
1085 }
1086
1087 finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj));
1088 if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
1089 if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
1090 goto errorexit;
1091
1092 PyBuffer_Release(&pdata);
1093 if (wdata != data)
1094 PyMem_Del(wdata);
1095 Py_XDECREF(buf.excobj);
1096 return buf.outobj;
1097
1098 errorexit:
1099 PyBuffer_Release(&pdata);
1100 if (wdata != NULL && wdata != data)
1101 PyMem_Del(wdata);
1102 Py_XDECREF(buf.excobj);
1103 Py_XDECREF(buf.outobj);
1104 return NULL;
1105 }
1106
1107 static PyObject *
1108 mbidecoder_reset(MultibyteIncrementalDecoderObject *self)
1109 {
1110 if (self->codec->decreset != NULL &&
1111 self->codec->decreset(&self->state, self->codec->config) != 0)
1112 return NULL;
1113 self->pendingsize = 0;
1114
1115 Py_RETURN_NONE;
1116 }
1117
1118 static struct PyMethodDef mbidecoder_methods[] = {
1119 {"decode", (PyCFunction)mbidecoder_decode,
1120 METH_VARARGS | METH_KEYWORDS, NULL},
1121 {"reset", (PyCFunction)mbidecoder_reset,
1122 METH_NOARGS, NULL},
1123 {NULL, NULL},
1124 };
1125
1126 static PyObject *
1127 mbidecoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1128 {
1129 MultibyteIncrementalDecoderObject *self;
1130 PyObject *codec = NULL;
1131 char *errors = NULL;
1132
1133 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder",
1134 incnewkwarglist, &errors))
1135 return NULL;
1136
1137 self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0);
1138 if (self == NULL)
1139 return NULL;
1140
1141 codec = PyObject_GetAttrString((PyObject *)type, "codec");
1142 if (codec == NULL)
1143 goto errorexit;
1144 if (!MultibyteCodec_Check(codec)) {
1145 PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
1146 goto errorexit;
1147 }
1148
1149 self->codec = ((MultibyteCodecObject *)codec)->codec;
1150 self->pendingsize = 0;
1151 self->errors = internal_error_callback(errors);
1152 if (self->errors == NULL)
1153 goto errorexit;
1154 if (self->codec->decinit != NULL &&
1155 self->codec->decinit(&self->state, self->codec->config) != 0)
1156 goto errorexit;
1157
1158 Py_DECREF(codec);
1159 return (PyObject *)self;
1160
1161 errorexit:
1162 Py_XDECREF(self);
1163 Py_XDECREF(codec);
1164 return NULL;
1165 }
1166
1167 static int
1168 mbidecoder_init(PyObject *self, PyObject *args, PyObject *kwds)
1169 {
1170 return 0;
1171 }
1172
1173 static int
1174 mbidecoder_traverse(MultibyteIncrementalDecoderObject *self,
1175 visitproc visit, void *arg)
1176 {
1177 if (ERROR_ISCUSTOM(self->errors))
1178 Py_VISIT(self->errors);
1179 return 0;
1180 }
1181
1182 static void
1183 mbidecoder_dealloc(MultibyteIncrementalDecoderObject *self)
1184 {
1185 PyObject_GC_UnTrack(self);
1186 ERROR_DECREF(self->errors);
1187 Py_TYPE(self)->tp_free(self);
1188 }
1189
1190 static PyTypeObject MultibyteIncrementalDecoder_Type = {
1191 PyVarObject_HEAD_INIT(NULL, 0)
1192 "MultibyteIncrementalDecoder", /* tp_name */
1193 sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */
1194 0, /* tp_itemsize */
1195 /* methods */
1196 (destructor)mbidecoder_dealloc, /* tp_dealloc */
1197 0, /* tp_print */
1198 0, /* tp_getattr */
1199 0, /* tp_setattr */
1200 0, /* tp_compare */
1201 0, /* tp_repr */
1202 0, /* tp_as_number */
1203 0, /* tp_as_sequence */
1204 0, /* tp_as_mapping */
1205 0, /* tp_hash */
1206 0, /* tp_call */
1207 0, /* tp_str */
1208 PyObject_GenericGetAttr, /* tp_getattro */
1209 0, /* tp_setattro */
1210 0, /* tp_as_buffer */
1211 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
1212 | Py_TPFLAGS_BASETYPE, /* tp_flags */
1213 0, /* tp_doc */
1214 (traverseproc)mbidecoder_traverse, /* tp_traverse */
1215 0, /* tp_clear */
1216 0, /* tp_richcompare */
1217 0, /* tp_weaklistoffset */
1218 0, /* tp_iter */
1219 0, /* tp_iterext */
1220 mbidecoder_methods, /* tp_methods */
1221 0, /* tp_members */
1222 codecctx_getsets, /* tp_getset */
1223 0, /* tp_base */
1224 0, /* tp_dict */
1225 0, /* tp_descr_get */
1226 0, /* tp_descr_set */
1227 0, /* tp_dictoffset */
1228 mbidecoder_init, /* tp_init */
1229 0, /* tp_alloc */
1230 mbidecoder_new, /* tp_new */
1231 };
1232
1233
1234 /**
1235 * MultibyteStreamReader object
1236 */
1237
1238 static PyObject *
1239 mbstreamreader_iread(MultibyteStreamReaderObject *self,
1240 const char *method, Py_ssize_t sizehint)
1241 {
1242 MultibyteDecodeBuffer buf;
1243 PyObject *cres;
1244 Py_ssize_t rsize, finalsize = 0;
1245
1246 if (sizehint == 0)
1247 return PyUnicode_FromUnicode(NULL, 0);
1248
1249 buf.outobj = buf.excobj = NULL;
1250 cres = NULL;
1251
1252 for (;;) {
1253 int endoffile;
1254
1255 if (sizehint < 0)
1256 cres = PyObject_CallMethod(self->stream,
1257 (char *)method, NULL);
1258 else
1259 cres = PyObject_CallMethod(self->stream,
1260 (char *)method, "i", sizehint);
1261 if (cres == NULL)
1262 goto errorexit;
1263
1264 if (!PyString_Check(cres)) {
1265 PyErr_SetString(PyExc_TypeError,
1266 "stream function returned a "
1267 "non-string object");
1268 goto errorexit;
1269 }
1270
1271 endoffile = (PyString_GET_SIZE(cres) == 0);
1272
1273 if (self->pendingsize > 0) {
1274 PyObject *ctr;
1275 char *ctrdata;
1276
1277 if (PyString_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) {
1278 PyErr_NoMemory();
1279 goto errorexit;
1280 }
1281 rsize = PyString_GET_SIZE(cres) + self->pendingsize;
1282 ctr = PyString_FromStringAndSize(NULL, rsize);
1283 if (ctr == NULL)
1284 goto errorexit;
1285 ctrdata = PyString_AS_STRING(ctr);
1286 memcpy(ctrdata, self->pending, self->pendingsize);
1287 memcpy(ctrdata + self->pendingsize,
1288 PyString_AS_STRING(cres),
1289 PyString_GET_SIZE(cres));
1290 Py_DECREF(cres);
1291 cres = ctr;
1292 self->pendingsize = 0;
1293 }
1294
1295 rsize = PyString_GET_SIZE(cres);
1296 if (decoder_prepare_buffer(&buf, PyString_AS_STRING(cres),
1297 rsize) != 0)
1298 goto errorexit;
1299
1300 if (rsize > 0 && decoder_feed_buffer(
1301 (MultibyteStatefulDecoderContext *)self, &buf))
1302 goto errorexit;
1303
1304 if (endoffile || sizehint < 0) {
1305 if (buf.inbuf < buf.inbuf_end &&
1306 multibytecodec_decerror(self->codec, &self->state,
1307 &buf, self->errors, MBERR_TOOFEW))
1308 goto errorexit;
1309 }
1310
1311 if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */
1312 if (decoder_append_pending(STATEFUL_DCTX(self),
1313 &buf) != 0)
1314 goto errorexit;
1315 }
1316
1317 finalsize = (Py_ssize_t)(buf.outbuf -
1318 PyUnicode_AS_UNICODE(buf.outobj));
1319 Py_DECREF(cres);
1320 cres = NULL;
1321
1322 if (sizehint < 0 || finalsize != 0 || rsize == 0)
1323 break;
1324
1325 sizehint = 1; /* read 1 more byte and retry */
1326 }
1327
1328 if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
1329 if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
1330 goto errorexit;
1331
1332 Py_XDECREF(cres);
1333 Py_XDECREF(buf.excobj);
1334 return buf.outobj;
1335
1336 errorexit:
1337 Py_XDECREF(cres);
1338 Py_XDECREF(buf.excobj);
1339 Py_XDECREF(buf.outobj);
1340 return NULL;
1341 }
1342
1343 static PyObject *
1344 mbstreamreader_read(MultibyteStreamReaderObject *self, PyObject *args)
1345 {
1346 PyObject *sizeobj = NULL;
1347 Py_ssize_t size;
1348
1349 if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj))
1350 return NULL;
1351
1352 if (sizeobj == Py_None || sizeobj == NULL)
1353 size = -1;
1354 else if (PyInt_Check(sizeobj))
1355 size = PyInt_AsSsize_t(sizeobj);
1356 else {
1357 PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
1358 return NULL;
1359 }
1360
1361 return mbstreamreader_iread(self, "read", size);
1362 }
1363
1364 static PyObject *
1365 mbstreamreader_readline(MultibyteStreamReaderObject *self, PyObject *args)
1366 {
1367 PyObject *sizeobj = NULL;
1368 Py_ssize_t size;
1369
1370 if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj))
1371 return NULL;
1372
1373 if (sizeobj == Py_None || sizeobj == NULL)
1374 size = -1;
1375 else if (PyInt_Check(sizeobj))
1376 size = PyInt_AsSsize_t(sizeobj);
1377 else {
1378 PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
1379 return NULL;
1380 }
1381
1382 return mbstreamreader_iread(self, "readline", size);
1383 }
1384
1385 static PyObject *
1386 mbstreamreader_readlines(MultibyteStreamReaderObject *self, PyObject *args)
1387 {
1388 PyObject *sizehintobj = NULL, *r, *sr;
1389 Py_ssize_t sizehint;
1390
1391 if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj))
1392 return NULL;
1393
1394 if (sizehintobj == Py_None || sizehintobj == NULL)
1395 sizehint = -1;
1396 else if (PyInt_Check(sizehintobj))
1397 sizehint = PyInt_AsSsize_t(sizehintobj);
1398 else {
1399 PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
1400 return NULL;
1401 }
1402
1403 r = mbstreamreader_iread(self, "read", sizehint);
1404 if (r == NULL)
1405 return NULL;
1406
1407 sr = PyUnicode_Splitlines(r, 1);
1408 Py_DECREF(r);
1409 return sr;
1410 }
1411
1412 static PyObject *
1413 mbstreamreader_reset(MultibyteStreamReaderObject *self)
1414 {
1415 if (self->codec->decreset != NULL &&
1416 self->codec->decreset(&self->state, self->codec->config) != 0)
1417 return NULL;
1418 self->pendingsize = 0;
1419
1420 Py_RETURN_NONE;
1421 }
1422
1423 static struct PyMethodDef mbstreamreader_methods[] = {
1424 {"read", (PyCFunction)mbstreamreader_read,
1425 METH_VARARGS, NULL},
1426 {"readline", (PyCFunction)mbstreamreader_readline,
1427 METH_VARARGS, NULL},
1428 {"readlines", (PyCFunction)mbstreamreader_readlines,
1429 METH_VARARGS, NULL},
1430 {"reset", (PyCFunction)mbstreamreader_reset,
1431 METH_NOARGS, NULL},
1432 {NULL, NULL},
1433 };
1434
1435 static PyMemberDef mbstreamreader_members[] = {
1436 {"stream", T_OBJECT,
1437 offsetof(MultibyteStreamReaderObject, stream),
1438 READONLY, NULL},
1439 {NULL,}
1440 };
1441
1442 static PyObject *
1443 mbstreamreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1444 {
1445 MultibyteStreamReaderObject *self;
1446 PyObject *stream, *codec = NULL;
1447 char *errors = NULL;
1448
1449 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader",
1450 streamkwarglist, &stream, &errors))
1451 return NULL;
1452
1453 self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0);
1454 if (self == NULL)
1455 return NULL;
1456
1457 codec = PyObject_GetAttrString((PyObject *)type, "codec");
1458 if (codec == NULL)
1459 goto errorexit;
1460 if (!MultibyteCodec_Check(codec)) {
1461 PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
1462 goto errorexit;
1463 }
1464
1465 self->codec = ((MultibyteCodecObject *)codec)->codec;
1466 self->stream = stream;
1467 Py_INCREF(stream);
1468 self->pendingsize = 0;
1469 self->errors = internal_error_callback(errors);
1470 if (self->errors == NULL)
1471 goto errorexit;
1472 if (self->codec->decinit != NULL &&
1473 self->codec->decinit(&self->state, self->codec->config) != 0)
1474 goto errorexit;
1475
1476 Py_DECREF(codec);
1477 return (PyObject *)self;
1478
1479 errorexit:
1480 Py_XDECREF(self);
1481 Py_XDECREF(codec);
1482 return NULL;
1483 }
1484
1485 static int
1486 mbstreamreader_init(PyObject *self, PyObject *args, PyObject *kwds)
1487 {
1488 return 0;
1489 }
1490
1491 static int
1492 mbstreamreader_traverse(MultibyteStreamReaderObject *self,
1493 visitproc visit, void *arg)
1494 {
1495 if (ERROR_ISCUSTOM(self->errors))
1496 Py_VISIT(self->errors);
1497 Py_VISIT(self->stream);
1498 return 0;
1499 }
1500
1501 static void
1502 mbstreamreader_dealloc(MultibyteStreamReaderObject *self)
1503 {
1504 PyObject_GC_UnTrack(self);
1505 ERROR_DECREF(self->errors);
1506 Py_XDECREF(self->stream);
1507 Py_TYPE(self)->tp_free(self);
1508 }
1509
1510 static PyTypeObject MultibyteStreamReader_Type = {
1511 PyVarObject_HEAD_INIT(NULL, 0)
1512 "MultibyteStreamReader", /* tp_name */
1513 sizeof(MultibyteStreamReaderObject), /* tp_basicsize */
1514 0, /* tp_itemsize */
1515 /* methods */
1516 (destructor)mbstreamreader_dealloc, /* tp_dealloc */
1517 0, /* tp_print */
1518 0, /* tp_getattr */
1519 0, /* tp_setattr */
1520 0, /* tp_compare */
1521 0, /* tp_repr */
1522 0, /* tp_as_number */
1523 0, /* tp_as_sequence */
1524 0, /* tp_as_mapping */
1525 0, /* tp_hash */
1526 0, /* tp_call */
1527 0, /* tp_str */
1528 PyObject_GenericGetAttr, /* tp_getattro */
1529 0, /* tp_setattro */
1530 0, /* tp_as_buffer */
1531 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
1532 | Py_TPFLAGS_BASETYPE, /* tp_flags */
1533 0, /* tp_doc */
1534 (traverseproc)mbstreamreader_traverse, /* tp_traverse */
1535 0, /* tp_clear */
1536 0, /* tp_richcompare */
1537 0, /* tp_weaklistoffset */
1538 0, /* tp_iter */
1539 0, /* tp_iterext */
1540 mbstreamreader_methods, /* tp_methods */
1541 mbstreamreader_members, /* tp_members */
1542 codecctx_getsets, /* tp_getset */
1543 0, /* tp_base */
1544 0, /* tp_dict */
1545 0, /* tp_descr_get */
1546 0, /* tp_descr_set */
1547 0, /* tp_dictoffset */
1548 mbstreamreader_init, /* tp_init */
1549 0, /* tp_alloc */
1550 mbstreamreader_new, /* tp_new */
1551 };
1552
1553
1554 /**
1555 * MultibyteStreamWriter object
1556 */
1557
1558 static int
1559 mbstreamwriter_iwrite(MultibyteStreamWriterObject *self,
1560 PyObject *unistr)
1561 {
1562 PyObject *str, *wr;
1563
1564 str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0);
1565 if (str == NULL)
1566 return -1;
1567
1568 wr = PyObject_CallMethod(self->stream, "write", "O", str);
1569 Py_DECREF(str);
1570 if (wr == NULL)
1571 return -1;
1572
1573 Py_DECREF(wr);
1574 return 0;
1575 }
1576
1577 static PyObject *
1578 mbstreamwriter_write(MultibyteStreamWriterObject *self, PyObject *strobj)
1579 {
1580 if (mbstreamwriter_iwrite(self, strobj))
1581 return NULL;
1582 else
1583 Py_RETURN_NONE;
1584 }
1585
1586 static PyObject *
1587 mbstreamwriter_writelines(MultibyteStreamWriterObject *self, PyObject *lines)
1588 {
1589 PyObject *strobj;
1590 int i, r;
1591
1592 if (!PySequence_Check(lines)) {
1593 PyErr_SetString(PyExc_TypeError,
1594 "arg must be a sequence object");
1595 return NULL;
1596 }
1597
1598 for (i = 0; i < PySequence_Length(lines); i++) {
1599 /* length can be changed even within this loop */
1600 strobj = PySequence_GetItem(lines, i);
1601 if (strobj == NULL)
1602 return NULL;
1603
1604 r = mbstreamwriter_iwrite(self, strobj);
1605 Py_DECREF(strobj);
1606 if (r == -1)
1607 return NULL;
1608 }
1609 /* PySequence_Length() can fail */
1610 if (PyErr_Occurred())
1611 return NULL;
1612
1613 Py_RETURN_NONE;
1614 }
1615
1616 static PyObject *
1617 mbstreamwriter_reset(MultibyteStreamWriterObject *self)
1618 {
1619 const Py_UNICODE *pending;
1620 PyObject *pwrt;
1621
1622 pending = self->pending;
1623 pwrt = multibytecodec_encode(self->codec, &self->state,
1624 &pending, self->pendingsize, self->errors,
1625 MBENC_FLUSH | MBENC_RESET);
1626 /* some pending buffer can be truncated when UnicodeEncodeError is
1627 * raised on 'strict' mode. but, 'reset' method is designed to
1628 * reset the pending buffer or states so failed string sequence
1629 * ought to be missed */
1630 self->pendingsize = 0;
1631 if (pwrt == NULL)
1632 return NULL;
1633
1634 if (PyString_Size(pwrt) > 0) {
1635 PyObject *wr;
1636 wr = PyObject_CallMethod(self->stream, "write", "O", pwrt);
1637 if (wr == NULL) {
1638 Py_DECREF(pwrt);
1639 return NULL;
1640 }
1641 }
1642 Py_DECREF(pwrt);
1643
1644 Py_RETURN_NONE;
1645 }
1646
1647 static PyObject *
1648 mbstreamwriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1649 {
1650 MultibyteStreamWriterObject *self;
1651 PyObject *stream, *codec = NULL;
1652 char *errors = NULL;
1653
1654 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter",
1655 streamkwarglist, &stream, &errors))
1656 return NULL;
1657
1658 self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0);
1659 if (self == NULL)
1660 return NULL;
1661
1662 codec = PyObject_GetAttrString((PyObject *)type, "codec");
1663 if (codec == NULL)
1664 goto errorexit;
1665 if (!MultibyteCodec_Check(codec)) {
1666 PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
1667 goto errorexit;
1668 }
1669
1670 self->codec = ((MultibyteCodecObject *)codec)->codec;
1671 self->stream = stream;
1672 Py_INCREF(stream);
1673 self->pendingsize = 0;
1674 self->errors = internal_error_callback(errors);
1675 if (self->errors == NULL)
1676 goto errorexit;
1677 if (self->codec->encinit != NULL &&
1678 self->codec->encinit(&self->state, self->codec->config) != 0)
1679 goto errorexit;
1680
1681 Py_DECREF(codec);
1682 return (PyObject *)self;
1683
1684 errorexit:
1685 Py_XDECREF(self);
1686 Py_XDECREF(codec);
1687 return NULL;
1688 }
1689
1690 static int
1691 mbstreamwriter_init(PyObject *self, PyObject *args, PyObject *kwds)
1692 {
1693 return 0;
1694 }
1695
1696 static int
1697 mbstreamwriter_traverse(MultibyteStreamWriterObject *self,
1698 visitproc visit, void *arg)
1699 {
1700 if (ERROR_ISCUSTOM(self->errors))
1701 Py_VISIT(self->errors);
1702 Py_VISIT(self->stream);
1703 return 0;
1704 }
1705
1706 static void
1707 mbstreamwriter_dealloc(MultibyteStreamWriterObject *self)
1708 {
1709 PyObject_GC_UnTrack(self);
1710 ERROR_DECREF(self->errors);
1711 Py_XDECREF(self->stream);
1712 Py_TYPE(self)->tp_free(self);
1713 }
1714
1715 static struct PyMethodDef mbstreamwriter_methods[] = {
1716 {"write", (PyCFunction)mbstreamwriter_write,
1717 METH_O, NULL},
1718 {"writelines", (PyCFunction)mbstreamwriter_writelines,
1719 METH_O, NULL},
1720 {"reset", (PyCFunction)mbstreamwriter_reset,
1721 METH_NOARGS, NULL},
1722 {NULL, NULL},
1723 };
1724
1725 static PyMemberDef mbstreamwriter_members[] = {
1726 {"stream", T_OBJECT,
1727 offsetof(MultibyteStreamWriterObject, stream),
1728 READONLY, NULL},
1729 {NULL,}
1730 };
1731
1732 static PyTypeObject MultibyteStreamWriter_Type = {
1733 PyVarObject_HEAD_INIT(NULL, 0)
1734 "MultibyteStreamWriter", /* tp_name */
1735 sizeof(MultibyteStreamWriterObject), /* tp_basicsize */
1736 0, /* tp_itemsize */
1737 /* methods */
1738 (destructor)mbstreamwriter_dealloc, /* tp_dealloc */
1739 0, /* tp_print */
1740 0, /* tp_getattr */
1741 0, /* tp_setattr */
1742 0, /* tp_compare */
1743 0, /* tp_repr */
1744 0, /* tp_as_number */
1745 0, /* tp_as_sequence */
1746 0, /* tp_as_mapping */
1747 0, /* tp_hash */
1748 0, /* tp_call */
1749 0, /* tp_str */
1750 PyObject_GenericGetAttr, /* tp_getattro */
1751 0, /* tp_setattro */
1752 0, /* tp_as_buffer */
1753 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
1754 | Py_TPFLAGS_BASETYPE, /* tp_flags */
1755 0, /* tp_doc */
1756 (traverseproc)mbstreamwriter_traverse, /* tp_traverse */
1757 0, /* tp_clear */
1758 0, /* tp_richcompare */
1759 0, /* tp_weaklistoffset */
1760 0, /* tp_iter */
1761 0, /* tp_iterext */
1762 mbstreamwriter_methods, /* tp_methods */
1763 mbstreamwriter_members, /* tp_members */
1764 codecctx_getsets, /* tp_getset */
1765 0, /* tp_base */
1766 0, /* tp_dict */
1767 0, /* tp_descr_get */
1768 0, /* tp_descr_set */
1769 0, /* tp_dictoffset */
1770 mbstreamwriter_init, /* tp_init */
1771 0, /* tp_alloc */
1772 mbstreamwriter_new, /* tp_new */
1773 };
1774
1775
1776 /**
1777 * Exposed factory function
1778 */
1779
1780 static PyObject *
1781 __create_codec(PyObject *ignore, PyObject *arg)
1782 {
1783 MultibyteCodecObject *self;
1784 MultibyteCodec *codec;
1785
1786 if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) {
1787 PyErr_SetString(PyExc_ValueError, "argument type invalid");
1788 return NULL;
1789 }
1790
1791 codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME);
1792 if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0)
1793 return NULL;
1794
1795 self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type);
1796 if (self == NULL)
1797 return NULL;
1798 self->codec = codec;
1799
1800 return (PyObject *)self;
1801 }
1802
1803 static struct PyMethodDef __methods[] = {
1804 {"__create_codec", (PyCFunction)__create_codec, METH_O},
1805 {NULL, NULL},
1806 };
1807
1808 PyMODINIT_FUNC
1809 init_multibytecodec(void)
1810 {
1811 int i;
1812 PyObject *m;
1813 PyTypeObject *typelist[] = {
1814 &MultibyteIncrementalEncoder_Type,
1815 &MultibyteIncrementalDecoder_Type,
1816 &MultibyteStreamReader_Type,
1817 &MultibyteStreamWriter_Type,
1818 NULL
1819 };
1820
1821 if (PyType_Ready(&MultibyteCodec_Type) < 0)
1822 return;
1823
1824 m = Py_InitModule("_multibytecodec", __methods);
1825 if (m == NULL)
1826 return;
1827
1828 for (i = 0; typelist[i] != NULL; i++) {
1829 if (PyType_Ready(typelist[i]) < 0)
1830 return;
1831 Py_INCREF(typelist[i]);
1832 PyModule_AddObject(m, typelist[i]->tp_name,
1833 (PyObject *)typelist[i]);
1834 }
1835
1836 if (PyErr_Occurred())
1837 Py_FatalError("can't initialize the _multibytecodec module");
1838 }