Skip to content

Commit ede2776

Browse files
committed
Add examples
1 parent 3ba1d1c commit ede2776

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

Lib/test/test_capi/test_bytes.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,12 @@ def test_format_i(self):
364364
writer.format_i(b'y=%i', 456)
365365
self.assertEqual(writer.finish(), self.result_type(b'x=123, y=456'))
366366

367+
def test_abc(self):
368+
self.assertEqual(_testcapi.byteswriter_abc(), b'abc')
369+
370+
def test_resize(self):
371+
self.assertEqual(_testcapi.byteswriter_resize(), b'Hello World')
372+
367373

368374
class ByteArrayWriterTest(BytesWriterTest):
369375
result_type = bytearray

Modules/_testcapi/bytes.c

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
289334
static 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

Comments
 (0)