8000 gh-110289: C API: Add PyUnicode_EqualToUTF8() function by serhiy-storchaka · Pull Request #110297 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-110289: C API: Add PyUnicode_EqualToUTF8() function #110297

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add tests and address review comments.
  • Loading branch information
serhiy-storchaka committed Oct 3, 2023
commit 4793161fcb730e2d09794a2b7cf91460b2d48a87
4 changes: 3 additions & 1 deletion Doc/c-api/unicode.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1396,10 +1396,12 @@ They all return ``NULL`` or ``-1`` if an exception occurs.
:c:func:`PyErr_Occurred` to check for errors.


.. c:function:: int PyUnicode_EqualToString(PyObject *unicode, const char *string)
.. c:function:: int PyUnicode_EqualToUTF8(PyObject *unicode, const char *string)

Compare a Unicode object with a UTF-8 encoded C string and return true
if they are equal and false otherwise.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Compare a Unicode object with a UTF-8 encoded C string and return true
if they are equal and false otherwise.
Compare a Unicode object with a UTF-8 encoded C string and return non-zero
if they are equal or 0 otherwise.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks to me, that "return true" is more often used than "return non-zero". In this case it is more accurate, because it always returns 1, not other non-zero value. Perhaps other functions which return non-zero was a macro that returned not 1 (something like (arg->flags & FLAG))?

If the Unicode object contains null or surrogate characters or
the C string not encoded to UTF-8 return false.

This function does not raise exceptions.

Expand Down
2 changes: 1 addition & 1 deletion Doc/data/stable_abi.dat

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1001,7 +1001,7 @@ New Features
:c:macro:`Py_TPFLAGS_MANAGED_DICT` flag.
(Contributed by Victor Stinner in :gh:`107073`.)

* Add :c:func:`PyUnicode_EqualToString` function: compare Unicode object with
* Add :c:func:`PyUnicode_EqualToUTF8` function: compare Unicode object with
a :c:expr:`const char*` UTF-8 encoded bytes string and return true if they
are equal or false otherwise.
Copy link
8000 Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
a :c:expr:`const char*` UTF-8 encoded bytes string and return true if they
are equal or false otherwise.
a :c:expr:`const char*` UTF-8 encoded bytes string and return non-zero if they
are equal or 0 otherwise.

