From da52601d1f8e524359cf09698811acb1f889203e Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Mon, 9 Jun 2025 14:45:13 +0200 Subject: [PATCH] Add PyUnicodeWriter_WriteASCII() --- docs/api.rst | 4 ++++ docs/changelog.rst | 1 + pythoncapi_compat.h | 12 ++++++++++++ tests/test_pythoncapi_compat_cext.c | 7 ++++++- 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/api.rst b/docs/api.rst index 609edbd..6efae15 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -136,6 +136,10 @@ Python 3.14 See `PyUnicodeWriter_WriteUTF8() documentation `__. +.. c:function:: int PyUnicodeWriter_WriteASCII(PyUnicodeWriter *writer, const char *str, Py_ssize_t size) + + See `PyUnicodeWriter_WriteASCII() documentation `__. + .. c:function:: int PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, const wchar_t *str, Py_ssize_t size) See `PyUnicodeWriter_WriteWideChar() documentation `__. diff --git a/docs/changelog.rst b/docs/changelog.rst index bb981c4..b8e3a86 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,7 @@ Changelog ========= +* 2025-06-09: Add ``PyUnicodeWriter_WriteASCII()`` function. * 2025-06-03: Add functions: * ``PySys_GetAttr()`` diff --git a/pythoncapi_compat.h b/pythoncapi_compat.h index eb84307..20646af 100644 --- a/pythoncapi_compat.h +++ b/pythoncapi_compat.h @@ -1456,6 +1456,18 @@ PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer, return res; } +static inline int +PyUnicodeWriter_WriteASCII(PyUnicodeWriter *writer, + const char *str, Py_ssize_t size) +{ + if (size < 0) { + size = (Py_ssize_t)strlen(str); + } + + return _PyUnicodeWriter_WriteASCIIString((_PyUnicodeWriter*)writer, + str, size); +} + static inline int PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, const wchar_t *str, Py_ssize_t size) diff --git a/tests/test_pythoncapi_compat_cext.c b/tests/test_pythoncapi_compat_cext.c index 82cf387..6e76316 100644 --- a/tests/test_pythoncapi_compat_cext.c +++ b/tests/test_pythoncapi_compat_cext.c @@ -1847,6 +1847,11 @@ test_unicodewriter(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args)) goto error; } + // test PyUnicodeWriter_WriteASCII() + if (PyUnicodeWriter_WriteASCII(writer, " non-ASCII", -1) < 0) { + goto error; + } + // test PyUnicodeWriter_WriteUTF8() if (PyUnicodeWriter_WriteUTF8(writer, " valu\xC3\xA9", -1) < 0) { goto error; @@ -1870,7 +1875,7 @@ test_unicodewriter(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args)) if (result == NULL) { return NULL; } - assert(PyUnicode_EqualToUTF8(result, "var=long valu\xC3\xA9 'repr'")); + assert(PyUnicode_EqualToUTF8(result, "var=long non-ASCII valu\xC3\xA9 'repr'")); Py_DECREF(result); }