Skip to content

Commit

Permalink
Add PyUnicode_Equal() function (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner authored Oct 9, 2024
1 parent bb0934e commit abc0f29
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ Python 3.14
See `PyLong_GetSign() documentation <https://docs.python.org/dev/c-api/long.html#c.PyLong_GetSign>`__.
.. c:function:: int PyUnicode_Equal(PyObject *str1, PyObject *str2)
See `PyUnicode_Equal() documentation <https://docs.python.org/dev/c-api/unicode.html#c.PyUnicode_Equal>`__.
.. c:function:: PyUnicodeWriter* PyUnicodeWriter_Create(Py_ssize_t length)
See `PyUnicodeWriter_Create() documentation <https://docs.python.org/dev/c-api/unicode.html#c.PyUnicodeWriter_Create>`__.
Expand Down
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Changelog
=========

* 2024-10-09: Add ``PyUnicode_Equal()`` function.
* 2024-07-18: Add functions:

* ``PyUnicodeWriter_Create()``
Expand Down
32 changes: 32 additions & 0 deletions pythoncapi_compat.h
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,38 @@ static inline int PyLong_GetSign(PyObject *obj, int *sign)
#endif


// gh-124502 added PyUnicode_Equal() to Python 3.14.0a0
#if PY_VERSION_HEX < 0x030E00A0
static inline int PyUnicode_Equal(PyObject *str1, PyObject *str2)
{
if (!PyUnicode_Check(str1)) {
PyErr_Format(PyExc_TypeError,
"first argument must be str, not %s",
Py_TYPE(str1)->tp_name);
return -1;
}
if (!PyUnicode_Check(str2)) {
PyErr_Format(PyExc_TypeError,
"second argument must be str, not %s",
Py_TYPE(str2)->tp_name);
return -1;
}

#if PY_VERSION_HEX >= 0x030d0000 && !defined(PYPY_VERSION)
extern int _PyUnicode_Equal(PyObject *str1, PyObject *str2);

return _PyUnicode_Equal(str1, str2);
#elif PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION)
return _PyUnicode_EQ(str1, str2);
#elif PY_VERSION_HEX >= 0x03090000 && defined(PYPY_VERSION)
return _PyUnicode_EQ(str1, str2);
#else
return (PyUnicode_Compare(str1, str2) == 0);
#endif
}
#endif


#ifdef __cplusplus
}
#endif
Expand Down
7 changes: 7 additions & 0 deletions tests/test_pythoncapi_compat_cext.c
Original file line number Diff line number Diff line change
Expand Up @@ -1531,6 +1531,13 @@ test_unicode(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
assert(PyErr_ExceptionMatches(PyExc_MemoryError));
PyErr_Clear();

// Test PyUnicode_Equal()
assert(PyUnicode_Equal(abc, abc) == 1);
assert(PyUnicode_Equal(abc, abc0def) == 0);
assert(PyUnicode_Equal(abc, Py_True) == -1);
assert(PyErr_ExceptionMatches(PyExc_TypeError));
PyErr_Clear();

Py_DECREF(abc);
Py_DECREF(abc0def);
Py_RETURN_NONE;
Expand Down

0 comments on commit abc0f29

Please sign in to comment.