Skip to content

Commit 10b118f

Browse files
committed
gh-158660: Add PyListBuilder_FromBuffer() function
1 parent e2fc103 commit 10b118f

9 files changed

Lines changed: 199 additions & 1 deletion

File tree

‎Doc/c-api/list.rst‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,3 +331,15 @@ created list.
331331
Both on success and on error, these references are transferred to the builder;
332332
the caller must not use them after the call.
333333
(To clarify: on error, the references are "lost".)
334+
335+
.. c:function:: int PyListBuilder_FromBuffer(PyListBuilder *builder, Py_buffer *view)
336+
337+
Add values from a buffer.
338+
339+
*view* must have 1 dimension.
340+
341+
On success, return ``0``.
342+
On error, set an exception, leave the builder unchanged, and return ``-1``.
343+
344+
On failure, the builder is restored to its previous state. That is, items
345+
added by a failed call are discarded from the builder.

‎Doc/whatsnew/3.16.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1628,6 +1628,7 @@ New features
16281628
* :c:func:`PyListBuilder_Extend`
16291629
* :c:func:`PyListBuilder_ExtendArray`
16301630
* :c:func:`PyListBuilder_ExtendArraySteal`
1631+
* :c:func:`PyListBuilder_FromBuffer`
16311632

16321633
(Contributed by Victor Stinner in :gh:`158660`.)
16331634

‎Include/internal/pycore_list.h‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,32 @@ PyAPI_FUNC(PyObject *)_PyList_AsTupleAndClear(PyListObject *v);
8989
# define _PyListBuilder_INIT_ITEMS 0
9090
#endif
9191

92+
extern int _PyListBuilder_Resize(
93+
PyListBuilder *builder,
94+
Py_ssize_t new_size);
95+
extern void _PyListBuilder_ResetSize(
96+
PyListBuilder *builder,
97+
Py_ssize_t old_size);
98+
99+
100+
// The caller is reponsible to allocate enough items.
101+
// A writer list item must be set exactly once.
102+
// item must not be NULL.
103+
static inline void
104+
_PyListBuilder_SET_ITEM_STEAL(PyListBuilder *writer, Py_ssize_t index,
105+
PyObject *item)
106+
{
107+
assert(item != NULL);
108+
109+
PyListObject *list = (PyListObject*)writer;
110+
assert(0 <= index && index < Py_SIZE(list));
111+
#if _PyListBuilder_INIT_ITEMS
112+
assert(list->ob_item[index] == NULL);
113+
#endif
114+
115+
list->ob_item[index] = item;
116+
}
117+
92118
#ifdef __cplusplus
93119
}
94120
#endif

‎Include/listobject.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ PyAPI_FUNC(int) PyListBuilder_ExtendArraySteal(
6969
PyListBuilder *builder,
7070
PyObject *const *items,
7171
Py_ssize_t nitem);
72+
PyAPI_FUNC(int) PyListBuilder_FromBuffer(
73+
PyListBuilder *builder,
74+
const Py_buffer *view);
7275
#endif
7376

7477

‎Lib/test/test_capi/test_list.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1+
import array
12
import sys
23
import threading
34
import unittest
45
from collections import UserList
56
from test import support
67
from test.support import import_helper
78
from test.support import threading_helper
9+
try:
10+
import _testbuffer
11+
except ImportError:
12+
_testbuffer = None
813

914
_testcapi = import_helper.import_module('_testcapi')
1015
_testlimitedcapi = import_helper.import_module('_testlimitedcapi')
@@ -587,6 +592,49 @@ def thread_func(builder):
587592

588593
self.list_equal(builder.finish(), list('abcde'))
589594

