@@ -286,9 +286,56 @@ static PyType_Spec Writer_spec = {
286286};
287287
288288
289+ static PyObject *
290+ byteswriter_abc (PyObject * Py_UNUSED (module ), PyObject * Py_UNUSED (args ))
291+ {
292+ PyBytesWriter * writer = PyBytesWriter_Create (3 );
293+ if (writer == NULL ) {
294+ return NULL ;
295+ }
296+
297+ char * str = PyBytesWriter_GetData (writer );
298+ memcpy (str , "abc" , 3 );
299+
300+ return PyBytesWriter_Finish (writer );
301+ }
302+
303+
304+ static PyObject *
305+ byteswriter_resize (PyObject * Py_UNUSED (module ), PyObject * Py_UNUSED (args ))
306+ {
307+ // Allocate 10 bytes
308+ PyBytesWriter * writer = PyBytesWriter_Create (10 );
309+ if (writer == NULL ) {
310+ return NULL ;
311+ }
312+ char * buf = PyBytesWriter_GetData (writer );
313+
314+ // Write some bytes
315+ memcpy (buf , "Hello " , strlen ("Hello " ));
316+ buf += strlen ("Hello " );
317+
318+ // Allocate 10 more bytes
319+ buf = PyBytesWriter_GrowAndUpdatePointer (writer , 10 , buf );
320+ if (buf == NULL ) {
321+ PyBytesWriter_Discard (writer );
322+ return NULL ;
323+ }
324+
325+ // Write more bytes
326+ memcpy (buf , "World" , strlen ("World" ));
327+ buf += strlen ("World" );
328+
329+ // Truncate to the exact size and create a bytes object
330+ return PyBytesWriter_FinishWithPointer (writer , buf );
331+ }
332+
333+
289334static PyMethodDef test_methods [] = {
290335 {"bytes_resize" , bytes_resize , METH_VARARGS },
291336 {"bytes_join" , bytes_join , METH_VARARGS },
337+ {"byteswriter_abc" , byteswriter_abc , METH_NOARGS },
338+ {"byteswriter_resize" , byteswriter_resize , METH_NOARGS },
292339 {NULL },
293340};
294341
0 commit comments