#pragma once
#include "core/error/error_macros.h"
#include "core/os/memory.h"
#include "core/string/print_string.h"
#include "core/templates/safe_refcount.h"
#include "core/templates/span.h"
#include <initializer_list>
#include <type_traits>
static_assert(std::is_trivially_destructible_v<std::atomic<uint64_t>>);
GODOT_GCC_WARNING_PUSH
GODOT_GCC_WARNING_IGNORE("-Wplacement-new")
GODOT_GCC_WARNING_IGNORE("-Wmaybe-uninitialized")
GODOT_GCC_WARNING_IGNORE("-Warray-bounds")
GODOT_GCC_WARNING_IGNORE("-Wrestrict")
GODOT_GCC_PRAGMA(GCC diagnostic warning "-Wstringop-overflow=0")
#ifdef WINDOWS_ENABLED
GODOT_GCC_PRAGMA(GCC diagnostic warning "-Wdangling-pointer=0")
#endif
template <typename T>
class CowData {
public:
typedef int64_t Size;
typedef uint64_t USize;
static constexpr USize MAX_INT = INT64_MAX;
private:
static constexpr size_t REF_COUNT_OFFSET = 0;
static constexpr size_t CAPACITY_OFFSET = Memory::get_aligned_address(REF_COUNT_OFFSET + sizeof(SafeNumeric<USize>), alignof(USize));
static constexpr size_t SIZE_OFFSET = Memory::get_aligned_address(CAPACITY_OFFSET + sizeof(USize), alignof(USize));
static constexpr size_t DATA_OFFSET = Memory::get_aligned_address(SIZE_OFFSET + sizeof(USize), Memory::MAX_ALIGN);
mutable T *_ptr = nullptr;
static constexpr _FORCE_INLINE_ USize grow_capacity(USize p_previous_capacity) {
return MAX((USize)2, p_previous_capacity + ((1 + p_previous_capacity) >> 1));
}
static constexpr _FORCE_INLINE_ USize next_capacity(USize p_previous_capacity, USize p_size) {
if (p_previous_capacity < p_size) {
return MAX(grow_capacity(p_previous_capacity), p_size);
}
return p_previous_capacity;
}
static constexpr _FORCE_INLINE_ USize smaller_capacity(USize p_previous_capacity, USize p_size) {
if (p_size < p_previous_capacity >> 2) {
return grow_capacity(p_size);
}
return p_previous_capacity;
}
static _FORCE_INLINE_ T *_get_data_ptr(uint8_t *p_ptr) {
return (T *)(p_ptr + DATA_OFFSET);
}
_FORCE_INLINE_ SafeNumeric<USize> *_get_refcount() const {
return (SafeNumeric<USize> *)((uint8_t *)_ptr - DATA_OFFSET + REF_COUNT_OFFSET);
}
_FORCE_INLINE_ USize *_get_size() const {
return (USize *)((uint8_t *)_ptr - DATA_OFFSET + SIZE_OFFSET);
}
_FORCE_INLINE_ USize *_get_capacity() const {
return (USize *)((uint8_t *)_ptr - DATA_OFFSET + CAPACITY_OFFSET);
}
void _unref();
void _ref(const CowData *p_from);
void _ref(const CowData &p_from);
Error _alloc_exact(USize p_capacity);
Error _realloc_exact(USize p_capacity);
[[nodiscard]] Error _copy_to_new_buffer_exact(USize p_capacity, USize p_size_from_start, USize p_gap, USize p_size_from_back);
[[nodiscard]] Error _copy_on_write();
public:
void operator=(const CowData<T> &p_from) { _ref(p_from); }
void operator=(CowData<T> &&p_from) {
if (_ptr == p_from._ptr) {
return;
}
_unref();
_ptr = p_from._ptr;
p_from._ptr = nullptr;
}
_FORCE_INLINE_ T *ptrw() {
CRASH_COND(_copy_on_write());
return _ptr;
}
_FORCE_INLINE_ const T *ptr() const {
return _ptr;
}
_FORCE_INLINE_ Size size() const { return !_ptr ? 0 : *_get_size(); }
_FORCE_INLINE_ USize capacity() const { return !_ptr ? 0 : *_get_capacity(); }
_FORCE_INLINE_ USize refcount() const { return !_ptr ? 0 : *_get_refcount(); }
_FORCE_INLINE_ void clear() { _unref(); }
_FORCE_INLINE_ bool is_empty() const { return size() == 0; }
_FORCE_INLINE_ void set(Size p_index, const T &p_elem) {
ERR_FAIL_INDEX(p_index, size());
CRASH_COND(_copy_on_write());
_ptr[p_index] = p_elem;
}
_FORCE_INLINE_ T &get_m(Size p_index) {
CRASH_BAD_INDEX(p_index, size());
CRASH_COND(_copy_on_write());
return _ptr[p_index];
}
_FORCE_INLINE_ const T &get(Size p_index) const {
CRASH_BAD_INDEX(p_index, size());
return _ptr[p_index];
}
template <bool p_init = false>
Error resize(Size p_size);
template <bool p_exact = false>
Error reserve(USize p_min_capacity);
_FORCE_INLINE_ Error reserve_exact(USize p_capacity) {
return reserve<true>(p_capacity);
}
_FORCE_INLINE_ void remove_at(Size p_index);
Error insert(Size p_pos, T &&p_val);
Error push_back(T &&p_val);
_FORCE_INLINE_ operator Span<T>() const { return Span<T>(ptr(), size()); }
_FORCE_INLINE_ Span<T> span() const { return operator Span<T>(); }
_FORCE_INLINE_ CowData() {}
_FORCE_INLINE_ ~CowData() { _unref(); }
_FORCE_INLINE_ CowData(std::initializer_list<T> p_init);
_FORCE_INLINE_ CowData(const CowData<T> &p_from) { _ref(p_from); }
_FORCE_INLINE_ CowData(CowData<T> &&p_from) {
_ptr = p_from._ptr;
p_from._ptr = nullptr;
}
};
template <typename T>
void CowData<T>::_unref() {
if (!_ptr) {
return;
}
if (_get_refcount()->decrement() > 0) {
_ptr = nullptr;
return;
}
USize current_size = size();
T *prev_ptr = _ptr;
_ptr = nullptr;
destruct_arr_placement(prev_ptr, current_size);
DEV_ASSERT(!_ptr);
Memory::free_static((uint8_t *)prev_ptr - DATA_OFFSET, false);
#ifdef DEBUG_ENABLED
ERR_FAIL_COND_MSG(_ptr != nullptr, "Internal bug, please report: CowData was modified during destruction.");
#endif
}
template <typename T>
void CowData<T>::remove_at(Size p_index) {
const Size prev_size = size();
ERR_FAIL_INDEX(p_index, prev_size);
if (prev_size == 1) {
_unref();
return;
}
const USize new_size = prev_size - 1;
if (_get_refcount()->get() == 1) {
_ptr[p_index].~T();
memmove((void *)(_ptr + p_index), (void *)(_ptr + p_index + 1), (new_size - p_index) * sizeof(T));
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 {
Error err = _copy_to_new_buffer_exact(smaller_capacity(capacity(), new_size), p_index, 0, new_size - p_index);
CRASH_COND(err);
}
}
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);
if (!_ptr) {
_alloc_exact(next_capacity(0, 1));
*_get_size() = 1;
} else if (_get_refcount()->get() == 1) {
if ((USize)new_size > capacity()) {
const Error error = _realloc_exact(grow_capacity(capacity()));
if (error) {
return error;
}
}
memmove((void *)(_ptr + p_pos + 1), (void *)(_ptr + p_pos), (size() - p_pos) * sizeof(T));
*_get_size() = new_size;
} else {
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);
if (error) {
return error;
}
}
memnew_placement(_ptr + p_pos, T(std::move(p_val)));
return OK;
}
template <typename T>
Error CowData<T>::push_back(T &&p_val) {
const Size new_size = size() + 1;
if (!_ptr) {
_alloc_exact(next_capacity(0, 1));
*_get_size() = 1;
} else if (_get_refcount()->get() == 1) {
if ((USize)new_size > capacity()) {
const Error error = _realloc_exact(grow_capacity(capacity()));
if (error) {
return error;
}
}
*_get_size() = new_size;
} else {
const USize new_capacity = next_capacity(capacity(), new_size);
const Error error = _copy_to_new_buffer_exact(new_capacity, size(), 1, 0);
if (error) {
return error;
}
}
memnew_placement(_ptr + new_size - 1, T(std::move(p_val)));
return OK;
}
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 < (USize)size()) {
WARN_VERBOSE("reserve() called with a capacity smaller than the current size. This is likely a mistake.");
}
return OK;
}
if (!_ptr) {
return _alloc_exact(new_capacity);
} else if (_get_refcount()->get() == 1) {
return _realloc_exact(new_capacity);
} else {
return _copy_to_new_buffer_exact(new_capacity, size(), 0, 0);
}
}
template <typename T>
template <bool p_initialize>
Error CowData<T>::resize(Size p_size) {
ERR_FAIL_COND_V(p_size < 0, ERR_INVALID_PARAMETER);
const Size prev_size = size();
if (p_size == prev_size) {
return OK;
}
if (p_size > prev_size) {
if (!_ptr) {
const Error error = _alloc_exact(next_capacity(0, p_size));
if (error) {
return error;
}
} else if (_get_refcount()->get() == 1) {
if ((USize)p_size > capacity()) {
const Error error = _realloc_exact(next_capacity(capacity(), p_size));
if (error) {
return error;
}
}
} else {
const Error error = _copy_to_new_buffer_exact(next_capacity(capacity(), p_size), prev_size, 0, 0);
if (error) {
return error;
}
}
if constexpr (p_initialize) {
memnew_arr_placement(_ptr + prev_size, p_size - prev_size);
}
*_get_size() = p_size;
return OK;
} else {
if (p_size == 0) {
_unref();
return OK;
} else if (_get_refcount()->get() == 1) {
destruct_arr_placement(_ptr + p_size, prev_size - p_size);
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 {
const USize new_capacity = smaller_capacity(capacity(), p_size);
return _copy_to_new_buffer_exact(new_capacity, p_size, 0, 0);
}
}
}
template <typename T>
Error CowData<T>::_alloc_exact(USize p_capacity) {
DEV_ASSERT(!_ptr);
uint8_t *mem_new = (uint8_t *)Memory::alloc_static(p_capacity * sizeof(T) + DATA_OFFSET, false);
ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
_ptr = _get_data_ptr(mem_new);
new (_get_refcount()) SafeNumeric<USize>(1);
*_get_size() = 0;
*_get_capacity() = p_capacity;
return OK;
}
template <typename T>
Error CowData<T>::_realloc_exact(USize p_capacity) {
DEV_ASSERT(_ptr);
uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, p_capacity * sizeof(T) + DATA_OFFSET, false);
ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
_ptr = _get_data_ptr(mem_new);
DEV_ASSERT(_get_refcount()->get() == 1);
*_get_capacity() = 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);
const CowData prev_data;
prev_data._ptr = _ptr;
_ptr = nullptr;
const Error error = _alloc_exact(p_capacity);
if (error) {
_ptr = prev_data._ptr;
prev_data._ptr = nullptr;
return error;
}
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) {
return OK;
}
return _copy_to_new_buffer_exact(capacity(), size(), 0, 0);
}
template <typename T>
void CowData<T>::_ref(const CowData *p_from) {
_ref(*p_from);
}
template <typename T>
void CowData<T>::_ref(const CowData &p_from) {
if (_ptr == p_from._ptr) {
return;
}
_unref();
if (!p_from._ptr) {
return;
}
if (p_from._get_refcount()->conditional_increment() > 0) {
_ptr = p_from._ptr;
}
}
template <typename T>
CowData<T>::CowData(std::initializer_list<T> p_init) {
CRASH_COND(_alloc_exact(p_init.size()));
copy_arr_placement(_ptr, p_init.begin(), p_init.size());
*_get_size() = p_init.size();
}
GODOT_GCC_WARNING_POP
template <typename T>
struct is_zero_constructible<CowData<T>> : std::true_type {};