blob: 3aa1f386e7be9aebc948ac4e20ef3b8f8c6ca6b2 [file] [log] [blame]
Guido van Rossumfeee4b92000-03-10 22:57:27 +00001/* ------------------------------------------------------------------------
2
3 Python Codec Registry and support functions
4
5Written by Marc-Andre Lemburg (mal@lemburg.com).
6
Guido van Rossum16b1ad92000-08-03 16:24:25 +00007Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumfeee4b92000-03-10 22:57:27 +00008
9 ------------------------------------------------------------------------ */
10
11#include "Python.h"
12#include <ctype.h>
13
Guido van Rossumfeee4b92000-03-10 22:57:27 +000014/* --- Codec Registry ----------------------------------------------------- */
15
16/* Import the standard encodings package which will register the first
17 codec search function.
18
19 This is done in a lazy way so that the Unicode implementation does
20 not downgrade startup time of scripts not needing it.
21
Guido van Rossumb95de4f2000-03-31 17:25:23 +000022 ImportErrors are silently ignored by this function. Only one try is
23 made.
Guido van Rossumfeee4b92000-03-10 22:57:27 +000024
25*/
26
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000027static int _PyCodecRegistry_Init(void); /* Forward */
Guido van Rossumfeee4b92000-03-10 22:57:27 +000028
Guido van Rossumfeee4b92000-03-10 22:57:27 +000029int PyCodec_Register(PyObject *search_function)
30{
Nicholas Bastine5662ae2004-03-24 22:22:12 +000031 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000032 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
33 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000034 if (search_function == NULL) {
35 PyErr_BadArgument();
Guido van Rossumb95de4f2000-03-31 17:25:23 +000036 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000037 }
38 if (!PyCallable_Check(search_function)) {
Neal Norwitz3715c3e2005-11-24 22:09:18 +000039 PyErr_SetString(PyExc_TypeError, "argument must be callable");
Guido van Rossumb95de4f2000-03-31 17:25:23 +000040 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000041 }
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000042 return PyList_Append(interp->codec_search_path, search_function);
Guido van Rossumb95de4f2000-03-31 17:25:23 +000043
44 onError:
45 return -1;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000046}
47
Guido van Rossum9e896b32000-04-05 20:11:21 +000048/* Convert a string to a normalized Python string: all characters are
49 converted to lower case, spaces are replaced with underscores. */
50
Guido van Rossumfeee4b92000-03-10 22:57:27 +000051static
Guido van Rossum9e896b32000-04-05 20:11:21 +000052PyObject *normalizestring(const char *string)
Guido van Rossumfeee4b92000-03-10 22:57:27 +000053{
Guido van Rossum33831132000-06-29 14:50:15 +000054 register size_t i;
Guido van Rossum582acec2000-06-28 22:07:35 +000055 size_t len = strlen(string);
Guido van Rossumfeee4b92000-03-10 22:57:27 +000056 char *p;
57 PyObject *v;
58
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059 if (len > PY_SSIZE_T_MAX) {
60 PyErr_SetString(PyExc_OverflowError, "string is too large");
61 return NULL;
62 }
Guido van Rossum582acec2000-06-28 22:07:35 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064 v = PyString_FromStringAndSize(NULL, len);
Guido van Rossumfeee4b92000-03-10 22:57:27 +000065 if (v == NULL)
66 return NULL;
67 p = PyString_AS_STRING(v);
Guido van Rossum9e896b32000-04-05 20:11:21 +000068 for (i = 0; i < len; i++) {
69 register char ch = string[i];
70 if (ch == ' ')
71 ch = '-';
72 else
Thomas Wouters477c8d52006-05-27 19:21:47 +000073 ch = tolower(Py_CHARMASK(ch));
Guido van Rossum9e896b32000-04-05 20:11:21 +000074 p[i] = ch;
75 }
Guido van Rossumfeee4b92000-03-10 22:57:27 +000076 return v;
77}
78
79/* Lookup the given encoding and return a tuple providing the codec
80 facilities.
81
82 The encoding string is looked up converted to all lower-case
83 characters. This makes encodings looked up through this mechanism
84 effectively case-insensitive.
85
Fred Drake766de832000-05-09 19:55:59 +000086 If no codec is found, a LookupError is set and NULL returned.
Guido van Rossumb95de4f2000-03-31 17:25:23 +000087
88 As side effect, this tries to load the encodings package, if not
89 yet done. This is part of the lazy load strategy for the encodings
90 package.
91
92*/
Guido van Rossumfeee4b92000-03-10 22:57:27 +000093
94PyObject *_PyCodec_Lookup(const char *encoding)
95{
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000096 PyInterpreterState *interp;
Guido van Rossum5ba3c842000-03-24 20:52:23 +000097 PyObject *result, *args = NULL, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +000098 Py_ssize_t i, len;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000099
Fred Drake766de832000-05-09 19:55:59 +0000100 if (encoding == NULL) {
101 PyErr_BadArgument();
102 goto onError;
103 }
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000104
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000105 interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000106 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
Barry Warsaw51ac5802000-03-20 16:36:48 +0000107 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000108
Guido van Rossum9e896b32000-04-05 20:11:21 +0000109 /* Convert the encoding to a normalized Python string: all
Thomas Wouters7e474022000-07-16 12:04:32 +0000110 characters are converted to lower case, spaces and hyphens are
Guido van Rossum9e896b32000-04-05 20:11:21 +0000111 replaced with underscores. */
112 v = normalizestring(encoding);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000113 if (v == NULL)
114 goto onError;
115 PyString_InternInPlace(&v);
116
117 /* First, try to lookup the name in the registry dictionary */
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000118 result = PyDict_GetItem(interp->codec_search_cache, v);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000119 if (result != NULL) {
120 Py_INCREF(result);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000121 Py_DECREF(v);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000122 return result;
123 }
124
125 /* Next, scan the search functions in order of registration */
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000126 args = PyTuple_New(1);
127 if (args == NULL)
128 goto onError;
129 PyTuple_SET_ITEM(args,0,v);
Guido van Rossum5ba3c842000-03-24 20:52:23 +0000130
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000131 len = PyList_Size(interp->codec_search_path);
Guido van Rossum5ba3c842000-03-24 20:52:23 +0000132 if (len < 0)
133 goto onError;
Guido van Rossumb95de4f2000-03-31 17:25:23 +0000134 if (len == 0) {
135 PyErr_SetString(PyExc_LookupError,
136 "no codec search functions registered: "
137 "can't find encoding");
138 goto onError;
139 }
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000140
141 for (i = 0; i < len; i++) {
142 PyObject *func;
143
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000144 func = PyList_GetItem(interp->codec_search_path, i);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000145 if (func == NULL)
146 goto onError;
Guido van Rossum5ba3c842000-03-24 20:52:23 +0000147 result = PyEval_CallObject(func, args);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000148 if (result == NULL)
149 goto onError;
150 if (result == Py_None) {
151 Py_DECREF(result);
152 continue;
153 }
154 if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
155 PyErr_SetString(PyExc_TypeError,
156 "codec search functions must return 4-tuples");
157 Py_DECREF(result);
158 goto onError;
159 }
160 break;
161 }
162 if (i == len) {
163 /* XXX Perhaps we should cache misses too ? */
Martin v. Löwiseb42b022002-09-26 16:01:24 +0000164 PyErr_Format(PyExc_LookupError,
165 "unknown encoding: %s", encoding);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000166 goto onError;
167 }
168
169 /* Cache and return the result */
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000170 PyDict_SetItem(interp->codec_search_cache, v, result);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000171 Py_DECREF(args);
172 return result;
173
174 onError:
175 Py_XDECREF(args);
176 return NULL;
177}
178
179static
180PyObject *args_tuple(PyObject *object,
181 const char *errors)
182{
183 PyObject *args;
184
185 args = PyTuple_New(1 + (errors != NULL));
186 if (args == NULL)
187 return NULL;
188 Py_INCREF(object);
189 PyTuple_SET_ITEM(args,0,object);
190 if (errors) {
191 PyObject *v;
192
193 v = PyString_FromString(errors);
194 if (v == NULL) {
195 Py_DECREF(args);
196 return NULL;
197 }
198 PyTuple_SET_ITEM(args, 1, v);
199 }
200 return args;
201}
202
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000203/* Helper function to get a codec item */
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000204
205static
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206PyObject *codec_getitem(const char *encoding, int index)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000207{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000208 PyObject *codecs;
209 PyObject *v;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000210
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211 codecs = _PyCodec_Lookup(encoding);
212 if (codecs == NULL)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000213 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000214 v = PyTuple_GET_ITEM(codecs, index);
215 Py_DECREF(codecs);
216 Py_INCREF(v);
217 return v;
218}
219
220/* Helper function to create an incremental codec. */
221
222static
223PyObject *codec_getincrementalcodec(const char *encoding,
224 const char *errors,
225 const char *attrname)
226{
227 PyObject *codecs, *ret, *inccodec;
228
229 codecs = _PyCodec_Lookup(encoding);
230 if (codecs == NULL)
231 return NULL;
232 inccodec = PyObject_GetAttrString(codecs, attrname);
233 Py_DECREF(codecs);
234 if (inccodec == NULL)
235 return NULL;
236 if (errors)
237 ret = PyObject_CallFunction(inccodec, "s", errors);
238 else
239 ret = PyObject_CallFunction(inccodec, NULL);
240 Py_DECREF(inccodec);
241 return ret;
242}
243
244/* Helper function to create a stream codec. */
245
246static
247PyObject *codec_getstreamcodec(const char *encoding,
248 PyObject *stream,
249 const char *errors,
250 const int index)
251{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252 PyObject *codecs, *streamcodec, *codeccls;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000253
254 codecs = _PyCodec_Lookup(encoding);
255 if (codecs == NULL)
256 return NULL;
257
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000258 codeccls = PyTuple_GET_ITEM(codecs, index);
259 if (errors != NULL)
260 streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors);
261 else
262 streamcodec = PyObject_CallFunction(codeccls, "O", stream);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000263 Py_DECREF(codecs);
264 return streamcodec;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000265}
266
267/* Convenience APIs to query the Codec registry.
268
269 All APIs return a codec object with incremented refcount.
270
271 */
272
273PyObject *PyCodec_Encoder(const char *encoding)
274{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000275 return codec_getitem(encoding, 0);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000276}
277
278PyObject *PyCodec_Decoder(const char *encoding)
279{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000280 return codec_getitem(encoding, 1);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000281}
282
Thomas Woutersa9773292006-04-21 09:43:23 +0000283PyObject *PyCodec_IncrementalEncoder(const char *encoding,
284 const char *errors)
285{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 return codec_getincrementalcodec(encoding, errors, "incrementalencoder");
Thomas Woutersa9773292006-04-21 09:43:23 +0000287}
288
289PyObject *PyCodec_IncrementalDecoder(const char *encoding,
290 const char *errors)
291{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292 return codec_getincrementalcodec(encoding, errors, "incrementaldecoder");
Thomas Woutersa9773292006-04-21 09:43:23 +0000293}
294
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000295PyObject *PyCodec_StreamReader(const char *encoding,
296 PyObject *stream,
297 const char *errors)
298{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000299 return codec_getstreamcodec(encoding, stream, errors, 2);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000300}
301
302PyObject *PyCodec_StreamWriter(const char *encoding,
303 PyObject *stream,
304 const char *errors)
305{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306 return codec_getstreamcodec(encoding, stream, errors, 3);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000307}
308
309/* Encode an object (e.g. an Unicode object) using the given encoding
310 and return the resulting encoded object (usually a Python string).
311
312 errors is passed to the encoder factory as argument if non-NULL. */
313
314PyObject *PyCodec_Encode(PyObject *object,
315 const char *encoding,
316 const char *errors)
317{
318 PyObject *encoder = NULL;
Neal Norwitz3715c3e2005-11-24 22:09:18 +0000319 PyObject *args = NULL, *result = NULL;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000320 PyObject *v;
321
322 encoder = PyCodec_Encoder(encoding);
323 if (encoder == NULL)
324 goto onError;
325
326 args = args_tuple(object, errors);
327 if (args == NULL)
328 goto onError;
329
330 result = PyEval_CallObject(encoder,args);
331 if (result == NULL)
332 goto onError;
333
334 if (!PyTuple_Check(result) ||
335 PyTuple_GET_SIZE(result) != 2) {
336 PyErr_SetString(PyExc_TypeError,
337 "encoder must return a tuple (object,integer)");
338 goto onError;
339 }
340 v = PyTuple_GET_ITEM(result,0);
341 Py_INCREF(v);
342 /* We don't check or use the second (integer) entry. */
343
344 Py_DECREF(args);
345 Py_DECREF(encoder);
346 Py_DECREF(result);
347 return v;
348
349 onError:
Neal Norwitz3715c3e2005-11-24 22:09:18 +0000350 Py_XDECREF(result);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000351 Py_XDECREF(args);
352 Py_XDECREF(encoder);
353 return NULL;
354}
355
356/* Decode an object (usually a Python string) using the given encoding
357 and return an equivalent object (e.g. an Unicode object).
358
359 errors is passed to the decoder factory as argument if non-NULL. */
360
361PyObject *PyCodec_Decode(PyObject *object,
362 const char *encoding,
363 const char *errors)
364{
365 PyObject *decoder = NULL;
366 PyObject *args = NULL, *result = NULL;
367 PyObject *v;
368
369 decoder = PyCodec_Decoder(encoding);
370 if (decoder == NULL)
371 goto onError;
372
373 args = args_tuple(object, errors);
374 if (args == NULL)
375 goto onError;
376
377 result = PyEval_CallObject(decoder,args);
378 if (result == NULL)
379 goto onError;
380 if (!PyTuple_Check(result) ||
381 PyTuple_GET_SIZE(result) != 2) {
382 PyErr_SetString(PyExc_TypeError,
383 "decoder must return a tuple (object,integer)");
384 goto onError;
385 }
386 v = PyTuple_GET_ITEM(result,0);
387 Py_INCREF(v);
388 /* We don't check or use the second (integer) entry. */
389
390 Py_DECREF(args);
391 Py_DECREF(decoder);
392 Py_DECREF(result);
393 return v;
394
395 onError:
396 Py_XDECREF(args);
397 Py_XDECREF(decoder);
398 Py_XDECREF(result);
399 return NULL;
400}
401
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000402/* Register the error handling callback function error under the name
403 name. This function will be called by the codec when it encounters
404 an unencodable characters/undecodable bytes and doesn't know the
405 callback name, when name is specified as the error parameter
406 in the call to the encode/decode function.
407 Return 0 on success, -1 on error */
408int PyCodec_RegisterError(const char *name, PyObject *error)
409{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000410 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000411 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
412 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000413 if (!PyCallable_Check(error)) {
414 PyErr_SetString(PyExc_TypeError, "handler must be callable");
415 return -1;
416 }
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000417 return PyDict_SetItemString(interp->codec_error_registry,
418 (char *)name, error);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000419}
420
421/* Lookup the error handling callback function registered under the
422 name error. As a special case NULL can be passed, in which case
423 the error handling callback for strict encoding will be returned. */
424PyObject *PyCodec_LookupError(const char *name)
425{
426 PyObject *handler = NULL;
427
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000428 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000429 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
430 return NULL;
431
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000432 if (name==NULL)
433 name = "strict";
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000434 handler = PyDict_GetItemString(interp->codec_error_registry, (char *)name);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000435 if (!handler)
436 PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name);
437 else
438 Py_INCREF(handler);
439 return handler;
440}
441
442static void wrong_exception_type(PyObject *exc)
443{
444 PyObject *type = PyObject_GetAttrString(exc, "__class__");
445 if (type != NULL) {
Walter Dörwald573c08c2007-05-25 15:46:59 +0000446 PyObject *name = PyObject_GetAttrString(type, "__name__");
447 Py_DECREF(type);
448 if (name != NULL) {
449 PyErr_Format(PyExc_TypeError,
450 "don't know how to handle %S in error callback", name);
451 Py_DECREF(name);
452 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000453 }
454}
455
456PyObject *PyCodec_StrictErrors(PyObject *exc)
457{
Brett Cannonbf364092006-03-01 04:25:17 +0000458 if (PyExceptionInstance_Check(exc))
459 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000460 else
461 PyErr_SetString(PyExc_TypeError, "codec must pass exception instance");
462 return NULL;
463}
464
465
466PyObject *PyCodec_IgnoreErrors(PyObject *exc)
467{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468 Py_ssize_t end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000469 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
470 if (PyUnicodeEncodeError_GetEnd(exc, &end))
471 return NULL;
472 }
473 else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
474 if (PyUnicodeDecodeError_GetEnd(exc, &end))
475 return NULL;
476 }
477 else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
478 if (PyUnicodeTranslateError_GetEnd(exc, &end))
479 return NULL;
480 }
481 else {
482 wrong_exception_type(exc);
483 return NULL;
484 }
485 /* ouch: passing NULL, 0, pos gives None instead of u'' */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000486 return Py_BuildValue("(u#n)", &end, 0, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000487}
488
489
490PyObject *PyCodec_ReplaceErrors(PyObject *exc)
491{
492 PyObject *restuple;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000493 Py_ssize_t start;
494 Py_ssize_t end;
495 Py_ssize_t i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000496
497 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
498 PyObject *res;
499 Py_UNICODE *p;
500 if (PyUnicodeEncodeError_GetStart(exc, &start))
501 return NULL;
502 if (PyUnicodeEncodeError_GetEnd(exc, &end))
503 return NULL;
504 res = PyUnicode_FromUnicode(NULL, end-start);
505 if (res == NULL)
506 return NULL;
507 for (p = PyUnicode_AS_UNICODE(res), i = start;
508 i<end; ++p, ++i)
509 *p = '?';
Martin v. Löwis18e16552006-02-15 17:27:45 +0000510 restuple = Py_BuildValue("(On)", res, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000511 Py_DECREF(res);
512 return restuple;
513 }
514 else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
515 Py_UNICODE res = Py_UNICODE_REPLACEMENT_CHARACTER;
516 if (PyUnicodeDecodeError_GetEnd(exc, &end))
517 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000518 return Py_BuildValue("(u#n)", &res, 1, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000519 }
520 else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
521 PyObject *res;
522 Py_UNICODE *p;
523 if (PyUnicodeTranslateError_GetStart(exc, &start))
524 return NULL;
525 if (PyUnicodeTranslateError_GetEnd(exc, &end))
526 return NULL;
527 res = PyUnicode_FromUnicode(NULL, end-start);
528 if (res == NULL)
529 return NULL;
530 for (p = PyUnicode_AS_UNICODE(res), i = start;
531 i<end; ++p, ++i)
532 *p = Py_UNICODE_REPLACEMENT_CHARACTER;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000533 restuple = Py_BuildValue("(On)", res, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000534 Py_DECREF(res);
535 return restuple;
536 }
537 else {
538 wrong_exception_type(exc);
539 return NULL;
540 }
541}
542
543PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
544{
545 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
546 PyObject *restuple;
547 PyObject *object;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000548 Py_ssize_t start;
549 Py_ssize_t end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000550 PyObject *res;
551 Py_UNICODE *p;
552 Py_UNICODE *startp;
553 Py_UNICODE *outp;
554 int ressize;
555 if (PyUnicodeEncodeError_GetStart(exc, &start))
556 return NULL;
557 if (PyUnicodeEncodeError_GetEnd(exc, &end))
558 return NULL;
559 if (!(object = PyUnicodeEncodeError_GetObject(exc)))
560 return NULL;
561 startp = PyUnicode_AS_UNICODE(object);
562 for (p = startp+start, ressize = 0; p < startp+end; ++p) {
563 if (*p<10)
564 ressize += 2+1+1;
565 else if (*p<100)
566 ressize += 2+2+1;
567 else if (*p<1000)
568 ressize += 2+3+1;
569 else if (*p<10000)
570 ressize += 2+4+1;
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000571#ifndef Py_UNICODE_WIDE
572 else
573 ressize += 2+5+1;
574#else
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000575 else if (*p<100000)
576 ressize += 2+5+1;
577 else if (*p<1000000)
578 ressize += 2+6+1;
579 else
580 ressize += 2+7+1;
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000581#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000582 }
583 /* allocate replacement */
584 res = PyUnicode_FromUnicode(NULL, ressize);
585 if (res == NULL) {
586 Py_DECREF(object);
587 return NULL;
588 }
589 /* generate replacement */
590 for (p = startp+start, outp = PyUnicode_AS_UNICODE(res);
591 p < startp+end; ++p) {
592 Py_UNICODE c = *p;
593 int digits;
594 int base;
595 *outp++ = '&';
596 *outp++ = '#';
597 if (*p<10) {
598 digits = 1;
599 base = 1;
600 }
601 else if (*p<100) {
602 digits = 2;
603 base = 10;
604 }
605 else if (*p<1000) {
606 digits = 3;
607 base = 100;
608 }
609 else if (*p<10000) {
610 digits = 4;
611 base = 1000;
612 }
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000613#ifndef Py_UNICODE_WIDE
614 else {
615 digits = 5;
616 base = 10000;
617 }
618#else
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000619 else if (*p<100000) {
620 digits = 5;
621 base = 10000;
622 }
623 else if (*p<1000000) {
624 digits = 6;
625 base = 100000;
626 }
627 else {
628 digits = 7;
629 base = 1000000;
630 }
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000631#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000632 while (digits-->0) {
633 *outp++ = '0' + c/base;
634 c %= base;
635 base /= 10;
636 }
637 *outp++ = ';';
638 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000639 restuple = Py_BuildValue("(On)", res, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000640 Py_DECREF(res);
641 Py_DECREF(object);
642 return restuple;
643 }
644 else {
645 wrong_exception_type(exc);
646 return NULL;
647 }
648}
649
650static Py_UNICODE hexdigits[] = {
651 '0', '1', '2', '3', '4', '5', '6', '7',
652 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
653};
654
655PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
656{
657 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
658 PyObject *restuple;
659 PyObject *object;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000660 Py_ssize_t start;
661 Py_ssize_t end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000662 PyObject *res;
663 Py_UNICODE *p;
664 Py_UNICODE *startp;
665 Py_UNICODE *outp;
666 int ressize;
667 if (PyUnicodeEncodeError_GetStart(exc, &start))
668 return NULL;
669 if (PyUnicodeEncodeError_GetEnd(exc, &end))
670 return NULL;
671 if (!(object = PyUnicodeEncodeError_GetObject(exc)))
672 return NULL;
673 startp = PyUnicode_AS_UNICODE(object);
674 for (p = startp+start, ressize = 0; p < startp+end; ++p) {
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000675#ifdef Py_UNICODE_WIDE
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000676 if (*p >= 0x00010000)
677 ressize += 1+1+8;
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000678 else
679#endif
680 if (*p >= 0x100) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000681 ressize += 1+1+4;
682 }
683 else
684 ressize += 1+1+2;
685 }
686 res = PyUnicode_FromUnicode(NULL, ressize);
687 if (res==NULL)
688 return NULL;
689 for (p = startp+start, outp = PyUnicode_AS_UNICODE(res);
690 p < startp+end; ++p) {
691 Py_UNICODE c = *p;
692 *outp++ = '\\';
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000693#ifdef Py_UNICODE_WIDE
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000694 if (c >= 0x00010000) {
695 *outp++ = 'U';
696 *outp++ = hexdigits[(c>>28)&0xf];
697 *outp++ = hexdigits[(c>>24)&0xf];
698 *outp++ = hexdigits[(c>>20)&0xf];
699 *outp++ = hexdigits[(c>>16)&0xf];
700 *outp++ = hexdigits[(c>>12)&0xf];
701 *outp++ = hexdigits[(c>>8)&0xf];
702 }
Hye-Shik Chang7db07e62003-12-29 01:36:01 +0000703 else
704#endif
705 if (c >= 0x100) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000706 *outp++ = 'u';
707 *outp++ = hexdigits[(c>>12)&0xf];
708 *outp++ = hexdigits[(c>>8)&0xf];
709 }
710 else
711 *outp++ = 'x';
712 *outp++ = hexdigits[(c>>4)&0xf];
713 *outp++ = hexdigits[c&0xf];
714 }
715
Martin v. Löwis18e16552006-02-15 17:27:45 +0000716 restuple = Py_BuildValue("(On)", res, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000717 Py_DECREF(res);
718 Py_DECREF(object);
719 return restuple;
720 }
721 else {
722 wrong_exception_type(exc);
723 return NULL;
724 }
725}
726
727static PyObject *strict_errors(PyObject *self, PyObject *exc)
728{
729 return PyCodec_StrictErrors(exc);
730}
731
732
733static PyObject *ignore_errors(PyObject *self, PyObject *exc)
734{
735 return PyCodec_IgnoreErrors(exc);
736}
737
738
739static PyObject *replace_errors(PyObject *self, PyObject *exc)
740{
741 return PyCodec_ReplaceErrors(exc);
742}
743
744
745static PyObject *xmlcharrefreplace_errors(PyObject *self, PyObject *exc)
746{
747 return PyCodec_XMLCharRefReplaceErrors(exc);
748}
749
750
751static PyObject *backslashreplace_errors(PyObject *self, PyObject *exc)
752{
753 return PyCodec_BackslashReplaceErrors(exc);
754}
755
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000756static int _PyCodecRegistry_Init(void)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000757{
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000758 static struct {
759 char *name;
760 PyMethodDef def;
761 } methods[] =
762 {
763 {
764 "strict",
765 {
766 "strict_errors",
767 strict_errors,
768 METH_O
769 }
770 },
771 {
772 "ignore",
773 {
774 "ignore_errors",
775 ignore_errors,
776 METH_O
777 }
778 },
779 {
780 "replace",
781 {
782 "replace_errors",
783 replace_errors,
784 METH_O
785 }
786 },
787 {
788 "xmlcharrefreplace",
789 {
790 "xmlcharrefreplace_errors",
791 xmlcharrefreplace_errors,
792 METH_O
793 }
794 },
795 {
796 "backslashreplace",
797 {
798 "backslashreplace_errors",
799 backslashreplace_errors,
800 METH_O
801 }
802 }
803 };
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000804
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000805 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000806 PyObject *mod;
Neal Norwitz739a8f82004-07-08 01:55:58 +0000807 unsigned i;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000808
809 if (interp->codec_search_path != NULL)
810 return 0;
811
812 interp->codec_search_path = PyList_New(0);
813 interp->codec_search_cache = PyDict_New();
814 interp->codec_error_registry = PyDict_New();
815
816 if (interp->codec_error_registry) {
817 for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) {
818 PyObject *func = PyCFunction_New(&methods[i].def, NULL);
819 int res;
820 if (!func)
821 Py_FatalError("can't initialize codec error registry");
822 res = PyCodec_RegisterError(methods[i].name, func);
823 Py_DECREF(func);
824 if (res)
825 Py_FatalError("can't initialize codec error registry");
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000826 }
827 }
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000828
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000829 if (interp->codec_search_path == NULL ||
830 interp->codec_search_cache == NULL ||
831 interp->codec_error_registry == NULL)
832 Py_FatalError("can't initialize codec registry");
833
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000834 mod = PyImport_ImportModuleLevel("encodings", NULL, NULL, NULL, 0);
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000835 if (mod == NULL) {
836 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
837 /* Ignore ImportErrors... this is done so that
838 distributions can disable the encodings package. Note
839 that other errors are not masked, e.g. SystemErrors
840 raised to inform the user of an error in the Python
841 configuration are still reported back to the user. */
842 PyErr_Clear();
843 return 0;
844 }
845 return -1;
846 }
847 Py_DECREF(mod);
848 return 0;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000849}