Repository navigation
[C API] Add PyBytesWriter API #121710
Copy link
Copy link
Closed as not planned
Labels
Description
Activity
- addedtype-featureA feature request or enhancementA feature request or enhancement
on Jul 13, 2024 Example creating the bytes string
b"abcdef"withPyBytesWriter_WriteBytes():static PyObject* create_string(void) { char *str; PyBytesWriter *writer = PyBytesWriter_Create(6, &str); if (writer == NULL) { return NULL; } if (PyBytesWriter_WriteBytes(writer, &str, "abc", 3) < 0) { goto error; } if (PyBytesWriter_WriteBytes(writer, &str, "def", 3) < 0) { goto error; } return PyBytesWriter_Finish(writer, str); error: PyBytesWriter_Discard(writer); return NULL; }
Example creating the bytes string
b"Hello."usingPyBytesWriter_Prepare():static PyObject * test_byteswriter_prepare(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args)) { char *str; PyBytesWriter *writer = PyBytesWriter_Create(0, &str); if (writer == NULL) { return NULL; } if (PyBytesWriter_Prepare(writer, &str, 6) < 0) { PyBytesWriter_Discard(writer); return NULL; } memcpy(str, "Hello", 5); str += 5; *str++ = '.'; return PyBytesWriter_Finish(writer, str); }
- added a commit that references this issue
on Jul 13, 2024 The implementation is based on the existing private _PyBytesWriter API which exists for many years
The proposed public API is different than the private API: it allows to still use the writer when an error occurs, whereas the private API requires the function to discard the writer instance. The public API is also simpler to be less error-prone.
Reacted by Erlend E. Aasland- added a commit that references this issue
on Jul 13, 2024 - added a commit that references this issue
on Jul 27, 2024 I decided to reject this API for now. It's too low-level and too error prone: capi-workgroup/decisions#39 (comment)
Feature or enhancement
I propose adding a new
PyBytesWriterAPI to create a Python bytes object.API:
The
PyBytesWriterwriter is responsible to manage memor and uses overallocation to be more efficient, str is a cursor to write into the bytes string.The implementation is based on the existing private
_PyBytesWriterAPI which exists for many years and is used by many functions such as ASCII and Latin1 encoders,binasciimodule,_picklemodule,_structmodule, bytes methods, etc.Linked PRs