Use Python API to determine overflow

This commit is contained in:
Michael Droettboom 2018-10-03 14:15:40 -04:00
parent cb1d7da166
commit b7769908f6
1 changed files with 15 additions and 16 deletions

View File

@ -127,24 +127,23 @@ _python2js(PyObject* x, PyObject* map)
} else if (x == Py_False) { } else if (x == Py_False) {
return hiwire_false(); return hiwire_false();
} else if (PyLong_Check(x)) { } else if (PyLong_Check(x)) {
long x_long = PyLong_AsLongLong(x); int overflow;
if (x_long == -1 && PyErr_Occurred()) { long x_long = PyLong_AsLongAndOverflow(x, &overflow);
return HW_ERROR; if (x_long == -1) {
} if (overflow) {
// Since Javascript doesn't support > 32-bit ints, use floats PyObject* py_float = PyNumber_Float(x);
// when the Python int gets too large. This will lose precision, if (py_float == NULL) {
// but is less problematic than truncation. return HW_ERROR;
if (labs(x_long) > 0x7fffffff) { }
PyObject* py_float = PyNumber_Float(x); double x_double = PyFloat_AsDouble(py_float);
if (py_float == NULL) { Py_DECREF(py_float);
if (x_double == -1.0 && PyErr_Occurred()) {
return HW_ERROR;
}
return hiwire_double(x_double);
} else if (PyErr_Occurred()) {
return HW_ERROR; return HW_ERROR;
} }
double x_double = PyFloat_AsDouble(py_float);
Py_DECREF(py_float);
if (x_double == -1.0 && PyErr_Occurred()) {
return HW_ERROR;
}
return hiwire_double(x_double);
} }
return hiwire_int(x_long); return hiwire_int(x_long);
} else if (PyFloat_Check(x)) { } else if (PyFloat_Check(x)) {