cowdata.h 14 KB

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