Skip to content

Commit 703da5e

Browse files
authored
pythongh-129813, PEP 782: Use PyBytesWriter in memoryview (python#138836)
Replace PyBytes_FromStringAndSize(NULL, size) with the new public PyBytesWriter API.
1 parent bb743b6 commit 703da5e

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

Objects/memoryobject.c

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2285,7 +2285,6 @@ memoryview_tobytes_impl(PyMemoryViewObject *self, const char *order)
22852285
{
22862286
Py_buffer *src = VIEW_ADDR(self);
22872287
char ord = 'C';
2288-
PyObject *bytes;
22892288

22902289
CHECK_RELEASED(self);
22912290

@@ -2303,16 +2302,18 @@ memoryview_tobytes_impl(PyMemoryViewObject *self, const char *order)
23032302
}
23042303
}
23052304

2306-
bytes = PyBytes_FromStringAndSize(NULL, src->len);
2307-
if (bytes == NULL)
2305+
PyBytesWriter *writer = PyBytesWriter_Create(src->len);
2306+
if (writer == NULL) {
23082307
return NULL;
2308+
}
23092309

2310-
if (PyBuffer_ToContiguous(PyBytes_AS_STRING(bytes), src, src->len, ord) < 0) {
2311-
Py_DECREF(bytes);
2310+
if (PyBuffer_ToContiguous(PyBytesWriter_GetData(writer),
2311+
src, src->len, ord) < 0) {
2312+
PyBytesWriter_Discard(writer);
23122313
return NULL;
23132314
}
23142315

2315-
return bytes;
2316+
return PyBytesWriter_Finish(writer);
23162317
}
23172318

23182319
/*[clinic input]
@@ -2344,28 +2345,29 @@ memoryview_hex_impl(PyMemoryViewObject *self, PyObject *sep,
23442345
/*[clinic end generated code: output=430ca760f94f3ca7 input=539f6a3a5fb56946]*/
23452346
{
23462347
Py_buffer *src = VIEW_ADDR(self);
2347-
PyObject *bytes;
2348-
PyObject *ret;
23492348

23502349
CHECK_RELEASED(self);
23512350

23522351
if (MV_C_CONTIGUOUS(self->flags)) {
23532352
return _Py_strhex_with_sep(src->buf, src->len, sep, bytes_per_sep);
23542353
}
23552354

2356-
bytes = PyBytes_FromStringAndSize(NULL, src->len);
2357-
if (bytes == NULL)
2355+
PyBytesWriter *writer = PyBytesWriter_Create(src->len);
2356+
if (writer == NULL) {
23582357
return NULL;
2358+
}
23592359

2360-
if (PyBuffer_ToContiguous(PyBytes_AS_STRING(bytes), src, src->len, 'C') < 0) {
2361-
Py_DECREF(bytes);
2360+
if (PyBuffer_ToContiguous(PyBytesWriter_GetData(writer),
2361+
src, src->len, 'C') < 0) {
2362+
PyBytesWriter_Discard(writer);
23622363
return NULL;
23632364
}
23642365

2365-
ret = _Py_strhex_with_sep(
2366-
PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes),
2367-
sep, bytes_per_sep);
2368-
Py_DECREF(bytes);
2366+
PyObject *ret = _Py_strhex_with_sep(
2367+
PyBytesWriter_GetData(writer),
2368+
PyBytesWriter_GetSize(writer),
2369+
sep, bytes_per_sep);
2370+
PyBytesWriter_Discard(writer);
23692371

23702372
return ret;
23712373
}

0 commit comments

Comments
 (0)