This function does not raise exceptions.
Expand Down
2 changes: 1 addition & 1 deletion Include/unicodeobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -962,7 +962,7 @@ PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString(
and 0 otherwise.
This function does not raise exceptions. */

PyAPI_FUNC(int) PyUnicode_EqualToString(PyObject *, const char *);
PyAPI_FUNC(int) PyUnicode_EqualToUTF8(PyObject *, const char *);
#endif

/* Rich compare two strings and return one of the following:
Expand Down
31 changes: 31 additions & 0 deletions Lib/test/test_capi/test_unicode.py
Original file line number Diff line number Diff line change
Expand Up @@ -1297,6 +1297,37 @@ def test_comparewithasciistring(self):
# CRASHES comparewithasciistring([], b'abc')
# CRASHES comparewithasciistring(NULL, b'abc')

@support.cpython_only
@unittest.skipIf(_testcapi is None, 'need _testcapi module')
def test_equaltoutf8(self):
"""Test PyUnicode_EqualToUTF8()"""
from _testcapi import unicode_equaltoutf8 as equaltoutf8

strings = [
'abc', '\xa1\xa2\xa3', '\u4f60\u597d\u4e16',
'\U0001f600\U0001f601\U0001f602'
]
for s in strings:
b = s.encode()
self.assertEqual(equaltoutf8(s, b), 1)
self.assertEqual(equaltoutf8(b.decode(), b), 1)
self.assertEqual(equaltoutf8(s + 'x', b + b'x'), 1)
self.assertEqual(equaltoutf8(s + 'x', b + b'y'), 0)
self.assertEqual(equaltoutf8(s + '\0', b + b'\0'), 0)
self.assertEqual(equaltoutf8(s, b + b'x'), 0)
self.assertEqual(equaltoutf8(s, b[:-1]), 0)
self.assertEqual(equaltoutf8(s, b[:-1] + b'x'), 0)

# surrogateescape
self.assertEqual(equaltoutf8('\udcfe', b'\xfe'), 0)
# surrogatepass
self.assertEqual(equaltoutf8('\udcfe', b'\xed\xb3\xbe'), 0)

# CRASHES equaltoutf8(b'abc', b'abc')
# CRASHES equaltoutf8([], b'abc')
# CRASHES equaltoutf8(NULL, b'abc')
# CRASHES equaltoutf8('abc') # NULL
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# CRASHES equaltoutf8('abc') # NULL
# CRASHES equaltoutf8('abc', NULL)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it does not work so.

NULL is defined as None, and equaltoutf8('abc', None) is a TypeError.

If equaltoutf8() is called with only one argument, it sets the second argument for PyUnicode_EqualToUTF8() to NULL, so we can test it and ensure that it indeed crashes. It is a common approach used in other tests in this file for const char * argument. Some functions do not crash, but raise exception or return successfully for NULL, but this function simply crashes in debug build.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh ok, I thought that they were just pseudo-code as comments. Sure, you can leave # NULL if you prefer.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I copied this pattern from the test for PyUnicode_CompareWithASCIIString() which was one of the first written tests. In newer tests I use "z#" which allows to pass None for NULL. Or perhaps I changed this everywhere except the test for PyUnicode_CompareWithASCIIString(). So perhaps I can change this too.


@support.cpython_only
@unittest.skipIf(_testcapi is None, 'need _testcapi module')
def test_richcompare(self):
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_stable_abi_ctypes.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1 +1 @@
Add :c:func:`PyUnicode_EqualToString` function.
Add :c:func:`PyUnicode_EqualToUTF8` function.
2 changes: 1 addition & 1 deletion Misc/stable_abi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2460,5 +2460,5 @@
added = '3.13'
[function.PyMapping_HasKeyStringWithError]
added = '3.13'
[function.PyUnicode_EqualToString]
[function.PyUnicode_EqualToUTF8]
added = '3.13'
19 changes: 19 additions & 0 deletions Modules/_testcapi/unicode.c
Original file line number Diff line number Diff line change
Expand Up @@ -1429,6 +1429,24 @@ unicode_comparewithasciistring(PyObject *self, PyObject *args)
return PyLong_FromLong(result);
}

/* Test PyUnicode_EqualToUTF8() */
static PyObject *
unicode_equaltoutf8(PyObject *self, PyObject *args)
{
PyObject *left;
const char *right = NULL;
Py_ssize_t right_len;
int result;

if (!PyArg_ParseTuple(args, "O|y#", &left, &right, &right_len))
return NULL;

NULLABLE(left);
result = PyUnicode_EqualToUTF8(left, right);
assert(!PyErr_Occurred());
return PyLong_FromLong(result);
}

/* Test PyUnicode_RichCompare() */
static PyObject *
unicode_richcompare(PyObject *self, PyObject *args)
Expand Down Expand Up @@ -2044,6 +2062,7 @@ static PyMethodDef TestMethods[] = {
{"unicode_replace", unicode_replace, METH_VARARGS},
{"unicode_compare", unicode_compare, METH_VARARGS},
{"unicode_comparewithasciistring",unicode_comparewithasciistring,METH_VARARGS},
{"unicode_equaltoutf8", unicode_equaltoutf8, METH_VARARGS},
{"unicode_richcompare", unicode_richcompare, METH_VARARGS},
{"unicode_format", unicode_format, METH_VARARGS},
{"unicode_contains", unicode_contains, METH_VARARGS},
Expand Down
4 changes: 2 additions & 2 deletions Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -10674,7 +10674,7 @@ PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
}

int
PyUnicode_EqualToString(PyObject *unicode, const char *str)
PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
{
assert(_PyUnicode_CHECK(unicode));
assert(str);
Expand All @@ -10696,7 +10696,7 @@ PyUnicode_EqualToString(PyObject *unicode, const char *str)
/* Compare Unicode string and UTF-8 string */
for (Py_ssize_t i = 0; i < len; i++) {
ch = PyUnicode_READ(kind, data, i);
if (ch == 0x80) {
if (ch == 0) {
return 0;
}
else if (ch < 0x80) {
Expand Down
2 changes: 1 addition & 1 deletion PC/python3dll.c

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0