GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cpython/Python/codecs.c at main · python/cpython Expand file tree/ Copy pathcodecs.cMore file actions 1709 lines (1485 loc) · 48.3 KB / Copy pathcodecs.cFile metadata and controls1709 lines (1485 loc) · 48.3 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /* ------------------------------------------------------------------------ Python Codec Registry and support functions Written by Marc-Andre Lemburg ([email protected]). Copyright (c) Corporation for National Research Initiatives. ------------------------------------------------------------------------ */ #include "Python.h" #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_codecs.h" // export _PyCodec_LookupTextEncoding() #include "pycore_initconfig.h" // _Py_DumpPathConfig() #include "pycore_interp.h" // PyInterpreterState.codec_search_path #include "pycore_pyerrors.h" // _PyErr_FormatNote() #include "pycore_pystate.h" // _PyInterpreterState_GET() #include "pycore_runtime.h" // _Py_ID() #include "pycore_ucnhash.h" // _PyUnicode_Name_CAPI #include "pycore_unicodeobject.h" // _PyUnicode_InternMortal() #include "pycore_pyatomic_ft_wrappers.h" static const char *codecs_builtin_error_handlers[] = { "strict", "ignore", "replace", "xmlcharrefreplace", "backslashreplace", "namereplace", "surrogatepass", "surrogateescape", }; const char *Py_hexdigits = "0123456789abcdef"; /* --- Codec Registry ----------------------------------------------------- */ int PyCodec_Register(PyObject *search_function) { PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->codecs.initialized); if (search_function == NULL) { PyErr_BadArgument(); goto onError; } if (!PyCallable_Check(search_function)) { PyErr_SetString(PyExc_TypeError, "argument must be callable"); goto onError; } FT_MUTEX_LOCK(&interp->codecs.search_path_mutex); int ret = PyList_Append(interp->codecs.search_path, search_function); FT_MUTEX_UNLOCK(&interp->codecs.search_path_mutex); return ret; onError: return -1; } int PyCodec_Unregister(PyObject *search_function) { PyInterpreterState *interp = _PyInterpreterState_GET(); if (interp->codecs.initialized != 1) { /* Do nothing if codecs state was cleared (only possible during interpreter shutdown). */ return 0; } PyObject *codec_search_path = interp->codecs.search_path; assert(PyList_CheckExact(codec_search_path)); FT_MUTEX_LOCK(&interp->codecs.search_path_mutex); for (Py_ssize_t i = 0; i < PyList_GET_SIZE(codec_search_path); i++) { if (PyList_GET_ITEM(codec_search_path, i) == search_function) { // Keep the function alive until after releasing the mutex. Py_INCREF(search_function); int ret = PyList_SetSlice(codec_search_path, i, i+1, NULL); FT_MUTEX_UNLOCK(&interp->codecs.search_path_mutex); Py_DECREF(search_function); assert(interp->codecs.search_cache != NULL); assert(PyDict_CheckExact(interp->codecs.search_cache)); PyDict_Clear(interp->codecs.search_cache); return ret; } } FT_MUTEX_UNLOCK(&interp->codecs.search_path_mutex); return 0; } /* Convert a string to a normalized Python string: all ASCII letters are converted to lower case, spaces are replaced with hyphens. */ static PyObject* normalizestring(const char *string) { size_t i; size_t len = strlen(string); char *p; PyObject *v; if (len > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "string is too large"); return NULL; } p = PyMem_Malloc(len + 1); if (p == NULL) return PyErr_NoMemory(); for (i = 0; i < len; i++) { char ch = string[i]; if (ch == ' ') ch = '-'; else ch = Py_TOLOWER(Py_CHARMASK(ch)); p[i] = ch; } p[i] = '\0'; v = PyUnicode_FromString(p); PyMem_Free(p); return v; } /* Lookup the given encoding and return a tuple providing the codec facilities. ASCII letters in the encoding string is looked up converted to all lower case. This makes encodings looked up through this mechanism effectively case-insensitive. Spaces are replaced with hyphens for names like "US ASCII" and "ISO 8859-1". If no codec is found, a LookupError is set and NULL returned. As side effect, this tries to load the encodings package, if not yet done. This is part of the lazy load strategy for the encodings package. */ PyObject *_PyCodec_Lookup(const char *encoding) { if (encoding == NULL) { PyErr_BadArgument(); return NULL; } PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->codecs.initialized); /* Convert the encoding to a normalized Python string: all ASCII letters are converted to lower case, spaces are replaced with hyphens. */ PyObject *v = normalizestring(encoding); if (v == NULL) { return NULL; } /* Intern the string. We'll make it immortal later if lookup succeeds. */ _PyUnicode_InternMortal(interp, &v); /* First, try to lookup the name in the registry dictionary */ PyObject *result; if (PyDict_GetItemRef(interp->codecs.search_cache, v, &result) < 0) { goto onError; } if (result != NULL) { Py_DECREF(v); return result; } /* Next, scan the search functions in order of registration */ const Py_ssize_t len = PyList_Size(interp->codecs.search_path); if (len < 0) goto onError; if (len == 0) { PyErr_SetString(PyExc_LookupError, "no codec search functions registered: " "can't find encoding"); goto onError; } Py_ssize_t i; for (i = 0; i < len; i++) { PyObject *func; func = PyList_GetItemRef(interp->codecs.search_path, i); if (func == NULL) goto onError; result = PyObject_CallOneArg(func, v); Py_DECREF(func); if (result == NULL) goto onError; if (result == Py_None) { Py_CLEAR(result); continue; } if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { PyErr_SetString(PyExc_TypeError, "codec search functions must return 4-tuples"); Py_DECREF(result); goto onError; } break; } if (result == NULL) { /* XXX Perhaps we should cache misses too ? */ PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding); goto onError; } _PyUnicode_InternImmortal(interp, &v); /* Cache and return the result */ if (PyDict_SetItem(interp->codecs.search_cache, v, result) < 0) { Py_DECREF(result); goto onError; } Py_DECREF(v); return result; onError: Py_DECREF(v); return NULL; } /* Codec registry encoding check API. */ int PyCodec_KnownEncoding(const char *encoding) { PyObject *codecs; codecs = _PyCodec_Lookup(encoding); if (!codecs) { PyErr_Clear(); return 0; } else { Py_DECREF(codecs); return 1; } } static PyObject *args_tuple(PyObject *object, const char *errors) { PyObject *args; args = PyTuple_New(1 + (errors != NULL)); if (args == NULL) return NULL; PyTuple_SET_ITEM(args, 0, Py_NewRef(object)); if (errors) { PyObject *v; v = PyUnicode_FromString(errors); if (v == NULL) { Py_DECREF(args); return NULL; } PyTuple_SET_ITEM(args, 1, v); } return args; } /* Helper function to get a codec item */ static PyObject *codec_getitem(const char *encoding, int index) { PyObject *codecs; PyObject *v; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) return NULL; v = Py_NewRef(PyTuple_GET_ITEM(codecs, index)); Py_DECREF(codecs); return v; } /* Helper functions to create an incremental codec. */ static PyObject *codec_makeincrementalcodec(PyObject *codec_info, const char *errors, const char *attrname) { PyObject *ret, *inccodec; inccodec = PyObject_GetAttrString(codec_info, attrname); if (inccodec == NULL) return NULL; if (errors) ret = PyObject_CallFunction(inccodec, "s", errors); else ret = _PyObject_CallNoArgs(inccodec); Py_DECREF(inccodec); return ret; } static PyObject *codec_getincrementalcodec(const char *encoding, const char *errors, const char *attrname) { PyObject *codec_info, *ret; codec_info = _PyCodec_Lookup(encoding); if (codec_info == NULL) return NULL; ret = codec_makeincrementalcodec(codec_info, errors, attrname); Py_DECREF(codec_info); return ret; } /* Helper function to create a stream codec. */ static PyObject *codec_getstreamcodec(const char *encoding, PyObject *stream, const char *errors, const int index) { PyObject *codecs, *streamcodec, *codeccls; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) return NULL; codeccls = PyTuple_GET_ITEM(codecs, index); if (errors != NULL) streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); else streamcodec = PyObject_CallOneArg(codeccls, stream); Py_DECREF(codecs); return streamcodec; } /* Helpers to work with the result of _PyCodec_Lookup */ PyObject *_PyCodecInfo_GetIncrementalDecoder(PyObject *codec_info, const char *errors) { return codec_makeincrementalcodec(codec_info, errors, "incrementaldecoder"); } PyObject *_PyCodecInfo_GetIncrementalEncoder(PyObject *codec_info, const char *errors) { return codec_makeincrementalcodec(codec_info, errors, "incrementalencoder"); } /* Convenience APIs to query the Codec registry. All APIs return a codec object with incremented refcount. */ PyObject *PyCodec_Encoder(const char *encoding) { return codec_getitem(encoding, 0); } PyObject *PyCodec_Decoder(const char *encoding) { return codec_getitem(encoding, 1); } PyObject *PyCodec_IncrementalEncoder(const char *encoding, const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementalencoder"); } PyObject *PyCodec_IncrementalDecoder(const char *encoding, const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementaldecoder"); } PyObject *PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 2); } PyObject *PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 3); } /* Encode an object (e.g. a Unicode object) using the given encoding and return the resulting encoded object (usually a Python string). errors is passed to the encoder factory as argument if non-NULL. */ static PyObject * _PyCodec_EncodeInternal(PyObject *object, PyObject *encoder, const char *encoding, const char *errors) { PyObject *args = NULL, *result = NULL; PyObject *v = NULL; args = args_tuple(object, errors); if (args == NULL) goto onError; result = PyObject_Call(encoder, args, NULL); if (result == NULL) { _PyErr_FormatNote("%s with '%s' codec failed", "encoding", encoding); goto onError; } if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) { PyErr_SetString(PyExc_TypeError, "encoder must return a tuple (object, integer)"); goto onError; } v = Py_NewRef(PyTuple_GET_ITEM(result,0)); /* We don't check or use the second (integer) entry. */ Py_DECREF(args); Py_DECREF(encoder); Py_DECREF(result); return v; onError: Py_XDECREF(result); Py_XDECREF(args); Py_XDECREF(encoder); return NULL; } /* Decode an object (usually a Python string) using the given encoding and return an equivalent object (e.g. a Unicode object). errors is passed to the decoder factory as argument if non-NULL. */ static PyObject * _PyCodec_DecodeInternal(PyObject *object, PyObject *decoder, const char *encoding, const char *errors) { PyObject *args = NULL, *result = NULL; PyObject *v; args = args_tuple(object, errors); if (args == NULL) goto onError; result = PyObject_Call(decoder, args, NULL); if (result == NULL) { _PyErr_FormatNote("%s with '%s' codec failed", "decoding", encoding); goto onError; } if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) { PyErr_SetString(PyExc_TypeError, "decoder must return a tuple (object,integer)"); goto onError; } v = Py_NewRef(PyTuple_GET_ITEM(result,0)); /* We don't check or use the second (integer) entry. */ Py_DECREF(args); Py_DECREF(decoder); Py_DECREF(result); return v; onError: Py_XDECREF(args); Py_XDECREF(decoder); Py_XDECREF(result); return NULL; } /* Generic encoding/decoding API */ PyObject *PyCodec_Encode(PyObject *object, const char *encoding, const char *errors) { PyObject *encoder; encoder = PyCodec_Encoder(encoding); if (encoder == NULL) return NULL; return _PyCodec_EncodeInternal(object, encoder, encoding, errors); } PyObject *PyCodec_Decode(PyObject *object, const char *encoding, const char *errors) { PyObject *decoder; decoder = PyCodec_Decoder(encoding); if (decoder == NULL) return NULL; return _PyCodec_DecodeInternal(object, decoder, encoding, errors); } /* Text encoding/decoding API */ PyObject * _PyCodec_LookupTextEncoding(const char *encoding, const char *alternate_command) { PyObject *codec; PyObject *attr; int is_text_codec; codec = _PyCodec_Lookup(encoding); if (codec == NULL) return NULL; /* Backwards compatibility: assume any raw tuple describes a text * encoding, and the same for anything lacking the private * attribute. */ if (!PyTuple_CheckExact(codec)) { if (PyObject_GetOptionalAttr(codec, &_Py_ID(_is_text_encoding), &attr) < 0) { Py_DECREF(codec); return NULL; } if (attr != NULL) { is_text_codec = PyObject_IsTrue(attr); Py_DECREF(attr); if (is_text_codec <= 0) { Py_DECREF(codec); if (!is_text_codec) { if (alternate_command != NULL) { PyErr_Format(PyExc_LookupError, "'%.400s' is not a text encoding; " "use %s to handle arbitrary codecs", encoding, alternate_command); } else { PyErr_Format(PyExc_LookupError, "'%.400s' is not a text encoding", encoding); } } return NULL; } } } /* This appears to be a valid text encoding */ return codec; } static PyObject *codec_getitem_checked(const char *encoding, const char *alternate_command, int index) { PyObject *codec; PyObject *v; codec = _PyCodec_LookupTextEncoding(encoding, alternate_command); if (codec == NULL) return NULL; v = Py_NewRef(PyTuple_GET_ITEM(codec, index)); Py_DECREF(codec); return v; } static PyObject * _PyCodec_TextEncoder(const char *encoding) { return codec_getitem_checked(encoding, "codecs.encode()", 0); } static PyObject * _PyCodec_TextDecoder(const char *encoding) { return codec_getitem_checked(encoding, "codecs.decode()", 1); } PyObject *_PyCodec_EncodeText(PyObject *object, const char *encoding, const char *errors) { PyObject *encoder; encoder = _PyCodec_TextEncoder(encoding); if (encoder == NULL) return NULL; return _PyCodec_EncodeInternal(object, encoder, encoding, errors); } PyObject *_PyCodec_DecodeText(PyObject *object, const char *encoding, const char *errors) { PyObject *decoder; decoder = _PyCodec_TextDecoder(encoding); if (decoder == NULL) return NULL; return _PyCodec_DecodeInternal(object, decoder, encoding, errors); } /* Register the error handling callback function error under the name name. This function will be called by the codec when it encounters an unencodable characters/undecodable bytes and doesn't know the callback name, when name is specified as the error parameter in the call to the encode/decode function. Return 0 on success, -1 on error */ int PyCodec_RegisterError(const char *name, PyObject *error) { PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->codecs.initialized); if (!PyCallable_Check(error)) { PyErr_SetString(PyExc_TypeError, "handler must be callable"); return -1; } return PyDict_SetItemString(interp->codecs.error_registry, name, error); } int _PyCodec_UnregisterError(const char *name) { for (size_t i = 0; i < Py_ARRAY_LENGTH(codecs_builtin_error_handlers); ++i) { if (strcmp(name, codecs_builtin_error_handlers[i]) == 0) { PyErr_Format(PyExc_ValueError, "cannot un-register built-in error handler '%s'", name); return -1; } } PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->codecs.initialized); return PyDict_PopString(interp->codecs.error_registry, name, NULL); } /* Lookup the error handling callback function registered under the name error. As a special case NULL can be passed, in which case the error handling callback for strict encoding will be returned. */ PyObject *PyCodec_LookupError(const char *name) { PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->codecs.initialized); if (name==NULL) name = "strict"; PyObject *handler; if (PyDict_GetItemStringRef(interp->codecs.error_registry, name, &handler) < 0) { return NULL; } if (handler == NULL) { PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); return NULL; } return handler; } static inline void wrong_exception_type(PyObject *exc) { PyErr_Format(PyExc_TypeError, "don't know how to handle %T in error callback", exc); } #define _PyIsUnicodeEncodeError(EXC) \ PyObject_TypeCheck(EXC, (PyTypeObject *)PyExc_UnicodeEncodeError) #define _PyIsUnicodeDecodeError(EXC) \ PyObject_TypeCheck(EXC, (PyTypeObject *)PyExc_UnicodeDecodeError) #define _PyIsUnicodeTranslateError(EXC) \ PyObject_TypeCheck(EXC, (PyTypeObject *)PyExc_UnicodeTranslateError) // --- codecs handlers: utilities --------------------------------------------- /* * Return the number of characters (including special prefixes) * needed to represent 'ch' by codec_handler_write_unicode_hex(). */ static inline Py_ssize_t codec_handler_unicode_hex_width(Py_UCS4 ch) { if (ch >= 0x10000) { // format: '\\' + 'U' + 8 hex digits return 1 + 1 + 8; } else if (ch >= 0x100) { // format: '\\' + 'u' + 4 hex digits return 1 + 1 + 4; } else { // format: '\\' + 'x' + 2 hex digits return 1 + 1 + 2; } } /* * Write the hexadecimal representation of 'ch' to the buffer pointed by 'p' * using 2, 4, or 8 characters prefixed by '\x', '\u', or '\U' respectively. */ static inline void codec_handler_write_unicode_hex(Py_UCS1 **p, Py_UCS4 ch) { *(*p)++ = '\\'; if (ch >= 0x10000) { *(*p)++ = 'U'; *(*p)++ = Py_hexdigits[(ch >> 28) & 0xf]; *(*p)++ = Py_hexdigits[(ch >> 24) & 0xf]; *(*p)++ = Py_hexdigits[(ch >> 20) & 0xf]; *(*p)++ = Py_hexdigits[(ch >> 16) & 0xf]; *(*p)++ = Py_hexdigits[(ch >> 12) & 0xf]; *(*p)++ = Py_hexdigits[(ch >> 8) & 0xf]; } else if (ch >= 0x100) { *(*p)++ = 'u'; *(*p)++ = Py_hexdigits[(ch >> 12) & 0xf]; *(*p)++ = Py_hexdigits[(ch >> 8) & 0xf]; } else { *(*p)++ = 'x'; } *(*p)++ = Py_hexdigits[(ch >> 4) & 0xf]; *(*p)++ = Py_hexdigits[ch & 0xf]; } /* * Determine the number of digits for a decimal representation of Unicode * codepoint 'ch' (by design, Unicode codepoints are limited to 7 digits). */ static inline int n_decimal_digits_for_codepoint(Py_UCS4 ch) { if (ch < 10) return 1; if (ch < 100) return 2; if (ch < 1000) return 3; if (ch < 10000) return 4; if (ch < 100000) return 5; if (ch < 1000000) return 6; if (ch < 10000000) return 7; // Unicode codepoints are limited to 1114111 (7 decimal digits) Py_UNREACHABLE(); } /* * Create a Unicode string containing 'count' copies of the official * Unicode REPLACEMENT CHARACTER (0xFFFD). */ static PyObject * codec_handler_unicode_replacement_character(Py_ssize_t count) { PyObject *res = PyUnicode_New(count, Py_UNICODE_REPLACEMENT_CHARACTER); if (res == NULL) { return NULL; } assert(count == 0 || PyUnicode_KIND(res) == PyUnicode_2BYTE_KIND); Py_UCS2 *outp = PyUnicode_2BYTE_DATA(res); for (Py_ssize_t i = 0; i < count; ++i) { outp[i] = Py_UNICODE_REPLACEMENT_CHARACTER; } assert(_PyUnicode_CheckConsistency(res, 1)); return res; } // --- handler: 'strict' ------------------------------------------------------ PyObject *PyCodec_StrictErrors(PyObject *exc) { if (PyExceptionInstance_Check(exc)) { PyErr_SetObject(PyExceptionInstance_Class(exc), exc); } else { PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); } return NULL; } // --- handler: 'ignore' ------------------------------------------------------ static PyObject * _PyCodec_IgnoreError(PyObject *exc, int as_bytes) { Py_ssize_t end; if (_PyUnicodeError_GetParams(exc, NULL, NULL, NULL, &end, NULL, as_bytes) < 0) { return NULL; } return Py_BuildValue("(Nn)", Py_GetConstant(Py_CONSTANT_EMPTY_STR), end); } PyObject *PyCodec_IgnoreErrors(PyObject *exc) { if (_PyIsUnicodeEncodeError(exc) || _PyIsUnicodeTranslateError(exc)) { return _PyCodec_IgnoreError(exc, false); } else if (_PyIsUnicodeDecodeError(exc)) { return _PyCodec_IgnoreError(exc, true); } else { wrong_exception_type(exc); return NULL; } } // --- handler: 'replace' ----------------------------------------------------- static PyObject * _PyCodec_ReplaceUnicodeEncodeError(PyObject *exc) { Py_ssize_t start, end, slen; if (_PyUnicodeError_GetParams(exc, NULL, NULL, &start, &end, &slen, false) < 0) { return NULL; } PyObject *res = PyUnicode_New(slen, '?'); if (res == NULL) { return NULL; } assert(PyUnicode_KIND(res) == PyUnicode_1BYTE_KIND); Py_UCS1 *outp = PyUnicode_1BYTE_DATA(res); memset(outp, '?', sizeof(Py_UCS1) * slen); assert(_PyUnicode_CheckConsistency(res, 1)); return Py_BuildValue("(Nn)", res, end); } static PyObject * _PyCodec_ReplaceUnicodeDecodeError(PyObject *exc) { Py_ssize_t end; if (PyUnicodeDecodeError_GetEnd(exc, &end) < 0) { return NULL; } PyObject *res = codec_handler_unicode_replacement_character(1); if (res == NULL) { return NULL; } return Py_BuildValue("(Nn)", res, end); } static PyObject * _PyCodec_ReplaceUnicodeTranslateError(PyObject *exc) { Py_ssize_t start, end, slen; if (_PyUnicodeError_GetParams(exc, NULL, NULL, &start, &end, &slen, false) < 0) { return NULL; } PyObject *res = codec_handler_unicode_replacement_character(slen); if (res == NULL) { return NULL; } return Py_BuildValue("(Nn)", res, end); } PyObject *PyCodec_ReplaceErrors(PyObject *exc) { if (_PyIsUnicodeEncodeError(exc)) { return _PyCodec_ReplaceUnicodeEncodeError(exc); } else if (_PyIsUnicodeDecodeError(exc)) { return _PyCodec_ReplaceUnicodeDecodeError(exc); } else if (_PyIsUnicodeTranslateError(exc)) { return _PyCodec_ReplaceUnicodeTranslateError(exc); } else { wrong_exception_type(exc); return NULL; } } // --- handler: 'xmlcharrefreplace' ------------------------------------------- PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc) { if (!_PyIsUnicodeEncodeError(exc)) { wrong_exception_type(exc); return NULL; } PyObject *obj; Py_ssize_t objlen, start, end, slen; if (_PyUnicodeError_GetParams(exc, &obj, &objlen, &start, &end, &slen, false) < 0) { return NULL; } // The number of characters that each character 'ch' contributes // in the result is 2 + k + 1, where k = min{t >= 1 | 10^t > ch} // and will be formatted as "&#" + DIGITS + ";". Since the Unicode // range is below 10^7, each "block" requires at most 2 + 7 + 1 // characters. if (slen > PY_SSIZE_T_MAX / (2 + 7 + 1)) { end = start + PY_SSIZE_T_MAX / (2 + 7 + 1); end = Py_MIN(end, objlen); slen = Py_MAX(0, end - start); } Py_ssize_t ressize = 0; for (Py_ssize_t i = start; i < end; ++i) { Py_UCS4 ch = PyUnicode_READ_CHAR(obj, i); int k = n_decimal_digits_for_codepoint(ch); assert(k != 0); assert(k <= 7); ressize += 2 + k + 1; } /* allocate replacement */ PyObject *res = PyUnicode_New(ressize, 127); if (res == NULL) { Py_DECREF(obj); return NULL; } Py_UCS1 *outp = PyUnicode_1BYTE_DATA(res); /* generate replacement */ for (Py_ssize_t i = start; i < end; ++i) { Py_UCS4 ch = PyUnicode_READ_CHAR(obj, i); /* * Write the decimal representation of 'ch' to the buffer pointed by 'p' * using at most 7 characters prefixed by '&#' and suffixed by ';'. */ *outp++ = '&'; *outp++ = '#'; Py_UCS1 *digit_end = outp + n_decimal_digits_for_codepoint(ch); for (Py_UCS1 *p_digit = digit_end - 1; p_digit >= outp; --p_digit) { *p_digit = '0' + (ch % 10); ch /= 10; } assert(ch == 0); outp = digit_end; *outp++ = ';'; } assert(_PyUnicode_CheckConsistency(res, 1)); PyObject *restuple = Py_BuildValue("(Nn)", res, end); Py_DECREF(obj); return restuple; } // --- handler: 'backslashreplace' -------------------------------------------- static PyObject * _PyCodec_BackslashReplaceUnicodeEncodeError(PyObject *exc) { PyObject *obj; Py_ssize_t objlen, start, end, slen; if (_PyUnicodeError_GetParams(exc, &obj, &objlen, &start, &end, &slen, false) < 0) { return NULL; } // The number of characters that each character 'ch' contributes // in the result is 1 + 1 + k, where k >= min{t >= 1 | 16^t > ch} // and will be formatted as "\\" + ('U'|'u'|'x') + HEXDIGITS, // where the number of hexdigits is either 2, 4, or 8 (not 6). // Since the Unicode range is below 10^7, we choose k = 8 whence // each "block" requires at most 1 + 1 + 8 characters. if (slen > PY_SSIZE_T_MAX / (1 + 1 + 8)) { end = start + PY_SSIZE_T_MAX / (1 + 1 + 8); end = Py_MIN(end, objlen); slen = Py_MAX(0, end - start); } Py_ssize_t ressize = 0; for (Py_ssize_t i = start; i < end; ++i) { Py_UCS4 c = PyUnicode_READ_CHAR(obj, i); ressize += codec_handler_unicode_hex_width(c); } PyObject *res = PyUnicode_New(ressize, 127); if (res == NULL) { Py_DECREF(obj); return NULL; } Py_UCS1 *outp = PyUnicode_1BYTE_DATA(res); for (Py_ssize_t i = start; i < end; ++i) { |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |