Skip to content

Commit 486d7cd

Browse files
committed
Add 'center' example
1 parent 7cb444b commit 486d7cd

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

Lib/test/test_capi/test_bytes.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,12 @@ def test_format(self):
365365
self.assertEqual(writer.get_remaining(), 0)
366366
self.assertEqual(writer.finish(), b'123456')
367367

368+
def test_example_center(self):
369+
self.assertEqual(_testcapi.byteswriter_center(0, b'writer'),
370+
b'writer')
371+
self.assertEqual(_testcapi.byteswriter_center(3, b'writer'),
372+
b' writer ')
373+
368374

369375
if __name__ == "__main__":
370376
unittest.main()

Modules/_testcapi/bytes.c

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,9 +254,63 @@ static PyType_Spec Writer_spec = {
254254
};
255255

256256

257+
static PyObject *
258+
byteswriter_center_example(Py_ssize_t spaces, char *str, Py_ssize_t str_size)
259+
{
260+
PyBytesWriter *writer;
261+
char *buf = PyBytesWriter_Create(&writer, spaces * 2);
262+
if (buf == NULL) {
263+
goto error;
264+
}
265+
assert(PyBytesWriter_GetRemaining(writer, buf) == spaces * 2);
266+
267+
// Add left spaces
268+
memset(buf, ' ', spaces);
269+
buf += spaces;
270+
assert(PyBytesWriter_GetRemaining(writer, buf) == spaces);
271+
272+
// Copy string
273+
buf = PyBytesWriter_Extend(writer, buf, str_size);
274+
if (buf == NULL) {
275+
goto error;
276+
}
277+
assert(PyBytesWriter_GetRemaining(writer, buf) == spaces + str_size);
278+
279+
memcpy(buf, str, str_size);
280+
buf += str_size;
281+
assert(PyBytesWriter_GetRemaining(writer, buf) == spaces);
282+
283+
// Add right spaces
284+
memset(buf, ' ', spaces);
285+
buf += spaces;
286+
assert(PyBytesWriter_GetRemaining(writer, buf) == 0);
287+
288+
return PyBytesWriter_Finish(writer, buf);
289+
290+
error:
291+
PyBytesWriter_Discard(writer);
292+
return NULL;
293+
}
294+
295+
296+
static PyObject *
297+
byteswriter_center(PyObject *Py_UNUSED(module), PyObject *args)
298+
{
299+
Py_ssize_t spaces;
300+
char *str;
301+
Py_ssize_t str_size;
302+
if (!PyArg_ParseTuple(args, "ny#", &spaces, &str, &str_size)) {
303+
return NULL;
304+
}
305+
306+
return byteswriter_center_example(spaces, str, str_size);
307+
}
308+
309+
257310
static PyMethodDef test_methods[] = {
258311
{"bytes_resize", bytes_resize, METH_VARARGS},
259312
{"bytes_join", bytes_join, METH_VARARGS},
313+
{"byteswriter_center", byteswriter_center, METH_VARARGS},
260314
{NULL},
261315
};
262316

0 commit comments

Comments
 (0)