Skip to content

Commit fc01ce1

Browse files
Aaron WieczorekAaron Wieczorek
authored andcommitted
Refactor save_picklebuffer to use PyObject_GetBuffer on PickleBuffer directly
1 parent 0d70297 commit fc01ce1

1 file changed

Lines changed: 12 additions & 19 deletions

File tree

Modules/_pickle.c

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2636,23 +2636,18 @@ save_picklebuffer(PickleState *st, PicklerObject *self, PyObject *obj)
26362636
"PickleBuffer can only be pickled with protocol >= 5");
26372637
return -1;
26382638
}
2639-
const Py_buffer* view = PyPickleBuffer_GetBuffer(obj);
2640-
if (view == NULL) {
2639+
Py_buffer view;
2640+
if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) != 0) {
26412641
return -1;
26422642
}
2643-
if (view->suboffsets != NULL || !PyBuffer_IsContiguous(view, 'A')) {
2643+
if (view.suboffsets != NULL || !PyBuffer_IsContiguous(&view, 'A')) {
26442644
PyErr_SetString(st->PicklingError,
26452645
"PickleBuffer can not be pickled when "
26462646
"pointing to a non-contiguous buffer");
2647-
return -1;
2647+
goto error;
26482648
}
26492649

26502650
int rc = 0;
2651-
Py_buffer keepalive_view; // to ensure that 'view' is kept alive
2652-
if (PyObject_GetBuffer(view->obj, &keepalive_view, PyBUF_FULL_RO) != 0) {
2653-
return -1;
2654-
}
2655-
26562651
int in_band = 1;
26572652
if (self->buffer_callback != NULL) {
26582653
PyObject *ret = PyObject_CallOneArg(self->buffer_callback, obj);
@@ -2667,36 +2662,34 @@ save_picklebuffer(PickleState *st, PicklerObject *self, PyObject *obj)
26672662
}
26682663
if (in_band) {
26692664
/* Write data in-band */
2670-
if (view->readonly) {
2671-
rc = _save_bytes_data(st, self, obj, (const char *)view->buf,
2672-
view->len);
2665+
if (view.readonly) {
2666+
rc = _save_bytes_data(st, self, obj, (const char *)view.buf,
2667+
view.len);
26732668
}
26742669
else {
2675-
rc = _save_bytearray_data(st, self, obj, (const char *)view->buf,
2676-
view->len);
2670+
rc = _save_bytearray_data(st, self, obj, (const char *)view.buf,
2671+
view.len);
26772672
}
2678-
goto exit;
26792673
}
26802674
else {
26812675
/* Write data out-of-band */
26822676
const char next_buffer_op = NEXT_BUFFER;
26832677
if (_Pickler_Write(self, &next_buffer_op, 1) < 0) {
26842678
goto error;
26852679
}
2686-
if (view->readonly) {
2680+
if (view.readonly) {
26872681
const char readonly_buffer_op = READONLY_BUFFER;
26882682
if (_Pickler_Write(self, &readonly_buffer_op, 1) < 0) {
26892683
goto error;
26902684
}
26912685
}
26922686
}
26932687

2694-
exit:
2695-
PyBuffer_Release(&keepalive_view);
2688+
PyBuffer_Release(&view);
26962689
return rc;
26972690

26982691
error:
2699-
PyBuffer_Release(&keepalive_view);
2692+
PyBuffer_Release(&view);
27002693
return -1;
27012694
}
27022695

0 commit comments

Comments
 (0)