diff --git a/Doc/c-api/list.rst b/Doc/c-api/list.rst index 21769c4c5c869c..2b66c1a0bd9a74 100644 --- a/Doc/c-api/list.rst +++ b/Doc/c-api/list.rst @@ -227,3 +227,107 @@ List Objects Return a new tuple object containing the contents of *list*; equivalent to ``tuple(list)``. + + +.. _pylistbuilder: + +PyListBuilder +------------- + +The :c:type:`PyListBuilder` API can be used to create a Python :class:`list` +object. + +On the free-threaded build, it's more efficient than the ``PyList`` C API to +create a :class:`list`, because it can avoid the critical section on the +created list. + +.. versionadded:: next + + +.. c:type:: PyListBuilder + + A list builder object. + + The API is **not thread safe**. To share a builder with multiple threads, + external synchronization is needed. + + The instance must be destroyed by :c:func:`PyListBuilder_Finish` on + success, or :c:func:`PyListBuilder_Discard` on error. + + +.. c:function:: PyListBuilder* PyListBuilder_Create(Py_ssize_t size) + + Create a :c:type:`PyListBuilder` and preallocate *size* items. + + On error, set an exception and return ``NULL``. + + *size* must be positive or zero. + +.. c:function:: PyObject* PyListBuilder_Finish(PyListBuilder *builder) + + Finish a :c:type:`PyListBuilder` created by + :c:func:`PyListBuilder_Create`. + + On success, return a Python :class:`list` object. + On error, set an exception and return ``NULL``. + + The builder instance is invalid after the call in any case. + No API can be called on the builder after :c:func:`PyListBuilder_Finish`. + +.. c:function:: void PyListBuilder_Discard(PyListBuilder *builder) + + Discard a :c:type:`PyListBuilder` created by :c:func:`PyListBuilder_Create`. + + Do nothing if *builder* is ``NULL``. + + The builder instance is invalid after the call. + No API can be called on the builder after :c:func:`PyListBuilder_Discard`. + +.. c:function:: int PyListBuilder_Append(PyListBuilder *builder, PyObject *item) + + Append an item to the list builder. + Similar to :c:func:`PyList_Append`. + + On success, return ``0``. + On error, set an exception, leave the builder unchanged, and return ``-1``. + +.. c:function:: int PyListBuilder_AppendSteal(PyListBuilder *builder, PyObject *item) + + Same as :c:func:`PyListBuilder_Append`, except this function + :term:`steals ` the reference to *item*. + +.. c:function:: int PyListBuilder_Extend(PyListBuilder *builder, PyObject *iterable) + + Extend the list builder with the contents of *iterable*. + Similar to :c:func:`PyList_Extend`. + + On success, return ``0``. + On error, set an exception, leave the builder unchanged, and return ``-1``. + + If consuming *iterable* raises an exception, the builder is restored to its + previous state, that is, items added by a failed call are discarded. + However, note that *iterable* is not reverted: items consumed from an + iterator are not added back. + +.. c:function:: int PyListBuilder_ExtendArray(PyListBuilder *builder, PyObject *const *items, Py_ssize_t nitem) + + Extend the list builder with the contents of *items*: copy references from + *items* to the list builder. + + On success, return ``0``. + On error, set an exception, leave the builder unchanged, and return ``-1``. + + *nitem* must not be negative. + + On failure, the builder is restored to its previous state. That is, items + added by a failed call are discarded from the builder. + +.. c:function:: int PyListBuilder_ExtendArraySteal(PyListBuilder *builder, PyObject *const *items, Py_ssize_t nitem) + + Same as :c:func:`PyListBuilder_ExtendArray`, but :term:`steal` references + instead of copying them. + + The caller must hold a strong reference to each item in *item*. + Both on success and on error, these references are transferred to the builder; + the caller must not use them after the call. + (To clarify: on error, the references are "lost".) diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 336171ca041f90..3819f77bf77ad2 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1607,6 +1607,22 @@ New features * Add :c:func:`Py_HashBuffer` to the limited C API. (Contributed by Victor Stinner in :gh:`148233`.) +* Add a new :ref:`PyListBuilder ` C API to create a :class:`list` + object. On the free-threaded build, it's more efficient than the ``PyList`` C + API to create a :class:`list`, because it can avoid locking the + list as it's being built. Add functions: + + * :c:func:`PyListBuilder_Create` + * :c:func:`PyListBuilder_Finish` + * :c:func:`PyListBuilder_Discard` + * :c:func:`PyListBuilder_Append` + * :c:func:`PyListBuilder_AppendSteal` + * :c:func:`PyListBuilder_Extend` + * :c:func:`PyListBuilder_ExtendArray` + * :c:func:`PyListBuilder_ExtendArraySteal` + + (Contributed by Victor Stinner in :gh:`158660`.) + * Add :c:macro:`Py_SETREF` and :c:macro:`Py_XSETREF` macros to the limited C API. (Contributed by Nathan Goldbaum and Victor Stinner in :gh:`158842`.) diff --git a/Include/cpython/listobject.h b/Include/cpython/listobject.h index 49f5e8d6d1a0d6..f4aa8a0d3bff77 100644 --- a/Include/cpython/listobject.h +++ b/Include/cpython/listobject.h @@ -51,3 +51,29 @@ PyList_SET_ITEM(PyObject *op, Py_ssize_t index, PyObject *value) { PyAPI_FUNC(int) PyList_Extend(PyObject *self, PyObject *iterable); PyAPI_FUNC(int) PyList_Clear(PyObject *self); + + +/* --- PyListBuilder API -------------------------------------------------- */ + +typedef struct PyListBuilder PyListBuilder; + +PyAPI_FUNC(PyListBuilder*) PyListBuilder_Create(Py_ssize_t size); +PyAPI_FUNC(PyObject*) PyListBuilder_Finish(PyListBuilder *builder); +PyAPI_FUNC(void) PyListBuilder_Discard(PyListBuilder *builder); +PyAPI_FUNC(int) PyListBuilder_Append( + PyListBuilder *builder, + PyObject *item); +PyAPI_FUNC(int) PyListBuilder_AppendSteal( + PyListBuilder *builder, + PyObject *item); +PyAPI_FUNC(int) PyListBuilder_Extend( + PyListBuilder *builder, + PyObject *iterable); +PyAPI_FUNC(int) PyListBuilder_ExtendArray( + PyListBuilder *builder, + PyObject *const *items, + Py_ssize_t nitem); +PyAPI_FUNC(int) PyListBuilder_ExtendArraySteal( + PyListBuilder *builder, + PyObject *const *items, + Py_ssize_t nitem); diff --git a/Include/internal/pycore_list.h b/Include/internal/pycore_list.h index df0d00f752573b..f55aca258ee65c 100644 --- a/Include/internal/pycore_list.h +++ b/Include/internal/pycore_list.h @@ -12,6 +12,8 @@ extern "C" { #include "pycore_stackref.h" #endif +#define _Py_LIST_SMALL_ALLOCATED 32 + PyAPI_FUNC(PyObject*) _PyList_Extend(PyListObject *, PyObject *); PyAPI_FUNC(PyObject) *_PyList_SliceSubscript(PyObject*, PyObject*); PyAPI_FUNC(PyObject *) _PyList_BinarySlice(PyObject *, PyObject *, PyObject *); @@ -77,6 +79,16 @@ union _PyStackRef; PyAPI_FUNC(PyObject *)_PyList_FromStackRefStealOnSuccess(const union _PyStackRef *src, Py_ssize_t n); PyAPI_FUNC(PyObject *)_PyList_AsTupleAndClear(PyListObject *v); +#ifdef Py_DEBUG + // In debug mode, PyListBuilder_Finish() makes sure that all list items + // are initialized. +# define _PyListBuilder_INIT_ITEMS 1 +#else + // In release mode, list items are not initialized for best performance. + // The caller is responsible to initialize all items. +# define _PyListBuilder_INIT_ITEMS 0 +#endif + #ifdef __cplusplus } #endif diff --git a/Lib/test/test_capi/test_list.py b/Lib/test/test_capi/test_list.py index 05cc36b993b1ad..158fcbc94f1909 100644 --- a/Lib/test/test_capi/test_list.py +++ b/Lib/test/test_capi/test_list.py @@ -1,13 +1,19 @@ import sys +import threading import unittest -from test.support import import_helper from collections import UserList +from test import support +from test.support import import_helper +from test.support import threading_helper + _testcapi = import_helper.import_module('_testcapi') _testlimitedcapi = import_helper.import_module('_testlimitedcapi') + NULL = None PY_SSIZE_T_MIN = _testcapi.PY_SSIZE_T_MIN PY_SSIZE_T_MAX = _testcapi.PY_SSIZE_T_MAX +LIST_SMALL_ALLOCATED = _testcapi.LIST_SMALL_ALLOCATED class ListSubclass(list): pass @@ -359,5 +365,226 @@ def test_uninitialized_list_repr(self): self.assertEqual(repr(lst), '[, , ]') +class ListBuilderTests(unittest.TestCase): + def create_builder(self, size): + # Test PyListBuilder_Create() + return _testcapi.PyListBuilder(size) + + def list_equal(self, result, expected): + if not isinstance(expected, list): + expected = list(expected) + self.assertEqual(result, expected) + self.assertEqual(type(result), list) + + def create_items(self, nitem): + # Call object() to create unique objects. Don't use small integers + # which are immortal (and so would not check for reference leaks). + return tuple(object() for i in range(nitem)) + + def test_create_overflow(self): + # Test PyListBuilder_Create() check for integer overflow + max_nitem = sys.maxsize // _testcapi.SIZEOF_VOID_P + self.assertRaises(MemoryError, self.create_builder, max_nitem + 1) + self.assertRaises(MemoryError, self.create_builder, sys.maxsize) + + def check_append(self, method): + items = self.create_items(3) + for size in (0, len(items), len(items) * 10): + with self.subTest(size=size): + builder = self.create_builder(size) + append = getattr(builder, method) + for item in items: + append(item) + self.list_equal(builder.finish(), items) + + # test MemoryError + builder = self.create_builder(0) + append = getattr(builder, method) + with self.assertRaises(MemoryError): + with support.inject_memory_error_cm(): + append("alloc failed") + for item in items: + append(item) + self.list_equal(builder.finish(), items) + + def test_append(self): + # Test PyListBuilder_Append() + self.check_append('append') + + def test_append_steal(self): + # Test PyListBuilder_AppendSteal() + self.check_append('append_steal') + + def check_extend(self, method): + items = self.create_items(5) + for size in (0, len(items), len(items) * 10): + with self.subTest(size=size): + builder = self.create_builder(size) + extend = getattr(builder, method) + extend(items) + self.list_equal(builder.finish(), items) + + # test MemoryError + builder = self.create_builder(0) + extend = getattr(builder, method) + items_error = ("alloc failed",) + with self.assertRaises(MemoryError): + with support.inject_memory_error_cm(): + extend(items_error) + extend(items) + self.list_equal(builder.finish(), items) + + if method != 'extend' and support.Py_DEBUG: + items = (object(), object(), NULL) + builder = self.create_builder(0) + extend = getattr(builder, method) + with self.assertRaises(SystemError): + extend(items) + # On error, added items are discarded + self.list_equal(builder.finish(), []) + + def test_extend(self): + # Test PyListBuilder_Extend() + self.check_extend('extend') + + def test_extend_iter_error(self): + class IterError: + def __init__(self): + self.index = 1 + + def __iter__(self): + return self + + def __next__(self): + value = self.index + self.index += 1 + if value >= 3: + raise ValueError("iter error") + return value + + # On error, restore the builder to its previous state: + # discard added items + iterable = IterError() + builder = self.create_builder(0) + builder.append("before") + with self.assertRaisesRegex(ValueError, "iter error"): + builder.extend(iterable) + self.assertEqual(iterable.index, 4) + builder.append("after") + self.list_equal(builder.finish(), ["before", "after"]) + + def test_extend_array(self): + # Test PyListBuilder_ExtendArray() + self.check_extend('extend_array') + + def test_extend_array_steal(self): + # Test PyListBuilder_ExtendArraySteal() + self.check_extend('extend_array_steal') + + def test_empty(self): + list_get_allocated = _testcapi._list_get_allocated + empty_tuple = () + + for size in (0, LIST_SMALL_ALLOCATED, 1024): + with self.subTest(size=size): + builder = self.create_builder(size) + builder.extend(empty_tuple) + builder.extend_array(empty_tuple) + builder.extend_array_steal(empty_tuple) + result = builder.finish() + self.list_equal(result, []) + + if size == 0 or size > LIST_SMALL_ALLOCATED: + expected = 0 + else: + expected = size + self.assertEqual(list_get_allocated(result), expected) + + def test_finish_shrink(self): + # PyListBuilder_Finish() shrinks the list if its allocated size + # is way too big + list_get_allocated = _testcapi._list_get_allocated + + def compute_allocated(size): + return (size + (size >> 3) + 6) & ~3 + + def check_allocated(items, alloc, expected): + builder = self.create_builder(alloc) + # Don't use PyListBuilder_Extend() since it can shrink the list + for item in items: + builder.append(item) + result = builder.finish() + self.list_equal(result, list(items)) + self.assertEqual(list_get_allocated(result), expected) + + # small list + items = [1, 2, 3] + check_allocated(items, + 1024, + compute_allocated(len(items))) + + alloc = LIST_SMALL_ALLOCATED + check_allocated(items, alloc, alloc) + + # larger list + items = tuple(range(100)) + check_allocated(items, + (len(items) + 1) * 2, + compute_allocated(len(items))) + + alloc = len(items) * 2 + check_allocated(items, alloc, alloc) + + # do not shrink on MemoryError + alloc = 1024 + builder = self.create_builder(alloc) + builder.append(1) + with support.inject_memory_error_cm(): + # list_resize() never fails when shrinking + result = builder.finish() + self.list_equal(result, [1]) + self.assertEqual(list_get_allocated(result), alloc) + + def test_combined(self): + # Call each method twice: it must not fail/crash. + builder = self.create_builder(0) + builder.append('a') + builder.append_steal('b') + builder.extend(('c',)) + builder.extend_array(('d',)) + builder.extend_array_steal(('e',)) + builder.append('A') + builder.append_steal('B') + builder.extend(('C',)) + builder.extend_array(('D',)) + builder.extend_array_steal(('E',)) + self.list_equal(builder.finish(), list('abcdeABCDE')) + + def test_discard(self): + # Test PyListBuilder_Discard(): must not leak memory + builder = self.create_builder(0) + builder.extend([2, 5, 7]) + builder.discard() + + @threading_helper.requires_working_threading() + def test_thread(self): + # PyListBuilder can be used by multiple threads: it's up to the caller + # to implement a lock to prevent concurrent accesses. + builder = self.create_builder(0) + + def thread_func(builder): + builder.append('a') + builder.append_steal('b') + builder.extend(('c',)) + builder.extend_array(('d',)) + builder.extend_array_steal(('e',)) + + thread = threading.Thread(target=thread_func, args=(builder,)) + thread.start() + threading_helper.join_thread(thread) + + self.list_equal(builder.finish(), list('abcde')) + + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/C_API/2026-10-21-16-35-42.gh-issue-158660.KvixNp.rst b/Misc/NEWS.d/next/C_API/2026-10-21-16-35-42.gh-issue-158660.KvixNp.rst new file mode 100644 index 00000000000000..82e32f07afd2d3 --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-10-21-16-35-42.gh-issue-158660.KvixNp.rst @@ -0,0 +1,15 @@ +Add a new :ref:`PyListBuilder ` C API to create a :class:`list` +object. On the free-threaded build, it's more efficient than the ``PyList`` C +API to create a :class:`list`, because it can avoid the critical section on the +created list. Add functions: + +* :c:func:`PyListBuilder_Create` +* :c:func:`PyListBuilder_Finish` +* :c:func:`PyListBuilder_Discard` +* :c:func:`PyListBuilder_Append` +* :c:func:`PyListBuilder_AppendSteal` +* :c:func:`PyListBuilder_Extend` +* :c:func:`PyListBuilder_ExtendArray` +* :c:func:`PyListBuilder_ExtendArraySteal` + +Patch by Victor Stinner. diff --git a/Modules/_testcapi/list.c b/Modules/_testcapi/list.c index 530b47780ac94e..d39107ec5a8cab 100644 --- a/Modules/_testcapi/list.c +++ b/Modules/_testcapi/list.c @@ -1,12 +1,17 @@ +// Use pycore_list.h +#define PYTESTCAPI_NEED_INTERNAL_API + #include "parts.h" #include "util.h" +#include "pycore_list.h" // _Py_LIST_SMALL_ALLOCATED + static PyObject * list_get_size(PyObject *Py_UNUSED(module), PyObject *obj) { NULLABLE(obj); - RETURN_SIZE(PyList_GET_SIZE(obj)); + RETURN_SIZE(PyList_GET_SIZE(obj)); // crash if not list or NULL } @@ -103,6 +108,256 @@ test_list_api(PyObject *self, PyObject *Py_UNUSED(ignored)) } +static PyObject * +_list_get_allocated(PyObject *Py_UNUSED(module), PyObject *obj) +{ + NULLABLE(obj); + PyListObject *list = (PyListObject*)obj; + return PyLong_FromSsize_t(list->allocated); +} + + +typedef struct { + PyObject_HEAD + PyListBuilder *builder; +} BuilderObject; + + +static inline int +builder_check(BuilderObject *self) +{ + if (self->builder == NULL) { + PyErr_SetString(PyExc_ValueError, + "operation on finished/discarded builder"); + return -1; + } + return 0; +} + + +static PyObject * +builder_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +{ + BuilderObject *self = (BuilderObject *)type->tp_alloc(type, 0); + if (!self) { + return NULL; + } + self->builder = NULL; + return (PyObject*)self; +} + + +// Test PyListBuilder_Create() +static int +builder_init(PyObject *self_raw, PyObject *args, PyObject *kwargs) +{ + if (kwargs && PyDict_GET_SIZE(kwargs)) { + PyErr_Format(PyExc_TypeError, + "PyListBuilder() takes no keyword arguments"); + return -1; + } + + Py_ssize_t size = 0; + if (!PyArg_ParseTuple(args, "|n", &size)) { + return -1; + } + + BuilderObject *self = (BuilderObject *)self_raw; + PyListBuilder_Discard(self->builder); + + self->builder = PyListBuilder_Create(size); + if (self->builder == NULL) { + return -1; + } + return 0; +} + + +// Test PyListBuilder_Discard() +static void +builder_dealloc(PyObject *self_raw) +{ + BuilderObject *self = (BuilderObject *)self_raw; + PyTypeObject *tp = Py_TYPE(self); + PyListBuilder_Discard(self->builder); // self->builder can be NULL + tp->tp_free(self); + Py_DECREF(tp); +} + + +// Test PyListBuilder_Append() +static PyObject* +builder_append(PyObject *self_raw, PyObject *item) +{ + BuilderObject *self = (BuilderObject *)self_raw; + if (builder_check(self) < 0) { + return NULL; + } + + if (PyListBuilder_Append(self->builder, item) < 0) { + return NULL; + } + Py_RETURN_NONE; +} + + +// Test PyListBuilder_AppendSteal() +static PyObject* +builder_append_steal(PyObject *self_raw, PyObject *item) +{ + BuilderObject *self = (BuilderObject *)self_raw; + if (builder_check(self) < 0) { + return NULL; + } + + if (PyListBuilder_AppendSteal(self->builder, Py_NewRef(item)) < 0) { + return NULL; + } + Py_RETURN_NONE; +} + + +// Test PyListBuilder_Extend() +static PyObject* +builder_extend(PyObject *self_raw, PyObject *iterable) +{ + BuilderObject *self = (BuilderObject *)self_raw; + if (builder_check(self) < 0) { + return NULL; + } + + if (PyListBuilder_Extend(self->builder, iterable) < 0) { + return NULL; + } + Py_RETURN_NONE; +} + + +static PyObject* +builder_extend_array_impl(PyObject *self_raw, PyObject *tuple, int steal) +{ + BuilderObject *self = (BuilderObject *)self_raw; + if (builder_check(self) < 0) { + return NULL; + } + + if (!PyTuple_Check(tuple)) { + PyErr_Format(PyExc_TypeError, + "expect tuple, got %T", tuple); + return NULL; + } + PyObject **items = &PyTuple_GET_ITEM(tuple, 0); + Py_ssize_t len = PyTuple_GET_SIZE(tuple); + + // Copy the array to replace None with NULL + PyObject **array = PyMem_Malloc(len * sizeof(PyObject*)); + if (array == NULL) { + PyErr_NoMemory(); + return NULL; + } + for (Py_ssize_t i = 0; i < len; i++) { + PyObject *item = items[i]; + if (item != Py_None) { + if (!steal) { + array[i] = item; + } + else { + array[i] = Py_NewRef(item); + } + } + else { + array[i] = NULL; + } + } + + int res; + if (!steal) { + res = PyListBuilder_ExtendArray(self->builder, array, len); + } + else { + res = PyListBuilder_ExtendArraySteal(self->builder, array, len); + } + PyMem_Free(array); + if (res < 0) { + return NULL; + } + Py_RETURN_NONE; +} + + +// Test PyListBuilder_ExtendArray() +static PyObject* +builder_extend_array(PyObject *self, PyObject *tuple) +{ + return builder_extend_array_impl(self, tuple, 0); +} + + +// Test PyListBuilder_ExtendArraySteal() +static PyObject* +builder_extend_array_steal(PyObject *self, PyObject *tuple) +{ + return builder_extend_array_impl(self, tuple, 1); +} + + +// Test PyListBuilder_Finish() +static PyObject* +builder_finish(PyObject *self_raw, PyObject *Py_UNUSED(args)) +{ + BuilderObject *self = (BuilderObject *)self_raw; + if (builder_check(self) < 0) { + return NULL; + } + + PyObject *list = PyListBuilder_Finish(self->builder); + self->builder = NULL; + return list; +} + + +// Test PyListBuilder_Discard() +static PyObject* +builder_discard(PyObject *self_raw, PyObject *Py_UNUSED(args)) +{ + BuilderObject *self = (BuilderObject *)self_raw; + if (builder_check(self) < 0) { + return NULL; + } + + PyListBuilder_Discard(self->builder); + self->builder = NULL; + Py_RETURN_NONE; +} + + +static PyMethodDef builder_methods[] = { + {"append", _PyCFunction_CAST(builder_append), METH_O}, + {"append_steal", _PyCFunction_CAST(builder_append_steal), METH_O}, + {"extend", _PyCFunction_CAST(builder_extend), METH_O}, + {"extend_array", _PyCFunction_CAST(builder_extend_array), METH_O}, + {"extend_array_steal", _PyCFunction_CAST(builder_extend_array_steal), METH_O}, + {"finish", _PyCFunction_CAST(builder_finish), METH_NOARGS}, + {"discard", _PyCFunction_CAST(builder_discard), METH_NOARGS}, + {NULL, NULL} /* sentinel */ +}; + +static PyType_Slot Builder_Type_slots[] = { + {Py_tp_new, builder_new}, + {Py_tp_init, builder_init}, + {Py_tp_dealloc, builder_dealloc}, + {Py_tp_methods, builder_methods}, + {0, 0}, /* sentinel */ +}; + +static PyType_Spec Builder_spec = { + .name = "_testcapi.PyListBuilder", + .basicsize = sizeof(BuilderObject), + .flags = Py_TPFLAGS_DEFAULT, + .slots = Builder_Type_slots, +}; + + static PyMethodDef test_methods[] = { {"list_get_size", list_get_size, METH_O}, {"list_get_item", list_get_item, METH_VARARGS}, @@ -110,11 +365,29 @@ static PyMethodDef test_methods[] = { {"list_clear", list_clear, METH_O}, {"list_extend", list_extend, METH_VARARGS}, {"test_list_api", test_list_api, METH_NOARGS}, + {"_list_get_allocated", _list_get_allocated, METH_O}, {NULL}, }; int _PyTestCapi_Init_List(PyObject *m) { - return PyModule_AddFunctions(m, test_methods); + if (PyModule_AddFunctions(m, test_methods) < 0) { + return -1; + } + + PyTypeObject *builder_type = (PyTypeObject *)PyType_FromSpec(&Builder_spec); + if (builder_type == NULL) { + return -1; + } + if (PyModule_AddType(m, builder_type) < 0) { + Py_DECREF(builder_type); + return -1; + } + Py_DECREF(builder_type); + + if (PyModule_AddIntConstant(m, "LIST_SMALL_ALLOCATED", _Py_LIST_SMALL_ALLOCATED) < 0) { + return -1; + } + return 0; } diff --git a/Objects/listobject.c b/Objects/listobject.c index c5fe704df0e23d..b4b30bb10502a9 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -91,7 +91,7 @@ ensure_shared_on_resize(PyListObject *self) #endif } -#define LIST_SMALL_ALLOCATED 32 +#define LIST_SMALL_ALLOCATED _Py_LIST_SMALL_ALLOCATED static int py_list_resize(PyListObject *self, Py_ssize_t newsize); @@ -300,30 +300,50 @@ PyList_New(Py_ssize_t size) return (PyObject *) op; } +// Similar to PyList_New() but don't initialize memory and do not track +// the newly created list in the garbage collector. +// +// The list is initialized with a size of 0. +// +// size must be >= 0. static PyObject * list_new_prealloc(Py_ssize_t size) { - assert(size > 0); - PyListObject *op = (PyListObject *) PyList_New(0); + // The caller is responsible to check the size + assert(size >= 0); + + PyListObject *op = _Py_FREELIST_POP(PyListObject, lists); if (op == NULL) { - return NULL; + op = PyObject_GC_New(PyListObject, &PyList_Type); + if (op == NULL) { + return NULL; + } } - assert(op->ob_item == NULL); -#ifdef Py_GIL_DISABLED - _PyListArray *array = list_allocate_array(size); - if (array == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); + + Py_SET_SIZE(op, 0); + op->allocated = size; + + if (size == 0) { + op->ob_item = NULL; } - op->ob_item = array->ob_item; + else { +#ifdef Py_GIL_DISABLED + _PyListArray *array = list_allocate_array(size); + if (array == NULL) { + op->ob_item = NULL; + Py_DECREF(op); + return PyErr_NoMemory(); + } + op->ob_item = array->ob_item; #else - op->ob_item = PyMem_New(PyObject *, size); - if (op->ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } + op->ob_item = PyMem_New(PyObject *, size); + if (op->ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } #endif - op->allocated = size; + } + return (PyObject *) op; } @@ -767,6 +787,7 @@ list_slice_lock_held(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) dest[i] = Py_NewRef(v); } Py_SET_SIZE(np, len); + _PyObject_GC_TRACK(np); return (PyObject *)np; } @@ -849,6 +870,7 @@ list_concat_lock_held(PyListObject *a, PyListObject *b) dest[i] = Py_NewRef(v); } Py_SET_SIZE(np, size); + _PyObject_GC_TRACK(np); return (PyObject *)np; } @@ -919,6 +941,7 @@ list_repeat_impl(PyListObject *a, Py_ssize_t n) } Py_SET_SIZE(np, output_size); + _PyObject_GC_TRACK(np); return (PyObject *) np; } @@ -1508,6 +1531,7 @@ list_extend_dictitems(PyListObject *self, PyDictObject *dict) return 0; } +// If you update this function, update also PyListBuilder_Extend(). static int _list_extend(PyListObject *self, PyObject *iterable) { @@ -3728,6 +3752,7 @@ list_slice_step_lock_held(PyListObject *a, Py_ssize_t start, Py_ssize_t step, Py dest[i] = Py_NewRef(v); } Py_SET_SIZE(np, len); + _PyObject_GC_TRACK(np); return (PyObject *)np; } @@ -4393,3 +4418,333 @@ listiter_reduce_general(void *_it, int forward) } return Py_BuildValue("N(N)", iter, list); } + + +/* --- PyListBuilder API -------------------------------------------------- */ + +#ifndef NDEBUG +static int +listbuilder_check_consistency(PyListBuilder *builder) +{ + assert(builder != NULL); + assert(PyList_CheckExact(_PyObject_CAST(builder))); + PyListObject *list = (PyListObject*)builder; + assert(Py_SIZE(list) >= 0); + assert(Py_SIZE(list) <= list->allocated); + // Don't test _PyObject_IsUniquelyReferenced() since a list builder can + // be shared between multiple threads with external locking. + assert(Py_REFCNT(list) == 1); + assert(!_PyObject_GC_IS_TRACKED(list)); + return 1; +} +#endif + + +PyListBuilder* +PyListBuilder_Create(Py_ssize_t size) +{ + if (size < 0) { + PyErr_SetString(PyExc_ValueError, "size must not be negative"); + return NULL; + } + + PyObject *list = list_new_prealloc(size); + if (list == NULL) { + return NULL; + } + assert(Py_SIZE(list) == 0); + // In release mode, list items are uninitialized pointers which is safe, + // since the list object is not tracked by the GC, and the builder caller + // must initialize all items. + +#if _PyListBuilder_INIT_ITEMS + // In debug mode, set all items to NULL to be able to check that they are + // non-NULL in PyListBuilder_Finish(). + if (0 < size) { + memset(_PyList_CAST(list)->ob_item, 0, size * sizeof(PyObject*)); + } +#endif + + PyListBuilder *builder = (PyListBuilder*)list; + assert(listbuilder_check_consistency(builder)); + return builder; +} + + +void +PyListBuilder_Discard(PyListBuilder *builder) +{ + if (builder == NULL) { + return; + } + + assert(listbuilder_check_consistency(builder)); + PyObject *list = _PyObject_CAST(builder); + Py_DECREF(list); +} + + +PyObject* +PyListBuilder_Finish(PyListBuilder *builder) +{ + assert(listbuilder_check_consistency(builder)); + PyListObject *list = _PyList_CAST(builder); + + // Shrink the list if the allocated size is greater than the double size. + // For example, if PyListBuilder_Create() argument overestimated the final + // size. + if (list_resize(list, Py_SIZE(list)) < 0) { + // This case cannot happen: list_resize() never fails when shrinking + PyListBuilder_Discard(builder); + return NULL; + } + +#if _PyListBuilder_INIT_ITEMS + // Make sure that all list items have been set + Py_ssize_t size = Py_SIZE(list); + PyObject **list_items = list->ob_item; + for (Py_ssize_t index = 0; index < size; index++) { + if (list_items[index] == NULL) { + PyErr_Format(PyExc_SystemError, "list item #%zd is NULL", index); + Py_DECREF(list); + return NULL; + } + } +#endif + + // Now that the list is fully initialized, it's safe to track it in the GC + _PyObject_GC_TRACK(list); + return _PyObject_CAST(list); +} + + +static int +listbuilder_resize(PyListBuilder *builder, Py_ssize_t new_size) +{ + PyListObject *list = _PyList_CAST(builder); +#if _PyListBuilder_INIT_ITEMS + Py_ssize_t old_size = Py_SIZE(list); +#endif + assert(Py_SIZE(list) < new_size); + + // On Free Threading, it can call _PyObject_GC_SET_SHARED() on the list + int res = list_resize(list, new_size); + +#if _PyListBuilder_INIT_ITEMS + Py_ssize_t allocated = list->allocated; + if (res == 0 && allocated > old_size) { + // Set newly allocated items to NULL + memset(&list->ob_item[old_size], 0, + (allocated - old_size) * sizeof(PyObject*)); + } +#endif + return res; +} + + +int +PyListBuilder_AppendSteal(PyListBuilder *builder, PyObject *item) +{ + assert(listbuilder_check_consistency(builder)); + assert(item != NULL); + PyListObject *list = _PyList_CAST(builder); + + Py_ssize_t index = Py_SIZE(list); + Py_ssize_t allocated = list->allocated; + if (index < allocated) { + Py_SET_SIZE(list, index + 1); + list->ob_item[index] = item; + return 0; + } + + if (listbuilder_resize(builder, index + 1) < 0) { + Py_DECREF(item); + return -1; + } + + list->ob_item[index] = item; + return 0; +} + + +int +PyListBuilder_Append(PyListBuilder *builder, PyObject *item) +{ + return PyListBuilder_AppendSteal(builder, Py_NewRef(item)); +} + + +static void +listbuilder_reset_size(PyListBuilder *builder, Py_ssize_t size) +{ + assert(listbuilder_check_consistency(builder)); + PyListObject *list = _PyList_CAST(builder); + + Py_ssize_t new_size = Py_SIZE(list); + assert(0 <= size && size <= new_size); + + Py_SET_SIZE(list, size); + + // Discard added items + PyObject **items = list->ob_item; + for (Py_ssize_t i = size; i < new_size; i++) { + Py_DECREF(items[i]); +#if _PyListBuilder_INIT_ITEMS + items[i] = NULL; +#endif + } +} + + +// Similar to _list_extend() but don't lock the builder list. +// If you update this function, update also _list_extend(). +int +PyListBuilder_Extend(PyListBuilder *builder, PyObject *iterable) +{ + assert(listbuilder_check_consistency(builder)); + PyListObject *self = _PyList_CAST(builder); + assert(_PyObject_CAST(self) != iterable); + +#if _PyListBuilder_INIT_ITEMS + Py_ssize_t old_allocated = self->allocated; +#endif + Py_ssize_t old_size = Py_SIZE(self); + int res; + if (PyList_CheckExact(iterable)) { + Py_BEGIN_CRITICAL_SECTION(iterable); + res = list_extend_lock_held(self, iterable); + Py_END_CRITICAL_SECTION(); + } + else if (PyTuple_CheckExact(iterable)) { + res = list_extend_lock_held(self, iterable); + } + else if (PyAnySet_CheckExact(iterable)) { + Py_BEGIN_CRITICAL_SECTION(iterable); + res = list_extend_set(self, (PySetObject *)iterable); + Py_END_CRITICAL_SECTION(); + } + else if (PyDict_CheckExact(iterable)) { + Py_BEGIN_CRITICAL_SECTION(iterable); + res = list_extend_dict(self, (PyDictObject *)iterable, 0 /*keys*/); + Py_END_CRITICAL_SECTION(); + } + else if (Py_IS_TYPE(iterable, &PyDictKeys_Type)) { + PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict; + Py_BEGIN_CRITICAL_SECTION(dict); + res = list_extend_dict(self, dict, 0 /*keys*/); + Py_END_CRITICAL_SECTION(); + } + else if (Py_IS_TYPE(iterable, &PyDictValues_Type)) { + PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict; + Py_BEGIN_CRITICAL_SECTION(dict); + res = list_extend_dict(self, dict, 1 /*values*/); + Py_END_CRITICAL_SECTION(); + } + else if (Py_IS_TYPE(iterable, &PyDictItems_Type)) { + PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict; + Py_BEGIN_CRITICAL_SECTION(dict); + res = list_extend_dictitems(self, dict); + Py_END_CRITICAL_SECTION(); + } + else { + res = list_extend_iter_lock_held(self, iterable); + } + +#if _PyListBuilder_INIT_ITEMS + Py_ssize_t new_size = Py_SIZE(self); + // Check if the list has been resized + if (old_allocated < self->allocated && new_size < self->allocated) { + // Initialize newly allocated items to NULL + memset(&self->ob_item[new_size], 0, + (self->allocated - new_size) * sizeof(PyObject*)); + } +#endif + + if (res < 0) { + // On error, reset the builder to its previous state: + // discard added items + listbuilder_reset_size(builder, old_size); + } + + return res; +} + + +// Force inlining to optimize "if (steal)" at build time. +// On error if steal is non-zero, the caller must clear the array. +static inline Py_ALWAYS_INLINE int +listbuilder_extend_array(PyListBuilder *builder, + PyObject *const *items, Py_ssize_t nitem, + int steal) +{ +#ifdef Py_DEBUG + if (nitem < 0) { + PyErr_Format(PyExc_ValueError, "nitem must be >= 0"); + return -1; + } +#endif + + assert(listbuilder_check_consistency(builder)); + assert(nitem >= 0); + + if (nitem == 0) { + // Fast path. Avoid also memcpy(dst, src, 0) undefined behavior below. + return 0; + } + +#ifdef Py_DEBUG + for (Py_ssize_t index = 0; index < nitem; index++) { + if (items[index] == NULL) { + PyErr_Format(PyExc_SystemError, "array item #%zd is NULL", index); + return -1; + } + } +#endif + + PyListObject *list = _PyList_CAST(builder); + Py_ssize_t old_size = Py_SIZE(list); + Py_ssize_t new_size = old_size + nitem; + if (new_size > list->allocated) { + if (listbuilder_resize(builder, new_size) < 0) { + return -1; + } + } + else { + Py_SET_SIZE(list, new_size); + } + + PyObject **list_items = &list->ob_item[old_size]; + if (steal) { + memcpy(list_items, items, nitem * sizeof(PyObject*)); + } + else { + for (Py_ssize_t i = 0; i < nitem; i++) { + list_items[i] = Py_NewRef(items[i]); + } + } + return 0; +} + + +int +PyListBuilder_ExtendArray(PyListBuilder *builder, + PyObject *const *items, Py_ssize_t nitem) +{ + return listbuilder_extend_array(builder, items, nitem, 0); +} + + +int +PyListBuilder_ExtendArraySteal(PyListBuilder *builder, + PyObject *const *items, Py_ssize_t nitem) +{ + int res = listbuilder_extend_array(builder, items, nitem, 1); + if (res < 0) { + for (Py_ssize_t index = 0; index < nitem; index++) { + // In debug mode, PyListBuilder_ExtendArraySteal() raises + // SystemError if an item is NULL + Py_XDECREF(items[index]); + } + } + return res; +}