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/Objects/bytesobject.c at main · python/cpython Expand file tree/ Copy pathbytesobject.cMore file actions 4268 lines (3726 loc) · 124 KB / Copy pathbytesobject.cFile metadata and controls4268 lines (3726 loc) · 124 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 /* bytes object implementation */ #include "Python.h" #include "pycore_abstract.h" // _PyIndex_Check() #include "pycore_bytes_methods.h" // _Py_bytes_startswith() #include "pycore_bytesobject.h" // _PyBytes_Find(), _PyBytes_RepeatBuffer() #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_ceval.h" // _PyEval_GetBuiltin() #include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST() #include "pycore_format.h" // F_LJUST #include "pycore_freelist.h" // _Py_FREELIST_FREE() #include "pycore_global_objects.h"// _Py_GET_GLOBAL_OBJECT() #include "pycore_initconfig.h" // _PyStatus_OK() #include "pycore_long.h" // _PyLong_DigitValue #include "pycore_list.h" // _PyList_GetItemRef #include "pycore_object.h" // _PyObject_GC_TRACK #include "pycore_pymem.h" // PYMEM_CLEANBYTE #include "pycore_strhex.h" // _Py_strhex_with_sep() #include "pycore_unicodeobject.h" // _PyUnicode_FormatLong() #include <stddef.h> /*[clinic input] class bytes "PyBytesObject *" "&PyBytes_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7a238f965d64892b]*/ #include "clinic/bytesobject.c.h" #define PyBytesObject_SIZE _PyBytesObject_SIZE /* Forward declaration */ static void* _PyBytesWriter_ResizeAndUpdatePointer(PyBytesWriter *writer, Py_ssize_t size, void *data); static Py_ssize_t _PyBytesWriter_ResizeToAllocated(PyBytesWriter *writer); #define CHARACTERS _Py_SINGLETON(bytes_characters) #define CHARACTER(ch) \ ((PyBytesObject *)&(CHARACTERS[ch])) #define EMPTY (&_Py_SINGLETON(bytes_empty)) // Return a reference to the immortal empty bytes string singleton. static inline PyObject* bytes_get_empty(void) { PyObject *empty = &EMPTY->ob_base.ob_base; assert(_Py_IsImmortal(empty)); return empty; } // The function cannot fail static inline PyObject* bytes_get_char(uint8_t ch) { PyObject *obj = (PyObject*)CHARACTER(ch); assert(_Py_IsImmortal(obj)); return obj; } static inline void set_ob_shash(PyBytesObject *a, Py_hash_t hash) { _Py_COMP_DIAG_PUSH _Py_COMP_DIAG_IGNORE_DEPR_DECLS #ifdef Py_GIL_DISABLED _Py_atomic_store_ssize_relaxed(&a->ob_shash, hash); #else a->ob_shash = hash; #endif _Py_COMP_DIAG_POP } // Similar to set_ob_shash() but don't use an atomic operation on Free // Threading. This function must only be used on newly allocated bytes objects. static inline void set_ob_shash_unsafe(PyBytesObject *a, Py_hash_t hash) { // Don't test _PyObject_IsUniquelyReferenced(), so the function can be // called by bytes_resize_inplace(). assert(Py_REFCNT(a) == 1); _Py_COMP_DIAG_PUSH _Py_COMP_DIAG_IGNORE_DEPR_DECLS a->ob_shash = hash; _Py_COMP_DIAG_POP } #define get_ob_shash(op) _PyBytes_GET_CACHED_HASH(op) /* For PyBytes_FromString(), the parameter 'str' points to a null-terminated string containing exactly 'size' bytes. For PyBytes_FromStringAndSize(), the parameter 'str' is either NULL or else points to a string containing at least 'size' bytes. For PyBytes_FromStringAndSize(), the string in the 'str' parameter does not have to be null-terminated. (Therefore it is safe to construct a substring by calling 'PyBytes_FromStringAndSize(origstring, substrlen)'.) If 'str' is NULL then PyBytes_FromStringAndSize() will allocate 'size+1' bytes (setting the last byte to the null terminating character) and you can fill in the data yourself. If 'str' is non-NULL then the resulting PyBytes object must be treated as immutable and you must not fill in nor alter the data yourself, since the strings may be shared. The PyObject member 'op->ob_size', which denotes the number of "extra items" in a variable-size object, will contain the number of bytes allocated for string data, not counting the null terminating character. It is therefore equal to the 'size' parameter (for PyBytes_FromStringAndSize()) or the length of the string in the 'str' parameter (for PyBytes_FromString()). */ // Allocate a new bytes object with contents left uninitialized. The caller is // responsible to fill the contents. size must be greater than 0. static PyObject * bytes_alloc(Py_ssize_t size) { assert(size >= 1); if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) { PyErr_SetString(PyExc_OverflowError, "byte string is too large"); return NULL; } size_t alloc = PyBytesObject_SIZE + size; /* Inline PyObject_NewVar */ PyBytesObject *op = (PyBytesObject *)PyObject_Malloc(alloc); if (op == NULL) { return PyErr_NoMemory(); } _PyObject_InitVar(_PyVarObject_CAST(op), &PyBytes_Type, size); set_ob_shash_unsafe(op, -1); op->ob_sval[size] = '\0'; return (PyObject *) op; } // Create a new bytes object with contents initialized to zero. size can be 0. static PyObject * _PyBytes_FromSizeZero(Py_ssize_t size) { PyBytesObject *op; assert(size >= 0); if (size == 0) { return bytes_get_empty(); } if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) { PyErr_SetString(PyExc_OverflowError, "byte string is too large"); return NULL; } size_t alloc = PyBytesObject_SIZE + size; /* Inline PyObject_NewVar */ op = (PyBytesObject *)PyObject_Calloc(1, alloc); if (op == NULL) { return PyErr_NoMemory(); } _PyObject_InitVar((PyVarObject*)op, &PyBytes_Type, size); set_ob_shash_unsafe(op, -1); // op->ob_sval[size] is equal to '\0' return (PyObject *) op; } // Similar to PyBytes_FromStringAndSize(), but str must not be NULL. static PyObject * _PyBytes_FromStringAndSize(const char *str, Py_ssize_t size) { assert(str != NULL); assert(size >= 0); if (size == 0) { return bytes_get_empty(); } if (size == 1) { return bytes_get_char((uint8_t)str[0]); } PyBytesObject *op = (PyBytesObject *)bytes_alloc(size); if (op == NULL) { return NULL; } memcpy(op->ob_sval, str, size); return (PyObject *) op; } PyObject * PyBytes_FromStringAndSize(const char *str, Py_ssize_t size) { if (size < 0) { PyErr_SetString(PyExc_SystemError, "Negative size passed to PyBytes_FromStringAndSize"); return NULL; } if (str != NULL) { return _PyBytes_FromStringAndSize(str, size); } else { if (size == 0) { return bytes_get_empty(); } return bytes_alloc(size); } } PyObject * PyBytes_FromString(const char *str) { assert(str != NULL); size_t size = strlen(str); if (size == 0) { return bytes_get_empty(); } if (size == 1) { return bytes_get_char((uint8_t)str[0]); } PyBytesObject *op = (PyBytesObject *)bytes_alloc(size); if (op == NULL) { return PyErr_NoMemory(); } memcpy(op->ob_sval, str, size+1); return (PyObject *) op; } static char* bytes_fromformat(PyBytesWriter *writer, Py_ssize_t writer_pos, const char *format, va_list vargs) { /* Longest 64-bit formatted numbers: - "18446744073709551615\0" (21 bytes) - "-9223372036854775808\0" (21 bytes) Decimal takes the most space (it isn't enough for octal.) Longest 64-bit pointer representation: "0xffffffffffffffff\0" (19 bytes). Longest 64-bit "%p" with "0x" prefix: len(hex(2**64-1)+'\0') = 19. */ char buffer[21]; char *s = (char*)PyBytesWriter_GetData(writer) + writer_pos; #define WRITE_BYTES(str, len_expr) \ do { \ size_t _len = (len_expr); \ size_t _prealloc = (f - p + 1); \ if (_len > _prealloc) { \ s = PyBytesWriter_GrowAndUpdatePointer(writer, _len - _prealloc, s); \ if (s == NULL) { \ return NULL; \ } \ } \ memcpy(s, (str), _len); \ s += _len; \ } while (0) for (const char *f = format; *f; f++) { if (*f != '%') { *s++ = *f; continue; } const char *p = f++; /* ignore the width (ex: 10 in "%10s") */ while (Py_ISDIGIT(*f)) f++; /* parse the precision (ex: 10 in "%.10s") */ Py_ssize_t prec = 0; if (*f == '.') { f++; for (; Py_ISDIGIT(*f); f++) { prec = (prec * 10) + (*f - '0'); } } assert(prec >= 0); while (*f && *f != '%' && !Py_ISALPHA(*f)) { f++; } /* handle the long flag ('l'), but only for %ld and %lu. others can be added when necessary. */ int longflag = 0; if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { longflag = 1; ++f; } /* handle the size_t flag ('z'). */ int size_tflag = 0; if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { size_tflag = 1; ++f; } Py_ssize_t len; switch (*f) { case 'c': { int c = va_arg(vargs, int); if (c < 0 || c > 255) { PyErr_SetString(PyExc_OverflowError, "PyBytes_FromFormatV(): %c format " "expects an integer in range [0; 255]"); return NULL; } *s++ = (unsigned char)c; break; } case 'd': if (longflag) { len = sprintf(buffer, "%ld", va_arg(vargs, long)); } else if (size_tflag) { len = sprintf(buffer, "%zd", va_arg(vargs, Py_ssize_t)); } else { len = sprintf(buffer, "%d", va_arg(vargs, int)); } assert(1 <= len && len < (Py_ssize_t)sizeof(buffer)); WRITE_BYTES(buffer, len); break; case 'u': if (longflag) { len = sprintf(buffer, "%lu", va_arg(vargs, unsigned long)); } else if (size_tflag) { len = sprintf(buffer, "%zu", va_arg(vargs, size_t)); } else { len = sprintf(buffer, "%u", va_arg(vargs, unsigned int)); } assert(1 <= len && len < (Py_ssize_t)sizeof(buffer)); WRITE_BYTES(buffer, len); break; case 'i': len = sprintf(buffer, "%i", va_arg(vargs, int)); assert(1 <= len && len < (Py_ssize_t)sizeof(buffer)); WRITE_BYTES(buffer, len); break; case 'x': len = sprintf(buffer, "%x", va_arg(vargs, int)); assert(1 <= len && len < (Py_ssize_t)sizeof(buffer)); WRITE_BYTES(buffer, len); break; case 's': { const char *str = va_arg(vargs, const char*); if (prec == 0) { len = strlen(str); } else { const char *end = memchr(str, 0, prec); if (end != NULL) { len = (end - str); } else { len = (size_t)prec; } } WRITE_BYTES(str, len); break; } case 'p': len = sprintf(buffer, "%p", va_arg(vargs, void*)); assert(1 <= len && len < (Py_ssize_t)sizeof(buffer)); /* %p is ill-defined: ensure leading 0x. */ if (buffer[1] == 'X') { buffer[1] = 'x'; } else if (buffer[1] != 'x') { memmove(buffer + 2, buffer, len + 1); buffer[0] = '0'; buffer[1] = 'x'; len += 2; } WRITE_BYTES(buffer, len); break; case '%': *s++ = '%'; break; default: // Invalid format string: copy unformatted string and exit. // No need to grow the writer buffer, we already preallocated // enough bytes. len = strlen(p); memcpy(s, p, len); s += len; return s; } } return s; #undef WRITE_BYTES } PyObject * PyBytes_FromFormatV(const char *format, va_list vargs) { Py_ssize_t alloc = strlen(format); PyBytesWriter *writer = PyBytesWriter_Create(alloc); if (writer == NULL) { return NULL; } char *s = bytes_fromformat(writer, 0, format, vargs); if (s == NULL) { PyBytesWriter_Discard(writer); return NULL; } return PyBytesWriter_FinishWithPointer(writer, s); } PyObject * PyBytes_FromFormat(const char *format, ...) { PyObject* ret; va_list vargs; va_start(vargs, format); ret = PyBytes_FromFormatV(format, vargs); va_end(vargs); return ret; } /* Helpers for formatstring */ #define FORMAT_ERROR(EXC, FMT, ...) do { \ if (key != NULL) { \ PyErr_Format((EXC), "format argument %R: " FMT, \ key, __VA_ARGS__); \ } \ else if (argidx >= 0) { \ PyErr_Format((EXC), "format argument %zd: " FMT, \ argidx, __VA_ARGS__); \ } \ else { \ PyErr_Format((EXC), "format argument: " FMT, __VA_ARGS__); \ } \ } while (0) Py_LOCAL_INLINE(PyObject *) getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx, int allowone) { Py_ssize_t argidx = *p_argidx; if (argidx < arglen) { (*p_argidx)++; if (arglen >= 0) { return PyTuple_GetItem(args, argidx); } else if (allowone) { return args; } } PyErr_Format(PyExc_TypeError, "not enough arguments for format string (got %zd)", arglen < 0 ? 1 : arglen); return NULL; } /* Returns a new reference to a PyBytes object, or NULL on failure. */ static char* formatfloat(PyObject *v, Py_ssize_t argidx, PyObject *key, int flags, int prec, int type, PyObject **p_result, PyBytesWriter *writer, char *str) { char *p; PyObject *result; double x; size_t len; int dtoa_flags = 0; x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { FORMAT_ERROR(PyExc_TypeError, "%%%c requires a real number, not %T", type, v); } return NULL; } if (prec < 0) prec = 6; if (flags & F_ALT) { dtoa_flags |= Py_DTSF_ALT; } p = PyOS_double_to_string(x, type, prec, dtoa_flags, NULL); if (p == NULL) return NULL; len = strlen(p); if (writer != NULL) { str = PyBytesWriter_GrowAndUpdatePointer(writer, len, str); if (str == NULL) { PyMem_Free(p); return NULL; } memcpy(str, p, len); PyMem_Free(p); str += len; return str; } result = _PyBytes_FromStringAndSize(p, len); PyMem_Free(p); *p_result = result; return result != NULL ? str : NULL; } static PyObject * formatlong(PyObject *v, Py_ssize_t argidx, PyObject *key, int flags, int prec, int type) { PyObject *result, *iobj; if (PyLong_Check(v)) return _PyUnicode_FormatLong(v, flags & F_ALT, prec, type); if (PyNumber_Check(v)) { /* make sure number is a type of integer for o, x, and X */ if (type == 'o' || type == 'x' || type == 'X') iobj = _PyNumber_Index(v); else iobj = PyNumber_Long(v); if (iobj != NULL) { assert(PyLong_Check(iobj)); result = _PyUnicode_FormatLong(iobj, flags & F_ALT, prec, type); Py_DECREF(iobj); return result; } if (!PyErr_ExceptionMatches(PyExc_TypeError)) return NULL; } FORMAT_ERROR(PyExc_TypeError, "%%%c requires %s, not %T", type, (type == 'o' || type == 'x' || type == 'X') ? "an integer" : "a real number", v); return NULL; } static int byte_converter(PyObject *arg, Py_ssize_t argidx, PyObject *key, char *p) { if (PyBytes_Check(arg)) { if (PyBytes_GET_SIZE(arg) != 1) { FORMAT_ERROR(PyExc_TypeError, "%%c requires an integer in range(256) or " "a single byte, not a bytes object of length %zd", PyBytes_GET_SIZE(arg)); return 0; } *p = PyBytes_AS_STRING(arg)[0]; return 1; } else if (PyByteArray_Check(arg)) { if (PyByteArray_GET_SIZE(arg) != 1) { FORMAT_ERROR(PyExc_TypeError, "%%c requires an integer in range(256) or " "a single byte, not a bytearray object of length %zd", PyByteArray_GET_SIZE(arg)); return 0; } *p = PyByteArray_AS_STRING(arg)[0]; return 1; } else if (PyIndex_Check(arg)) { int overflow; long ival = PyLong_AsLongAndOverflow(arg, &overflow); if (ival == -1 && PyErr_Occurred()) { return 0; } if (!(0 <= ival && ival <= 255)) { /* this includes an overflow in converting to C long */ FORMAT_ERROR(PyExc_OverflowError, "%%c argument not in range(256)%s", ""); return 0; } *p = (char)ival; return 1; } FORMAT_ERROR(PyExc_TypeError, "%%c requires an integer in range(256) or " "a single byte, not %T", arg); return 0; } static PyObject *_PyBytes_FromBuffer(PyObject *x); static PyObject * format_obj(PyObject *v, Py_ssize_t argidx, PyObject *key, const char **pbuf, Py_ssize_t *plen) { PyObject *func, *result; /* is it a bytes object? */ if (PyBytes_Check(v)) { *pbuf = PyBytes_AS_STRING(v); *plen = PyBytes_GET_SIZE(v); return Py_NewRef(v); } if (PyByteArray_Check(v)) { *pbuf = PyByteArray_AS_STRING(v); *plen = PyByteArray_GET_SIZE(v); return Py_NewRef(v); } /* does it support __bytes__? */ func = _PyObject_LookupSpecial(v, &_Py_ID(__bytes__)); if (func != NULL) { result = _PyObject_CallNoArgs(func); Py_DECREF(func); if (result == NULL) return NULL; if (!PyBytes_Check(result)) { PyErr_Format(PyExc_TypeError, "%T.__bytes__() must return a bytes, not %T", v, result); Py_DECREF(result); return NULL; } *pbuf = PyBytes_AS_STRING(result); *plen = PyBytes_GET_SIZE(result); return result; } else if (PyErr_Occurred()) { return NULL; } /* does it support buffer protocol? */ if (PyObject_CheckBuffer(v)) { /* maybe we can avoid making a copy of the buffer object here? */ result = _PyBytes_FromBuffer(v); if (result == NULL) return NULL; *pbuf = PyBytes_AS_STRING(result); *plen = PyBytes_GET_SIZE(result); return result; } FORMAT_ERROR(PyExc_TypeError, "%%b requires a bytes-like object, " "or an object that implements __bytes__, not %T", v); return NULL; } /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */ PyObject * _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, PyObject *args, int use_bytearray) { const char *fmt; Py_ssize_t arglen, argidx; Py_ssize_t fmtcnt; int args_owned = 0; PyObject *dict = NULL; PyObject *key = NULL; if (args == NULL) { PyErr_BadInternalCall(); return NULL; } fmt = format; fmtcnt = format_len; PyBytesWriter *writer; if (use_bytearray) { writer = _PyBytesWriter_CreateByteArray(fmtcnt); } else { writer = PyBytesWriter_Create(fmtcnt); } if (writer == NULL) { return NULL; } char *res = PyBytesWriter_GetData(writer); if (PyTuple_Check(args)) { arglen = PyTuple_GET_SIZE(args); argidx = 0; } else { arglen = -1; argidx = -2; } if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript && !PyTuple_Check(args) && !PyBytes_Check(args) && !PyUnicode_Check(args) && !PyByteArray_Check(args)) { dict = args; } while (--fmtcnt >= 0) { if (*fmt != '%') { Py_ssize_t len; char *pos; pos = (char *)memchr(fmt + 1, '%', fmtcnt); if (pos != NULL) len = pos - fmt; else len = fmtcnt + 1; assert(len != 0); memcpy(res, fmt, len); res += len; fmt += len; fmtcnt -= (len - 1); } else { /* Got a format specifier */ int flags = 0; Py_ssize_t width = -1; int prec = -1; int c = '\0'; int fill; PyObject *v = NULL; PyObject *temp = NULL; const char *pbuf = NULL; int sign; Py_ssize_t len = 0; char onechar; /* For byte_converter() */ Py_ssize_t alloc; const char *start = fmt; fmt++; if (*fmt == '%') { *res++ = '%'; fmt++; fmtcnt--; continue; } Py_CLEAR(key); const char *fmtstart = fmt; if (*fmt == '(') { const char *keystart; Py_ssize_t keylen; int pcount = 1; if (dict == NULL) { PyErr_Format(PyExc_TypeError, "format requires a mapping, not %T", args); goto error; } ++fmt; --fmtcnt; keystart = fmt; /* Skip over balanced parentheses */ while (pcount > 0 && --fmtcnt >= 0) { if (*fmt == ')') --pcount; else if (*fmt == '(') ++pcount; fmt++; } keylen = fmt - keystart - 1; if (fmtcnt < 0 || pcount > 0) { PyErr_Format(PyExc_ValueError, "stray %% or incomplete format key " "at position %zd", (Py_ssize_t)(fmtstart - format - 1)); goto error; } key = _PyBytes_FromStringAndSize(keystart, keylen); if (key == NULL) goto error; if (args_owned) { Py_DECREF(args); args_owned = 0; } args = PyObject_GetItem(dict, key); if (args == NULL) { goto error; } args_owned = 1; arglen = -3; argidx = -4; } else { if (arglen < -1) { PyErr_Format(PyExc_ValueError, "format requires a parenthesised mapping key " "at position %zd", (Py_ssize_t)(fmtstart - format - 1)); goto error; } } /* Parse flags. Example: "%+i" => flags=F_SIGN. */ while (--fmtcnt >= 0) { switch (c = *fmt++) { case '-': flags |= F_LJUST; continue; case '+': flags |= F_SIGN; continue; case ' ': flags |= F_BLANK; continue; case '#': flags |= F_ALT; continue; case '0': flags |= F_ZERO; continue; } break; } /* Parse width. Example: "%10s" => width=10 */ if (c == '*') { if (arglen < -1) { PyErr_Format(PyExc_ValueError, "* cannot be used with a parenthesised mapping key " "at position %zd", (Py_ssize_t)(fmtstart - format - 1)); goto error; } v = getnextarg(args, arglen, &argidx, 0); if (v == NULL) goto error; if (!PyLong_Check(v)) { FORMAT_ERROR(PyExc_TypeError, "* requires int, not %T", v); goto error; } width = PyLong_AsSsize_t(v); if (width == -1 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_OverflowError)) { FORMAT_ERROR(PyExc_OverflowError, "too big for width%s", ""); } goto error; } if (width < 0) { if (width == PY_SSIZE_T_MIN) { FORMAT_ERROR(PyExc_OverflowError, "too big for width%s", ""); goto error; } flags |= F_LJUST; width = -width; } if (--fmtcnt >= 0) c = *fmt++; } else if (c >= 0 && Py_ISDIGIT(c)) { width = c - '0'; while (--fmtcnt >= 0) { c = Py_CHARMASK(*fmt++); if (!Py_ISDIGIT(c)) break; if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) { PyErr_Format(PyExc_ValueError, "width too big at position %zd", (Py_ssize_t)(fmtstart - format - 1)); goto error; } width = width*10 + (c - '0'); } } /* Parse precision. Example: "%.3f" => prec=3 */ if (c == '.') { prec = 0; if (--fmtcnt >= 0) c = *fmt++; if (c == '*') { if (arglen < -1) { PyErr_Format(PyExc_ValueError, "* cannot be used with a parenthesised mapping key " "at position %zd", (Py_ssize_t)(fmtstart - format - 1)); goto error; } v = getnextarg(args, arglen, &argidx, 0); if (v == NULL) goto error; if (!PyLong_Check(v)) { FORMAT_ERROR(PyExc_TypeError, "* requires int, not %T", v); goto error; } prec = PyLong_AsInt(v); if (prec == -1 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_OverflowError)) { FORMAT_ERROR(PyExc_OverflowError, "too big for precision%s", ""); } goto error; } if (prec < 0) prec = 0; if (--fmtcnt >= 0) c = *fmt++; } else if (c >= 0 && Py_ISDIGIT(c)) { prec = c - '0'; while (--fmtcnt >= 0) { c = Py_CHARMASK(*fmt++); if (!Py_ISDIGIT(c)) break; if (prec > (INT_MAX - ((int)c - '0')) / 10) { PyErr_Format(PyExc_ValueError, "precision too big at position %zd", (Py_ssize_t)(fmtstart - format - 1)); goto error; } prec = prec*10 + (c - '0'); } } } /* prec */ if (fmtcnt >= 0) { if (c == 'h' || c == 'l' || c == 'L') { if (--fmtcnt >= 0) c = *fmt++; } } if (fmtcnt < 0) { PyErr_Format(PyExc_ValueError, "stray %% at position %zd", (Py_ssize_t)(fmtstart - format - 1)); goto error; } v = getnextarg(args, arglen, &argidx, 1); if (v == NULL) goto error; if (fmtcnt == 0) { /* last write: disable writer overallocation */ writer->overallocate = 0; } sign = 0; fill = ' '; switch (c) { case 'r': // %r is only for 2/3 code; 3 only code should use %a case 'a': temp = PyObject_ASCII(v); if (temp == NULL) goto error; assert(PyUnicode_IS_ASCII(temp)); pbuf = (const char *)PyUnicode_1BYTE_DATA(temp); len = PyUnicode_GET_LENGTH(temp); if (prec >= 0 && len > prec) len = prec; break; case 's': // %s is only for 2/3 code; 3 only code should use %b case 'b': temp = format_obj(v, argidx, key, &pbuf, &len); if (temp == NULL) goto error; if (prec >= 0 && len > prec) len = prec; break; case 'i': case 'd': case 'u': case 'o': case 'x': case 'X': if (PyLong_CheckExact(v) && width == -1 && prec == -1 && !(flags & (F_SIGN | F_BLANK)) && c != 'X') { /* Fast path */ int alternate = flags & F_ALT; int base; switch(c) { default: Py_UNREACHABLE(); case 'd': case 'i': case 'u': base = 10; |
| 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. |