Debian Codegraph @

core/templates/cowdata.h

raw symbols SCIP
1 /**************************************************************************/
2 /* cowdata.h */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #pragma once
32
33 #include "core/error/error_macros.h"
34 #include "core/os/memory.h"
35 #include "core/string/print_string.h"
36 #include "core/templates/safe_refcount.h"
37 #include "core/templates/span.h"
38
39 #include <initializer_list>
40 #include <type_traits>
41
42 static_assert(std::is_trivially_destructible_v<std::atomic<uint64_t>>);
43
44 // Silences false-positive warnings.
45 GODOT_GCC_WARNING_PUSH
46 GODOT_GCC_WARNING_IGNORE("-Wplacement-new") // Silence a false positive warning (see GH-52119).
47 GODOT_GCC_WARNING_IGNORE("-Wmaybe-uninitialized") // False positive raised when using constexpr.
48 GODOT_GCC_WARNING_IGNORE("-Warray-bounds")
49 GODOT_GCC_WARNING_IGNORE("-Wrestrict")
50 GODOT_GCC_PRAGMA(GCC diagnostic warning "-Wstringop-overflow=0") // Can't "ignore" this for some reason.
51 #ifdef WINDOWS_ENABLED
52 GODOT_GCC_PRAGMA(GCC diagnostic warning "-Wdangling-pointer=0") // Can't "ignore" this for some reason.
53 #endif
54
55 template <typename T>
56 class CowData {
57 public:
58 typedef int64_t Size;
59 typedef uint64_t USize;
60 static constexpr USize MAX_INT = INT64_MAX;
61
62 private:
63 // Alignment: ↓ max_align_t ↓ USize ↓ USize ↓ MAX_ALIGN
64 // ┌────────────────────┬──┬───────────────┬──┬─────────────┬──┬───────────...
65 // │ SafeNumeric<USize> │░░│ USize │░░│ USize │░░│ T[]
66 // │ ref. count │░░│ data capacity │░░│ data size │░░│ data
67 // └────────────────────┴──┴───────────────┴──┴─────────────┴──┴───────────...
68 // Offset: ↑ REF_COUNT_OFFSET ↑ CAPACITY_OFFSET ↑ SIZE_OFFSET ↑ DATA_OFFSET
69
70 static constexpr size_t REF_COUNT_OFFSET = 0;
71 static constexpr size_t CAPACITY_OFFSET = Memory::get_aligned_address(REF_COUNT_OFFSET + sizeof(SafeNumeric<USize>), alignof(USize));
72 static constexpr size_t SIZE_OFFSET = Memory::get_aligned_address(CAPACITY_OFFSET + sizeof(USize), alignof(USize));
73 static constexpr size_t DATA_OFFSET = Memory::get_aligned_address(SIZE_OFFSET + sizeof(USize), Memory::MAX_ALIGN);
74
75 mutable T *_ptr = nullptr;
76
77 // internal helpers
78
79 static constexpr _FORCE_INLINE_ USize grow_capacity(USize p_previous_capacity) {
80 // 1.5x the given size.
81 // This ratio was chosen because it is close to the ideal growth rate of the golden ratio.
82 // See https://archive.ph/Z2R8w for details.
83 return MAX((USize)2, p_previous_capacity + ((1 + p_previous_capacity) >> 1));
84 }
85
86 static constexpr _FORCE_INLINE_ USize next_capacity(USize p_previous_capacity, USize p_size) {
87 if (p_previous_capacity < p_size) {
88 return MAX(grow_capacity(p_previous_capacity), p_size);
89 }
90 return p_previous_capacity;
91 }
92
93 static constexpr _FORCE_INLINE_ USize smaller_capacity(USize p_previous_capacity, USize p_size) {
94 if (p_size < p_previous_capacity >> 2) {
95 return grow_capacity(p_size);
96 }
97 return p_previous_capacity;
98 }
99
100 static _FORCE_INLINE_ T *_get_data_ptr(uint8_t *p_ptr) {
101 return (T *)(p_ptr + DATA_OFFSET);
102 }
103
104 /// Note: Assumes _ptr != nullptr.
105 _FORCE_INLINE_ SafeNumeric<USize> *_get_refcount() const {
106 return (SafeNumeric<USize> *)((uint8_t *)_ptr - DATA_OFFSET + REF_COUNT_OFFSET);
107 }
108
109 /// Note: Assumes _ptr != nullptr.
110 _FORCE_INLINE_ USize *_get_size() const {
111 return (USize *)((uint8_t *)_ptr - DATA_OFFSET + SIZE_OFFSET);
112 }
113
114 /// Note: Assumes _ptr != nullptr.
115 _FORCE_INLINE_ USize *_get_capacity() const {
116 return (USize *)((uint8_t *)_ptr - DATA_OFFSET + CAPACITY_OFFSET);
117 }
118
119 // Decrements the reference count. Deallocates the backing buffer if needed.
120 // After this function, _ptr is guaranteed to be NULL.
121 void _unref();
122 void _ref(const CowData *p_from);
123 void _ref(const CowData &p_from);
124
125 /// Allocates a backing array of the given capacity. The reference count is initialized to 1, size to 0.
126 /// It is the responsibility of the caller to:
127 /// - Ensure _ptr == nullptr
128 /// - Ensure p_capacity > 0
129 Error _alloc_exact(USize p_capacity);
130
131 /// Re-allocates the backing array to the given capacity.
132 /// It is the responsibility of the caller to:
133 /// - Ensure we are the only owner of the backing array
134 /// - Ensure p_capacity > 0
135 Error _realloc_exact(USize p_capacity);
136
137 /// Create a new buffer and copies over elements from the old buffer.
138 /// Elements are inserted first from the start, then a gap is left uninitialized, and then elements are inserted from the back.
139 /// It is the responsibility of the caller to:
140 /// - Construct elements in the gap.
141 /// - Ensure size() >= p_size_from_start and size() >= p_size_from_back.
142 /// - Ensure p_capacity is enough to hold all elements.
143 [[nodiscard]] Error _copy_to_new_buffer_exact(USize p_capacity, USize p_size_from_start, USize p_gap, USize p_size_from_back);
144
145 /// Ensure we are the only owners of the backing buffer.
146 [[nodiscard]] Error _copy_on_write();
147
148 public:
149 void operator=(const CowData<T> &p_from) { _ref(p_from); }
150 void operator=(CowData<T> &&p_from) {
151 if (_ptr == p_from._ptr) {
152 return;
153 }
154
155 _unref();
156 _ptr = p_from._ptr;
157 p_from._ptr = nullptr;
158 }
159
160 _FORCE_INLINE_ T *ptrw() {
161 // If forking fails, we can only crash.
162 CRASH_COND(_copy_on_write());
163 return _ptr;
164 }
165
166 _FORCE_INLINE_ const T *ptr() const {
167 return _ptr;
168 }
169
170 _FORCE_INLINE_ Size size() const { return !_ptr ? 0 : *_get_size(); }
171 _FORCE_INLINE_ USize capacity() const { return !_ptr ? 0 : *_get_capacity(); }
172 _FORCE_INLINE_ USize refcount() const { return !_ptr ? 0 : *_get_refcount(); }
173
174 _FORCE_INLINE_ void clear() { _unref(); }
175 _FORCE_INLINE_ bool is_empty() const { return size() == 0; }
176
177 _FORCE_INLINE_ void set(Size p_index, const T &p_elem) {
178 ERR_FAIL_INDEX(p_index, size());
179 // TODO Returning the error would be more appropriate.
180 CRASH_COND(_copy_on_write());
181 _ptr[p_index] = p_elem;
182 }
183
184 _FORCE_INLINE_ T &get_m(Size p_index) {
185 CRASH_BAD_INDEX(p_index, size());
186 // If we fail to fork, all we can do is crash,
187 // since the caller may write incorrectly to the unforked array.
188 CRASH_COND(_copy_on_write());
189 return _ptr[p_index];
190 }
191
192 _FORCE_INLINE_ const T &get(Size p_index) const {
193 CRASH_BAD_INDEX(p_index, size());
194
195 return _ptr[p_index];
196 }
197
198 template <bool p_init = false>
199 Error resize(Size p_size);
200
201 template <bool p_exact = false>
202 Error reserve(USize p_min_capacity);
203 _FORCE_INLINE_ Error reserve_exact(USize p_capacity) {
204 return reserve<true>(p_capacity);
205 }
206
207 _FORCE_INLINE_ void remove_at(Size p_index);
208
209 Error insert(Size p_pos, T &&p_val);
210 Error push_back(T &&p_val);
211
212 _FORCE_INLINE_ operator Span<T>() const { return Span<T>(ptr(), size()); }
213 _FORCE_INLINE_ Span<T> span() const { return operator Span<T>(); }
214
215 _FORCE_INLINE_ CowData() {}
216 _FORCE_INLINE_ ~CowData() { _unref(); }
217 _FORCE_INLINE_ CowData(std::initializer_list<T> p_init);
218 _FORCE_INLINE_ CowData(const CowData<T> &p_from) { _ref(p_from); }
219 _FORCE_INLINE_ CowData(CowData<T> &&p_from) {
220 _ptr = p_from._ptr;
221 p_from._ptr = nullptr;
222 }
223 };
224
225 template <typename T>
226 void CowData<T>::_unref() {
227 if (!_ptr) {
228 return;
229 }
230
231 if (_get_refcount()->decrement() > 0) {
232 // Data is still in use elsewhere.
233 _ptr = nullptr;
234 return;
235 }
236 // We had the only reference; destroy the data.
237
238 // First, invalidate our own reference.
239 // NOTE: It is required to do so immediately because it must not be observable outside of this
240 // function after refcount has already been reduced to 0.
241 // WARNING: It must be done before calling the destructors, because one of them may otherwise
242 // observe it through a reference to us. In this case, it may try to access the buffer,
243 // which is illegal after some of the elements in it have already been destructed, and
244 // may lead to a segmentation fault.
245 USize current_size = size();
246 T *prev_ptr = _ptr;
247 _ptr = nullptr;
248
249 destruct_arr_placement(prev_ptr, current_size);
250
251 // Safety check; none of the destructors should have added elements during destruction.
252 DEV_ASSERT(!_ptr);
253
254 // Free Memory.
255 Memory::free_static((uint8_t *)prev_ptr - DATA_OFFSET, false);
256
257 #ifdef DEBUG_ENABLED
258 // If any destructors access us through pointers, it is a bug.
259 // We can't really test for that, but we can at least check no items have been added.
260 ERR_FAIL_COND_MSG(_ptr != nullptr, "Internal bug, please report: CowData was modified during destruction.");
261 #endif
262 }
263
264 template <typename T>
265 void CowData<T>::remove_at(Size p_index) {
266 const Size prev_size = size();
267 ERR_FAIL_INDEX(p_index, prev_size);
268
269 if (prev_size == 1) {
270 // Removing the only element.
271 _unref();
272 return;
273 }
274
275 const USize new_size = prev_size - 1;
276
277 if (_get_refcount()->get() == 1) {
278 // We're the only owner; remove in-place.
279
280 // Destruct the element, then relocate the rest one down.
281 _ptr[p_index].~T();
282 memmove((void *)(_ptr + p_index), (void *)(_ptr + p_index + 1), (new_size - p_index) * sizeof(T));
283
284 // Shrink to fit if necessary.
285 const USize new_capacity = smaller_capacity(capacity(), new_size);
286 if (new_capacity < capacity()) {
287 Error err = _realloc_exact(new_capacity);
288 CRASH_COND(err);
289 }
290 *_get_size() = new_size;
291 } else {
292 // Remove by forking.
293 Error err = _copy_to_new_buffer_exact(smaller_capacity(capacity(), new_size), p_index, 0, new_size - p_index);
294 CRASH_COND(err);
295 }
296 }
297
298 template <typename T>
299 Error CowData<T>::insert(Size p_pos, T &&p_val) {
300 const Size new_size = size() + 1;
301 ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);
302
303 if (!_ptr) {
304 _alloc_exact(next_capacity(0, 1));
305 *_get_size() = 1;
306 } else if (_get_refcount()->get() == 1) {
307 if ((USize)new_size > capacity()) {
308 // Need to grow.
309 const Error error = _realloc_exact(grow_capacity(capacity()));
310 if (error) {
311 return error;
312 }
313 }
314
315 // Relocate elements one position up.
316 memmove((void *)(_ptr + p_pos + 1), (void *)(_ptr + p_pos), (size() - p_pos) * sizeof(T));
317 *_get_size() = new_size;
318 } else {
319 // Insert new element by forking.
320 // Use the max of capacity and new_size, to ensure we don't accidentally shrink after reserve.
321 const USize new_capacity = next_capacity(capacity(), new_size);
322 const Error error = _copy_to_new_buffer_exact(new_capacity, p_pos, 1, size() - p_pos);
323 if (error) {
324 return error;
325 }
326 }
327
328 // Create the new element at the given index.
329 memnew_placement(_ptr + p_pos, T(std::move(p_val)));
330
331 return OK;
332 }
333
334 template <typename T>
335 Error CowData<T>::push_back(T &&p_val) {
336 const Size new_size = size() + 1;
337
338 if (!_ptr) {
339 // Grow by allocating.
340 _alloc_exact(next_capacity(0, 1));
341 *_get_size() = 1;
342 } else if (_get_refcount()->get() == 1) {
343 // Grow in-place.
344 if ((USize)new_size > capacity()) {
345 // Need to grow.
346 const Error error = _realloc_exact(grow_capacity(capacity()));
347 if (error) {
348 return error;
349 }
350 }
351
352 *_get_size() = new_size;
353 } else {
354 // Grow by forking.
355 // Use the max of capacity and new_size, to ensure we don't accidentally shrink after reserve.
356 const USize new_capacity = next_capacity(capacity(), new_size);
357 const Error error = _copy_to_new_buffer_exact(new_capacity, size(), 1, 0);
358 if (error) {
359 return error;
360 }
361 }
362
363 // Create the new element at the given index.
364 memnew_placement(_ptr + new_size - 1, T(std::move(p_val)));
365
366 return OK;
367 }
368
369 template <typename T>
370 template <bool p_exact>
371 Error CowData<T>::reserve(USize p_min_capacity) {
372 USize new_capacity = p_exact ? p_min_capacity : next_capacity(capacity(), p_min_capacity);
373 if (new_capacity <= capacity()) {
374 if (p_min_capacity < (USize)size()) {
375 WARN_VERBOSE("reserve() called with a capacity smaller than the current size. This is likely a mistake.");
376 }
377 // No need to reserve more, we already have (at least) the right size.
378 return OK;
379 }
380
381 if (!_ptr) {
382 // Initial allocation.
383 return _alloc_exact(new_capacity);
384 } else if (_get_refcount()->get() == 1) {
385 // Grow in-place.
386 return _realloc_exact(new_capacity);
387 } else {
388 // Grow by forking.
389 return _copy_to_new_buffer_exact(new_capacity, size(), 0, 0);
390 }
391 }
392
393 template <typename T>
394 template <bool p_initialize>
395 Error CowData<T>::resize(Size p_size) {
396 ERR_FAIL_COND_V(p_size < 0, ERR_INVALID_PARAMETER);
397
398 const Size prev_size = size();
399 if (p_size == prev_size) {
400 // Caller wants to stay the same size, so we do nothing.
401 return OK;
402 }
403
404 if (p_size > prev_size) {
405 // Caller wants to grow.
406
407 if (!_ptr) {
408 // Grow by allocating.
409 const Error error = _alloc_exact(next_capacity(0, p_size));
410 if (error) {
411 return error;
412 }
413 } else if (_get_refcount()->get() == 1) {
414 // Grow in-place.
415 if ((USize)p_size > capacity()) {
416 const Error error = _realloc_exact(next_capacity(capacity(), p_size));
417 if (error) {
418 return error;
419 }
420 }
421 } else {
422 // Grow by forking.
423 const Error error = _copy_to_new_buffer_exact(next_capacity(capacity(), p_size), prev_size, 0, 0);
424 if (error) {
425 return error;
426 }
427 }
428
429 // Construct new elements.
430 if constexpr (p_initialize) {
431 memnew_arr_placement(_ptr + prev_size, p_size - prev_size);
432 }
433 *_get_size() = p_size;
434
435 return OK;
436 } else {
437 // Caller wants to shrink.
438
439 if (p_size == 0) {
440 _unref();
441 return OK;
442 } else if (_get_refcount()->get() == 1) {
443 // Shrink in-place.
444 destruct_arr_placement(_ptr + p_size, prev_size - p_size);
445
446 // Shrink buffer if necessary.
447 const USize new_capacity = smaller_capacity(capacity(), p_size);
448 if (new_capacity < capacity()) {
449 Error err = _realloc_exact(new_capacity);
450 CRASH_COND(err);
451 }
452
453 *_get_size() = p_size;
454 return OK;
455 } else {
456 // Shrink by forking.
457 const USize new_capacity = smaller_capacity(capacity(), p_size);
458 return _copy_to_new_buffer_exact(new_capacity, p_size, 0, 0);
459 }
460 }
461 }
462
463 template <typename T>
464 Error CowData<T>::_alloc_exact(USize p_capacity) {
465 DEV_ASSERT(!_ptr);
466
467 uint8_t *mem_new = (uint8_t *)Memory::alloc_static(p_capacity * sizeof(T) + DATA_OFFSET, false);
468 ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
469
470 _ptr = _get_data_ptr(mem_new);
471
472 // If we alloc, we're guaranteed to be the only reference.
473 new (_get_refcount()) SafeNumeric<USize>(1);
474 *_get_size() = 0;
475 // The actual capacity is whatever we can stuff into the alloc_size.
476 *_get_capacity() = p_capacity;
477
478 return OK;
479 }
480
481 template <typename T>
482 Error CowData<T>::_realloc_exact(USize p_capacity) {
483 DEV_ASSERT(_ptr);
484
485 uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, p_capacity * sizeof(T) + DATA_OFFSET, false);
486 ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
487
488 _ptr = _get_data_ptr(mem_new);
489
490 // If we realloc, we're guaranteed to be the only reference.
491 // So the reference was 1 and was copied to be 1 again.
492 DEV_ASSERT(_get_refcount()->get() == 1);
493 // The size was also copied from the previous allocation.
494 // The actual capacity is whatever we can stuff into the alloc_size.
495 *_get_capacity() = p_capacity;
496
497 return OK;
498 }
499
500 template <typename T>
501 Error CowData<T>::_copy_to_new_buffer_exact(USize p_capacity, USize p_size_from_start, USize p_gap, USize p_size_from_back) {
502 DEV_ASSERT(p_capacity >= p_size_from_start + p_size_from_back + p_gap);
503 DEV_ASSERT((USize)size() >= p_size_from_start && (USize)size() >= p_size_from_back);
504
505 // Create a temporary CowData to hold ownership over our _ptr.
506 // It will be used to copy elements from the old buffer over to our new buffer.
507 // At the end of the block, it will be automatically destructed by going out of scope.
508 const CowData prev_data;
509 prev_data._ptr = _ptr;
510 _ptr = nullptr;
511
512 const Error error = _alloc_exact(p_capacity);
513 if (error) {
514 // On failure to allocate, recover the old data and return the error.
515 _ptr = prev_data._ptr;
516 prev_data._ptr = nullptr;
517 return error;
518 }
519
520 // Copy over elements.
521 copy_arr_placement(_ptr, prev_data._ptr, p_size_from_start);
522 copy_arr_placement(
523 _ptr + p_size_from_start + p_gap,
524 prev_data._ptr + prev_data.size() - p_size_from_back,
525 p_size_from_back);
526 *_get_size() = p_size_from_start + p_gap + p_size_from_back;
527
528 return OK;
529 }
530
531 template <typename T>
532 Error CowData<T>::_copy_on_write() {
533 if (!_ptr || _get_refcount()->get() == 1) {
534 // Nothing to do.
535 return OK;
536 }
537
538 // Fork to become the only reference.
539 return _copy_to_new_buffer_exact(capacity(), size(), 0, 0);
540 }
541
542 template <typename T>
543 void CowData<T>::_ref(const CowData *p_from) {
544 _ref(*p_from);
545 }
546
547 template <typename T>
548 void CowData<T>::_ref(const CowData &p_from) {
549 if (_ptr == p_from._ptr) {
550 return; // self assign, do nothing.
551 }
552
553 _unref(); // Resets _ptr to nullptr.
554
555 if (!p_from._ptr) {
556 return; //nothing to do
557 }
558
559 if (p_from._get_refcount()->conditional_increment() > 0) { // could reference
560 _ptr = p_from._ptr;
561 }
562 }
563
564 template <typename T>
565 CowData<T>::CowData(std::initializer_list<T> p_init) {
566 CRASH_COND(_alloc_exact(p_init.size()));
567
568 copy_arr_placement(_ptr, p_init.begin(), p_init.size());
569 *_get_size() = p_init.size();
570 }
571
572 GODOT_GCC_WARNING_POP
573
574 // Zero-constructing CowData initializes _ptr to nullptr (and thus empty).
575 template <typename T>
576 struct is_zero_constructible<CowData<T>> : std::true_type {};