Skip to content

Commit 3bded64

Browse files
committed
gh-129813, PEP 782: Use PyBytesWriter in bytes_concat()
Replace PyBytes_FromStringAndSize(NULL, size) with the new public PyBytesWriter API.
1 parent c3fca5d commit 3bded64

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

Objects/bytesobject.c

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1477,12 +1477,16 @@ bytes_concat(PyObject *a, PyObject *b)
14771477
goto done;
14781478
}
14791479

1480-
result = PyBytes_FromStringAndSize(NULL, va.len + vb.len);
1481-
if (result != NULL) {
1482-
memcpy(PyBytes_AS_STRING(result), va.buf, va.len);
1483-
memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len);
1480+
PyBytesWriter *writer = PyBytesWriter_Create(va.len + vb.len);
1481+
if (writer == NULL) {
1482+
goto done;
14841483
}
14851484

1485+
char *data = PyBytesWriter_GetData(writer);
1486+
memcpy(data, va.buf, va.len);
1487+
memcpy(data + va.len, vb.buf, vb.len);
1488+
result = PyBytesWriter_Finish(writer);
1489+
14861490
done:
14871491
if (va.len != -1)
14881492
PyBuffer_Release(&va);
@@ -1659,8 +1663,6 @@ bytes_subscript(PyObject *op, PyObject* item)
16591663
Py_ssize_t start, stop, step, slicelength, i;
16601664
size_t cur;
16611665
const char* source_buf;
1662-
char* result_buf;
1663-
PyObject* result;
16641666

16651667
if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
16661668
return NULL;
@@ -1683,17 +1685,18 @@ bytes_subscript(PyObject *op, PyObject* item)
16831685
}
16841686
else {
16851687
source_buf = PyBytes_AS_STRING(self);
1686-
result = PyBytes_FromStringAndSize(NULL, slicelength);
1687-
if (result == NULL)
1688+
PyBytesWriter *writer = PyBytesWriter_Create(slicelength);
1689+
if (writer == NULL) {
16881690
return NULL;
1691+
}
1692+
char *buf = PyBytesWriter_GetData(writer);
16891693

1690-
result_buf = PyBytes_AS_STRING(result);
16911694
for (cur = start, i = 0; i < slicelength;
16921695
cur += step, i++) {
1693-
result_buf[i] = source_buf[cur];
1696+
buf[i] = source_buf[cur];
16941697
}
16951698

1696-
return result;
1699+
return PyBytesWriter_Finish(writer);
16971700
}
16981701
}
16991702
else {

0 commit comments

Comments
 (0)