Skip to content

Commit 1df4550

Browse files
gh-89653: PEP 670: Fix PyUnicode_READ() cast (GH-92872)
_Py_CAST() cannot be used with a constant type: use _Py_STATIC_CAST() instead. (cherry picked from commit e6fd799) Co-authored-by: Victor Stinner <[email protected]>
1 parent 38d95b5 commit 1df4550

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

Include/cpython/unicodeobject.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,8 @@ static inline Py_UCS4 PyUnicode_READ(int kind,
407407
}
408408
#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
409409
#define PyUnicode_READ(kind, data, index) \
410-
PyUnicode_READ(_Py_STATIC_CAST(int, kind), _Py_CAST(const void*, data), \
410+
PyUnicode_READ(_Py_STATIC_CAST(int, kind), \
411+
_Py_STATIC_CAST(const void*, data), \
411412
(index))
412413
#endif
413414

Lib/test/_testcppext.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,40 @@ test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
5050
}
5151

5252

53+
static PyObject *
54+
test_unicode(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
55+
{
56+
PyObject *str = PyUnicode_FromString("abc");
57+
if (str == nullptr) {
58+
return nullptr;
59+
}
60+
61+
assert(PyUnicode_Check(str));
62+
assert(PyUnicode_GET_LENGTH(str) == 3);
63+
64+
// gh-92800: test PyUnicode_READ()
65+
const void* data = PyUnicode_DATA(str);
66+
assert(data != nullptr);
67+
int kind = PyUnicode_KIND(str);
68+
assert(kind == PyUnicode_1BYTE_KIND);
69+
assert(PyUnicode_READ(kind, data, 0) == 'a');
70+
71+
// gh-92800: test PyUnicode_READ() casts
72+
const void* const_data = PyUnicode_DATA(str);
73+
unsigned int ukind = static_cast<unsigned int>(kind);
74+
assert(PyUnicode_READ(ukind, const_data, 2) == 'c');
75+
76+
assert(PyUnicode_READ_CHAR(str, 1) == 'b');
77+
78+
Py_DECREF(str);
79+
Py_RETURN_NONE;
80+
}
81+
82+
5383
static PyMethodDef _testcppext_methods[] = {
5484
{"add", _testcppext_add, METH_VARARGS, _testcppext_add_doc},
5585
{"test_api_casts", test_api_casts, METH_NOARGS, nullptr},
86+
{"test_unicode", test_unicode, METH_NOARGS, nullptr},
5687
{nullptr, nullptr, 0, nullptr} /* sentinel */
5788
};
5889

0 commit comments

Comments
 (0)