595+
def test_from_buffer(self):
596+
# Test PyListBuilder_FromBuffer()
597+
data = b'abc'
598+
builder = self.create_builder(0)
599+
mview = memoryview(data)
600+
builder.from_buffer(mview)
601+
self.list_equal(builder.finish(), list(data))
602+
603+
numbers = [1.5, 3.0, 5.0]
604+
builder = self.create_builder(0)
605+
mview = memoryview(array.array('d', numbers))
606+
builder.from_buffer(mview)
607+
self.list_equal(builder.finish(), numbers)
608+
609+
def test_from_buffer_memoryerror(self):
610+
# Inject MemoryError in the middle of the array: reset the builder
611+
# to its previous state, discard added float objects
612+
numbers = array.array('d', [2.0] * 128)
613+
mview = memoryview(numbers)
614+
builder = self.create_builder(0)
615+
with self.assertRaises(MemoryError):
616+
with support.inject_memory_error_cm(start=len(numbers) // 2):
617+
builder.from_buffer(mview)
618+
self.list_equal(builder.finish(), [])
619+
620+
@unittest.skipIf(_testbuffer is None, 'need _testbuffer')
621+
def test_from_buffer_ndarray(self):
622+
# PyListBuilder_FromBuffer() requires 1 dimension
623+
array_0d = _testbuffer.ndarray(ord(b"a"), format='B',
624+
shape=(), strides=())
625+
array_2d = _testbuffer.ndarray(list(b"abcdefgh"), format='B',
626+
shape=(4, 2), strides=(2, 1))
627+
628+
for array in (array_0d, array_2d):
629+
with self.subTest(array=array):
630+
builder = self.create_builder(0)
631+
ndim = array.ndim
632+
errmsg = ('require a buffer of 1 dimension, '
633+
f'got {ndim} dimentions')
634+
with self.assertRaisesRegex(ValueError, errmsg):
635+
builder.from_buffer(array)
636+
self.list_equal(builder.finish(), [])
637+
590638

591639
if __name__ == "__main__":
592640
unittest.main()

‎Misc/NEWS.d/next/C_API/2026-10-21-16-35-42.gh-issue-158660.KvixNp.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ created list. Add functions:
1212
* :c:func:`PyListBuilder_Extend`
1313
* :c:func:`PyListBuilder_ExtendArray`
1414
* :c:func:`PyListBuilder_ExtendArraySteal`
15+
* :c:func:`PyListBuilder_FromBuffer`
1516

1617
Patch by Victor Stinner.

‎Modules/_testlimitedcapi/list.c‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,12 +383,37 @@ builder_discard(PyObject *self_raw, PyObject *Py_UNUSED(args))
383383
}
384384

385385

386+
// Test PyListBuilder_FromBuffer()
387+
static PyObject*
388+
builder_from_buffer(PyObject *self_raw, PyObject *obj)
389+
{
390+
BuilderObject *self = BuilderObject_GET(self_raw);
391+
if (builder_check(self) < 0) {
392+
return NULL;
393+
}
394+
395+
Py_buffer view;
396+
int flags = PyBUF_FORMAT | PyBUF_ND | PyBUF_STRIDES;
397+
if (PyObject_GetBuffer(obj, &view, flags) < 0) {
398+
return NULL;
399+
}
400+
401+
int res = PyListBuilder_FromBuffer(self->builder, &view);
402+
PyBuffer_Release(&view);
403+
if (res < 0) {
404+
return NULL;
405+
}
406+
Py_RETURN_NONE;
407+
}
408+
409+
386410
static PyMethodDef builder_methods[] = {
387411
{"append", builder_append, METH_O},
388412
{"append_steal", builder_append_steal, METH_O},
389413
{"extend", builder_extend, METH_O},
390414
{"extend_array", builder_extend_array, METH_O},
391415
{"extend_array_steal", builder_extend_array_steal, METH_O},
416+
{"from_buffer", builder_from_buffer, METH_O},
392417
{"finish", builder_finish, METH_NOARGS},
393418
{"discard", builder_discard, METH_NOARGS},
394419
{NULL, NULL} // sentinel

‎Objects/listobject.c‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4604,6 +4604,13 @@ listbuilder_resize(PyListBuilder *builder, Py_ssize_t new_size)
46044604
}
46054605

46064606

4607+
int
4608+
_PyListBuilder_Resize(PyListBuilder *builder, Py_ssize_t new_size)
4609+
{
4610+
return listbuilder_resize(builder, new_size);
4611+
}
4612+
4613+
46074614
int
46084615
PyListBuilder_AppendSteal(PyListBuilder *builder, PyObject *item)
46094616
{
@@ -4655,6 +4662,13 @@ listbuilder_reset_size(PyListBuilder *builder, Py_ssize_t old_size)
46554662
}
46564663

