@@ -45,6 +45,13 @@ extern "C" {
4545# define _PyObject_CAST (op ) _Py_CAST(PyObject*, op)
4646#endif
4747
48+ #ifndef Py_BUILD_ASSERT
49+ # define Py_BUILD_ASSERT (cond ) \
50+ do { \
51+ (void )sizeof (char [1 - 2 * !(cond)]); \
52+ } while (0 )
53+ #endif
54+
4855
4956// bpo-42262 added Py_NewRef() to Python 3.10.0a3
5057#if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_NewRef)
@@ -1605,6 +1612,84 @@ static inline int PyIter_NextItem(PyObject *iter, PyObject **item)
16051612#endif
16061613
16071614
1615+ #if PY_VERSION_HEX < 0x030E00A0
1616+ static inline PyObject* PyLong_FromInt32 (int32_t value)
1617+ {
1618+ Py_BUILD_ASSERT (sizeof (long ) >= 4 );
1619+ return PyLong_FromLong (value);
1620+ }
1621+
1622+ static inline PyObject* PyLong_FromInt64 (int64_t value)
1623+ {
1624+ Py_BUILD_ASSERT (sizeof (long long ) >= 8 );
1625+ return PyLong_FromLongLong (value);
1626+ }
1627+
1628+ static inline PyObject* PyLong_FromUInt32 (uint32_t value)
1629+ {
1630+ Py_BUILD_ASSERT (sizeof (unsigned long ) >= 4 );
1631+ return PyLong_FromUnsignedLong (value);
1632+ }
1633+
1634+ static inline PyObject* PyLong_FromUInt64 (uint64_t value)
1635+ {
1636+ Py_BUILD_ASSERT (sizeof (unsigned long long ) >= 8 );
1637+ return PyLong_FromUnsignedLongLong (value);
1638+ }
1639+
1640+ static inline int PyLong_AsInt32 (PyObject *obj, int32_t *pvalue)
1641+ {
1642+ Py_BUILD_ASSERT (sizeof (int ) == 4 );
1643+ int value = PyLong_AsInt (obj);
1644+ if (value == -1 && PyErr_Occurred ()) {
1645+ return -1 ;
1646+ }
1647+ *pvalue = (int32_t )value;
1648+ return 0 ;
1649+ }
1650+
1651+ static inline int PyLong_AsInt64 (PyObject *obj, int64_t *pvalue)
1652+ {
1653+ Py_BUILD_ASSERT (sizeof (long long ) == 8 );
1654+ long long value = PyLong_AsLongLong (obj);
1655+ if (value == -1 && PyErr_Occurred ()) {
1656+ return -1 ;
1657+ }
1658+ *pvalue = (int64_t )value;
1659+ return 0 ;
1660+ }
1661+
1662+ static inline int PyLong_AsUInt32 (PyObject *obj, uint32_t *pvalue)
1663+ {
1664+ Py_BUILD_ASSERT (sizeof (long ) >= 4 );
1665+ unsigned long value = PyLong_AsUnsignedLong (obj);
1666+ if (value == (unsigned long )-1 && PyErr_Occurred ()) {
1667+ return -1 ;
1668+ }
1669+ #if SIZEOF_LONG > 4
1670+ if ((unsigned long )UINT32_MAX < value) {
1671+ PyErr_SetString (PyExc_OverflowError,
1672+ " Python int too large to convert to C uint32_t" );
1673+ return -1 ;
1674+ }
1675+ #endif
1676+ *pvalue = (uint32_t )value;
1677+ return 0 ;
1678+ }
1679+
1680+ static inline int PyLong_AsUInt64 (PyObject *obj, uint64_t *pvalue)
1681+ {
1682+ Py_BUILD_ASSERT (sizeof (long long ) == 8 );
1683+ unsigned long long value = PyLong_AsUnsignedLongLong (obj);
1684+ if (value == (unsigned long long )-1 && PyErr_Occurred ()) {
1685+ return -1 ;
1686+ }
1687+ *pvalue = (uint64_t )value;
1688+ return 0 ;
1689+ }
1690+ #endif
1691+
1692+
16081693#ifdef __cplusplus
16091694}
16101695#endif
0 commit comments