Skip to content

Commit 4397c53

Browse files
committed
Add PyBytes_FromStringAndSize() example
1 parent 6a6e24b commit 4397c53

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

peps/pep-0782.rst

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,34 @@ Create the bytes string ``b"Hello World"``::
320320
}
321321
322322
323+
Update ``PyBytes_FromStringAndSize()`` code
324+
-------------------------------------------
325+
326+
Example of code using the soft deprecated
327+
``PyBytes_FromStringAndSize(NULL, size)`` API::
328+
329+
PyObject *result = PyBytes_FromStringAndSize(NULL, num_bytes);
330+
if (result == NULL) {
331+
return NULL;
332+
}
333+
if (safe_memcpy(PyBytes_AS_STRING(result), start, num_bytes) < 0) {
334+
Py_CLEAR(result);
335+
}
336+
return result;
337+
338+
It can now be updated to::
339+
340+
PyBytesWriter *writer = PyBytesWriter_Create(num_bytes);
341+
if (writer == NULL) {
342+
return NULL;
343+
}
344+
if (safe_memcpy(PyBytesWriter_GetData(writer), start, num_bytes) < 0) {
345+
PyBytesWriter_Discard(writer);
346+
return NULL;
347+
}
348+
return PyBytesWriter_Finish(writer);
349+
350+
323351
Reference Implementation
324352
========================
325353

0 commit comments

Comments
 (0)