3 #include <torch/csrc/python_headers.h> 6 #include <torch/csrc/Exceptions.h> 7 #include <torch/csrc/utils/tensor_numpy.h> 8 #include <torch/csrc/jit/tracing_state.h> 11 const int64_t DOUBLE_INT_MAX = 9007199254740992;
13 inline PyObject* THPUtils_packInt64(int64_t value) {
14 #if PY_MAJOR_VERSION == 2 15 if (
sizeof(
long) ==
sizeof(int64_t)) {
16 return PyInt_FromLong(static_cast<long>(value));
17 }
else if (value <= INT32_MAX && value >= INT32_MIN) {
18 return PyInt_FromLong(static_cast<long>(value));
21 return PyLong_FromLongLong(value);
24 inline PyObject* THPUtils_packUInt64(uint64_t value) {
25 #if PY_MAJOR_VERSION == 2 26 if (value <= INT32_MAX) {
27 return PyInt_FromLong(static_cast<long>(value));
30 return PyLong_FromUnsignedLongLong(value);
33 inline PyObject* THPUtils_packDoubleAsInt(
double value) {
34 #if PY_MAJOR_VERSION == 2 35 if (value <= INT32_MAX && value >= INT32_MIN) {
36 return PyInt_FromLong(static_cast<long>(value));
39 return PyLong_FromDouble(value);
42 inline bool THPUtils_checkLong(PyObject* obj) {
43 #if PY_MAJOR_VERSION == 2 44 return (PyLong_Check(obj) || PyInt_Check(obj)) && !PyBool_Check(obj);
46 return PyLong_Check(obj) && !PyBool_Check(obj);
50 inline int64_t THPUtils_unpackLong(PyObject* obj) {
52 long long value = PyLong_AsLongLongAndOverflow(obj, &overflow);
53 if (value == -1 && PyErr_Occurred()) {
57 throw std::runtime_error(
"Overflow when unpacking long");
59 return (int64_t)value;
62 inline bool THPUtils_checkIndex(PyObject *obj) {
63 if (PyBool_Check(obj)) {
66 if (THPUtils_checkLong(obj)) {
78 inline int64_t THPUtils_unpackIndex(PyObject* obj) {
79 if (!THPUtils_checkLong(obj)) {
81 if (index ==
nullptr) {
86 return THPUtils_unpackLong(index.get());
88 return THPUtils_unpackLong(obj);
91 inline bool THPUtils_checkDouble(PyObject* obj) {
94 is_numpy_scalar = torch::utils::is_numpy_scalar(obj);
96 is_numpy_scalar =
false;
98 #if PY_MAJOR_VERSION == 2 99 return PyFloat_Check(obj) || PyLong_Check(obj) || PyInt_Check(obj) || is_numpy_scalar;
101 return PyFloat_Check(obj) || PyLong_Check(obj) || is_numpy_scalar;
105 inline double THPUtils_unpackDouble(PyObject* obj) {
106 if (PyFloat_Check(obj)) {
107 return PyFloat_AS_DOUBLE(obj);
109 if (PyLong_Check(obj)) {
111 long long value = PyLong_AsLongLongAndOverflow(obj, &overflow);
113 throw std::runtime_error(
"Overflow when unpacking double");
115 if (value > DOUBLE_INT_MAX || value < -DOUBLE_INT_MAX) {
116 throw std::runtime_error(
"Precision loss when unpacking double");
118 return (
double)value;
120 #if PY_MAJOR_VERSION == 2 121 if (PyInt_Check(obj)) {
122 return (
double)PyInt_AS_LONG(obj);
125 double value = PyFloat_AsDouble(obj);
126 if (value == -1 && PyErr_Occurred()) {
132 inline std::complex<double> THPUtils_unpackComplexDouble(PyObject *obj) {
133 Py_complex value = PyComplex_AsCComplex(obj);
134 if (value.real == -1.0 && PyErr_Occurred()) {
138 return std::complex<double>(value.real, value.imag);