46574664

4665+
void
4666+
_PyListBuilder_ResetSize(PyListBuilder *builder, Py_ssize_t old_size)
4667+
{
4668+
listbuilder_reset_size(builder, old_size);
4669+
}
4670+
4671+
46584672
// Similar to _list_extend() but don't lock the builder list, and discard
46594673
// added items on error.
46604674
int

‎Objects/memoryobject.c‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
#include "Python.h"
1414
#include "pycore_abstract.h" // _PyIndex_Check()
15+
#include "pycore_list.h" // _PyListBuilder_ResetSize()
1516
#include "pycore_memoryobject.h" // _PyManagedBuffer_Type
1617
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
1718
#include "pycore_strhex.h" // _Py_strhex_with_sep()
@@ -2002,7 +2003,10 @@ unpack_single(PyMemoryViewObject *self, const char *ptr, const char *fmt)
20022003
unsigned char uc;
20032004
void *p;
20042005

2005-
CHECK_RELEASED_AGAIN(self);
2006+
// self in NULL in PyListBuilder_FromBuffer()
2007+
if (self != NULL) {
2008+
CHECK_RELEASED_AGAIN(self);
2009+
}
20062010

20072011
#if PY_LITTLE_ENDIAN
20082012
int endian = 1;
@@ -2527,6 +2531,70 @@ memoryview_tolist_pinned(PyMemoryViewObject *self)
25272531
}
25282532
}
25292533

2534+
2535+
int
2536+
PyListBuilder_FromBuffer(PyListBuilder *builder, const Py_buffer *view)
2537+
{
2538+
if (view->ndim != 1) {
2539+
PyErr_Format(PyExc_ValueError,
2540+
"require a buffer of 1 dimension, got %i dimentions",
2541+
view->ndim);
2542+
return -1;
2543+
}
2544+
2545+
const char *fmt;
2546+
if (view->format != NULL) {
2547+
fmt = adjust_fmt(view);
2548+
if (fmt == NULL) {
2549+
return -1;
2550+
}
2551+
}
2552+
else {
2553+
// Same default value than init_shared_values()
2554+
fmt = "B";
2555+
}
2556+
2557+
PyListObject *list = _PyList_CAST(builder);
2558+
Py_ssize_t old_size = Py_SIZE(list);
2559+
2560+
const char *ptr = view->buf;
2561+
const Py_ssize_t shape = view->shape ? view->shape[0] : view->len;
2562+
const Py_ssize_t strides = view->strides ? view->strides[0] : view->itemsize;
2563+
const Py_ssize_t *suboffsets = view->suboffsets;
2564+
2565+
Py_ssize_t new_size = old_size + shape;
2566+
if (new_size > list->allocated) {
2567+
if (_PyListBuilder_Resize(builder, new_size) < 0) {
2568+
return -1;
2569+
}
2570+
}
2571+
else {
2572+
Py_SET_SIZE(list, new_size);
2573+
}
2574+
2575+
for (Py_ssize_t i = 0; i < shape; ptr += strides, i++) {
2576+
const char *xptr = ADJUST_PTR(ptr, suboffsets, 0);
2577+
2578+
PyObject *item = unpack_single(NULL, xptr, fmt);
2579+
if (item == NULL) {
2580+
Py_SET_SIZE(list, old_size + i);
2581+
goto error;
2582+
}
2583+
2584+
_PyListBuilder_SET_ITEM_STEAL(builder, old_size + i, item);
2585+
}
2586+
return 0;
2587+
2588+
error:
2589+
if (Py_SIZE(list) != old_size) {
2590+
// On error, reset the builder to its previous state:
2591+
// discard added items
2592+
_PyListBuilder_ResetSize(builder, old_size);
2593+
}
2594+
return -1;
2595+
}
2596+
2597+
25302598
/*[clinic input]
25312599
memoryview.tolist
25322600

0 commit comments

Comments
 (0)