tuple_ops.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Tuple primitive operations
  2. //
  3. // These are registered in mypyc.primitives.tuple_ops.
  4. #include <Python.h>
  5. #include "CPy.h"
  6. PyObject *CPySequenceTuple_GetItem(PyObject *tuple, CPyTagged index) {
  7. if (CPyTagged_CheckShort(index)) {
  8. Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);
  9. Py_ssize_t size = PyTuple_GET_SIZE(tuple);
  10. if (n >= 0) {
  11. if (n >= size) {
  12. PyErr_SetString(PyExc_IndexError, "tuple index out of range");
  13. return NULL;
  14. }
  15. } else {
  16. n += size;
  17. if (n < 0) {
  18. PyErr_SetString(PyExc_IndexError, "tuple index out of range");
  19. return NULL;
  20. }
  21. }
  22. PyObject *result = PyTuple_GET_ITEM(tuple, n);
  23. Py_INCREF(result);
  24. return result;
  25. } else {
  26. PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
  27. return NULL;
  28. }
  29. }
  30. PyObject *CPySequenceTuple_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {
  31. if (likely(PyTuple_CheckExact(obj)
  32. && CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end))) {
  33. Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start);
  34. Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end);
  35. if (startn < 0) {
  36. startn += PyTuple_GET_SIZE(obj);
  37. }
  38. if (endn < 0) {
  39. endn += PyTuple_GET_SIZE(obj);
  40. }
  41. return PyTuple_GetSlice(obj, startn, endn);
  42. }
  43. return CPyObject_GetSlice(obj, start, end);
  44. }
  45. // PyTuple_SET_ITEM does no error checking,
  46. // and should only be used to fill in brand new tuples.
  47. bool CPySequenceTuple_SetItemUnsafe(PyObject *tuple, CPyTagged index, PyObject *value)
  48. {
  49. if (CPyTagged_CheckShort(index)) {
  50. Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);
  51. PyTuple_SET_ITEM(tuple, n, value);
  52. return true;
  53. } else {
  54. PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
  55. return false;
  56. }
  57. }