Optimize.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. /*
  2. * Optional optimisations of built-in functions and methods.
  3. *
  4. * Required replacements of builtins are in Builtins.c.
  5. *
  6. * General object operations and protocols are in ObjectHandling.c.
  7. */
  8. /////////////// append.proto ///////////////
  9. static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x); /*proto*/
  10. /////////////// append ///////////////
  11. //@requires: ListAppend
  12. //@requires: ObjectHandling.c::PyObjectCallMethod1
  13. static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x) {
  14. if (likely(PyList_CheckExact(L))) {
  15. if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return -1;
  16. } else {
  17. PyObject* retval = __Pyx_PyObject_CallMethod1(L, PYIDENT("append"), x);
  18. if (unlikely(!retval))
  19. return -1;
  20. Py_DECREF(retval);
  21. }
  22. return 0;
  23. }
  24. /////////////// ListAppend.proto ///////////////
  25. #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
  26. static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) {
  27. PyListObject* L = (PyListObject*) list;
  28. Py_ssize_t len = Py_SIZE(list);
  29. if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) {
  30. Py_INCREF(x);
  31. PyList_SET_ITEM(list, len, x);
  32. __Pyx_SET_SIZE(list, len + 1);
  33. return 0;
  34. }
  35. return PyList_Append(list, x);
  36. }
  37. #else
  38. #define __Pyx_PyList_Append(L,x) PyList_Append(L,x)
  39. #endif
  40. /////////////// ListCompAppend.proto ///////////////
  41. #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
  42. static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) {
  43. PyListObject* L = (PyListObject*) list;
  44. Py_ssize_t len = Py_SIZE(list);
  45. if (likely(L->allocated > len)) {
  46. Py_INCREF(x);
  47. PyList_SET_ITEM(list, len, x);
  48. __Pyx_SET_SIZE(list, len + 1);
  49. return 0;
  50. }
  51. return PyList_Append(list, x);
  52. }
  53. #else
  54. #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x)
  55. #endif
  56. //////////////////// ListExtend.proto ////////////////////
  57. static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) {
  58. #if CYTHON_COMPILING_IN_CPYTHON
  59. PyObject* none = _PyList_Extend((PyListObject*)L, v);
  60. if (unlikely(!none))
  61. return -1;
  62. Py_DECREF(none);
  63. return 0;
  64. #else
  65. return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v);
  66. #endif
  67. }
  68. /////////////// pop.proto ///////////////
  69. static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L); /*proto*/
  70. #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
  71. static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L); /*proto*/
  72. #define __Pyx_PyObject_Pop(L) (likely(PyList_CheckExact(L)) ? \
  73. __Pyx_PyList_Pop(L) : __Pyx__PyObject_Pop(L))
  74. #else
  75. #define __Pyx_PyList_Pop(L) __Pyx__PyObject_Pop(L)
  76. #define __Pyx_PyObject_Pop(L) __Pyx__PyObject_Pop(L)
  77. #endif
  78. /////////////// pop ///////////////
  79. //@requires: ObjectHandling.c::PyObjectCallMethod0
  80. static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L) {
  81. if (Py_TYPE(L) == &PySet_Type) {
  82. return PySet_Pop(L);
  83. }
  84. return __Pyx_PyObject_CallMethod0(L, PYIDENT("pop"));
  85. }
  86. #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
  87. static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L) {
  88. /* Check that both the size is positive and no reallocation shrinking needs to be done. */
  89. if (likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) {
  90. __Pyx_SET_SIZE(L, Py_SIZE(L) - 1);
  91. return PyList_GET_ITEM(L, PyList_GET_SIZE(L));
  92. }
  93. return CALL_UNBOUND_METHOD(PyList_Type, "pop", L);
  94. }
  95. #endif
  96. /////////////// pop_index.proto ///////////////
  97. static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix); /*proto*/
  98. static PyObject* __Pyx__PyObject_PopIndex(PyObject* L, PyObject* py_ix); /*proto*/
  99. #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
  100. static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t ix); /*proto*/
  101. #define __Pyx_PyObject_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) ( \
  102. (likely(PyList_CheckExact(L) && __Pyx_fits_Py_ssize_t(ix, type, is_signed))) ? \
  103. __Pyx__PyList_PopIndex(L, py_ix, ix) : ( \
  104. (unlikely((py_ix) == Py_None)) ? __Pyx__PyObject_PopNewIndex(L, to_py_func(ix)) : \
  105. __Pyx__PyObject_PopIndex(L, py_ix)))
  106. #define __Pyx_PyList_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) ( \
  107. __Pyx_fits_Py_ssize_t(ix, type, is_signed) ? \
  108. __Pyx__PyList_PopIndex(L, py_ix, ix) : ( \
  109. (unlikely((py_ix) == Py_None)) ? __Pyx__PyObject_PopNewIndex(L, to_py_func(ix)) : \
  110. __Pyx__PyObject_PopIndex(L, py_ix)))
  111. #else
  112. #define __Pyx_PyList_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) \
  113. __Pyx_PyObject_PopIndex(L, py_ix, ix, is_signed, type, to_py_func)
  114. #define __Pyx_PyObject_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) ( \
  115. (unlikely((py_ix) == Py_None)) ? __Pyx__PyObject_PopNewIndex(L, to_py_func(ix)) : \
  116. __Pyx__PyObject_PopIndex(L, py_ix))
  117. #endif
  118. /////////////// pop_index ///////////////
  119. //@requires: ObjectHandling.c::PyObjectCallMethod1
  120. static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix) {
  121. PyObject *r;
  122. if (unlikely(!py_ix)) return NULL;
  123. r = __Pyx__PyObject_PopIndex(L, py_ix);
  124. Py_DECREF(py_ix);
  125. return r;
  126. }
  127. static PyObject* __Pyx__PyObject_PopIndex(PyObject* L, PyObject* py_ix) {
  128. return __Pyx_PyObject_CallMethod1(L, PYIDENT("pop"), py_ix);
  129. }
  130. #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
  131. static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t ix) {
  132. Py_ssize_t size = PyList_GET_SIZE(L);
  133. if (likely(size > (((PyListObject*)L)->allocated >> 1))) {
  134. Py_ssize_t cix = ix;
  135. if (cix < 0) {
  136. cix += size;
  137. }
  138. if (likely(__Pyx_is_valid_index(cix, size))) {
  139. PyObject* v = PyList_GET_ITEM(L, cix);
  140. __Pyx_SET_SIZE(L, Py_SIZE(L) - 1);
  141. size -= 1;
  142. memmove(&PyList_GET_ITEM(L, cix), &PyList_GET_ITEM(L, cix+1), (size_t)(size-cix)*sizeof(PyObject*));
  143. return v;
  144. }
  145. }
  146. if (py_ix == Py_None) {
  147. return __Pyx__PyObject_PopNewIndex(L, PyInt_FromSsize_t(ix));
  148. } else {
  149. return __Pyx__PyObject_PopIndex(L, py_ix);
  150. }
  151. }
  152. #endif
  153. /////////////// dict_getitem_default.proto ///////////////
  154. static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value); /*proto*/
  155. /////////////// dict_getitem_default ///////////////
  156. static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value) {
  157. PyObject* value;
  158. #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY
  159. value = PyDict_GetItemWithError(d, key);
  160. if (unlikely(!value)) {
  161. if (unlikely(PyErr_Occurred()))
  162. return NULL;
  163. value = default_value;
  164. }
  165. Py_INCREF(value);
  166. // avoid C compiler warning about unused utility functions
  167. if ((1));
  168. #else
  169. if (PyString_CheckExact(key) || PyUnicode_CheckExact(key) || PyInt_CheckExact(key)) {
  170. /* these presumably have safe hash functions */
  171. value = PyDict_GetItem(d, key);
  172. if (unlikely(!value)) {
  173. value = default_value;
  174. }
  175. Py_INCREF(value);
  176. }
  177. #endif
  178. else {
  179. if (default_value == Py_None)
  180. value = CALL_UNBOUND_METHOD(PyDict_Type, "get", d, key);
  181. else
  182. value = CALL_UNBOUND_METHOD(PyDict_Type, "get", d, key, default_value);
  183. }
  184. return value;
  185. }
  186. /////////////// dict_setdefault.proto ///////////////
  187. static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, int is_safe_type); /*proto*/
  188. /////////////// dict_setdefault ///////////////
  189. static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value,
  190. CYTHON_UNUSED int is_safe_type) {
  191. PyObject* value;
  192. #if PY_VERSION_HEX >= 0x030400A0
  193. // we keep the method call at the end to avoid "unused" C compiler warnings
  194. if ((1)) {
  195. value = PyDict_SetDefault(d, key, default_value);
  196. if (unlikely(!value)) return NULL;
  197. Py_INCREF(value);
  198. #else
  199. if (is_safe_type == 1 || (is_safe_type == -1 &&
  200. /* the following builtins presumably have repeatably safe and fast hash functions */
  201. #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY
  202. (PyUnicode_CheckExact(key) || PyString_CheckExact(key) || PyLong_CheckExact(key)))) {
  203. value = PyDict_GetItemWithError(d, key);
  204. if (unlikely(!value)) {
  205. if (unlikely(PyErr_Occurred()))
  206. return NULL;
  207. if (unlikely(PyDict_SetItem(d, key, default_value) == -1))
  208. return NULL;
  209. value = default_value;
  210. }
  211. Py_INCREF(value);
  212. #else
  213. (PyString_CheckExact(key) || PyUnicode_CheckExact(key) || PyInt_CheckExact(key) || PyLong_CheckExact(key)))) {
  214. value = PyDict_GetItem(d, key);
  215. if (unlikely(!value)) {
  216. if (unlikely(PyDict_SetItem(d, key, default_value) == -1))
  217. return NULL;
  218. value = default_value;
  219. }
  220. Py_INCREF(value);
  221. #endif
  222. #endif
  223. } else {
  224. value = CALL_UNBOUND_METHOD(PyDict_Type, "setdefault", d, key, default_value);
  225. }
  226. return value;
  227. }
  228. /////////////// py_dict_clear.proto ///////////////
  229. #define __Pyx_PyDict_Clear(d) (PyDict_Clear(d), 0)
  230. /////////////// py_dict_pop.proto ///////////////
  231. static CYTHON_INLINE PyObject *__Pyx_PyDict_Pop(PyObject *d, PyObject *key, PyObject *default_value); /*proto*/
  232. /////////////// py_dict_pop ///////////////
  233. static CYTHON_INLINE PyObject *__Pyx_PyDict_Pop(PyObject *d, PyObject *key, PyObject *default_value) {
  234. #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX > 0x030600B3
  235. if ((1)) {
  236. return _PyDict_Pop(d, key, default_value);
  237. } else
  238. // avoid "function unused" warnings
  239. #endif
  240. if (default_value) {
  241. return CALL_UNBOUND_METHOD(PyDict_Type, "pop", d, key, default_value);
  242. } else {
  243. return CALL_UNBOUND_METHOD(PyDict_Type, "pop", d, key);
  244. }
  245. }
  246. /////////////// dict_iter.proto ///////////////
  247. static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name,
  248. Py_ssize_t* p_orig_length, int* p_is_dict);
  249. static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos,
  250. PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict);
  251. /////////////// dict_iter ///////////////
  252. //@requires: ObjectHandling.c::UnpackTuple2
  253. //@requires: ObjectHandling.c::IterFinish
  254. //@requires: ObjectHandling.c::PyObjectCallMethod0
  255. static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name,
  256. Py_ssize_t* p_orig_length, int* p_source_is_dict) {
  257. is_dict = is_dict || likely(PyDict_CheckExact(iterable));
  258. *p_source_is_dict = is_dict;
  259. if (is_dict) {
  260. #if !CYTHON_COMPILING_IN_PYPY
  261. *p_orig_length = PyDict_Size(iterable);
  262. Py_INCREF(iterable);
  263. return iterable;
  264. #elif PY_MAJOR_VERSION >= 3
  265. // On PyPy3, we need to translate manually a few method names.
  266. // This logic is not needed on CPython thanks to the fast case above.
  267. static PyObject *py_items = NULL, *py_keys = NULL, *py_values = NULL;
  268. PyObject **pp = NULL;
  269. if (method_name) {
  270. const char *name = PyUnicode_AsUTF8(method_name);
  271. if (strcmp(name, "iteritems") == 0) pp = &py_items;
  272. else if (strcmp(name, "iterkeys") == 0) pp = &py_keys;
  273. else if (strcmp(name, "itervalues") == 0) pp = &py_values;
  274. if (pp) {
  275. if (!*pp) {
  276. *pp = PyUnicode_FromString(name + 4);
  277. if (!*pp)
  278. return NULL;
  279. }
  280. method_name = *pp;
  281. }
  282. }
  283. #endif
  284. }
  285. *p_orig_length = 0;
  286. if (method_name) {
  287. PyObject* iter;
  288. iterable = __Pyx_PyObject_CallMethod0(iterable, method_name);
  289. if (!iterable)
  290. return NULL;
  291. #if !CYTHON_COMPILING_IN_PYPY
  292. if (PyTuple_CheckExact(iterable) || PyList_CheckExact(iterable))
  293. return iterable;
  294. #endif
  295. iter = PyObject_GetIter(iterable);
  296. Py_DECREF(iterable);
  297. return iter;
  298. }
  299. return PyObject_GetIter(iterable);
  300. }
  301. static CYTHON_INLINE int __Pyx_dict_iter_next(
  302. PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos,
  303. PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) {
  304. PyObject* next_item;
  305. #if !CYTHON_COMPILING_IN_PYPY
  306. if (source_is_dict) {
  307. PyObject *key, *value;
  308. if (unlikely(orig_length != PyDict_Size(iter_obj))) {
  309. PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration");
  310. return -1;
  311. }
  312. if (unlikely(!PyDict_Next(iter_obj, ppos, &key, &value))) {
  313. return 0;
  314. }
  315. if (pitem) {
  316. PyObject* tuple = PyTuple_New(2);
  317. if (unlikely(!tuple)) {
  318. return -1;
  319. }
  320. Py_INCREF(key);
  321. Py_INCREF(value);
  322. PyTuple_SET_ITEM(tuple, 0, key);
  323. PyTuple_SET_ITEM(tuple, 1, value);
  324. *pitem = tuple;
  325. } else {
  326. if (pkey) {
  327. Py_INCREF(key);
  328. *pkey = key;
  329. }
  330. if (pvalue) {
  331. Py_INCREF(value);
  332. *pvalue = value;
  333. }
  334. }
  335. return 1;
  336. } else if (PyTuple_CheckExact(iter_obj)) {
  337. Py_ssize_t pos = *ppos;
  338. if (unlikely(pos >= PyTuple_GET_SIZE(iter_obj))) return 0;
  339. *ppos = pos + 1;
  340. next_item = PyTuple_GET_ITEM(iter_obj, pos);
  341. Py_INCREF(next_item);
  342. } else if (PyList_CheckExact(iter_obj)) {
  343. Py_ssize_t pos = *ppos;
  344. if (unlikely(pos >= PyList_GET_SIZE(iter_obj))) return 0;
  345. *ppos = pos + 1;
  346. next_item = PyList_GET_ITEM(iter_obj, pos);
  347. Py_INCREF(next_item);
  348. } else
  349. #endif
  350. {
  351. next_item = PyIter_Next(iter_obj);
  352. if (unlikely(!next_item)) {
  353. return __Pyx_IterFinish();
  354. }
  355. }
  356. if (pitem) {
  357. *pitem = next_item;
  358. } else if (pkey && pvalue) {
  359. if (__Pyx_unpack_tuple2(next_item, pkey, pvalue, source_is_dict, source_is_dict, 1))
  360. return -1;
  361. } else if (pkey) {
  362. *pkey = next_item;
  363. } else {
  364. *pvalue = next_item;
  365. }
  366. return 1;
  367. }
  368. /////////////// set_iter.proto ///////////////
  369. static CYTHON_INLINE PyObject* __Pyx_set_iterator(PyObject* iterable, int is_set,
  370. Py_ssize_t* p_orig_length, int* p_source_is_set); /*proto*/
  371. static CYTHON_INLINE int __Pyx_set_iter_next(
  372. PyObject* iter_obj, Py_ssize_t orig_length,
  373. Py_ssize_t* ppos, PyObject **value,
  374. int source_is_set); /*proto*/
  375. /////////////// set_iter ///////////////
  376. //@requires: ObjectHandling.c::IterFinish
  377. static CYTHON_INLINE PyObject* __Pyx_set_iterator(PyObject* iterable, int is_set,
  378. Py_ssize_t* p_orig_length, int* p_source_is_set) {
  379. #if CYTHON_COMPILING_IN_CPYTHON
  380. is_set = is_set || likely(PySet_CheckExact(iterable) || PyFrozenSet_CheckExact(iterable));
  381. *p_source_is_set = is_set;
  382. if (likely(is_set)) {
  383. *p_orig_length = PySet_Size(iterable);
  384. Py_INCREF(iterable);
  385. return iterable;
  386. }
  387. #else
  388. (void)is_set;
  389. *p_source_is_set = 0;
  390. #endif
  391. *p_orig_length = 0;
  392. return PyObject_GetIter(iterable);
  393. }
  394. static CYTHON_INLINE int __Pyx_set_iter_next(
  395. PyObject* iter_obj, Py_ssize_t orig_length,
  396. Py_ssize_t* ppos, PyObject **value,
  397. int source_is_set) {
  398. if (!CYTHON_COMPILING_IN_CPYTHON || unlikely(!source_is_set)) {
  399. *value = PyIter_Next(iter_obj);
  400. if (unlikely(!*value)) {
  401. return __Pyx_IterFinish();
  402. }
  403. (void)orig_length;
  404. (void)ppos;
  405. return 1;
  406. }
  407. #if CYTHON_COMPILING_IN_CPYTHON
  408. if (unlikely(PySet_GET_SIZE(iter_obj) != orig_length)) {
  409. PyErr_SetString(
  410. PyExc_RuntimeError,
  411. "set changed size during iteration");
  412. return -1;
  413. }
  414. {
  415. Py_hash_t hash;
  416. int ret = _PySet_NextEntry(iter_obj, ppos, value, &hash);
  417. // CPython does not raise errors here, only if !isinstance(iter_obj, set/frozenset)
  418. assert (ret != -1);
  419. if (likely(ret)) {
  420. Py_INCREF(*value);
  421. return 1;
  422. }
  423. }
  424. #endif
  425. return 0;
  426. }
  427. /////////////// py_set_discard_unhashable ///////////////
  428. //@requires: Builtins.c::pyfrozenset_new
  429. static int __Pyx_PySet_DiscardUnhashable(PyObject *set, PyObject *key) {
  430. PyObject *tmpkey;
  431. int rv;
  432. if (likely(!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)))
  433. return -1;
  434. PyErr_Clear();
  435. tmpkey = __Pyx_PyFrozenSet_New(key);
  436. if (tmpkey == NULL)
  437. return -1;
  438. rv = PySet_Discard(set, tmpkey);
  439. Py_DECREF(tmpkey);
  440. return rv;
  441. }
  442. /////////////// py_set_discard.proto ///////////////
  443. static CYTHON_INLINE int __Pyx_PySet_Discard(PyObject *set, PyObject *key); /*proto*/
  444. /////////////// py_set_discard ///////////////
  445. //@requires: py_set_discard_unhashable
  446. static CYTHON_INLINE int __Pyx_PySet_Discard(PyObject *set, PyObject *key) {
  447. int found = PySet_Discard(set, key);
  448. // Convert *key* to frozenset if necessary
  449. if (unlikely(found < 0)) {
  450. found = __Pyx_PySet_DiscardUnhashable(set, key);
  451. }
  452. // note: returns -1 on error, 0 (not found) or 1 (found) otherwise => error check for -1 or < 0 works
  453. return found;
  454. }
  455. /////////////// py_set_remove.proto ///////////////
  456. static CYTHON_INLINE int __Pyx_PySet_Remove(PyObject *set, PyObject *key); /*proto*/
  457. /////////////// py_set_remove ///////////////
  458. //@requires: py_set_discard_unhashable
  459. static int __Pyx_PySet_RemoveNotFound(PyObject *set, PyObject *key, int found) {
  460. // Convert *key* to frozenset if necessary
  461. if (unlikely(found < 0)) {
  462. found = __Pyx_PySet_DiscardUnhashable(set, key);
  463. }
  464. if (likely(found == 0)) {
  465. // Not found
  466. PyObject *tup;
  467. tup = PyTuple_Pack(1, key);
  468. if (!tup)
  469. return -1;
  470. PyErr_SetObject(PyExc_KeyError, tup);
  471. Py_DECREF(tup);
  472. return -1;
  473. }
  474. // note: returns -1 on error, 0 (not found) or 1 (found) otherwise => error check for -1 or < 0 works
  475. return found;
  476. }
  477. static CYTHON_INLINE int __Pyx_PySet_Remove(PyObject *set, PyObject *key) {
  478. int found = PySet_Discard(set, key);
  479. if (unlikely(found != 1)) {
  480. // note: returns -1 on error, 0 (not found) or 1 (found) otherwise => error check for -1 or < 0 works
  481. return __Pyx_PySet_RemoveNotFound(set, key, found);
  482. }
  483. return 0;
  484. }
  485. /////////////// unicode_iter.proto ///////////////
  486. static CYTHON_INLINE int __Pyx_init_unicode_iteration(
  487. PyObject* ustring, Py_ssize_t *length, void** data, int *kind); /* proto */
  488. /////////////// unicode_iter ///////////////
  489. static CYTHON_INLINE int __Pyx_init_unicode_iteration(
  490. PyObject* ustring, Py_ssize_t *length, void** data, int *kind) {
  491. #if CYTHON_PEP393_ENABLED
  492. if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return -1;
  493. *kind = PyUnicode_KIND(ustring);
  494. *length = PyUnicode_GET_LENGTH(ustring);
  495. *data = PyUnicode_DATA(ustring);
  496. #else
  497. *kind = 0;
  498. *length = PyUnicode_GET_SIZE(ustring);
  499. *data = (void*)PyUnicode_AS_UNICODE(ustring);
  500. #endif
  501. return 0;
  502. }
  503. /////////////// pyobject_as_double.proto ///////////////
  504. static double __Pyx__PyObject_AsDouble(PyObject* obj); /* proto */
  505. #if CYTHON_COMPILING_IN_PYPY
  506. #define __Pyx_PyObject_AsDouble(obj) \
  507. (likely(PyFloat_CheckExact(obj)) ? PyFloat_AS_DOUBLE(obj) : \
  508. likely(PyInt_CheckExact(obj)) ? \
  509. PyFloat_AsDouble(obj) : __Pyx__PyObject_AsDouble(obj))
  510. #else
  511. #define __Pyx_PyObject_AsDouble(obj) \
  512. ((likely(PyFloat_CheckExact(obj))) ? \
  513. PyFloat_AS_DOUBLE(obj) : __Pyx__PyObject_AsDouble(obj))
  514. #endif
  515. /////////////// pyobject_as_double ///////////////
  516. static double __Pyx__PyObject_AsDouble(PyObject* obj) {
  517. PyObject* float_value;
  518. #if !CYTHON_USE_TYPE_SLOTS
  519. float_value = PyNumber_Float(obj); if ((0)) goto bad;
  520. #else
  521. PyNumberMethods *nb = Py_TYPE(obj)->tp_as_number;
  522. if (likely(nb) && likely(nb->nb_float)) {
  523. float_value = nb->nb_float(obj);
  524. if (likely(float_value) && unlikely(!PyFloat_Check(float_value))) {
  525. PyErr_Format(PyExc_TypeError,
  526. "__float__ returned non-float (type %.200s)",
  527. Py_TYPE(float_value)->tp_name);
  528. Py_DECREF(float_value);
  529. goto bad;
  530. }
  531. } else if (PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) {
  532. #if PY_MAJOR_VERSION >= 3
  533. float_value = PyFloat_FromString(obj);
  534. #else
  535. float_value = PyFloat_FromString(obj, 0);
  536. #endif
  537. } else {
  538. PyObject* args = PyTuple_New(1);
  539. if (unlikely(!args)) goto bad;
  540. PyTuple_SET_ITEM(args, 0, obj);
  541. float_value = PyObject_Call((PyObject*)&PyFloat_Type, args, 0);
  542. PyTuple_SET_ITEM(args, 0, 0);
  543. Py_DECREF(args);
  544. }
  545. #endif
  546. if (likely(float_value)) {
  547. double value = PyFloat_AS_DOUBLE(float_value);
  548. Py_DECREF(float_value);
  549. return value;
  550. }
  551. bad:
  552. return (double)-1;
  553. }
  554. /////////////// PyNumberPow2.proto ///////////////
  555. #define __Pyx_PyNumber_InPlacePowerOf2(a, b, c) __Pyx__PyNumber_PowerOf2(a, b, c, 1)
  556. #define __Pyx_PyNumber_PowerOf2(a, b, c) __Pyx__PyNumber_PowerOf2(a, b, c, 0)
  557. static PyObject* __Pyx__PyNumber_PowerOf2(PyObject *two, PyObject *exp, PyObject *none, int inplace); /*proto*/
  558. /////////////// PyNumberPow2 ///////////////
  559. static PyObject* __Pyx__PyNumber_PowerOf2(PyObject *two, PyObject *exp, PyObject *none, int inplace) {
  560. // in CPython, 1<<N is substantially faster than 2**N
  561. // see http://bugs.python.org/issue21420
  562. #if !CYTHON_COMPILING_IN_PYPY
  563. Py_ssize_t shiftby;
  564. #if PY_MAJOR_VERSION < 3
  565. if (likely(PyInt_CheckExact(exp))) {
  566. shiftby = PyInt_AS_LONG(exp);
  567. } else
  568. #endif
  569. if (likely(PyLong_CheckExact(exp))) {
  570. #if CYTHON_USE_PYLONG_INTERNALS
  571. const Py_ssize_t size = Py_SIZE(exp);
  572. // tuned to optimise branch prediction
  573. if (likely(size == 1)) {
  574. shiftby = ((PyLongObject*)exp)->ob_digit[0];
  575. } else if (size == 0) {
  576. return PyInt_FromLong(1L);
  577. } else if (unlikely(size < 0)) {
  578. goto fallback;
  579. } else {
  580. shiftby = PyLong_AsSsize_t(exp);
  581. }
  582. #else
  583. shiftby = PyLong_AsSsize_t(exp);
  584. #endif
  585. } else {
  586. goto fallback;
  587. }
  588. if (likely(shiftby >= 0)) {
  589. if ((size_t)shiftby <= sizeof(long) * 8 - 2) {
  590. long value = 1L << shiftby;
  591. return PyInt_FromLong(value);
  592. #ifdef HAVE_LONG_LONG
  593. } else if ((size_t)shiftby <= sizeof(unsigned PY_LONG_LONG) * 8 - 1) {
  594. unsigned PY_LONG_LONG value = ((unsigned PY_LONG_LONG)1) << shiftby;
  595. return PyLong_FromUnsignedLongLong(value);
  596. #endif
  597. } else {
  598. PyObject *result, *one = PyInt_FromLong(1L);
  599. if (unlikely(!one)) return NULL;
  600. result = PyNumber_Lshift(one, exp);
  601. Py_DECREF(one);
  602. return result;
  603. }
  604. } else if (shiftby == -1 && PyErr_Occurred()) {
  605. PyErr_Clear();
  606. }
  607. fallback:
  608. #endif
  609. return (inplace ? PyNumber_InPlacePower : PyNumber_Power)(two, exp, none);
  610. }
  611. /////////////// PyIntCompare.proto ///////////////
  612. {{py: c_ret_type = 'PyObject*' if ret_type.is_pyobject else 'int'}}
  613. static CYTHON_INLINE {{c_ret_type}} __Pyx_PyInt_{{'' if ret_type.is_pyobject else 'Bool'}}{{op}}{{order}}(PyObject *op1, PyObject *op2, long intval, long inplace); /*proto*/
  614. /////////////// PyIntCompare ///////////////
  615. {{py: pyval, ival = ('op2', 'b') if order == 'CObj' else ('op1', 'a') }}
  616. {{py: c_ret_type = 'PyObject*' if ret_type.is_pyobject else 'int'}}
  617. {{py: return_true = 'Py_RETURN_TRUE' if ret_type.is_pyobject else 'return 1'}}
  618. {{py: return_false = 'Py_RETURN_FALSE' if ret_type.is_pyobject else 'return 0'}}
  619. {{py: slot_name = op.lower() }}
  620. {{py: c_op = {'Eq': '==', 'Ne': '!='}[op] }}
  621. {{py:
  622. return_compare = (
  623. (lambda a,b,c_op, return_true=return_true, return_false=return_false: "if ({a} {c_op} {b}) {return_true}; else {return_false};".format(
  624. a=a, b=b, c_op=c_op, return_true=return_true, return_false=return_false))
  625. if ret_type.is_pyobject else
  626. (lambda a,b,c_op: "return ({a} {c_op} {b});".format(a=a, b=b, c_op=c_op))
  627. )
  628. }}
  629. static CYTHON_INLINE {{c_ret_type}} __Pyx_PyInt_{{'' if ret_type.is_pyobject else 'Bool'}}{{op}}{{order}}(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED long inplace) {
  630. if (op1 == op2) {
  631. {{return_true if op == 'Eq' else return_false}};
  632. }
  633. #if PY_MAJOR_VERSION < 3
  634. if (likely(PyInt_CheckExact({{pyval}}))) {
  635. const long {{'a' if order == 'CObj' else 'b'}} = intval;
  636. long {{ival}} = PyInt_AS_LONG({{pyval}});
  637. {{return_compare('a', 'b', c_op)}}
  638. }
  639. #endif
  640. #if CYTHON_USE_PYLONG_INTERNALS
  641. if (likely(PyLong_CheckExact({{pyval}}))) {
  642. int unequal;
  643. unsigned long uintval;
  644. Py_ssize_t size = Py_SIZE({{pyval}});
  645. const digit* digits = ((PyLongObject*){{pyval}})->ob_digit;
  646. if (intval == 0) {
  647. // == 0 => Py_SIZE(pyval) == 0
  648. {{return_compare('size', '0', c_op)}}
  649. } else if (intval < 0) {
  650. // < 0 => Py_SIZE(pyval) < 0
  651. if (size >= 0)
  652. {{return_false if op == 'Eq' else return_true}};
  653. // both are negative => can use absolute values now.
  654. intval = -intval;
  655. size = -size;
  656. } else {
  657. // > 0 => Py_SIZE(pyval) > 0
  658. if (size <= 0)
  659. {{return_false if op == 'Eq' else return_true}};
  660. }
  661. // After checking that the sign is the same (and excluding 0), now compare the absolute values.
  662. // When inlining, the C compiler should select exactly one line from this unrolled loop.
  663. uintval = (unsigned long) intval;
  664. {{for _size in range(4, 0, -1)}}
  665. #if PyLong_SHIFT * {{_size}} < SIZEOF_LONG*8
  666. if (uintval >> (PyLong_SHIFT * {{_size}})) {
  667. // The C integer value is between (PyLong_BASE ** _size) and MIN(PyLong_BASE ** _size, LONG_MAX).
  668. unequal = (size != {{_size+1}}) || (digits[0] != (uintval & (unsigned long) PyLong_MASK))
  669. {{for _i in range(1, _size+1)}} | (digits[{{_i}}] != ((uintval >> ({{_i}} * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)){{endfor}};
  670. } else
  671. #endif
  672. {{endfor}}
  673. unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK));
  674. {{return_compare('unequal', '0', c_op)}}
  675. }
  676. #endif
  677. if (PyFloat_CheckExact({{pyval}})) {
  678. const long {{'a' if order == 'CObj' else 'b'}} = intval;
  679. double {{ival}} = PyFloat_AS_DOUBLE({{pyval}});
  680. {{return_compare('(double)a', '(double)b', c_op)}}
  681. }
  682. return {{'' if ret_type.is_pyobject else '__Pyx_PyObject_IsTrueAndDecref'}}(
  683. PyObject_RichCompare(op1, op2, Py_{{op.upper()}}));
  684. }
  685. /////////////// PyIntBinop.proto ///////////////
  686. {{py: c_ret_type = 'PyObject*' if ret_type.is_pyobject else 'int'}}
  687. #if !CYTHON_COMPILING_IN_PYPY
  688. static {{c_ret_type}} __Pyx_PyInt_{{'' if ret_type.is_pyobject else 'Bool'}}{{op}}{{order}}(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); /*proto*/
  689. #else
  690. #define __Pyx_PyInt_{{'' if ret_type.is_pyobject else 'Bool'}}{{op}}{{order}}(op1, op2, intval, inplace, zerodivision_check) \
  691. {{if op in ('Eq', 'Ne')}}{{'' if ret_type.is_pyobject else '__Pyx_PyObject_IsTrueAndDecref'}}(PyObject_RichCompare(op1, op2, Py_{{op.upper()}}))
  692. {{else}}(inplace ? PyNumber_InPlace{{op}}(op1, op2) : PyNumber_{{op}}(op1, op2))
  693. {{endif}}
  694. #endif
  695. /////////////// PyIntBinop ///////////////
  696. #if !CYTHON_COMPILING_IN_PYPY
  697. {{py: from Cython.Utility import pylong_join }}
  698. {{py: pyval, ival = ('op2', 'b') if order == 'CObj' else ('op1', 'a') }}
  699. {{py: c_ret_type = 'PyObject*' if ret_type.is_pyobject else 'int'}}
  700. {{py: return_true = 'Py_RETURN_TRUE' if ret_type.is_pyobject else 'return 1'}}
  701. {{py: return_false = 'Py_RETURN_FALSE' if ret_type.is_pyobject else 'return 0'}}
  702. {{py: slot_name = {'TrueDivide': 'true_divide', 'FloorDivide': 'floor_divide'}.get(op, op.lower()) }}
  703. {{py: cfunc_name = '__Pyx_PyInt_%s%s%s' % ('' if ret_type.is_pyobject else 'Bool', op, order)}}
  704. {{py: zerodiv_check = lambda operand, _cfunc_name=cfunc_name: '%s_ZeroDivisionError(%s)' % (_cfunc_name, operand)}}
  705. {{py:
  706. c_op = {
  707. 'Add': '+', 'Subtract': '-', 'Remainder': '%', 'TrueDivide': '/', 'FloorDivide': '/',
  708. 'Or': '|', 'Xor': '^', 'And': '&', 'Rshift': '>>', 'Lshift': '<<',
  709. 'Eq': '==', 'Ne': '!=',
  710. }[op]
  711. }}
  712. {{if op in ('TrueDivide', 'FloorDivide', 'Remainder')}}
  713. #if PY_MAJOR_VERSION < 3 || CYTHON_USE_PYLONG_INTERNALS
  714. #define {{zerodiv_check('operand')}} \
  715. if (unlikely(zerodivision_check && ((operand) == 0))) { \
  716. PyErr_SetString(PyExc_ZeroDivisionError, "integer division{{if op == 'Remainder'}} or modulo{{endif}} by zero"); \
  717. return NULL; \
  718. }
  719. #endif
  720. {{endif}}
  721. static {{c_ret_type}} {{cfunc_name}}(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) {
  722. // Prevent "unused" warnings.
  723. (void)inplace;
  724. (void)zerodivision_check;
  725. {{if op in ('Eq', 'Ne')}}
  726. if (op1 == op2) {
  727. {{return_true if op == 'Eq' else return_false}};
  728. }
  729. {{endif}}
  730. #if PY_MAJOR_VERSION < 3
  731. if (likely(PyInt_CheckExact({{pyval}}))) {
  732. const long {{'a' if order == 'CObj' else 'b'}} = intval;
  733. {{if c_op in '+-%' or op == 'FloorDivide'}}
  734. long x;
  735. {{endif}}
  736. long {{ival}} = PyInt_AS_LONG({{pyval}});
  737. {{if op in ('Eq', 'Ne')}}
  738. if (a {{c_op}} b) {
  739. {{return_true}};
  740. } else {
  741. {{return_false}};
  742. }
  743. {{elif c_op in '+-'}}
  744. // adapted from intobject.c in Py2.7:
  745. // casts in the line below avoid undefined behaviour on overflow
  746. x = (long)((unsigned long)a {{c_op}} b);
  747. if (likely((x^a) >= 0 || (x^{{ '~' if op == 'Subtract' else '' }}b) >= 0))
  748. return PyInt_FromLong(x);
  749. return PyLong_Type.tp_as_number->nb_{{slot_name}}(op1, op2);
  750. {{elif c_op == '%'}}
  751. {{zerodiv_check('b')}}
  752. // see ExprNodes.py :: mod_int_utility_code
  753. x = a % b;
  754. x += ((x != 0) & ((x ^ b) < 0)) * b;
  755. return PyInt_FromLong(x);
  756. {{elif op == 'TrueDivide'}}
  757. {{zerodiv_check('b')}}
  758. if (8 * sizeof(long) <= 53 || likely(labs({{ival}}) <= ((PY_LONG_LONG)1 << 53))) {
  759. return PyFloat_FromDouble((double)a / (double)b);
  760. }
  761. // let Python do the rounding
  762. return PyInt_Type.tp_as_number->nb_{{slot_name}}(op1, op2);
  763. {{elif op == 'FloorDivide'}}
  764. // INT_MIN / -1 is the only case that overflows, b == 0 is an error case
  765. {{zerodiv_check('b')}}
  766. if (unlikely(b == -1 && ((unsigned long)a) == 0-(unsigned long)a))
  767. return PyInt_Type.tp_as_number->nb_{{slot_name}}(op1, op2);
  768. else {
  769. long q, r;
  770. // see ExprNodes.py :: div_int_utility_code
  771. q = a / b;
  772. r = a - q*b;
  773. q -= ((r != 0) & ((r ^ b) < 0));
  774. x = q;
  775. }
  776. return PyInt_FromLong(x);
  777. {{elif op == 'Lshift'}}
  778. if (likely(b < (long) (sizeof(long)*8) && a == (a << b) >> b) || !a) {
  779. return PyInt_FromLong(a {{c_op}} b);
  780. }
  781. {{else}}
  782. // other operations are safe, no overflow
  783. return PyInt_FromLong(a {{c_op}} b);
  784. {{endif}}
  785. }
  786. #endif
  787. #if CYTHON_USE_PYLONG_INTERNALS
  788. if (likely(PyLong_CheckExact({{pyval}}))) {
  789. const long {{'a' if order == 'CObj' else 'b'}} = intval;
  790. long {{ival}}{{if op not in ('Eq', 'Ne')}}, x{{endif}};
  791. {{if op not in ('Eq', 'Ne', 'TrueDivide')}}
  792. #ifdef HAVE_LONG_LONG
  793. const PY_LONG_LONG ll{{'a' if order == 'CObj' else 'b'}} = intval;
  794. PY_LONG_LONG ll{{ival}}, llx;
  795. #endif
  796. {{endif}}
  797. const digit* digits = ((PyLongObject*){{pyval}})->ob_digit;
  798. const Py_ssize_t size = Py_SIZE({{pyval}});
  799. // handle most common case first to avoid indirect branch and optimise branch prediction
  800. if (likely(__Pyx_sst_abs(size) <= 1)) {
  801. {{ival}} = likely(size) ? digits[0] : 0;
  802. if (size == -1) {{ival}} = -{{ival}};
  803. } else {
  804. switch (size) {
  805. {{for _size in range(2, 5)}}
  806. {{for _case in (-_size, _size)}}
  807. case {{_case}}:
  808. if (8 * sizeof(long) - 1 > {{_size}} * PyLong_SHIFT{{if op == 'TrueDivide'}} && {{_size-1}} * PyLong_SHIFT < 53{{endif}}) {
  809. {{ival}} = {{'-' if _case < 0 else ''}}(long) {{pylong_join(_size, 'digits')}};
  810. break;
  811. {{if op not in ('Eq', 'Ne', 'TrueDivide')}}
  812. #ifdef HAVE_LONG_LONG
  813. } else if (8 * sizeof(PY_LONG_LONG) - 1 > {{_size}} * PyLong_SHIFT) {
  814. ll{{ival}} = {{'-' if _case < 0 else ''}}(PY_LONG_LONG) {{pylong_join(_size, 'digits', 'unsigned PY_LONG_LONG')}};
  815. goto long_long;
  816. #endif
  817. {{endif}}
  818. }
  819. // if size doesn't fit into a long or PY_LONG_LONG anymore, fall through to default
  820. CYTHON_FALLTHROUGH;
  821. {{endfor}}
  822. {{endfor}}
  823. {{if op in ('Eq', 'Ne')}}
  824. #if PyLong_SHIFT < 30 && PyLong_SHIFT != 15
  825. // unusual setup - your fault
  826. default: return {{'' if ret_type.is_pyobject else '__Pyx_PyObject_IsTrueAndDecref'}}(
  827. PyLong_Type.tp_richcompare({{'op1, op2' if order == 'ObjC' else 'op2, op1'}}, Py_{{op.upper()}}));
  828. #else
  829. // too large for the long values we allow => definitely not equal
  830. default: {{return_false if op == 'Eq' else return_true}};
  831. #endif
  832. {{else}}
  833. default: return PyLong_Type.tp_as_number->nb_{{slot_name}}(op1, op2);
  834. {{endif}}
  835. }
  836. }
  837. {{if op in ('Eq', 'Ne')}}
  838. if (a {{c_op}} b) {
  839. {{return_true}};
  840. } else {
  841. {{return_false}};
  842. }
  843. {{else}}
  844. {{if c_op == '%'}}
  845. {{zerodiv_check('b')}}
  846. // see ExprNodes.py :: mod_int_utility_code
  847. x = a % b;
  848. x += ((x != 0) & ((x ^ b) < 0)) * b;
  849. {{elif op == 'TrueDivide'}}
  850. {{zerodiv_check('b')}}
  851. if ((8 * sizeof(long) <= 53 || likely(labs({{ival}}) <= ((PY_LONG_LONG)1 << 53)))
  852. || __Pyx_sst_abs(size) <= 52 / PyLong_SHIFT) {
  853. return PyFloat_FromDouble((double)a / (double)b);
  854. }
  855. return PyLong_Type.tp_as_number->nb_{{slot_name}}(op1, op2);
  856. {{elif op == 'FloorDivide'}}
  857. {{zerodiv_check('b')}}
  858. {
  859. long q, r;
  860. // see ExprNodes.py :: div_int_utility_code
  861. q = a / b;
  862. r = a - q*b;
  863. q -= ((r != 0) & ((r ^ b) < 0));
  864. x = q;
  865. }
  866. {{else}}
  867. x = a {{c_op}} b;
  868. {{if op == 'Lshift'}}
  869. #ifdef HAVE_LONG_LONG
  870. if (unlikely(!(b < (long) (sizeof(long)*8) && a == x >> b)) && a) {
  871. ll{{ival}} = {{ival}};
  872. goto long_long;
  873. }
  874. #else
  875. if (likely(b < (long) (sizeof(long)*8) && a == x >> b) || !a) /* execute return statement below */
  876. #endif
  877. {{endif}}
  878. {{endif}}
  879. return PyLong_FromLong(x);
  880. {{if op != 'TrueDivide'}}
  881. #ifdef HAVE_LONG_LONG
  882. long_long:
  883. {{if c_op == '%'}}
  884. // see ExprNodes.py :: mod_int_utility_code
  885. llx = lla % llb;
  886. llx += ((llx != 0) & ((llx ^ llb) < 0)) * llb;
  887. {{elif op == 'FloorDivide'}}
  888. {
  889. PY_LONG_LONG q, r;
  890. // see ExprNodes.py :: div_int_utility_code
  891. q = lla / llb;
  892. r = lla - q*llb;
  893. q -= ((r != 0) & ((r ^ llb) < 0));
  894. llx = q;
  895. }
  896. {{else}}
  897. llx = lla {{c_op}} llb;
  898. {{if op == 'Lshift'}}
  899. if (likely(lla == llx >> llb)) /* then execute 'return' below */
  900. {{endif}}
  901. {{endif}}
  902. return PyLong_FromLongLong(llx);
  903. #endif
  904. {{endif}}{{# if op != 'TrueDivide' #}}
  905. {{endif}}{{# if op in ('Eq', 'Ne') #}}
  906. }
  907. #endif
  908. {{if c_op in '+-' or op in ('TrueDivide', 'Eq', 'Ne')}}
  909. if (PyFloat_CheckExact({{pyval}})) {
  910. const long {{'a' if order == 'CObj' else 'b'}} = intval;
  911. double {{ival}} = PyFloat_AS_DOUBLE({{pyval}});
  912. {{if op in ('Eq', 'Ne')}}
  913. if ((double)a {{c_op}} (double)b) {
  914. {{return_true}};
  915. } else {
  916. {{return_false}};
  917. }
  918. {{else}}
  919. double result;
  920. {{if op == 'TrueDivide'}}
  921. if (unlikely(zerodivision_check && b == 0)) {
  922. PyErr_SetString(PyExc_ZeroDivisionError, "float division by zero");
  923. return NULL;
  924. }
  925. {{endif}}
  926. // copied from floatobject.c in Py3.5:
  927. PyFPE_START_PROTECT("{{op.lower() if not op.endswith('Divide') else 'divide'}}", return NULL)
  928. result = ((double)a) {{c_op}} (double)b;
  929. PyFPE_END_PROTECT(result)
  930. return PyFloat_FromDouble(result);
  931. {{endif}}
  932. }
  933. {{endif}}
  934. {{if op in ('Eq', 'Ne')}}
  935. return {{'' if ret_type.is_pyobject else '__Pyx_PyObject_IsTrueAndDecref'}}(
  936. PyObject_RichCompare(op1, op2, Py_{{op.upper()}}));
  937. {{else}}
  938. return (inplace ? PyNumber_InPlace{{op}} : PyNumber_{{op}})(op1, op2);
  939. {{endif}}
  940. }
  941. #endif
  942. /////////////// PyFloatBinop.proto ///////////////
  943. {{py: c_ret_type = 'PyObject*' if ret_type.is_pyobject else 'int'}}
  944. #if !CYTHON_COMPILING_IN_PYPY
  945. static {{c_ret_type}} __Pyx_PyFloat_{{'' if ret_type.is_pyobject else 'Bool'}}{{op}}{{order}}(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check); /*proto*/
  946. #else
  947. #define __Pyx_PyFloat_{{'' if ret_type.is_pyobject else 'Bool'}}{{op}}{{order}}(op1, op2, floatval, inplace, zerodivision_check) \
  948. {{if op in ('Eq', 'Ne')}}{{'' if ret_type.is_pyobject else '__Pyx_PyObject_IsTrueAndDecref'}}(PyObject_RichCompare(op1, op2, Py_{{op.upper()}}))
  949. {{elif op == 'Divide'}}((inplace ? __Pyx_PyNumber_InPlaceDivide(op1, op2) : __Pyx_PyNumber_Divide(op1, op2)))
  950. {{else}}(inplace ? PyNumber_InPlace{{op}}(op1, op2) : PyNumber_{{op}}(op1, op2))
  951. {{endif}}
  952. #endif
  953. /////////////// PyFloatBinop ///////////////
  954. #if !CYTHON_COMPILING_IN_PYPY
  955. {{py: from Cython.Utility import pylong_join }}
  956. {{py: c_ret_type = 'PyObject*' if ret_type.is_pyobject else 'int'}}
  957. {{py: return_true = 'Py_RETURN_TRUE' if ret_type.is_pyobject else 'return 1'}}
  958. {{py: return_false = 'Py_RETURN_FALSE' if ret_type.is_pyobject else 'return 0'}}
  959. {{py: pyval, fval = ('op2', 'b') if order == 'CObj' else ('op1', 'a') }}
  960. {{py: cfunc_name = '__Pyx_PyFloat_%s%s%s' % ('' if ret_type.is_pyobject else 'Bool', op, order) }}
  961. {{py: zerodiv_check = lambda operand, _cfunc_name=cfunc_name: '%s_ZeroDivisionError(%s)' % (_cfunc_name, operand)}}
  962. {{py:
  963. c_op = {
  964. 'Add': '+', 'Subtract': '-', 'TrueDivide': '/', 'Divide': '/', 'Remainder': '%',
  965. 'Eq': '==', 'Ne': '!=',
  966. }[op]
  967. }}
  968. {{if order == 'CObj' and c_op in '%/'}}
  969. #define {{zerodiv_check('operand')}} if (unlikely(zerodivision_check && ((operand) == 0))) { \
  970. PyErr_SetString(PyExc_ZeroDivisionError, "float division{{if op == 'Remainder'}} or modulo{{endif}} by zero"); \
  971. return NULL; \
  972. }
  973. {{endif}}
  974. static {{c_ret_type}} {{cfunc_name}}(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check) {
  975. const double {{'a' if order == 'CObj' else 'b'}} = floatval;
  976. double {{fval}}{{if op not in ('Eq', 'Ne')}}, result{{endif}};
  977. // Prevent "unused" warnings.
  978. (void)inplace;
  979. (void)zerodivision_check;
  980. {{if op in ('Eq', 'Ne')}}
  981. if (op1 == op2) {
  982. {{return_true if op == 'Eq' else return_false}};
  983. }
  984. {{endif}}
  985. if (likely(PyFloat_CheckExact({{pyval}}))) {
  986. {{fval}} = PyFloat_AS_DOUBLE({{pyval}});
  987. {{if order == 'CObj' and c_op in '%/'}}{{zerodiv_check(fval)}}{{endif}}
  988. } else
  989. #if PY_MAJOR_VERSION < 3
  990. if (likely(PyInt_CheckExact({{pyval}}))) {
  991. {{fval}} = (double) PyInt_AS_LONG({{pyval}});
  992. {{if order == 'CObj' and c_op in '%/'}}{{zerodiv_check(fval)}}{{endif}}
  993. } else
  994. #endif
  995. if (likely(PyLong_CheckExact({{pyval}}))) {
  996. #if CYTHON_USE_PYLONG_INTERNALS
  997. const digit* digits = ((PyLongObject*){{pyval}})->ob_digit;
  998. const Py_ssize_t size = Py_SIZE({{pyval}});
  999. switch (size) {
  1000. case 0: {{if order == 'CObj' and c_op in '%/'}}{{zerodiv_check('0')}}{{else}}{{fval}} = 0.0;{{endif}} break;
  1001. case -1: {{fval}} = -(double) digits[0]; break;
  1002. case 1: {{fval}} = (double) digits[0]; break;
  1003. {{for _size in (2, 3, 4)}}
  1004. case -{{_size}}:
  1005. case {{_size}}:
  1006. if (8 * sizeof(unsigned long) > {{_size}} * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || ({{_size-1}} * PyLong_SHIFT < 53))) {
  1007. {{fval}} = (double) {{pylong_join(_size, 'digits')}};
  1008. // let CPython do its own float rounding from 2**53 on (max. consecutive integer in double float)
  1009. if ((8 * sizeof(unsigned long) < 53) || ({{_size}} * PyLong_SHIFT < 53) || ({{fval}} < (double) ((PY_LONG_LONG)1 << 53))) {
  1010. if (size == {{-_size}})
  1011. {{fval}} = -{{fval}};
  1012. break;
  1013. }
  1014. }
  1015. // Fall through if size doesn't fit safely into a double anymore.
  1016. // It may not be obvious that this is a safe fall-through given the "fval < 2**53"
  1017. // check above. However, the number of digits that CPython uses for a given PyLong
  1018. // value is minimal, and together with the "(size-1) * SHIFT < 53" check above,
  1019. // this should make it safe.
  1020. CYTHON_FALLTHROUGH;
  1021. {{endfor}}
  1022. default:
  1023. #else
  1024. {
  1025. #endif
  1026. {{if op in ('Eq', 'Ne')}}
  1027. return {{'' if ret_type.is_pyobject else '__Pyx_PyObject_IsTrueAndDecref'}}(
  1028. PyFloat_Type.tp_richcompare({{'op1, op2' if order == 'CObj' else 'op2, op1'}}, Py_{{op.upper()}}));
  1029. {{else}}
  1030. {{fval}} = PyLong_AsDouble({{pyval}});
  1031. if (unlikely({{fval}} == -1.0 && PyErr_Occurred())) return NULL;
  1032. {{if order == 'CObj' and c_op in '%/'}}{{zerodiv_check(fval)}}{{endif}}
  1033. {{endif}}
  1034. }
  1035. } else {
  1036. {{if op in ('Eq', 'Ne')}}
  1037. return {{'' if ret_type.is_pyobject else '__Pyx_PyObject_IsTrueAndDecref'}}(
  1038. PyObject_RichCompare(op1, op2, Py_{{op.upper()}}));
  1039. {{elif op == 'Divide'}}
  1040. return (inplace ? __Pyx_PyNumber_InPlaceDivide(op1, op2) : __Pyx_PyNumber_Divide(op1, op2));
  1041. {{else}}
  1042. return (inplace ? PyNumber_InPlace{{op}} : PyNumber_{{op}})(op1, op2);
  1043. {{endif}}
  1044. }
  1045. {{if op in ('Eq', 'Ne')}}
  1046. if (a {{c_op}} b) {
  1047. {{return_true}};
  1048. } else {
  1049. {{return_false}};
  1050. }
  1051. {{else}}
  1052. // copied from floatobject.c in Py3.5:
  1053. {{if order == 'CObj' and c_op in '%/'}}{{zerodiv_check('b')}}{{endif}}
  1054. PyFPE_START_PROTECT("{{op.lower() if not op.endswith('Divide') else 'divide'}}", return NULL)
  1055. {{if c_op == '%'}}
  1056. result = fmod(a, b);
  1057. if (result)
  1058. result += ((result < 0) ^ (b < 0)) * b;
  1059. else
  1060. result = copysign(0.0, b);
  1061. {{else}}
  1062. result = a {{c_op}} b;
  1063. {{endif}}
  1064. PyFPE_END_PROTECT(result)
  1065. return PyFloat_FromDouble(result);
  1066. {{endif}}
  1067. }
  1068. #endif