gh-121710: Add PyBytesWriter API by vstinner 路 Pull Request #121726 路 python/cpython (original) (raw)
@picnixz: I would prefer to make the API as small as possible. Where do these use cases come from? Did you see usage in the current C code of CPython with the _PyBytesWriter API?
In your list, the most appealing is PyBytesWriter_Format()
:-)
PyBytesWriter_Format(PyBytesWriter *, char **, const char *, ...)
While it's tempting to add as many features as PyUnicodeWriter API, I'm not convinced that this function is needed right now.
PyBytesWriter_WriteBytes(PyBytesWriter *, char **, PyObject *) which accepts PyObject * arguments
You can already call PyBytesWriter_WriteBytes(writer, &str, PyBytes_AsString(bytes), PyBytes_Size(bytes))
. I never had to "write" a Python bytes object when using the _PyBytesWriter
API. I'm not convinced that it's a common use case.
PyBytesWriter_WriteSubBytes(PyBytesWriter *, char **, PyObject *, Py_ssize_t, Py_ssize_t) (or any other name) for writing a sub-range of bytes object.
You can already call PyBytesWriter_WriteBytes(writer, &str, PyBytes_AsString(bytes) + start, PyBytes_Size(bytes) - skip)
to write a substring. Again, I'm not convinced that it's common to write Python bytes objects.
PyBytesWriter_WriteChar(PyBytesWriter *, char *_, char) -- efficient specialization for size = 1 (maybe not a char, but perhaps Py_UCS_`)
PyBytesWriter is not PyUnicodeWriter. The intended usage is to allocate enough bytes and then just use str pointer. Example:
ascii_data = PyBytesWriter_Prepare(&writer, 10);
*ascii_data++ = ' ';
memcpy(ascii_data, "abc", 3); ascii_data += 3;
*ascii_data++ = '-';
...
WriteChar() would be way slower.