1 #ifndef Py_INTERNAL_LONG_H 2 #define Py_INTERNAL_LONG_H 3 #ifdef __cplusplus 4 extern "C" { 5 #endif 6 7 #ifndef Py_BUILD_CORE 8 # error "this header requires Py_BUILD_CORE define" 9 #endif 10 11 #include "pycore_interp.h" // PyInterpreterState.small_ints 12 #include "pycore_pystate.h" // _PyThreadState_GET() 13 14 /* 15 * Default int base conversion size limitation: Denial of Service prevention. 16 * 17 * Chosen such that this isn't wildly slow on modern hardware and so that 18 * everyone's existing deployed numpy test suite passes before 19 * https://github.com/numpy/numpy/issues/22098 is widely available. 20 * 21 * $ python -m timeit -s 's = * "1"*4300' 'int(s)' 22 * 2000 loops, best of 5: 125 usec per loop 23 * $ python -m timeit -s 's = * "1"*4300; v = int(s)' 'str(v)' 24 * 1000 loops, best of 5: 311 usec per loop 25 * (zen2 cloud VM) 26 * 27 * 4300 decimal digits fits a ~14284 bit number. 28 */ 29 #define _PY_LONG_DEFAULT_MAX_STR_DIGITS 4300 30 /* 31 * Threshold for max digits check. For performance reasons int() and 32 * int.__str__() don't checks values that are smaller than this 33 * threshold. Acts as a guaranteed minimum size limit for bignums that 34 * applications can expect from CPython. 35 * 36 * % python -m timeit -s 's = "1"*640; v = int(s)' 'str(int(s))' 37 * 20000 loops, best of 5: 12 usec per loop 38 * 39 * "640 digits should be enough for anyone." - gps 40 * fits a ~2126 bit decimal number. 41 */ 42 #define _PY_LONG_MAX_STR_DIGITS_THRESHOLD 640 43 44 #if ((_PY_LONG_DEFAULT_MAX_STR_DIGITS != 0) && \ 45 (_PY_LONG_DEFAULT_MAX_STR_DIGITS < _PY_LONG_MAX_STR_DIGITS_THRESHOLD)) 46 # error "_PY_LONG_DEFAULT_MAX_STR_DIGITS smaller than threshold." 47 #endif 48 49 // Don't call this function but _PyLong_GetZero() and _PyLong_GetOne() __PyLong_GetSmallInt_internal(int value)50static inline PyObject* __PyLong_GetSmallInt_internal(int value) 51 { 52 PyInterpreterState *interp = _PyInterpreterState_GET(); 53 assert(-_PY_NSMALLNEGINTS <= value && value < _PY_NSMALLPOSINTS); 54 size_t index = _PY_NSMALLNEGINTS + value; 55 PyObject *obj = (PyObject*)interp->small_ints[index]; 56 // _PyLong_GetZero(), _PyLong_GetOne() and get_small_int() must not be 57 // called before _PyLong_Init() nor after _PyLong_Fini(). 58 assert(obj != NULL); 59 return obj; 60 } 61 62 // Return a borrowed reference to the zero singleton. 63 // The function cannot return NULL. _PyLong_GetZero(void)64static inline PyObject* _PyLong_GetZero(void) 65 { return __PyLong_GetSmallInt_internal(0); } 66 67 // Return a borrowed reference to the one singleton. 68 // The function cannot return NULL. _PyLong_GetOne(void)69static inline PyObject* _PyLong_GetOne(void) 70 { return __PyLong_GetSmallInt_internal(1); } 71 72 #ifdef __cplusplus 73 } 74 #endif 75 #endif /* !Py_INTERNAL_LONG_H */ 76