Godot Engine – Multi-platform 2D and 3D game engine
Refactor `CowData` around `_insert_uninitialized` and `_remove` to simplify callees. Add `Vector.append_array` with `Span`. Optimize `Vector.append_array`.
Lukas Tenbrink9ebdb6c7b039
diff --git a/core/templates/cowdata.h b/core/templates/cowdata.hindex c1ba9d76845..cafb7088cb5 100644--- a/core/templates/cowdata.h+++ b/core/templates/cowdata.h@@ -138,13 +138,16 @@ private:/// - Ensure p_capacity > 0Error _realloc_exact(USize p_capacity);- /// Create a new buffer and copies over elements from the old buffer.- /// Elements are inserted first from the start, then a gap is left uninitialized, and then elements are inserted from the back.- /// It is the responsibility of the caller to:- /// - Construct elements in the gap.- /// - Ensure size() >= p_size_from_start and size() >= p_size_from_back.- /// - Ensure p_capacity is enough to hold all elements.- [[nodiscard]] Error _copy_to_new_buffer_exact(USize p_capacity, USize p_size_from_start, USize p_gap, USize p_size_from_back);+ /// Adds a gap of new elements into the buffer at the specified position.+ /// After the call, this CowData is the only owner of the buffer so the new elements are ready to initialize.+ /// Does not modify the size.+ [[nodiscard]] Error _insert_uninitialized(USize p_index, USize p_count, USize p_capacity);+ [[nodiscard]] Error _insert_uninitialized(USize p_index, USize p_count) {+ return _insert_uninitialized(p_index, p_count, next_capacity(capacity(), size() + p_count));+ }+ /// Removes elements from the buffer at the specified position, moving elements behind to accommodate.+ /// After the call, this CowData is the only owner of the buffer.+ [[nodiscard]] Error _remove(USize p_index, USize p_count);/// Ensure we are the only owners of the backing buffer.[[nodiscard]] Error _copy_on_write();@@ -211,7 +214,10 @@ public:_FORCE_INLINE_ void remove_at(Size p_index);Error insert(Size p_pos, T &&p_val);+ /// The caller is required to ensure p_val is not in the buffer (see GH-31736).Error push_back(T &&p_val);+ Error append(const CowData<T> &p_data);+ Error append(Span<T> p_span);_FORCE_INLINE_ operator Span<T>() const _LIFETIME_BOUND_ { return Span<T>(ptr(), size()); }_FORCE_INLINE_ Span<T> span() const _LIFETIME_BOUND_ { return operator Span<T>(); }@@ -272,105 +278,162 @@ void CowData<T>::_unref() {template <typename T>void CowData<T>::remove_at(Size p_index) {- const Size prev_size = size();- ERR_FAIL_INDEX(p_index, prev_size);+ ERR_FAIL_INDEX(p_index, size());+ CRASH_COND(_remove(p_index, 1));+}- if (prev_size == 1) {- // Removing the only element.- _unref();- return;+template <typename T>+Error CowData<T>::insert(Size p_pos, T &&p_val) {+ const Size new_size = size() + 1;+ ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);++ Error error = _insert_uninitialized(p_pos, 1);+ if (error) {+ return error;}- const USize new_size = prev_size - 1;+ // Create the new element at the given index.+ memnew_placement(_ptr + p_pos, T(std::move(p_val)));+ *_get_size() = new_size;- if (_get_refcount()->get() == 1) {- // We're the only owner; remove in-place.+ return OK;+}- // Destruct the element, then relocate the rest one down.- _ptr[p_index].~T();- memmove((void *)(_ptr + p_index), (void *)(_ptr + p_index + 1), (new_size - p_index) * sizeof(T));+template <typename T>+Error CowData<T>::push_back(T &&p_val) {+ Error error = _insert_uninitialized(size(), 1);+ if (error) {+ return error;+ }- // Shrink to fit if necessary.- const USize new_capacity = smaller_capacity(capacity(), new_size);- if (new_capacity < capacity()) {- Error err = _realloc_exact(new_capacity);- CRASH_COND(err);- }- *_get_size() = new_size;- } else {- // Remove by forking.- Error err = _copy_to_new_buffer_exact(smaller_capacity(capacity(), new_size), p_index, 0, new_size - p_index);- CRASH_COND(err);+ memnew_placement(_ptr + size(), T(std::move(p_val)));+ *_get_size() = size() + 1;++ return OK;+}++template <typename T>+Error CowData<T>::append(const CowData<T> &p_data) {+ if (!_ptr) {+ // Grow by making a CoW copy.+ *this = p_data;+ return OK;}+ return append(p_data.span());}template <typename T>-Error CowData<T>::insert(Size p_pos, T &&p_val) {- const Size new_size = size() + 1;- ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);+Error CowData<T>::append(Span<T> p_span) {+ if (p_span.is_empty()) {+ return OK;+ }+ // If the span points inside our buffer, we need to resolve the index now.+ // Otherwise it might be invalidated on growth.+ const bool span_in_self = _ptr && p_span.ptr() >= _ptr && p_span.ptr() < _ptr + size();+ const Size idx_in_self = span_in_self ? (p_span.ptr() - _ptr) : -1;++ const Error error = _insert_uninitialized(size(), p_span.size());+ if (error) {+ return error;+ }+ const T *span_ptr = span_in_self ? (_ptr + idx_in_self) : p_span.ptr();+ copy_arr_placement(_ptr + size(), span_ptr, p_span.size());+ *_get_size() = size() + p_span.size();+ return OK;+}++template <typename T>+Error CowData<T>::_insert_uninitialized(USize p_index, USize p_count, USize p_capacity) {+ DEV_ASSERT(p_capacity >= (USize)size() + p_count);if (!_ptr) {- _alloc_exact(next_capacity(0, 1));- *_get_size() = 1;+ return _alloc_exact(p_capacity);} else if (_get_refcount()->get() == 1) {- if ((USize)new_size > capacity()) {+ if (capacity() < p_capacity) {// Need to grow.- const Error error = _realloc_exact(grow_capacity(capacity()));+ const Error error = _realloc_exact(p_capacity);if (error) {return error;}}- // Relocate elements one position up.- memmove((void *)(_ptr + p_pos + 1), (void *)(_ptr + p_pos), (size() - p_pos) * sizeof(T));- *_get_size() = new_size;+ // Relocate elements up.+ if (p_index != (USize)size()) {+ memmove((void *)(_ptr + p_index + p_count), (void *)(_ptr + p_index), (size() - p_index) * sizeof(T));+ }} else {// Insert new element by forking.- // Use the max of capacity and new_size, to ensure we don't accidentally shrink after reserve.- const USize new_capacity = next_capacity(capacity(), new_size);- const Error error = _copy_to_new_buffer_exact(new_capacity, p_pos, 1, size() - p_pos);+ // Initialize the data elsewhere first and only swap when it's ready.+ CowData new_data;++ const Error error = new_data._alloc_exact(p_capacity);if (error) {return error;}- }- // Create the new element at the given index.- memnew_placement(_ptr + p_pos, T(std::move(p_val)));+ // Copy over elements.+ copy_arr_placement(new_data._ptr, _ptr, p_index);+ copy_arr_placement(+ new_data._ptr + p_index + p_count,+ _ptr + p_index,+ size() - p_index);++ *new_data._get_size() = size();+ SWAP(_ptr, new_data._ptr);+ }return OK;}template <typename T>-Error CowData<T>::push_back(T &&p_val) {- const Size new_size = size() + 1;+Error CowData<T>::_remove(USize p_index, USize p_count) {+ DEV_ASSERT(_ptr);+ DEV_ASSERT(p_index + p_count <= (USize)size());- if (!_ptr) {- // Grow by allocating.- _alloc_exact(next_capacity(0, 1));- *_get_size() = 1;- } else if (_get_refcount()->get() == 1) {- // Grow in-place.- if ((USize)new_size > capacity()) {- // Need to grow.- const Error error = _realloc_exact(grow_capacity(capacity()));- if (error) {- return error;- }+ const Size prev_size = size();+ if ((USize)prev_size == p_count) {+ // Removing all elements.+ _unref();+ return OK;+ }++ const USize new_size = prev_size - p_count;++ if (_get_refcount()->get() == 1) {+ // We're the only owner; remove in-place.++ // Destruct the elements, then relocate the rest down.+ destruct_arr_placement(_ptr + p_index, p_count);+ if (p_index != prev_size - p_count) {+ memmove((void *)(_ptr + p_index), (void *)(_ptr + p_index + p_count), (new_size - p_index) * sizeof(T));}- *_get_size() = new_size;+ // Shrink to fit if necessary.+ const USize new_capacity = smaller_capacity(capacity(), new_size);+ if (new_capacity < capacity()) {+ Error err = _realloc_exact(new_capacity);+ CRASH_COND(err);+ }} else {- // Grow by forking.- // Use the max of capacity and new_size, to ensure we don't accidentally shrink after reserve.- const USize new_capacity = next_capacity(capacity(), new_size);- const Error error = _copy_to_new_buffer_exact(new_capacity, size(), 1, 0);+ // Remove by forking.+ CowData new_data;++ const Error error = new_data._alloc_exact(smaller_capacity(capacity(), new_size));if (error) {return error;}++ // Copy over elements.+ copy_arr_placement(new_data._ptr, _ptr, p_index);+ copy_arr_placement(+ new_data._ptr + p_index,+ _ptr + p_index + p_count,+ size() - p_index - p_count);++ SWAP(_ptr, new_data._ptr);}- // Create the new element at the given index.- memnew_placement(_ptr + new_size - 1, T(std::move(p_val)));+ *_get_size() = new_size;return OK;}@@ -378,8 +441,7 @@ Error CowData<T>::push_back(T &&p_val) {template <typename T>template <bool p_exact>Error CowData<T>::reserve(USize p_min_capacity) {- USize new_capacity = p_exact ? p_min_capacity : next_capacity(capacity(), p_min_capacity);- if (new_capacity <= capacity()) {+ if (p_min_capacity <= capacity()) {if (p_min_capacity < (USize)size()) {WARN_VERBOSE("reserve() called with a capacity smaller than the current size. This is likely a mistake.");}@@ -387,16 +449,8 @@ Error CowData<T>::reserve(USize p_min_capacity) {return OK;}- if (!_ptr) {- // Initial allocation.- return _alloc_exact(new_capacity);- } else if (_get_refcount()->get() == 1) {- // Grow in-place.- return _realloc_exact(new_capacity);- } else {- // Grow by forking.- return _copy_to_new_buffer_exact(new_capacity, size(), 0, 0);- }+ USize new_capacity = p_exact ? p_min_capacity : next_capacity(capacity(), p_min_capacity);+ return _insert_uninitialized(size(), 0, new_capacity);}template <typename T>@@ -413,26 +467,9 @@ Error CowData<T>::resize(Size p_size) {if (p_size > prev_size) {// Caller wants to grow.- if (!_ptr) {- // Grow by allocating.- const Error error = _alloc_exact(next_capacity(0, p_size));- if (error) {- return error;- }- } else if (_get_refcount()->get() == 1) {- // Grow in-place.- if ((USize)p_size > capacity()) {- const Error error = _realloc_exact(next_capacity(capacity(), p_size));- if (error) {- return error;- }- }- } else {- // Grow by forking.- const Error error = _copy_to_new_buffer_exact(next_capacity(capacity(), p_size), prev_size, 0, 0);- if (error) {- return error;- }+ const Error error = _insert_uninitialized(prev_size, p_size - prev_size);+ if (error) {+ return error;}// Construct new elements.@@ -444,28 +481,7 @@ Error CowData<T>::resize(Size p_size) {return OK;} else {// Caller wants to shrink.-- if (p_size == 0) {- _unref();- return OK;- } else if (_get_refcount()->get() == 1) {- // Shrink in-place.- destruct_arr_placement(_ptr + p_size, prev_size - p_size);-- // Shrink buffer if necessary.- const USize new_capacity = smaller_capacity(capacity(), p_size);- if (new_capacity < capacity()) {- Error err = _realloc_exact(new_capacity);- CRASH_COND(err);- }-- *_get_size() = p_size;- return OK;- } else {- // Shrink by forking.- const USize new_capacity = smaller_capacity(capacity(), p_size);- return _copy_to_new_buffer_exact(new_capacity, p_size, 0, 0);- }+ return _remove(p_size, prev_size - p_size);}}@@ -506,37 +522,6 @@ Error CowData<T>::_realloc_exact(USize p_capacity) {return OK;}-template <typename T>-Error CowData<T>::_copy_to_new_buffer_exact(USize p_capacity, USize p_size_from_start, USize p_gap, USize p_size_from_back) {- DEV_ASSERT(p_capacity >= p_size_from_start + p_size_from_back + p_gap);- DEV_ASSERT((USize)size() >= p_size_from_start && (USize)size() >= p_size_from_back);-- // Create a temporary CowData to hold ownership over our _ptr.- // It will be used to copy elements from the old buffer over to our new buffer.- // At the end of the block, it will be automatically destructed by going out of scope.- const CowData prev_data;- prev_data._ptr = _ptr;- _ptr = nullptr;-- const Error error = _alloc_exact(p_capacity);- if (error) {- // On failure to allocate, recover the old data and return the error.- _ptr = prev_data._ptr;- prev_data._ptr = nullptr;- return error;- }-- // Copy over elements.- copy_arr_placement(_ptr, prev_data._ptr, p_size_from_start);- copy_arr_placement(- _ptr + p_size_from_start + p_gap,- prev_data._ptr + prev_data.size() - p_size_from_back,- p_size_from_back);- *_get_size() = p_size_from_start + p_gap + p_size_from_back;-- return OK;-}-template <typename T>Error CowData<T>::_copy_on_write() {if (!_ptr || _get_refcount()->get() == 1) {@@ -545,7 +530,7 @@ Error CowData<T>::_copy_on_write() {}// Fork to become the only reference.- return _copy_to_new_buffer_exact(capacity(), size(), 0, 0);+ return _insert_uninitialized(size(), 0, capacity());}template <typename T>diff --git a/core/templates/vector.h b/core/templates/vector.hindex 251c4d7059b..4be47175431 100644--- a/core/templates/vector.h+++ b/core/templates/vector.h@@ -165,8 +165,8 @@ public:}Size count(const T &p_val) const { return span().count(p_val); }- // Must take a copy instead of a reference (see GH-31736).- void append_array(Vector<T> p_other);+ void append_array(const Vector<T> &p_other) { _cowdata.append(p_other._cowdata); }+ void append_array(Span<T> p_other) { _cowdata.append(p_other); }_FORCE_INLINE_ bool has(const T &p_val) const { return find(p_val) != -1; }@@ -337,20 +337,6 @@ void Vector<T>::reverse() {}}-template <typename T>-void Vector<T>::append_array(Vector<T> p_other) {- const Size ds = p_other.size();- if (ds == 0) {- return;- }- const Size bs = size();- resize(bs + ds);- T *p = ptrw();- for (Size i = 0; i < ds; ++i) {- p[bs + i] = p_other[i];- }-}-template <typename T>void Vector<T>::fill(T p_elem) {T *p = ptrw();diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cppindex 8d9c6beb490..408cf499cd6 100644--- a/core/variant/variant_call.cpp+++ b/core/variant/variant_call.cpp@@ -2625,6 +2625,9 @@ static void _register_variant_builtin_methods_misc() {bind_method(Dictionary, recursive_equal, sarray("dictionary", "recursion_count"), varray());}+template <typename T>+static constexpr auto vector_append_array = static_cast<void (Vector<T>::*)(const Vector<T> &)>(&Vector<T>::append_array);+static void _register_variant_builtin_methods_array() {/* Array */@@ -2708,7 +2711,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedByteArray, is_empty, sarray(), varray());bind_method(PackedByteArray, push_back, sarray("value"), varray());bind_method(PackedByteArray, append, sarray("value"), varray());- bind_method(PackedByteArray, append_array, sarray("array"), varray());+ bind_methodv(PackedByteArray, append_array, vector_append_array<uint8_t>, sarray("array"), varray());bind_method(PackedByteArray, remove_at, sarray("index"), varray());bind_method(PackedByteArray, insert, sarray("at_index", "value"), varray());bind_method(PackedByteArray, fill, sarray("value"), varray());@@ -2787,7 +2790,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedInt32Array, is_empty, sarray(), varray());bind_method(PackedInt32Array, push_back, sarray("value"), varray());bind_method(PackedInt32Array, append, sarray("value"), varray());- bind_method(PackedInt32Array, append_array, sarray("array"), varray());+ bind_methodv(PackedInt32Array, append_array, vector_append_array<int32_t>, sarray("array"), varray());bind_method(PackedInt32Array, remove_at, sarray("index"), varray());bind_method(PackedInt32Array, insert, sarray("at_index", "value"), varray());bind_method(PackedInt32Array, fill, sarray("value"), varray());@@ -2815,7 +2818,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedInt64Array, is_empty, sarray(), varray());bind_method(PackedInt64Array, push_back, sarray("value"), varray());bind_method(PackedInt64Array, append, sarray("value"), varray());- bind_method(PackedInt64Array, append_array, sarray("array"), varray());+ bind_methodv(PackedInt64Array, append_array, vector_append_array<int64_t>, sarray("array"), varray());bind_method(PackedInt64Array, remove_at, sarray("index"), varray());bind_method(PackedInt64Array, insert, sarray("at_index", "value"), varray());bind_method(PackedInt64Array, fill, sarray("value"), varray());@@ -2843,7 +2846,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedFloat32Array, is_empty, sarray(), varray());bind_method(PackedFloat32Array, push_back, sarray("value"), varray());bind_method(PackedFloat32Array, append, sarray("value"), varray());- bind_method(PackedFloat32Array, append_array, sarray("array"), varray());+ bind_methodv(PackedFloat32Array, append_array, vector_append_array<float>, sarray("array"), varray());bind_method(PackedFloat32Array, remove_at, sarray("index"), varray());bind_method(PackedFloat32Array, insert, sarray("at_index", "value"), varray());bind_method(PackedFloat32Array, fill, sarray("value"), varray());@@ -2871,7 +2874,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedFloat64Array, is_empty, sarray(), varray());bind_method(PackedFloat64Array, push_back, sarray("value"), varray());bind_method(PackedFloat64Array, append, sarray("value"), varray());- bind_method(PackedFloat64Array, append_array, sarray("array"), varray());+ bind_methodv(PackedFloat64Array, append_array, vector_append_array<double>, sarray("array"), varray());bind_method(PackedFloat64Array, remove_at, sarray("index"), varray());bind_method(PackedFloat64Array, insert, sarray("at_index", "value"), varray());bind_method(PackedFloat64Array, fill, sarray("value"), varray());@@ -2899,7 +2902,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedStringArray, is_empty, sarray(), varray());bind_method(PackedStringArray, push_back, sarray("value"), varray());bind_method(PackedStringArray, append, sarray("value"), varray());- bind_method(PackedStringArray, append_array, sarray("array"), varray());+ bind_methodv(PackedStringArray, append_array, vector_append_array<String>, sarray("array"), varray());bind_method(PackedStringArray, remove_at, sarray("index"), varray());bind_method(PackedStringArray, insert, sarray("at_index", "value"), varray());bind_method(PackedStringArray, fill, sarray("value"), varray());@@ -2927,7 +2930,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedVector2Array, is_empty, sarray(), varray());bind_method(PackedVector2Array, push_back, sarray("value"), varray());bind_method(PackedVector2Array, append, sarray("value"), varray());- bind_method(PackedVector2Array, append_array, sarray("array"), varray());+ bind_methodv(PackedVector2Array, append_array, vector_append_array<Vector2>, sarray("array"), varray());bind_method(PackedVector2Array, remove_at, sarray("index"), varray());bind_method(PackedVector2Array, insert, sarray("at_index", "value"), varray());bind_method(PackedVector2Array, fill, sarray("value"), varray());@@ -2955,7 +2958,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedVector3Array, is_empty, sarray(), varray());bind_method(PackedVector3Array, push_back, sarray("value"), varray());bind_method(PackedVector3Array, append, sarray("value"), varray());- bind_method(PackedVector3Array, append_array, sarray("array"), varray());+ bind_methodv(PackedVector3Array, append_array, vector_append_array<Vector3>, sarray("array"), varray());bind_method(PackedVector3Array, remove_at, sarray("index"), varray());bind_method(PackedVector3Array, insert, sarray("at_index", "value"), varray());bind_method(PackedVector3Array, fill, sarray("value"), varray());@@ -2983,7 +2986,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedColorArray, is_empty, sarray(), varray());bind_method(PackedColorArray, push_back, sarray("value"), varray());bind_method(PackedColorArray, append, sarray("value"), varray());- bind_method(PackedColorArray, append_array, sarray("array"), varray());+ bind_methodv(PackedColorArray, append_array, vector_append_array<Color>, sarray("array"), varray());bind_method(PackedColorArray, remove_at, sarray("index"), varray());bind_method(PackedColorArray, insert, sarray("at_index", "value"), varray());bind_method(PackedColorArray, fill, sarray("value"), varray());@@ -3011,7 +3014,7 @@ static void _register_variant_builtin_methods_array() {bind_method(PackedVector4Array, is_empty, sarray(), varray());bind_method(PackedVector4Array, push_back, sarray("value"), varray());bind_method(PackedVector4Array, append, sarray("value"), varray());- bind_method(PackedVector4Array, append_array, sarray("array"), varray());+ bind_methodv(PackedVector4Array, append_array, vector_append_array<Vector4>, sarray("array"), varray());bind_method(PackedVector4Array, remove_at, sarray("index"), varray());bind_method(PackedVector4Array, insert, sarray("at_index", "value"), varray());bind_method(PackedVector4Array, fill, sarray("value"), varray());