Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/core/templates/cowdata.h
9973 views
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/templates/safe_refcount.h"
36
#include "core/templates/span.h"
37
38
#include <initializer_list>
39
#include <type_traits>
40
41
static_assert(std::is_trivially_destructible_v<std::atomic<uint64_t>>);
42
43
GODOT_GCC_WARNING_PUSH
44
GODOT_GCC_WARNING_IGNORE("-Wplacement-new") // Silence a false positive warning (see GH-52119).
45
GODOT_GCC_WARNING_IGNORE("-Wmaybe-uninitialized") // False positive raised when using constexpr.
46
47
template <typename T>
48
class CowData {
49
public:
50
typedef int64_t Size;
51
typedef uint64_t USize;
52
static constexpr USize MAX_INT = INT64_MAX;
53
54
private:
55
// Alignment: ↓ max_align_t ↓ USize ↓ max_align_t
56
// ┌────────────────────┬──┬─────────────┬──┬───────────...
57
// │ SafeNumeric<USize> │░░│ USize │░░│ T[]
58
// │ ref. count │░░│ data size │░░│ data
59
// └────────────────────┴──┴─────────────┴──┴───────────...
60
// Offset: ↑ REF_COUNT_OFFSET ↑ SIZE_OFFSET ↑ DATA_OFFSET
61
62
static constexpr size_t REF_COUNT_OFFSET = 0;
63
static constexpr size_t SIZE_OFFSET = ((REF_COUNT_OFFSET + sizeof(SafeNumeric<USize>)) % alignof(USize) == 0) ? (REF_COUNT_OFFSET + sizeof(SafeNumeric<USize>)) : ((REF_COUNT_OFFSET + sizeof(SafeNumeric<USize>)) + alignof(USize) - ((REF_COUNT_OFFSET + sizeof(SafeNumeric<USize>)) % alignof(USize)));
64
static constexpr size_t DATA_OFFSET = ((SIZE_OFFSET + sizeof(USize)) % alignof(max_align_t) == 0) ? (SIZE_OFFSET + sizeof(USize)) : ((SIZE_OFFSET + sizeof(USize)) + alignof(max_align_t) - ((SIZE_OFFSET + sizeof(USize)) % alignof(max_align_t)));
65
66
mutable T *_ptr = nullptr;
67
68
// internal helpers
69
70
static _FORCE_INLINE_ T *_get_data_ptr(uint8_t *p_ptr) {
71
return (T *)(p_ptr + DATA_OFFSET);
72
}
73
74
_FORCE_INLINE_ SafeNumeric<USize> *_get_refcount() const {
75
if (!_ptr) {
76
return nullptr;
77
}
78
79
return (SafeNumeric<USize> *)((uint8_t *)_ptr - DATA_OFFSET + REF_COUNT_OFFSET);
80
}
81
82
_FORCE_INLINE_ USize *_get_size() const {
83
if (!_ptr) {
84
return nullptr;
85
}
86
87
return (USize *)((uint8_t *)_ptr - DATA_OFFSET + SIZE_OFFSET);
88
}
89
90
_FORCE_INLINE_ static USize _get_alloc_size(USize p_elements) {
91
return next_power_of_2(p_elements * (USize)sizeof(T));
92
}
93
94
_FORCE_INLINE_ static bool _get_alloc_size_checked(USize p_elements, USize *out) {
95
if (unlikely(p_elements == 0)) {
96
*out = 0;
97
return true;
98
}
99
#if defined(__GNUC__) && defined(IS_32_BIT)
100
USize o;
101
USize p;
102
if (__builtin_mul_overflow(p_elements, sizeof(T), &o)) {
103
*out = 0;
104
return false;
105
}
106
*out = next_power_of_2(o);
107
if (__builtin_add_overflow(o, static_cast<USize>(32), &p)) {
108
return false; // No longer allocated here.
109
}
110
#else
111
// Speed is more important than correctness here, do the operations unchecked
112
// and hope for the best.
113
*out = _get_alloc_size(p_elements);
114
#endif
115
return *out;
116
}
117
118
// Decrements the reference count. Deallocates the backing buffer if needed.
119
// After this function, _ptr is guaranteed to be NULL.
120
void _unref();
121
void _ref(const CowData *p_from);
122
void _ref(const CowData &p_from);
123
124
// Ensures that the backing buffer is at least p_size wide, and that this CowData instance is
125
// the only reference to it. The buffer is populated with as many element copies from the old
126
// array as possible.
127
// It is the responsibility of the caller to populate newly allocated space up to p_size.
128
Error _fork_allocate(USize p_size);
129
Error _copy_on_write() { return _fork_allocate(size()); }
130
131
// Allocates a backing array of the given capacity. The reference count is initialized to 1.
132
// It is the responsibility of the caller to populate the array and the new size property.
133
Error _alloc(USize p_alloc_size);
134
135
// Re-allocates the backing array to the given capacity. The reference count is initialized to 1.
136
// It is the responsibility of the caller to populate the array and the new size property.
137
// The caller must also make sure there are no other references to the data, as pointers may
138
// be invalidated.
139
Error _realloc(USize p_alloc_size);
140
141
public:
142
void operator=(const CowData<T> &p_from) { _ref(p_from); }
143
void operator=(CowData<T> &&p_from) {
144
if (_ptr == p_from._ptr) {
145
return;
146
}
147
148
_unref();
149
_ptr = p_from._ptr;
150
p_from._ptr = nullptr;
151
}
152
153
_FORCE_INLINE_ T *ptrw() {
154
_copy_on_write();
155
return _ptr;
156
}
157
158
_FORCE_INLINE_ const T *ptr() const {
159
return _ptr;
160
}
161
162
_FORCE_INLINE_ Size size() const {
163
USize *size = (USize *)_get_size();
164
if (size) {
165
return *size;
166
} else {
167
return 0;
168
}
169
}
170
171
_FORCE_INLINE_ void clear() { _unref(); }
172
_FORCE_INLINE_ bool is_empty() const { return _ptr == nullptr; }
173
174
_FORCE_INLINE_ void set(Size p_index, const T &p_elem) {
175
ERR_FAIL_INDEX(p_index, size());
176
_copy_on_write();
177
_ptr[p_index] = p_elem;
178
}
179
180
_FORCE_INLINE_ T &get_m(Size p_index) {
181
CRASH_BAD_INDEX(p_index, size());
182
_copy_on_write();
183
return _ptr[p_index];
184
}
185
186
_FORCE_INLINE_ const T &get(Size p_index) const {
187
CRASH_BAD_INDEX(p_index, size());
188
189
return _ptr[p_index];
190
}
191
192
template <bool p_initialize = true>
193
Error resize(Size p_size);
194
195
_FORCE_INLINE_ void remove_at(Size p_index) {
196
ERR_FAIL_INDEX(p_index, size());
197
T *p = ptrw();
198
Size len = size();
199
for (Size i = p_index; i < len - 1; i++) {
200
p[i] = std::move(p[i + 1]);
201
}
202
203
resize(len - 1);
204
}
205
206
Error insert(Size p_pos, const T &p_val) {
207
Size new_size = size() + 1;
208
ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);
209
Error err = resize(new_size);
210
ERR_FAIL_COND_V(err, err);
211
T *p = ptrw();
212
for (Size i = new_size - 1; i > p_pos; i--) {
213
p[i] = std::move(p[i - 1]);
214
}
215
p[p_pos] = p_val;
216
217
return OK;
218
}
219
220
_FORCE_INLINE_ operator Span<T>() const { return Span<T>(ptr(), size()); }
221
_FORCE_INLINE_ Span<T> span() const { return operator Span<T>(); }
222
223
_FORCE_INLINE_ CowData() {}
224
_FORCE_INLINE_ ~CowData() { _unref(); }
225
_FORCE_INLINE_ CowData(std::initializer_list<T> p_init);
226
_FORCE_INLINE_ CowData(const CowData<T> &p_from) { _ref(p_from); }
227
_FORCE_INLINE_ CowData(CowData<T> &&p_from) {
228
_ptr = p_from._ptr;
229
p_from._ptr = nullptr;
230
}
231
};
232
233
template <typename T>
234
void CowData<T>::_unref() {
235
if (!_ptr) {
236
return;
237
}
238
239
SafeNumeric<USize> *refc = _get_refcount();
240
if (refc->decrement() > 0) {
241
// Data is still in use elsewhere.
242
_ptr = nullptr;
243
return;
244
}
245
// We had the only reference; destroy the data.
246
247
// First, invalidate our own reference.
248
// NOTE: It is required to do so immediately because it must not be observable outside of this
249
// function after refcount has already been reduced to 0.
250
// WARNING: It must be done before calling the destructors, because one of them may otherwise
251
// observe it through a reference to us. In this case, it may try to access the buffer,
252
// which is illegal after some of the elements in it have already been destructed, and
253
// may lead to a segmentation fault.
254
USize current_size = *_get_size();
255
T *prev_ptr = _ptr;
256
_ptr = nullptr;
257
258
if constexpr (!std::is_trivially_destructible_v<T>) {
259
for (USize i = 0; i < current_size; ++i) {
260
prev_ptr[i].~T();
261
}
262
}
263
264
// Free memory.
265
Memory::free_static((uint8_t *)prev_ptr - DATA_OFFSET, false);
266
267
#ifdef DEBUG_ENABLED
268
// If any destructors access us through pointers, it is a bug.
269
// We can't really test for that, but we can at least check no items have been added.
270
ERR_FAIL_COND_MSG(_ptr != nullptr, "Internal bug, please report: CowData was modified during destruction.");
271
#endif
272
}
273
274
template <typename T>
275
Error CowData<T>::_fork_allocate(USize p_size) {
276
if (p_size == 0) {
277
// Wants to clean up.
278
_unref();
279
return OK;
280
}
281
282
USize alloc_size;
283
ERR_FAIL_COND_V(!_get_alloc_size_checked(p_size, &alloc_size), ERR_OUT_OF_MEMORY);
284
285
const USize prev_size = size();
286
287
if (!_ptr) {
288
// We had no data before; just allocate a new array.
289
const Error error = _alloc(alloc_size);
290
if (error) {
291
return error;
292
}
293
} else if (_get_refcount()->get() == 1) {
294
// Resize in-place.
295
// NOTE: This case is not just an optimization, but required, as some callers depend on
296
// `_copy_on_write()` calls not changing the pointer after the first fork
297
// (e.g. mutable iterators).
298
if (p_size == prev_size) {
299
// We can shortcut here; we don't need to do anything.
300
return OK;
301
}
302
303
// Destroy extraneous elements.
304
if constexpr (!std::is_trivially_destructible_v<T>) {
305
for (USize i = prev_size; i > p_size; i--) {
306
_ptr[i - 1].~T();
307
}
308
}
309
310
if (alloc_size != _get_alloc_size(prev_size)) {
311
const Error error = _realloc(alloc_size);
312
if (error) {
313
// Out of memory; the current array is still valid though.
314
return error;
315
}
316
}
317
} else {
318
// Resize by forking.
319
320
// Create a temporary CowData to hold ownership over our _ptr.
321
// It will be used to copy elements from the old buffer over to our new buffer.
322
// At the end of the block, it will be automatically destructed by going out of scope.
323
const CowData prev_data;
324
prev_data._ptr = _ptr;
325
_ptr = nullptr;
326
327
const Error error = _alloc(alloc_size);
328
if (error) {
329
// On failure to allocate, just give up the old data and return.
330
// We could recover our old pointer from prev_data, but by just dropping our data, we
331
// consciously invite early failure for the case that the caller does not handle this
332
// case gracefully.
333
return error;
334
}
335
336
// Copy over elements.
337
const USize copied_element_count = MIN(prev_size, p_size);
338
if (copied_element_count > 0) {
339
if constexpr (std::is_trivially_copyable_v<T>) {
340
memcpy((uint8_t *)_ptr, (uint8_t *)prev_data._ptr, copied_element_count * sizeof(T));
341
} else {
342
for (USize i = 0; i < copied_element_count; i++) {
343
memnew_placement(&_ptr[i], T(prev_data._ptr[i]));
344
}
345
}
346
}
347
}
348
349
// Set our new size.
350
*_get_size() = p_size;
351
352
return OK;
353
}
354
355
template <typename T>
356
template <bool p_initialize>
357
Error CowData<T>::resize(Size p_size) {
358
ERR_FAIL_COND_V(p_size < 0, ERR_INVALID_PARAMETER);
359
360
const Size prev_size = size();
361
if (p_size == prev_size) {
362
return OK;
363
}
364
365
const Error error = _fork_allocate(p_size);
366
if (error) {
367
return error;
368
}
369
370
if constexpr (p_initialize) {
371
if (p_size > prev_size) {
372
memnew_arr_placement(_ptr + prev_size, p_size - prev_size);
373
}
374
} else {
375
static_assert(std::is_trivially_destructible_v<T>);
376
}
377
378
return OK;
379
}
380
381
template <typename T>
382
Error CowData<T>::_alloc(USize p_alloc_size) {
383
uint8_t *mem_new = (uint8_t *)Memory::alloc_static(p_alloc_size + DATA_OFFSET, false);
384
ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
385
386
_ptr = _get_data_ptr(mem_new);
387
388
// If we alloc, we're guaranteed to be the only reference.
389
new (_get_refcount()) SafeNumeric<USize>(1);
390
391
return OK;
392
}
393
394
template <typename T>
395
Error CowData<T>::_realloc(USize p_alloc_size) {
396
uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, p_alloc_size + DATA_OFFSET, false);
397
ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
398
399
_ptr = _get_data_ptr(mem_new);
400
401
// If we realloc, we're guaranteed to be the only reference.
402
// So the reference was 1 and was copied to be 1 again.
403
DEV_ASSERT(_get_refcount()->get() == 1);
404
405
return OK;
406
}
407
408
template <typename T>
409
void CowData<T>::_ref(const CowData *p_from) {
410
_ref(*p_from);
411
}
412
413
template <typename T>
414
void CowData<T>::_ref(const CowData &p_from) {
415
if (_ptr == p_from._ptr) {
416
return; // self assign, do nothing.
417
}
418
419
_unref(); // Resets _ptr to nullptr.
420
421
if (!p_from._ptr) {
422
return; //nothing to do
423
}
424
425
if (p_from._get_refcount()->conditional_increment() > 0) { // could reference
426
_ptr = p_from._ptr;
427
}
428
}
429
430
template <typename T>
431
CowData<T>::CowData(std::initializer_list<T> p_init) {
432
Error err = resize(p_init.size());
433
if (err != OK) {
434
return;
435
}
436
437
Size i = 0;
438
for (const T &element : p_init) {
439
set(i++, element);
440
}
441
}
442
443
GODOT_GCC_WARNING_POP
444
445
// Zero-constructing CowData initializes _ptr to nullptr (and thus empty).
446
template <typename T>
447
struct is_zero_constructible<CowData<T>> : std::true_type {};
448
449