Changeset 388 for python/vendor/current/Objects/intobject.c
- Timestamp:
- Mar 19, 2014, 11:11:30 AM (11 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
python/vendor/current/Objects/intobject.c
r2 r388 4 4 #include "Python.h" 5 5 #include <ctype.h> 6 #include <float.h> 6 7 7 8 static PyObject *int_int(PyIntObject *v); … … 10 11 PyInt_GetMax(void) 11 12 { 12 return LONG_MAX;/* To initialize sys.maxint */13 return LONG_MAX; /* To initialize sys.maxint */ 13 14 } 14 15 … … 30 31 */ 31 32 32 #define BLOCK_SIZE 1000/* 1K less typical malloc overhead */33 #define BHEAD_SIZE 8/* Enough for a 64-bit pointer */34 #define N_INTOBJECTS 33 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ 34 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ 35 #define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject)) 35 36 36 37 struct _intblock { 37 38 38 struct _intblock *next; 39 PyIntObject objects[N_INTOBJECTS]; 39 40 }; 40 41 … … 47 48 fill_free_list(void) 48 49 { 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 50 PyIntObject *p, *q; 51 /* Python's object allocator isn't appropriate for large blocks. */ 52 p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock)); 53 if (p == NULL) 54 return (PyIntObject *) PyErr_NoMemory(); 55 ((PyIntBlock *)p)->next = block_list; 56 block_list = (PyIntBlock *)p; 57 /* Link the int objects together, from rear to front, then return 58 the address of the last int object in the block. */ 59 p = &((PyIntBlock *)p)->objects[0]; 60 q = p + N_INTOBJECTS; 61 while (--q > p) 62 Py_TYPE(q) = (struct _typeobject *)(q-1); 63 Py_TYPE(q) = NULL; 64 return p + N_INTOBJECTS - 1; 64 65 } 65 66 66 67 #ifndef NSMALLPOSINTS 67 #define NSMALLPOSINTS 68 #define NSMALLPOSINTS 257 68 69 #endif 69 70 #ifndef NSMALLNEGINTS 70 #define NSMALLNEGINTS 71 #define NSMALLNEGINTS 5 71 72 #endif 72 73 #if NSMALLNEGINTS + NSMALLPOSINTS > 0 … … 79 80 #endif 80 81 #ifdef COUNT_ALLOCS 81 int quick_int_allocs, quick_neg_int_allocs; 82 Py_ssize_t quick_int_allocs; 83 Py_ssize_t quick_neg_int_allocs; 82 84 #endif 83 85 … … 85 87 PyInt_FromLong(long ival) 86 88 { 87 89 register PyIntObject *v; 88 90 #if NSMALLNEGINTS + NSMALLPOSINTS > 0 89 90 91 91 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { 92 v = small_ints[ival + NSMALLNEGINTS]; 93 Py_INCREF(v); 92 94 #ifdef COUNT_ALLOCS 93 94 95 96 97 #endif 98 99 100 #endif 101 102 103 104 105 106 107 108 109 110 95 if (ival >= 0) 96 quick_int_allocs++; 97 else 98 quick_neg_int_allocs++; 99 #endif 100 return (PyObject *) v; 101 } 102 #endif 103 if (free_list == NULL) { 104 if ((free_list = fill_free_list()) == NULL) 105 return NULL; 106 } 107 /* Inline PyObject_New */ 108 v = free_list; 109 free_list = (PyIntObject *)Py_TYPE(v); 110 PyObject_INIT(v, &PyInt_Type); 111 v->ob_ival = ival; 112 return (PyObject *) v; 111 113 } 112 114 … … 114 116 PyInt_FromSize_t(size_t ival) 115 117 { 116 117 118 118 if (ival <= LONG_MAX) 119 return PyInt_FromLong((long)ival); 120 return _PyLong_FromSize_t(ival); 119 121 } 120 122 … … 122 124 PyInt_FromSsize_t(Py_ssize_t ival) 123 125 { 124 125 126 126 if (ival >= LONG_MIN && ival <= LONG_MAX) 127 return PyInt_FromLong((long)ival); 128 return _PyLong_FromSsize_t(ival); 127 129 } 128 130 … … 130 132 int_dealloc(PyIntObject *v) 131 133 { 132 133 134 135 136 137 134 if (PyInt_CheckExact(v)) { 135 Py_TYPE(v) = (struct _typeobject *)free_list; 136 free_list = v; 137 } 138 else 139 Py_TYPE(v)->tp_free((PyObject *)v); 138 140 } 139 141 … … 141 143 int_free(PyIntObject *v) 142 144 { 143 144 145 Py_TYPE(v) = (struct _typeobject *)free_list; 146 free_list = v; 145 147 } 146 148 … … 148 150 PyInt_AsLong(register PyObject *op) 149 151 { 150 PyNumberMethods *nb; 151 PyIntObject *io; 152 long val; 153 154 if (op && PyInt_Check(op)) 155 return PyInt_AS_LONG((PyIntObject*) op); 156 157 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL || 158 nb->nb_int == NULL) { 159 PyErr_SetString(PyExc_TypeError, "an integer is required"); 160 return -1; 161 } 162 163 io = (PyIntObject*) (*nb->nb_int) (op); 164 if (io == NULL) 165 return -1; 166 if (!PyInt_Check(io)) { 167 if (PyLong_Check(io)) { 168 /* got a long? => retry int conversion */ 169 val = PyLong_AsLong((PyObject *)io); 170 Py_DECREF(io); 171 if ((val == -1) && PyErr_Occurred()) 172 return -1; 173 return val; 174 } 175 else 176 { 177 Py_DECREF(io); 178 PyErr_SetString(PyExc_TypeError, 179 "nb_int should return int object"); 180 return -1; 181 } 182 } 183 184 val = PyInt_AS_LONG(io); 185 Py_DECREF(io); 186 187 return val; 152 PyNumberMethods *nb; 153 PyIntObject *io; 154 long val; 155 156 if (op && PyInt_Check(op)) 157 return PyInt_AS_LONG((PyIntObject*) op); 158 159 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL || 160 nb->nb_int == NULL) { 161 PyErr_SetString(PyExc_TypeError, "an integer is required"); 162 return -1; 163 } 164 165 io = (PyIntObject*) (*nb->nb_int) (op); 166 if (io == NULL) 167 return -1; 168 if (!PyInt_Check(io)) { 169 if (PyLong_Check(io)) { 170 /* got a long? => retry int conversion */ 171 val = PyLong_AsLong((PyObject *)io); 172 Py_DECREF(io); 173 if ((val == -1) && PyErr_Occurred()) 174 return -1; 175 return val; 176 } 177 else 178 { 179 Py_DECREF(io); 180 PyErr_SetString(PyExc_TypeError, 181 "__int__ method should return an integer"); 182 return -1; 183 } 184 } 185 186 val = PyInt_AS_LONG(io); 187 Py_DECREF(io); 188 189 return val; 190 } 191 192 int 193 _PyInt_AsInt(PyObject *obj) 194 { 195 long result = PyInt_AsLong(obj); 196 if (result == -1 && PyErr_Occurred()) 197 return -1; 198 if (result > INT_MAX || result < INT_MIN) { 199 PyErr_SetString(PyExc_OverflowError, 200 "Python int too large to convert to C int"); 201 return -1; 202 } 203 return (int)result; 188 204 } 189 205 … … 192 208 { 193 209 #if SIZEOF_SIZE_T != SIZEOF_LONG 194 195 196 197 #endif 198 199 200 201 202 203 204 205 206 207 210 PyNumberMethods *nb; 211 PyIntObject *io; 212 Py_ssize_t val; 213 #endif 214 215 if (op == NULL) { 216 PyErr_SetString(PyExc_TypeError, "an integer is required"); 217 return -1; 218 } 219 220 if (PyInt_Check(op)) 221 return PyInt_AS_LONG((PyIntObject*) op); 222 if (PyLong_Check(op)) 223 return _PyLong_AsSsize_t(op); 208 224 #if SIZEOF_SIZE_T == SIZEOF_LONG 209 225 return PyInt_AsLong(op); 210 226 #else 211 227 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 "nb_int should return int object");238 239 240 241 242 243 244 245 228 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || 229 (nb->nb_int == NULL && nb->nb_long == 0)) { 230 PyErr_SetString(PyExc_TypeError, "an integer is required"); 231 return -1; 232 } 233 234 if (nb->nb_long != 0) 235 io = (PyIntObject*) (*nb->nb_long) (op); 236 else 237 io = (PyIntObject*) (*nb->nb_int) (op); 238 if (io == NULL) 239 return -1; 240 if (!PyInt_Check(io)) { 241 if (PyLong_Check(io)) { 242 /* got a long? => retry int conversion */ 243 val = _PyLong_AsSsize_t((PyObject *)io); 244 Py_DECREF(io); 245 if ((val == -1) && PyErr_Occurred()) 246 return -1; 247 return val; 248 } 249 else 250 { 251 Py_DECREF(io); 252 PyErr_SetString(PyExc_TypeError, 253 "__int__ method should return an integer"); 254 return -1; 255 } 256 } 257 258 val = PyInt_AS_LONG(io); 259 Py_DECREF(io); 260 261 return val; 246 262 #endif 247 263 } … … 250 266 PyInt_AsUnsignedLongMask(register PyObject *op) 251 267 { 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 "nb_int should return int object");283 284 285 286 287 288 289 290 268 PyNumberMethods *nb; 269 PyIntObject *io; 270 unsigned long val; 271 272 if (op && PyInt_Check(op)) 273 return PyInt_AS_LONG((PyIntObject*) op); 274 if (op && PyLong_Check(op)) 275 return PyLong_AsUnsignedLongMask(op); 276 277 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL || 278 nb->nb_int == NULL) { 279 PyErr_SetString(PyExc_TypeError, "an integer is required"); 280 return (unsigned long)-1; 281 } 282 283 io = (PyIntObject*) (*nb->nb_int) (op); 284 if (io == NULL) 285 return (unsigned long)-1; 286 if (!PyInt_Check(io)) { 287 if (PyLong_Check(io)) { 288 val = PyLong_AsUnsignedLongMask((PyObject *)io); 289 Py_DECREF(io); 290 if (PyErr_Occurred()) 291 return (unsigned long)-1; 292 return val; 293 } 294 else 295 { 296 Py_DECREF(io); 297 PyErr_SetString(PyExc_TypeError, 298 "__int__ method should return an integer"); 299 return (unsigned long)-1; 300 } 301 } 302 303 val = PyInt_AS_LONG(io); 304 Py_DECREF(io); 305 306 return val; 291 307 } 292 308 … … 295 311 PyInt_AsUnsignedLongLongMask(register PyObject *op) 296 312 { 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 "nb_int should return int object");328 329 330 331 332 333 334 335 313 PyNumberMethods *nb; 314 PyIntObject *io; 315 unsigned PY_LONG_LONG val; 316 317 if (op && PyInt_Check(op)) 318 return PyInt_AS_LONG((PyIntObject*) op); 319 if (op && PyLong_Check(op)) 320 return PyLong_AsUnsignedLongLongMask(op); 321 322 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL || 323 nb->nb_int == NULL) { 324 PyErr_SetString(PyExc_TypeError, "an integer is required"); 325 return (unsigned PY_LONG_LONG)-1; 326 } 327 328 io = (PyIntObject*) (*nb->nb_int) (op); 329 if (io == NULL) 330 return (unsigned PY_LONG_LONG)-1; 331 if (!PyInt_Check(io)) { 332 if (PyLong_Check(io)) { 333 val = PyLong_AsUnsignedLongLongMask((PyObject *)io); 334 Py_DECREF(io); 335 if (PyErr_Occurred()) 336 return (unsigned PY_LONG_LONG)-1; 337 return val; 338 } 339 else 340 { 341 Py_DECREF(io); 342 PyErr_SetString(PyExc_TypeError, 343 "__int__ method should return an integer"); 344 return (unsigned PY_LONG_LONG)-1; 345 } 346 } 347 348 val = PyInt_AS_LONG(io); 349 Py_DECREF(io); 350 351 return val; 336 352 } 337 353 #endif … … 340 356 PyInt_FromString(char *s, char **pend, int base) 341 357 { 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 358 char *end; 359 long x; 360 Py_ssize_t slen; 361 PyObject *sobj, *srepr; 362 363 if ((base != 0 && base < 2) || base > 36) { 364 PyErr_SetString(PyExc_ValueError, 365 "int() base must be >= 2 and <= 36"); 366 return NULL; 367 } 368 369 while (*s && isspace(Py_CHARMASK(*s))) 370 s++; 371 errno = 0; 372 if (base == 0 && s[0] == '0') { 373 x = (long) PyOS_strtoul(s, &end, base); 374 if (x < 0) 375 return PyLong_FromString(s, pend, base); 376 } 377 else 378 x = PyOS_strtol(s, &end, base); 379 if (end == s || !isalnum(Py_CHARMASK(end[-1]))) 380 goto bad; 381 while (*end && isspace(Py_CHARMASK(*end))) 382 end++; 383 if (*end != '\0') { 368 384 bad: 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 385 slen = strlen(s) < 200 ? strlen(s) : 200; 386 sobj = PyString_FromStringAndSize(s, slen); 387 if (sobj == NULL) 388 return NULL; 389 srepr = PyObject_Repr(sobj); 390 Py_DECREF(sobj); 391 if (srepr == NULL) 392 return NULL; 393 PyErr_Format(PyExc_ValueError, 394 "invalid literal for int() with base %d: %s", 395 base, PyString_AS_STRING(srepr)); 396 Py_DECREF(srepr); 397 return NULL; 398 } 399 else if (errno != 0) 400 return PyLong_FromString(s, pend, base); 401 if (pend) 402 *pend = end; 403 return PyInt_FromLong(x); 388 404 } 389 405 … … 392 408 PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base) 393 409 { 394 395 396 397 398 399 400 401 402 403 404 405 406 410 PyObject *result; 411 char *buffer = (char *)PyMem_MALLOC(length+1); 412 413 if (buffer == NULL) 414 return PyErr_NoMemory(); 415 416 if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) { 417 PyMem_FREE(buffer); 418 return NULL; 419 } 420 result = PyInt_FromString(buffer, NULL, base); 421 PyMem_FREE(buffer); 422 return result; 407 423 } 408 424 #endif … … 414 430 integers. */ 415 431 416 #define CONVERT_TO_LONG(obj, lng) 417 if (PyInt_Check(obj)) {\418 lng = PyInt_AS_LONG(obj);\419 }\420 else {\421 Py_INCREF(Py_NotImplemented);\422 return Py_NotImplemented;\423 432 #define CONVERT_TO_LONG(obj, lng) \ 433 if (PyInt_Check(obj)) { \ 434 lng = PyInt_AS_LONG(obj); \ 435 } \ 436 else { \ 437 Py_INCREF(Py_NotImplemented); \ 438 return Py_NotImplemented; \ 439 } 424 440 425 441 /* ARGSUSED */ … … 428 444 /* flags -- not used but required by interface */ 429 445 { 430 long int_val = v->ob_ival; 431 Py_BEGIN_ALLOW_THREADS 432 fprintf(fp, "%ld", int_val); 433 Py_END_ALLOW_THREADS 434 return 0; 435 } 436 437 static PyObject * 438 int_repr(PyIntObject *v) 439 { 440 return _PyInt_Format(v, 10, 0); 446 long int_val = v->ob_ival; 447 Py_BEGIN_ALLOW_THREADS 448 fprintf(fp, "%ld", int_val); 449 Py_END_ALLOW_THREADS 450 return 0; 441 451 } 442 452 … … 444 454 int_compare(PyIntObject *v, PyIntObject *w) 445 455 { 446 447 448 456 register long i = v->ob_ival; 457 register long j = w->ob_ival; 458 return (i < j) ? -1 : (i > j) ? 1 : 0; 449 459 } 450 460 … … 452 462 int_hash(PyIntObject *v) 453 463 { 454 455 456 457 458 459 464 /* XXX If this is changed, you also need to change the way 465 Python's long, float and complex types are hashed. */ 466 long x = v -> ob_ival; 467 if (x == -1) 468 x = -2; 469 return x; 460 470 } 461 471 … … 463 473 int_add(PyIntObject *v, PyIntObject *w) 464 474 { 465 466 467 468 469 470 471 472 475 register long a, b, x; 476 CONVERT_TO_LONG(v, a); 477 CONVERT_TO_LONG(w, b); 478 /* casts in the line below avoid undefined behaviour on overflow */ 479 x = (long)((unsigned long)a + b); 480 if ((x^a) >= 0 || (x^b) >= 0) 481 return PyInt_FromLong(x); 482 return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w); 473 483 } 474 484 … … 476 486 int_sub(PyIntObject *v, PyIntObject *w) 477 487 { 478 479 480 481 482 483 484 485 486 488 register long a, b, x; 489 CONVERT_TO_LONG(v, a); 490 CONVERT_TO_LONG(w, b); 491 /* casts in the line below avoid undefined behaviour on overflow */ 492 x = (long)((unsigned long)a - b); 493 if ((x^a) >= 0 || (x^~b) >= 0) 494 return PyInt_FromLong(x); 495 return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v, 496 (PyObject *)w); 487 497 } 488 498 … … 516 526 int_mul(PyObject *v, PyObject *w) 517 527 { 518 519 long longprod;/* a*b in native long arithmetic */520 double doubled_longprod;/* (double)longprod */521 double doubleprod;/* (double)a * (double)b */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 528 long a, b; 529 long longprod; /* a*b in native long arithmetic */ 530 double doubled_longprod; /* (double)longprod */ 531 double doubleprod; /* (double)a * (double)b */ 532 533 CONVERT_TO_LONG(v, a); 534 CONVERT_TO_LONG(w, b); 535 /* casts in the next line avoid undefined behaviour on overflow */ 536 longprod = (long)((unsigned long)a * b); 537 doubleprod = (double)a * (double)b; 538 doubled_longprod = (double)longprod; 539 540 /* Fast path for normal case: small multiplicands, and no info 541 is lost in either method. */ 542 if (doubled_longprod == doubleprod) 543 return PyInt_FromLong(longprod); 544 545 /* Somebody somewhere lost info. Close enough, or way off? Note 546 that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0). 547 The difference either is or isn't significant compared to the 548 true value (of which doubleprod is a good approximation). 549 */ 550 { 551 const double diff = doubled_longprod - doubleprod; 552 const double absdiff = diff >= 0.0 ? diff : -diff; 553 const double absprod = doubleprod >= 0.0 ? doubleprod : 554 -doubleprod; 555 /* absdiff/absprod <= 1/32 iff 556 32 * absdiff <= absprod -- 5 good bits is "close enough" */ 557 if (32.0 * absdiff <= absprod) 558 return PyInt_FromLong(longprod); 559 else 560 return PyLong_Type.tp_as_number->nb_multiply(v, w); 561 } 552 562 } 553 563 … … 560 570 * weird "0-". 561 571 */ 562 #define UNARY_NEG_WOULD_OVERFLOW(x) 563 572 #define UNARY_NEG_WOULD_OVERFLOW(x) \ 573 ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x)) 564 574 565 575 /* Return type of i_divmod */ 566 576 enum divmod_result { 567 DIVMOD_OK,/* Correct result */568 DIVMOD_OVERFLOW,/* Overflow, try again using longs */569 DIVMOD_ERROR/* Exception raised */577 DIVMOD_OK, /* Correct result */ 578 DIVMOD_OVERFLOW, /* Overflow, try again using longs */ 579 DIVMOD_ERROR /* Exception raised */ 570 580 }; 571 581 … … 574 584 long *p_xdivy, long *p_xmody) 575 585 { 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 586 long xdivy, xmody; 587 588 if (y == 0) { 589 PyErr_SetString(PyExc_ZeroDivisionError, 590 "integer division or modulo by zero"); 591 return DIVMOD_ERROR; 592 } 593 /* (-sys.maxint-1)/-1 is the only overflow case. */ 594 if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x)) 595 return DIVMOD_OVERFLOW; 596 xdivy = x / y; 597 /* xdiv*y can overflow on platforms where x/y gives floor(x/y) 598 * for x and y with differing signs. (This is unusual 599 * behaviour, and C99 prohibits it, but it's allowed by C89; 600 * for an example of overflow, take x = LONG_MIN, y = 5 or x = 601 * LONG_MAX, y = -5.) However, x - xdivy*y is always 602 * representable as a long, since it lies strictly between 603 * -abs(y) and abs(y). We add casts to avoid intermediate 604 * overflow. 605 */ 606 xmody = (long)(x - (unsigned long)xdivy * y); 607 /* If the signs of x and y differ, and the remainder is non-0, 608 * C89 doesn't define whether xdivy is now the floor or the 609 * ceiling of the infinitely precise quotient. We want the floor, 610 * and we have it iff the remainder's sign matches y's. 611 */ 612 if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) { 613 xmody += y; 614 --xdivy; 615 assert(xmody && ((y ^ xmody) >= 0)); 616 } 617 *p_xdivy = xdivy; 618 *p_xmody = xmody; 619 return DIVMOD_OK; 610 620 } 611 621 … … 613 623 int_div(PyIntObject *x, PyIntObject *y) 614 624 { 615 616 617 618 619 620 621 622 623 624 625 626 627 625 long xi, yi; 626 long d, m; 627 CONVERT_TO_LONG(x, xi); 628 CONVERT_TO_LONG(y, yi); 629 switch (i_divmod(xi, yi, &d, &m)) { 630 case DIVMOD_OK: 631 return PyInt_FromLong(d); 632 case DIVMOD_OVERFLOW: 633 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x, 634 (PyObject *)y); 635 default: 636 return NULL; 637 } 628 638 } 629 639 … … 631 641 int_classic_div(PyIntObject *x, PyIntObject *y) 632 642 { 633 long xi, yi; 634 long d, m; 635 CONVERT_TO_LONG(x, xi); 636 CONVERT_TO_LONG(y, yi); 637 if (Py_DivisionWarningFlag && 638 PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0) 639 return NULL; 640 switch (i_divmod(xi, yi, &d, &m)) { 641 case DIVMOD_OK: 642 return PyInt_FromLong(d); 643 case DIVMOD_OVERFLOW: 644 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x, 645 (PyObject *)y); 646 default: 647 return NULL; 648 } 649 } 650 651 static PyObject * 652 int_true_divide(PyObject *v, PyObject *w) 653 { 654 /* If they aren't both ints, give someone else a chance. In 655 particular, this lets int/long get handled by longs, which 656 underflows to 0 gracefully if the long is too big to convert 657 to float. */ 658 if (PyInt_Check(v) && PyInt_Check(w)) 659 return PyFloat_Type.tp_as_number->nb_true_divide(v, w); 660 Py_INCREF(Py_NotImplemented); 661 return Py_NotImplemented; 643 long xi, yi; 644 long d, m; 645 CONVERT_TO_LONG(x, xi); 646 CONVERT_TO_LONG(y, yi); 647 if (Py_DivisionWarningFlag && 648 PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0) 649 return NULL; 650 switch (i_divmod(xi, yi, &d, &m)) { 651 case DIVMOD_OK: 652 return PyInt_FromLong(d); 653 case DIVMOD_OVERFLOW: 654 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x, 655 (PyObject *)y); 656 default: 657 return NULL; 658 } 659 } 660 661 static PyObject * 662 int_true_divide(PyIntObject *x, PyIntObject *y) 663 { 664 long xi, yi; 665 /* If they aren't both ints, give someone else a chance. In 666 particular, this lets int/long get handled by longs, which 667 underflows to 0 gracefully if the long is too big to convert 668 to float. */ 669 CONVERT_TO_LONG(x, xi); 670 CONVERT_TO_LONG(y, yi); 671 if (yi == 0) { 672 PyErr_SetString(PyExc_ZeroDivisionError, 673 "division by zero"); 674 return NULL; 675 } 676 if (xi == 0) 677 return PyFloat_FromDouble(yi < 0 ? -0.0 : 0.0); 678 679 #define WIDTH_OF_ULONG (CHAR_BIT*SIZEOF_LONG) 680 #if DBL_MANT_DIG < WIDTH_OF_ULONG 681 if ((xi >= 0 ? 0UL + xi : 0UL - xi) >> DBL_MANT_DIG || 682 (yi >= 0 ? 0UL + yi : 0UL - yi) >> DBL_MANT_DIG) 683 /* Large x or y. Use long integer arithmetic. */ 684 return PyLong_Type.tp_as_number->nb_true_divide( 685 (PyObject *)x, (PyObject *)y); 686 else 687 #endif 688 /* Both ints can be exactly represented as doubles. Do a 689 floating-point division. */ 690 return PyFloat_FromDouble((double)xi / (double)yi); 662 691 } 663 692 … … 665 694 int_mod(PyIntObject *x, PyIntObject *y) 666 695 { 667 668 669 670 671 672 673 674 675 676 677 678 679 696 long xi, yi; 697 long d, m; 698 CONVERT_TO_LONG(x, xi); 699 CONVERT_TO_LONG(y, yi); 700 switch (i_divmod(xi, yi, &d, &m)) { 701 case DIVMOD_OK: 702 return PyInt_FromLong(m); 703 case DIVMOD_OVERFLOW: 704 return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x, 705 (PyObject *)y); 706 default: 707 return NULL; 708 } 680 709 } 681 710 … … 683 712 int_divmod(PyIntObject *x, PyIntObject *y) 684 713 { 685 686 687 688 689 690 691 692 693 694 695 696 697 714 long xi, yi; 715 long d, m; 716 CONVERT_TO_LONG(x, xi); 717 CONVERT_TO_LONG(y, yi); 718 switch (i_divmod(xi, yi, &d, &m)) { 719 case DIVMOD_OK: 720 return Py_BuildValue("(ll)", d, m); 721 case DIVMOD_OVERFLOW: 722 return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x, 723 (PyObject *)y); 724 default: 725 return NULL; 726 } 698 727 } 699 728 … … 701 730 int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z) 702 731 { 703 register long iv, iw, iz=0, ix, temp, prev; 704 CONVERT_TO_LONG(v, iv); 705 CONVERT_TO_LONG(w, iw); 706 if (iw < 0) { 707 if ((PyObject *)z != Py_None) { 708 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " 709 "cannot be negative when 3rd argument specified"); 710 return NULL; 711 } 712 /* Return a float. This works because we know that 713 this calls float_pow() which converts its 714 arguments to double. */ 715 return PyFloat_Type.tp_as_number->nb_power( 716 (PyObject *)v, (PyObject *)w, (PyObject *)z); 717 } 718 if ((PyObject *)z != Py_None) { 719 CONVERT_TO_LONG(z, iz); 720 if (iz == 0) { 721 PyErr_SetString(PyExc_ValueError, 722 "pow() 3rd argument cannot be 0"); 723 return NULL; 724 } 725 } 726 /* 727 * XXX: The original exponentiation code stopped looping 728 * when temp hit zero; this code will continue onwards 729 * unnecessarily, but at least it won't cause any errors. 730 * Hopefully the speed improvement from the fast exponentiation 731 * will compensate for the slight inefficiency. 732 * XXX: Better handling of overflows is desperately needed. 733 */ 734 temp = iv; 735 ix = 1; 736 while (iw > 0) { 737 prev = ix; /* Save value for overflow check */ 738 if (iw & 1) { 739 ix = ix*temp; 740 if (temp == 0) 741 break; /* Avoid ix / 0 */ 742 if (ix / temp != prev) { 743 return PyLong_Type.tp_as_number->nb_power( 744 (PyObject *)v, 745 (PyObject *)w, 746 (PyObject *)z); 747 } 748 } 749 iw >>= 1; /* Shift exponent down by 1 bit */ 750 if (iw==0) break; 751 prev = temp; 752 temp *= temp; /* Square the value of temp */ 753 if (prev != 0 && temp / prev != prev) { 754 return PyLong_Type.tp_as_number->nb_power( 755 (PyObject *)v, (PyObject *)w, (PyObject *)z); 756 } 757 if (iz) { 758 /* If we did a multiplication, perform a modulo */ 759 ix = ix % iz; 760 temp = temp % iz; 761 } 762 } 763 if (iz) { 764 long div, mod; 765 switch (i_divmod(ix, iz, &div, &mod)) { 766 case DIVMOD_OK: 767 ix = mod; 768 break; 769 case DIVMOD_OVERFLOW: 770 return PyLong_Type.tp_as_number->nb_power( 771 (PyObject *)v, (PyObject *)w, (PyObject *)z); 772 default: 773 return NULL; 774 } 775 } 776 return PyInt_FromLong(ix); 732 register long iv, iw, iz=0, ix, temp, prev; 733 CONVERT_TO_LONG(v, iv); 734 CONVERT_TO_LONG(w, iw); 735 if (iw < 0) { 736 if ((PyObject *)z != Py_None) { 737 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " 738 "cannot be negative when 3rd argument specified"); 739 return NULL; 740 } 741 /* Return a float. This works because we know that 742 this calls float_pow() which converts its 743 arguments to double. */ 744 return PyFloat_Type.tp_as_number->nb_power( 745 (PyObject *)v, (PyObject *)w, (PyObject *)z); 746 } 747 if ((PyObject *)z != Py_None) { 748 CONVERT_TO_LONG(z, iz); 749 if (iz == 0) { 750 PyErr_SetString(PyExc_ValueError, 751 "pow() 3rd argument cannot be 0"); 752 return NULL; 753 } 754 } 755 /* 756 * XXX: The original exponentiation code stopped looping 757 * when temp hit zero; this code will continue onwards 758 * unnecessarily, but at least it won't cause any errors. 759 * Hopefully the speed improvement from the fast exponentiation 760 * will compensate for the slight inefficiency. 761 * XXX: Better handling of overflows is desperately needed. 762 */ 763 temp = iv; 764 ix = 1; 765 while (iw > 0) { 766 prev = ix; /* Save value for overflow check */ 767 if (iw & 1) { 768 /* 769 * The (unsigned long) cast below ensures that the multiplication 770 * is interpreted as an unsigned operation rather than a signed one 771 * (C99 6.3.1.8p1), thus avoiding the perils of undefined behaviour 772 * from signed arithmetic overflow (C99 6.5p5). See issue #12973. 773 */ 774 ix = (unsigned long)ix * temp; 775 if (temp == 0) 776 break; /* Avoid ix / 0 */ 777 if (ix / temp != prev) { 778 return PyLong_Type.tp_as_number->nb_power( 779 (PyObject *)v, 780 (PyObject *)w, 781 (PyObject *)z); 782 } 783 } 784 iw >>= 1; /* Shift exponent down by 1 bit */ 785 if (iw==0) break; 786 prev = temp; 787 temp = (unsigned long)temp * temp; /* Square the value of temp */ 788 if (prev != 0 && temp / prev != prev) { 789 return PyLong_Type.tp_as_number->nb_power( 790 (PyObject *)v, (PyObject *)w, (PyObject *)z); 791 } 792 if (iz) { 793 /* If we did a multiplication, perform a modulo */ 794 ix = ix % iz; 795 temp = temp % iz; 796 } 797 } 798 if (iz) { 799 long div, mod; 800 switch (i_divmod(ix, iz, &div, &mod)) { 801 case DIVMOD_OK: 802 ix = mod; 803 break; 804 case DIVMOD_OVERFLOW: 805 return PyLong_Type.tp_as_number->nb_power( 806 (PyObject *)v, (PyObject *)w, (PyObject *)z); 807 default: 808 return NULL; 809 } 810 } 811 return PyInt_FromLong(ix); 777 812 } 778 813 … … 780 815 int_neg(PyIntObject *v) 781 816 { 782 783 784 785 786 787 788 789 790 791 792 793 794 817 register long a; 818 a = v->ob_ival; 819 /* check for overflow */ 820 if (UNARY_NEG_WOULD_OVERFLOW(a)) { 821 PyObject *o = PyLong_FromLong(a); 822 if (o != NULL) { 823 PyObject *result = PyNumber_Negative(o); 824 Py_DECREF(o); 825 return result; 826 } 827 return NULL; 828 } 829 return PyInt_FromLong(-a); 795 830 } 796 831 … … 798 833 int_abs(PyIntObject *v) 799 834 { 800 801 802 803 835 if (v->ob_ival >= 0) 836 return int_int(v); 837 else 838 return int_neg(v); 804 839 } 805 840 … … 807 842 int_nonzero(PyIntObject *v) 808 843 { 809 844 return v->ob_ival != 0; 810 845 } 811 846 … … 813 848 int_invert(PyIntObject *v) 814 849 { 815 850 return PyInt_FromLong(~v->ob_ival); 816 851 } 817 852 … … 819 854 int_lshift(PyIntObject *v, PyIntObject *w) 820 855 { 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 856 long a, b, c; 857 PyObject *vv, *ww, *result; 858 859 CONVERT_TO_LONG(v, a); 860 CONVERT_TO_LONG(w, b); 861 if (b < 0) { 862 PyErr_SetString(PyExc_ValueError, "negative shift count"); 863 return NULL; 864 } 865 if (a == 0 || b == 0) 866 return int_int(v); 867 if (b >= LONG_BIT) { 868 vv = PyLong_FromLong(PyInt_AS_LONG(v)); 869 if (vv == NULL) 870 return NULL; 871 ww = PyLong_FromLong(PyInt_AS_LONG(w)); 872 if (ww == NULL) { 873 Py_DECREF(vv); 874 return NULL; 875 } 876 result = PyNumber_Lshift(vv, ww); 877 Py_DECREF(vv); 878 Py_DECREF(ww); 879 return result; 880 } 881 c = a << b; 882 if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) { 883 vv = PyLong_FromLong(PyInt_AS_LONG(v)); 884 if (vv == NULL) 885 return NULL; 886 ww = PyLong_FromLong(PyInt_AS_LONG(w)); 887 if (ww == NULL) { 888 Py_DECREF(vv); 889 return NULL; 890 } 891 result = PyNumber_Lshift(vv, ww); 892 Py_DECREF(vv); 893 Py_DECREF(ww); 894 return result; 895 } 896 return PyInt_FromLong(c); 862 897 } 863 898 … … 865 900 int_rshift(PyIntObject *v, PyIntObject *w) 866 901 { 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 902 register long a, b; 903 CONVERT_TO_LONG(v, a); 904 CONVERT_TO_LONG(w, b); 905 if (b < 0) { 906 PyErr_SetString(PyExc_ValueError, "negative shift count"); 907 return NULL; 908 } 909 if (a == 0 || b == 0) 910 return int_int(v); 911 if (b >= LONG_BIT) { 912 if (a < 0) 913 a = -1; 914 else 915 a = 0; 916 } 917 else { 918 a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b); 919 } 920 return PyInt_FromLong(a); 886 921 } 887 922 … … 889 924 int_and(PyIntObject *v, PyIntObject *w) 890 925 { 891 892 893 894 926 register long a, b; 927 CONVERT_TO_LONG(v, a); 928 CONVERT_TO_LONG(w, b); 929 return PyInt_FromLong(a & b); 895 930 } 896 931 … … 898 933 int_xor(PyIntObject *v, PyIntObject *w) 899 934 { 900 901 902 903 935 register long a, b; 936 CONVERT_TO_LONG(v, a); 937 CONVERT_TO_LONG(w, b); 938 return PyInt_FromLong(a ^ b); 904 939 } 905 940 … … 907 942 int_or(PyIntObject *v, PyIntObject *w) 908 943 { 909 910 911 912 944 register long a, b; 945 CONVERT_TO_LONG(v, a); 946 CONVERT_TO_LONG(w, b); 947 return PyInt_FromLong(a | b); 913 948 } 914 949 … … 916 951 int_coerce(PyObject **pv, PyObject **pw) 917 952 { 918 919 920 921 922 923 953 if (PyInt_Check(*pw)) { 954 Py_INCREF(*pv); 955 Py_INCREF(*pw); 956 return 0; 957 } 958 return 1; /* Can't do it */ 924 959 } 925 960 … … 927 962 int_int(PyIntObject *v) 928 963 { 929 930 931 932 933 964 if (PyInt_CheckExact(v)) 965 Py_INCREF(v); 966 else 967 v = (PyIntObject *)PyInt_FromLong(v->ob_ival); 968 return (PyObject *)v; 934 969 } 935 970 … … 937 972 int_long(PyIntObject *v) 938 973 { 939 return PyLong_FromLong((v -> ob_ival)); 940 } 974 return PyLong_FromLong((v -> ob_ival)); 975 } 976 977 static const unsigned char BitLengthTable[32] = { 978 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 979 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 980 }; 981 982 static int 983 bits_in_ulong(unsigned long d) 984 { 985 int d_bits = 0; 986 while (d >= 32) { 987 d_bits += 6; 988 d >>= 6; 989 } 990 d_bits += (int)BitLengthTable[d]; 991 return d_bits; 992 } 993 994 #if 8*SIZEOF_LONG-1 <= DBL_MANT_DIG 995 /* Every Python int can be exactly represented as a float. */ 941 996 942 997 static PyObject * 943 998 int_float(PyIntObject *v) 944 999 { 945 return PyFloat_FromDouble((double)(v -> ob_ival)); 946 } 1000 return PyFloat_FromDouble((double)(v -> ob_ival)); 1001 } 1002 1003 #else 1004 /* Here not all Python ints are exactly representable as floats, so we may 1005 have to round. We do this manually, since the C standards don't specify 1006 whether converting an integer to a float rounds up or down */ 1007 1008 static PyObject * 1009 int_float(PyIntObject *v) 1010 { 1011 unsigned long abs_ival, lsb; 1012 int round_up; 1013 1014 if (v->ob_ival < 0) 1015 abs_ival = 0U-(unsigned long)v->ob_ival; 1016 else 1017 abs_ival = (unsigned long)v->ob_ival; 1018 if (abs_ival < (1L << DBL_MANT_DIG)) 1019 /* small integer; no need to round */ 1020 return PyFloat_FromDouble((double)v->ob_ival); 1021 1022 /* Round abs_ival to MANT_DIG significant bits, using the 1023 round-half-to-even rule. abs_ival & lsb picks out the 'rounding' 1024 bit: the first bit after the most significant MANT_DIG bits of 1025 abs_ival. We round up if this bit is set, provided that either: 1026 1027 (1) abs_ival isn't exactly halfway between two floats, in which 1028 case at least one of the bits following the rounding bit must be 1029 set; i.e., abs_ival & lsb-1 != 0, or: 1030 1031 (2) the resulting rounded value has least significant bit 0; or 1032 in other words the bit above the rounding bit is set (this is the 1033 'to-even' bit of round-half-to-even); i.e., abs_ival & 2*lsb != 0 1034 1035 The condition "(1) or (2)" equates to abs_ival & 3*lsb-1 != 0. */ 1036 1037 lsb = 1L << (bits_in_ulong(abs_ival)-DBL_MANT_DIG-1); 1038 round_up = (abs_ival & lsb) && (abs_ival & (3*lsb-1)); 1039 abs_ival &= -2*lsb; 1040 if (round_up) 1041 abs_ival += 2*lsb; 1042 return PyFloat_FromDouble(v->ob_ival < 0 ? 1043 -(double)abs_ival : 1044 (double)abs_ival); 1045 } 1046 1047 #endif 947 1048 948 1049 static PyObject * 949 1050 int_oct(PyIntObject *v) 950 1051 { 951 1052 return _PyInt_Format(v, 8, 0); 952 1053 } 953 1054 … … 955 1056 int_hex(PyIntObject *v) 956 1057 { 957 1058 return _PyInt_Format(v, 16, 0); 958 1059 } 959 1060 … … 964 1065 int_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 965 1066 { 966 PyObject *x = NULL; 967 int base = -909; 968 static char *kwlist[] = {"x", "base", 0}; 969 970 if (type != &PyInt_Type) 971 return int_subtype_new(type, args, kwds); /* Wimp out */ 972 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, 973 &x, &base)) 974 return NULL; 975 if (x == NULL) 976 return PyInt_FromLong(0L); 977 if (base == -909) 978 return PyNumber_Int(x); 979 if (PyString_Check(x)) { 980 /* Since PyInt_FromString doesn't have a length parameter, 981 * check here for possible NULs in the string. */ 982 char *string = PyString_AS_STRING(x); 983 if (strlen(string) != PyString_Size(x)) { 984 /* create a repr() of the input string, 985 * just like PyInt_FromString does */ 986 PyObject *srepr; 987 srepr = PyObject_Repr(x); 988 if (srepr == NULL) 989 return NULL; 990 PyErr_Format(PyExc_ValueError, 991 "invalid literal for int() with base %d: %s", 992 base, PyString_AS_STRING(srepr)); 993 Py_DECREF(srepr); 994 return NULL; 995 } 996 return PyInt_FromString(string, NULL, base); 997 } 1067 PyObject *x = NULL; 1068 int base = -909; 1069 static char *kwlist[] = {"x", "base", 0}; 1070 1071 if (type != &PyInt_Type) 1072 return int_subtype_new(type, args, kwds); /* Wimp out */ 1073 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, 1074 &x, &base)) 1075 return NULL; 1076 if (x == NULL) { 1077 if (base != -909) { 1078 PyErr_SetString(PyExc_TypeError, 1079 "int() missing string argument"); 1080 return NULL; 1081 } 1082 return PyInt_FromLong(0L); 1083 } 1084 if (base == -909) 1085 return PyNumber_Int(x); 1086 if (PyString_Check(x)) { 1087 /* Since PyInt_FromString doesn't have a length parameter, 1088 * check here for possible NULs in the string. */ 1089 char *string = PyString_AS_STRING(x); 1090 if (strlen(string) != PyString_Size(x)) { 1091 /* create a repr() of the input string, 1092 * just like PyInt_FromString does */ 1093 PyObject *srepr; 1094 srepr = PyObject_Repr(x); 1095 if (srepr == NULL) 1096 return NULL; 1097 PyErr_Format(PyExc_ValueError, 1098 "invalid literal for int() with base %d: %s", 1099 base, PyString_AS_STRING(srepr)); 1100 Py_DECREF(srepr); 1101 return NULL; 1102 } 1103 return PyInt_FromString(string, NULL, base); 1104 } 998 1105 #ifdef Py_USING_UNICODE 999 1000 1001 1002 1003 #endif 1004 1005 1006 1106 if (PyUnicode_Check(x)) 1107 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x), 1108 PyUnicode_GET_SIZE(x), 1109 base); 1110 #endif 1111 PyErr_SetString(PyExc_TypeError, 1112 "int() can't convert non-string with explicit base"); 1113 return NULL; 1007 1114 } 1008 1115 … … 1015 1122 int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 1016 1123 { 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1124 PyObject *tmp, *newobj; 1125 long ival; 1126 1127 assert(PyType_IsSubtype(type, &PyInt_Type)); 1128 tmp = int_new(&PyInt_Type, args, kwds); 1129 if (tmp == NULL) 1130 return NULL; 1131 if (!PyInt_Check(tmp)) { 1132 ival = PyLong_AsLong(tmp); 1133 if (ival == -1 && PyErr_Occurred()) { 1134 Py_DECREF(tmp); 1135 return NULL; 1136 } 1137 } else { 1138 ival = ((PyIntObject *)tmp)->ob_ival; 1139 } 1140 1141 newobj = type->tp_alloc(type, 0); 1142 if (newobj == NULL) { 1143 Py_DECREF(tmp); 1144 return NULL; 1145 } 1146 ((PyIntObject *)newobj)->ob_ival = ival; 1147 Py_DECREF(tmp); 1148 return newobj; 1042 1149 } 1043 1150 … … 1045 1152 int_getnewargs(PyIntObject *v) 1046 1153 { 1047 return Py_BuildValue("(l)", v->ob_ival); 1048 } 1049 1050 static PyObject * 1051 int_getN(PyIntObject *v, void *context) { 1052 return PyInt_FromLong((Py_intptr_t)context); 1154 return Py_BuildValue("(l)", v->ob_ival); 1155 } 1156 1157 static PyObject * 1158 int_get0(PyIntObject *v, void *context) { 1159 return PyInt_FromLong(0L); 1160 } 1161 1162 static PyObject * 1163 int_get1(PyIntObject *v, void *context) { 1164 return PyInt_FromLong(1L); 1165 } 1166 1167 /* Convert an integer to a decimal string. On many platforms, this 1168 will be significantly faster than the general arbitrary-base 1169 conversion machinery in _PyInt_Format, thanks to optimization 1170 opportunities offered by division by a compile-time constant. */ 1171 static PyObject * 1172 int_to_decimal_string(PyIntObject *v) { 1173 char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend; 1174 long n = v->ob_ival; 1175 unsigned long absn; 1176 p = bufend = buf + sizeof(buf); 1177 absn = n < 0 ? 0UL - n : n; 1178 do { 1179 *--p = '0' + (char)(absn % 10); 1180 absn /= 10; 1181 } while (absn); 1182 if (n < 0) 1183 *--p = '-'; 1184 return PyString_FromStringAndSize(p, bufend - p); 1053 1185 } 1054 1186 … … 1060 1192 _PyInt_Format(PyIntObject *v, int base, int newstyle) 1061 1193 { 1062 /* There are no doubt many, many ways to optimize this, using code 1063 similar to _PyLong_Format */ 1064 long n = v->ob_ival; 1065 int negative = n < 0; 1066 int is_zero = n == 0; 1067 1068 /* For the reasoning behind this size, see 1069 http://c-faq.com/misc/hexio.html. Then, add a few bytes for 1070 the possible sign and prefix "0[box]" */ 1071 char buf[sizeof(n)*CHAR_BIT+6]; 1072 1073 /* Start by pointing to the end of the buffer. We fill in from 1074 the back forward. */ 1075 char* p = &buf[sizeof(buf)]; 1076 1077 assert(base >= 2 && base <= 36); 1078 1079 do { 1080 /* I'd use i_divmod, except it doesn't produce the results 1081 I want when n is negative. So just duplicate the salient 1082 part here. */ 1083 long div = n / base; 1084 long mod = n - div * base; 1085 1086 /* convert abs(mod) to the right character in [0-9, a-z] */ 1087 char cdigit = (char)(mod < 0 ? -mod : mod); 1088 cdigit += (cdigit < 10) ? '0' : 'a'-10; 1089 *--p = cdigit; 1090 1091 n = div; 1092 } while(n); 1093 1094 if (base == 2) { 1095 *--p = 'b'; 1096 *--p = '0'; 1097 } 1098 else if (base == 8) { 1099 if (newstyle) { 1100 *--p = 'o'; 1101 *--p = '0'; 1102 } 1103 else 1104 if (!is_zero) 1105 *--p = '0'; 1106 } 1107 else if (base == 16) { 1108 *--p = 'x'; 1109 *--p = '0'; 1110 } 1111 else if (base != 10) { 1112 *--p = '#'; 1113 *--p = '0' + base%10; 1114 if (base > 10) 1115 *--p = '0' + base/10; 1116 } 1117 if (negative) 1118 *--p = '-'; 1119 1120 return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p); 1194 /* There are no doubt many, many ways to optimize this, using code 1195 similar to _PyLong_Format */ 1196 long n = v->ob_ival; 1197 int negative = n < 0; 1198 int is_zero = n == 0; 1199 1200 /* For the reasoning behind this size, see 1201 http://c-faq.com/misc/hexio.html. Then, add a few bytes for 1202 the possible sign and prefix "0[box]" */ 1203 char buf[sizeof(n)*CHAR_BIT+6]; 1204 1205 /* Start by pointing to the end of the buffer. We fill in from 1206 the back forward. */ 1207 char* p = &buf[sizeof(buf)]; 1208 1209 assert(base >= 2 && base <= 36); 1210 1211 /* Special case base 10, for speed */ 1212 if (base == 10) 1213 return int_to_decimal_string(v); 1214 1215 do { 1216 /* I'd use i_divmod, except it doesn't produce the results 1217 I want when n is negative. So just duplicate the salient 1218 part here. */ 1219 long div = n / base; 1220 long mod = n - div * base; 1221 1222 /* convert abs(mod) to the right character in [0-9, a-z] */ 1223 char cdigit = (char)(mod < 0 ? -mod : mod); 1224 cdigit += (cdigit < 10) ? '0' : 'a'-10; 1225 *--p = cdigit; 1226 1227 n = div; 1228 } while(n); 1229 1230 if (base == 2) { 1231 *--p = 'b'; 1232 *--p = '0'; 1233 } 1234 else if (base == 8) { 1235 if (newstyle) { 1236 *--p = 'o'; 1237 *--p = '0'; 1238 } 1239 else 1240 if (!is_zero) 1241 *--p = '0'; 1242 } 1243 else if (base == 16) { 1244 *--p = 'x'; 1245 *--p = '0'; 1246 } 1247 else { 1248 *--p = '#'; 1249 *--p = '0' + base%10; 1250 if (base > 10) 1251 *--p = '0' + base/10; 1252 } 1253 if (negative) 1254 *--p = '-'; 1255 1256 return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p); 1121 1257 } 1122 1258 … … 1124 1260 int__format__(PyObject *self, PyObject *args) 1125 1261 { 1126 PyObject *format_spec; 1127 1128 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) 1129 return NULL; 1130 if (PyBytes_Check(format_spec)) 1131 return _PyInt_FormatAdvanced(self, 1132 PyBytes_AS_STRING(format_spec), 1133 PyBytes_GET_SIZE(format_spec)); 1134 if (PyUnicode_Check(format_spec)) { 1135 /* Convert format_spec to a str */ 1136 PyObject *result; 1137 PyObject *str_spec = PyObject_Str(format_spec); 1138 1139 if (str_spec == NULL) 1140 return NULL; 1141 1142 result = _PyInt_FormatAdvanced(self, 1143 PyBytes_AS_STRING(str_spec), 1144 PyBytes_GET_SIZE(str_spec)); 1145 1146 Py_DECREF(str_spec); 1147 return result; 1148 } 1149 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode"); 1150 return NULL; 1151 } 1262 PyObject *format_spec; 1263 1264 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) 1265 return NULL; 1266 if (PyBytes_Check(format_spec)) 1267 return _PyInt_FormatAdvanced(self, 1268 PyBytes_AS_STRING(format_spec), 1269 PyBytes_GET_SIZE(format_spec)); 1270 if (PyUnicode_Check(format_spec)) { 1271 /* Convert format_spec to a str */ 1272 PyObject *result; 1273 PyObject *str_spec = PyObject_Str(format_spec); 1274 1275 if (str_spec == NULL) 1276 return NULL; 1277 1278 result = _PyInt_FormatAdvanced(self, 1279 PyBytes_AS_STRING(str_spec), 1280 PyBytes_GET_SIZE(str_spec)); 1281 1282 Py_DECREF(str_spec); 1283 return result; 1284 } 1285 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode"); 1286 return NULL; 1287 } 1288 1289 static PyObject * 1290 int_bit_length(PyIntObject *v) 1291 { 1292 unsigned long n; 1293 1294 if (v->ob_ival < 0) 1295 /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */ 1296 n = 0U-(unsigned long)v->ob_ival; 1297 else 1298 n = (unsigned long)v->ob_ival; 1299 1300 return PyInt_FromLong(bits_in_ulong(n)); 1301 } 1302 1303 PyDoc_STRVAR(int_bit_length_doc, 1304 "int.bit_length() -> int\n\ 1305 \n\ 1306 Number of bits necessary to represent self in binary.\n\ 1307 >>> bin(37)\n\ 1308 '0b100101'\n\ 1309 >>> (37).bit_length()\n\ 1310 6"); 1152 1311 1153 1312 #if 0 … … 1155 1314 int_is_finite(PyObject *v) 1156 1315 { 1157 1316 Py_RETURN_TRUE; 1158 1317 } 1159 1318 #endif 1160 1319 1161 1320 static PyMethodDef int_methods[] = { 1162 {"conjugate", (PyCFunction)int_int, METH_NOARGS, 1163 "Returns self, the complex conjugate of any int."}, 1321 {"conjugate", (PyCFunction)int_int, METH_NOARGS, 1322 "Returns self, the complex conjugate of any int."}, 1323 {"bit_length", (PyCFunction)int_bit_length, METH_NOARGS, 1324 int_bit_length_doc}, 1164 1325 #if 0 1165 {"is_finite", (PyCFunction)int_is_finite,METH_NOARGS,1166 1167 #endif 1168 {"__trunc__", (PyCFunction)int_int,METH_NOARGS,1169 1170 {"__getnewargs__", (PyCFunction)int_getnewargs,METH_NOARGS},1171 1172 {NULL, NULL}/* sentinel */1326 {"is_finite", (PyCFunction)int_is_finite, METH_NOARGS, 1327 "Returns always True."}, 1328 #endif 1329 {"__trunc__", (PyCFunction)int_int, METH_NOARGS, 1330 "Truncating an Integral returns itself."}, 1331 {"__getnewargs__", (PyCFunction)int_getnewargs, METH_NOARGS}, 1332 {"__format__", (PyCFunction)int__format__, METH_VARARGS}, 1333 {NULL, NULL} /* sentinel */ 1173 1334 }; 1174 1335 1175 1336 static PyGetSetDef int_getset[] = { 1176 {"real", 1177 1178 1179 1180 {"imag", 1181 (getter)int_getN, (setter)NULL,1182 1183 (void*)0},1184 {"numerator", 1185 1186 1187 1188 {"denominator", 1189 (getter)int_getN, (setter)NULL,1190 1191 (void*)1},1192 1337 {"real", 1338 (getter)int_int, (setter)NULL, 1339 "the real part of a complex number", 1340 NULL}, 1341 {"imag", 1342 (getter)int_get0, (setter)NULL, 1343 "the imaginary part of a complex number", 1344 NULL}, 1345 {"numerator", 1346 (getter)int_int, (setter)NULL, 1347 "the numerator of a rational number in lowest terms", 1348 NULL}, 1349 {"denominator", 1350 (getter)int_get1, (setter)NULL, 1351 "the denominator of a rational number in lowest terms", 1352 NULL}, 1353 {NULL} /* Sentinel */ 1193 1354 }; 1194 1355 1195 1356 PyDoc_STRVAR(int_doc, 1196 "int(x[, base]) -> integer\n\ 1357 "int(x=0) -> int or long\n\ 1358 int(x, base=10) -> int or long\n\ 1197 1359 \n\ 1198 Convert a string or number to an integer, if possible. A floating point\n\ 1199 argument will be truncated towards zero (this does not include a string\n\ 1200 representation of a floating point number!) When converting a string, use\n\ 1201 the optional base. It is an error to supply a base when converting a\n\ 1202 non-string. If base is zero, the proper base is guessed based on the\n\ 1203 string content. If the argument is outside the integer range a\n\ 1204 long object will be returned instead."); 1360 Convert a number or string to an integer, or return 0 if no arguments\n\ 1361 are given. If x is floating point, the conversion truncates towards zero.\n\ 1362 If x is outside the integer range, the function returns a long instead.\n\ 1363 \n\ 1364 If x is not a number or if base is given, then x must be a string or\n\ 1365 Unicode object representing an integer literal in the given base. The\n\ 1366 literal can be preceded by '+' or '-' and be surrounded by whitespace.\n\ 1367 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to\n\ 1368 interpret the base from the string as an integer literal.\n\ 1369 >>> int('0b100', base=0)\n\ 1370 4"); 1205 1371 1206 1372 static PyNumberMethods int_as_number = { 1207 (binaryfunc)int_add,/*nb_add*/1208 (binaryfunc)int_sub,/*nb_subtract*/1209 (binaryfunc)int_mul,/*nb_multiply*/1210 1211 (binaryfunc)int_mod,/*nb_remainder*/1212 (binaryfunc)int_divmod,/*nb_divmod*/1213 (ternaryfunc)int_pow,/*nb_power*/1214 (unaryfunc)int_neg,/*nb_negative*/1215 (unaryfunc)int_int,/*nb_positive*/1216 (unaryfunc)int_abs,/*nb_absolute*/1217 (inquiry)int_nonzero,/*nb_nonzero*/1218 (unaryfunc)int_invert,/*nb_invert*/1219 (binaryfunc)int_lshift,/*nb_lshift*/1220 (binaryfunc)int_rshift,/*nb_rshift*/1221 (binaryfunc)int_and,/*nb_and*/1222 (binaryfunc)int_xor,/*nb_xor*/1223 (binaryfunc)int_or,/*nb_or*/1224 int_coerce,/*nb_coerce*/1225 (unaryfunc)int_int,/*nb_int*/1226 (unaryfunc)int_long,/*nb_long*/1227 (unaryfunc)int_float,/*nb_float*/1228 (unaryfunc)int_oct,/*nb_oct*/1229 (unaryfunc)int_hex,/*nb_hex*/1230 0,/*nb_inplace_add*/1231 0,/*nb_inplace_subtract*/1232 0,/*nb_inplace_multiply*/1233 0,/*nb_inplace_divide*/1234 0,/*nb_inplace_remainder*/1235 0,/*nb_inplace_power*/1236 0,/*nb_inplace_lshift*/1237 0,/*nb_inplace_rshift*/1238 0,/*nb_inplace_and*/1239 0,/*nb_inplace_xor*/1240 0,/*nb_inplace_or*/1241 (binaryfunc)int_div,/* nb_floor_divide */1242 int_true_divide,/* nb_true_divide */1243 0,/* nb_inplace_floor_divide */1244 0,/* nb_inplace_true_divide */1245 (unaryfunc)int_int,/* nb_index */1373 (binaryfunc)int_add, /*nb_add*/ 1374 (binaryfunc)int_sub, /*nb_subtract*/ 1375 (binaryfunc)int_mul, /*nb_multiply*/ 1376 (binaryfunc)int_classic_div, /*nb_divide*/ 1377 (binaryfunc)int_mod, /*nb_remainder*/ 1378 (binaryfunc)int_divmod, /*nb_divmod*/ 1379 (ternaryfunc)int_pow, /*nb_power*/ 1380 (unaryfunc)int_neg, /*nb_negative*/ 1381 (unaryfunc)int_int, /*nb_positive*/ 1382 (unaryfunc)int_abs, /*nb_absolute*/ 1383 (inquiry)int_nonzero, /*nb_nonzero*/ 1384 (unaryfunc)int_invert, /*nb_invert*/ 1385 (binaryfunc)int_lshift, /*nb_lshift*/ 1386 (binaryfunc)int_rshift, /*nb_rshift*/ 1387 (binaryfunc)int_and, /*nb_and*/ 1388 (binaryfunc)int_xor, /*nb_xor*/ 1389 (binaryfunc)int_or, /*nb_or*/ 1390 int_coerce, /*nb_coerce*/ 1391 (unaryfunc)int_int, /*nb_int*/ 1392 (unaryfunc)int_long, /*nb_long*/ 1393 (unaryfunc)int_float, /*nb_float*/ 1394 (unaryfunc)int_oct, /*nb_oct*/ 1395 (unaryfunc)int_hex, /*nb_hex*/ 1396 0, /*nb_inplace_add*/ 1397 0, /*nb_inplace_subtract*/ 1398 0, /*nb_inplace_multiply*/ 1399 0, /*nb_inplace_divide*/ 1400 0, /*nb_inplace_remainder*/ 1401 0, /*nb_inplace_power*/ 1402 0, /*nb_inplace_lshift*/ 1403 0, /*nb_inplace_rshift*/ 1404 0, /*nb_inplace_and*/ 1405 0, /*nb_inplace_xor*/ 1406 0, /*nb_inplace_or*/ 1407 (binaryfunc)int_div, /* nb_floor_divide */ 1408 (binaryfunc)int_true_divide, /* nb_true_divide */ 1409 0, /* nb_inplace_floor_divide */ 1410 0, /* nb_inplace_true_divide */ 1411 (unaryfunc)int_int, /* nb_index */ 1246 1412 }; 1247 1413 1248 1414 PyTypeObject PyInt_Type = { 1249 1250 1251 1252 1253 (destructor)int_dealloc,/* tp_dealloc */1254 (printfunc)int_print,/* tp_print */1255 0,/* tp_getattr */1256 0,/* tp_setattr */1257 (cmpfunc)int_compare,/* tp_compare */1258 (reprfunc)int_repr,/* tp_repr */1259 &int_as_number,/* tp_as_number */1260 0,/* tp_as_sequence */1261 0,/* tp_as_mapping */1262 (hashfunc)int_hash,/* tp_hash */1263 0,/* tp_call */1264 (reprfunc)int_repr,/* tp_str */1265 PyObject_GenericGetAttr,/* tp_getattro */1266 0,/* tp_setattro */1267 0,/* tp_as_buffer */1268 1269 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS,/* tp_flags */1270 int_doc,/* tp_doc */1271 0,/* tp_traverse */1272 0,/* tp_clear */1273 0,/* tp_richcompare */1274 0,/* tp_weaklistoffset */1275 0,/* tp_iter */1276 0,/* tp_iternext */1277 int_methods,/* tp_methods */1278 0,/* tp_members */1279 int_getset,/* tp_getset */1280 0,/* tp_base */1281 0,/* tp_dict */1282 0,/* tp_descr_get */1283 0,/* tp_descr_set */1284 0,/* tp_dictoffset */1285 0,/* tp_init */1286 0,/* tp_alloc */1287 int_new,/* tp_new */1288 (freefunc)int_free,/* tp_free */1415 PyVarObject_HEAD_INIT(&PyType_Type, 0) 1416 "int", 1417 sizeof(PyIntObject), 1418 0, 1419 (destructor)int_dealloc, /* tp_dealloc */ 1420 (printfunc)int_print, /* tp_print */ 1421 0, /* tp_getattr */ 1422 0, /* tp_setattr */ 1423 (cmpfunc)int_compare, /* tp_compare */ 1424 (reprfunc)int_to_decimal_string, /* tp_repr */ 1425 &int_as_number, /* tp_as_number */ 1426 0, /* tp_as_sequence */ 1427 0, /* tp_as_mapping */ 1428 (hashfunc)int_hash, /* tp_hash */ 1429 0, /* tp_call */ 1430 (reprfunc)int_to_decimal_string, /* tp_str */ 1431 PyObject_GenericGetAttr, /* tp_getattro */ 1432 0, /* tp_setattro */ 1433 0, /* tp_as_buffer */ 1434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | 1435 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */ 1436 int_doc, /* tp_doc */ 1437 0, /* tp_traverse */ 1438 0, /* tp_clear */ 1439 0, /* tp_richcompare */ 1440 0, /* tp_weaklistoffset */ 1441 0, /* tp_iter */ 1442 0, /* tp_iternext */ 1443 int_methods, /* tp_methods */ 1444 0, /* tp_members */ 1445 int_getset, /* tp_getset */ 1446 0, /* tp_base */ 1447 0, /* tp_dict */ 1448 0, /* tp_descr_get */ 1449 0, /* tp_descr_set */ 1450 0, /* tp_dictoffset */ 1451 0, /* tp_init */ 1452 0, /* tp_alloc */ 1453 int_new, /* tp_new */ 1454 (freefunc)int_free, /* tp_free */ 1289 1455 }; 1290 1456 … … 1292 1458 _PyInt_Init(void) 1293 1459 { 1294 1295 1460 PyIntObject *v; 1461 int ival; 1296 1462 #if NSMALLNEGINTS + NSMALLPOSINTS > 0 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 #endif 1308 1463 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) { 1464 if (!free_list && (free_list = fill_free_list()) == NULL) 1465 return 0; 1466 /* PyObject_New is inlined */ 1467 v = free_list; 1468 free_list = (PyIntObject *)Py_TYPE(v); 1469 PyObject_INIT(v, &PyInt_Type); 1470 v->ob_ival = ival; 1471 small_ints[ival + NSMALLNEGINTS] = v; 1472 } 1473 #endif 1474 return 1; 1309 1475 } 1310 1476 … … 1312 1478 PyInt_ClearFreeList(void) 1313 1479 { 1314 1315 1316 1317 int u;/* remaining unfreed ints per block */1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1480 PyIntObject *p; 1481 PyIntBlock *list, *next; 1482 int i; 1483 int u; /* remaining unfreed ints per block */ 1484 int freelist_size = 0; 1485 1486 list = block_list; 1487 block_list = NULL; 1488 free_list = NULL; 1489 while (list != NULL) { 1490 u = 0; 1491 for (i = 0, p = &list->objects[0]; 1492 i < N_INTOBJECTS; 1493 i++, p++) { 1494 if (PyInt_CheckExact(p) && p->ob_refcnt != 0) 1495 u++; 1496 } 1497 next = list->next; 1498 if (u) { 1499 list->next = block_list; 1500 block_list = list; 1501 for (i = 0, p = &list->objects[0]; 1502 i < N_INTOBJECTS; 1503 i++, p++) { 1504 if (!PyInt_CheckExact(p) || 1505 p->ob_refcnt == 0) { 1506 Py_TYPE(p) = (struct _typeobject *) 1507 free_list; 1508 free_list = p; 1509 } 1344 1510 #if NSMALLNEGINTS + NSMALLPOSINTS > 0 1345 1346 1347 1348 1349 1350 1351 1352 1353 #endif 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1511 else if (-NSMALLNEGINTS <= p->ob_ival && 1512 p->ob_ival < NSMALLPOSINTS && 1513 small_ints[p->ob_ival + 1514 NSMALLNEGINTS] == NULL) { 1515 Py_INCREF(p); 1516 small_ints[p->ob_ival + 1517 NSMALLNEGINTS] = p; 1518 } 1519 #endif 1520 } 1521 } 1522 else { 1523 PyMem_FREE(list); 1524 } 1525 freelist_size += u; 1526 list = next; 1527 } 1528 1529 return freelist_size; 1364 1530 } 1365 1531 … … 1367 1533 PyInt_Fini(void) 1368 1534 { 1369 1370 1371 1372 int u;/* total unfreed ints per block */1535 PyIntObject *p; 1536 PyIntBlock *list; 1537 int i; 1538 int u; /* total unfreed ints per block */ 1373 1539 1374 1540 #if NSMALLNEGINTS + NSMALLPOSINTS > 0 1375 1376 1377 1378 1379 1380 1381 1382 1383 #endif 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 } 1541 PyIntObject **q; 1542 1543 i = NSMALLNEGINTS + NSMALLPOSINTS; 1544 q = small_ints; 1545 while (--i >= 0) { 1546 Py_XDECREF(*q); 1547 *q++ = NULL; 1548 } 1549 #endif 1550 u = PyInt_ClearFreeList(); 1551 if (!Py_VerboseFlag) 1552 return; 1553 fprintf(stderr, "# cleanup ints"); 1554 if (!u) { 1555 fprintf(stderr, "\n"); 1556 } 1557 else { 1558 fprintf(stderr, 1559 ": %d unfreed int%s\n", 1560 u, u == 1 ? "" : "s"); 1561 } 1562 if (Py_VerboseFlag > 1) { 1563 list = block_list; 1564 while (list != NULL) { 1565 for (i = 0, p = &list->objects[0]; 1566 i < N_INTOBJECTS; 1567 i++, p++) { 1568 if (PyInt_CheckExact(p) && p->ob_refcnt != 0) 1569 /* XXX(twouters) cast refcount to 1570 long until %zd is universally 1571 available 1572 */ 1573 fprintf(stderr, 1574 "# <int at %p, refcnt=%ld, val=%ld>\n", 1575 p, (long)p->ob_refcnt, 1576 p->ob_ival); 1577 } 1578 list = list->next; 1579 } 1580 } 1581 }
Note:
See TracChangeset
for help on using the changeset viewer.