Skip to content

Commit 0146025

Browse files
committed
Add _PyBytes_Resize() example
1 parent 4397c53 commit 0146025

File tree

1 file changed

+50
-19
lines changed

1 file changed

+50
-19
lines changed

peps/pep-0782.rst

Lines changed: 50 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -283,8 +283,8 @@ Example creating the bytes string ``b"abc"``, with a fixed size of 3 bytes::
283283
return PyBytesWriter_Finish(writer);
284284
}
285285
286-
GrowAndUpdatePointer() example
287-
------------------------------
286+
``GrowAndUpdatePointer()`` example
287+
----------------------------------
288288
289289
Example using a pointer to write bytes and to track the written size.
290290
@@ -326,26 +326,57 @@ Update ``PyBytes_FromStringAndSize()`` code
326326
Example of code using the soft deprecated
327327
``PyBytes_FromStringAndSize(NULL, size)`` API::
328328
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;
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;
337337
338338
It can now be updated to::
339339
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);
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+
351+
Update ``_PyBytes_Resize()`` code
352+
---------------------------------
353+
354+
Example of code using the soft deprecated ``_PyBytes_Resize()`` API::
355+
356+
PyObject *v = PyBytes_FromStringAndSize(NULL, size);
357+
if (v == NULL) {
358+
return NULL;
359+
}
360+
char *p = PyBytes_AS_STRING(v);
361+
362+
// ... fill bytes into 'p' ...
363+
364+
if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) {
365+
return NULL;
366+
}
367+
return v;
368+
369+
It can now be updated to::
370+
371+
PyBytesWriter *writer = PyBytesWriter_Create(size);
372+
if (writer == NULL) {
373+
return NULL;
374+
}
375+
char *p = PyBytesWriter_GetData(writer);
376+
377+
// ... fill bytes into 'p' ...
378+
379+
return PyBytesWriter_FinishWithPointer(writer, p);
349380
350381
351382
Reference Implementation

0 commit comments

Comments
 (0)