Skip to content

Commit 8483d79

Browse files
committed
Abstract CowData's reallocations into _realloc to consolidate duplicate logic.
1 parent ba2c5c1 commit 8483d79

File tree

1 file changed

+25
-19
lines changed

1 file changed

+25
-19
lines changed

core/templates/cowdata.h

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ class CowData {
164164
void _ref(const CowData *p_from);
165165
void _ref(const CowData &p_from);
166166
USize _copy_on_write();
167+
Error _realloc(Size p_alloc_size);
167168

168169
public:
169170
void operator=(const CowData<T> &p_from) { _ref(p_from); }
@@ -342,7 +343,7 @@ Error CowData<T>::resize(Size p_size) {
342343
}
343344

344345
// possibly changing size, copy on write
345-
USize rc = _copy_on_write();
346+
_copy_on_write();
346347

347348
USize current_alloc_size = _get_alloc_size(current_size);
348349
USize alloc_size;
@@ -365,15 +366,10 @@ Error CowData<T>::resize(Size p_size) {
365366
_ptr = _data_ptr;
366367

367368
} else {
368-
uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, alloc_size + DATA_OFFSET, false);
369-
ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
370-
371-
SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
372-
T *_data_ptr = _get_data_ptr(mem_new);
373-
374-
new (_refc_ptr) SafeNumeric<USize>(rc); //refcount
375-
376-
_ptr = _data_ptr;
369+
const Error error = _realloc(alloc_size);
370+
if (error) {
371+
return error;
372+
}
377373
}
378374
}
379375

@@ -399,15 +395,10 @@ Error CowData<T>::resize(Size p_size) {
399395
}
400396

401397
if (alloc_size != current_alloc_size) {
402-
uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, alloc_size + DATA_OFFSET, false);
403-
ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
404-
405-
SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
406-
T *_data_ptr = _get_data_ptr(mem_new);
407-
408-
new (_refc_ptr) SafeNumeric<USize>(rc); //refcount
409-
410-
_ptr = _data_ptr;
398+
const Error error = _realloc(alloc_size);
399+
if (error) {
400+
return error;
401+
}
411402
}
412403

413404
*_get_size() = p_size;
@@ -416,6 +407,21 @@ Error CowData<T>::resize(Size p_size) {
416407
return OK;
417408
}
418409

410+
template <typename T>
411+
Error CowData<T>::_realloc(Size p_alloc_size) {
412+
uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, p_alloc_size + DATA_OFFSET, false);
413+
ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
414+
415+
SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
416+
T *_data_ptr = _get_data_ptr(mem_new);
417+
418+
// If we realloc, we're guaranteed to be the only reference.
419+
new (_refc_ptr) SafeNumeric<USize>(1);
420+
_ptr = _data_ptr;
421+
422+
return OK;
423+
}
424+
419425
template <typename T>
420426
typename CowData<T>::Size CowData<T>::find(const T &p_val, Size p_from) const {
421427
Size ret = -1;

0 commit comments

Comments
 (0)