[Python-checkins] gh-89653: PEP 670: Fix PyUnicode_READ() cast (GH-92872)

miss-islington webhook-mailer at python.org
Tue May 17 13:46:22 EDT 2022


https://github.com/python/cpython/commit/1df455042d610afac71e792ae2689060dd43178e
commit: 1df455042d610afac71e792ae2689060dd43178e
branch: 3.11
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2022-05-17T10:45:55-07:00
summary:

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 e6fd7992a92879103215b3e9f218fe07212af9b1)

Co-authored-by: Victor Stinner <vstinner at python.org>

files:
M Include/cpython/unicodeobject.h
M Lib/test/_testcppext.cpp

diff --git a/Include/cpython/unicodeobject.h b/Include/cpython/unicodeobject.h
index 8ec2fccaecf99..84307d1885472 100644
--- a/Include/cpython/unicodeobject.h
+++ b/Include/cpython/unicodeobject.h
@@ -407,7 +407,8 @@ static inline Py_UCS4 PyUnicode_READ(int kind,
 }
 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
 #define PyUnicode_READ(kind, data, index) \
-    PyUnicode_READ(_Py_STATIC_CAST(int, kind), _Py_CAST(const void*, data), \
+    PyUnicode_READ(_Py_STATIC_CAST(int, kind), \
+                   _Py_STATIC_CAST(const void*, data), \
                    (index))
 #endif
 
diff --git a/Lib/test/_testcppext.cpp b/Lib/test/_testcppext.cpp
index dc40f0ee9eb1c..f38b4870e0edb 100644
--- a/Lib/test/_testcppext.cpp
+++ b/Lib/test/_testcppext.cpp
@@ -50,9 +50,40 @@ test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
 }
 
 
+static PyObject *
+test_unicode(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
+{
+    PyObject *str = PyUnicode_FromString("abc");
+    if (str == nullptr) {
+        return nullptr;
+    }
+
+    assert(PyUnicode_Check(str));
+    assert(PyUnicode_GET_LENGTH(str) == 3);
+
+    // gh-92800: test PyUnicode_READ()
+    const void* data = PyUnicode_DATA(str);
+    assert(data != nullptr);
+    int kind = PyUnicode_KIND(str);
+    assert(kind == PyUnicode_1BYTE_KIND);
+    assert(PyUnicode_READ(kind, data, 0) == 'a');
+
+    // gh-92800: test PyUnicode_READ() casts
+    const void* const_data = PyUnicode_DATA(str);
+    unsigned int ukind = static_cast<unsigned int>(kind);
+    assert(PyUnicode_READ(ukind, const_data, 2) == 'c');
+
+    assert(PyUnicode_READ_CHAR(str, 1) == 'b');
+
+    Py_DECREF(str);
+    Py_RETURN_NONE;
+}
+
+
 static PyMethodDef _testcppext_methods[] = {
     {"add", _testcppext_add, METH_VARARGS, _testcppext_add_doc},
     {"test_api_casts", test_api_casts, METH_NOARGS, nullptr},
+    {"test_unicode", test_unicode, METH_NOARGS, nullptr},
     {nullptr, nullptr, 0, nullptr}  /* sentinel */
 };
 



More information about the Python-checkins mailing list