cowdata.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 <string.h>
  36. #include <initializer_list>
  37. #include <type_traits>
  38. template <typename T>
  39. class Vector;
  40. class String;
  41. class Char16String;
  42. class CharString;
  43. template <typename T, typename V>
  44. class VMap;
  45. static_assert(std::is_trivially_destructible_v<std::atomic<uint64_t>>);
  46. // Silence a false positive warning (see GH-52119).
  47. #if defined(__GNUC__) && !defined(__clang__)
  48. #pragma GCC diagnostic push
  49. #pragma GCC diagnostic ignored "-Wplacement-new"
  50. #endif
  51. template <typename T>
  52. class CowData {
  53. template <typename TV>
  54. friend class Vector;
  55. friend class String;
  56. friend class Char16String;
  57. friend class CharString;
  58. template <typename TV, typename VV>
  59. friend class VMap;
  60. public:
  61. typedef int64_t Size;
  62. typedef uint64_t USize;
  63. static constexpr USize MAX_INT = INT64_MAX;
  64. private:
  65. // Function to find the next power of 2 to an integer.
  66. static _FORCE_INLINE_ USize next_po2(USize x) {
  67. if (x == 0) {
  68. return 0;
  69. }
  70. --x;
  71. x |= x >> 1;
  72. x |= x >> 2;
  73. x |= x >> 4;
  74. x |= x >> 8;
  75. x |= x >> 16;
  76. if (sizeof(USize) == 8) {
  77. x |= x >> 32;
  78. }
  79. return ++x;
  80. }
  81. // Alignment: ↓ max_align_t ↓ USize ↓ max_align_t
  82. // ┌────────────────────┬──┬─────────────┬──┬───────────...
  83. // │ SafeNumeric<USize> │░░│ USize │░░│ T[]
  84. // │ ref. count │░░│ data size │░░│ data
  85. // └────────────────────┴──┴─────────────┴──┴───────────...
  86. // Offset: ↑ REF_COUNT_OFFSET ↑ SIZE_OFFSET ↑ DATA_OFFSET
  87. static constexpr size_t REF_COUNT_OFFSET = 0;
  88. 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)));
  89. 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)));
  90. mutable T *_ptr = nullptr;
  91. // internal helpers
  92. static _FORCE_INLINE_ SafeNumeric<USize> *_get_refcount_ptr(uint8_t *p_ptr) {
  93. return (SafeNumeric<USize> *)(p_ptr + REF_COUNT_OFFSET);
  94. }
  95. static _FORCE_INLINE_ USize *_get_size_ptr(uint8_t *p_ptr) {
  96. return (USize *)(p_ptr + SIZE_OFFSET);
  97. }
  98. static _FORCE_INLINE_ T *_get_data_ptr(uint8_t *p_ptr) {
  99. return (T *)(p_ptr + DATA_OFFSET);
  100. }
  101. _FORCE_INLINE_ SafeNumeric<USize> *_get_refcount() const {
  102. if (!_ptr) {
  103. return nullptr;
  104. }
  105. return (SafeNumeric<USize> *)((uint8_t *)_ptr - DATA_OFFSET + REF_COUNT_OFFSET);
  106. }
  107. _FORCE_INLINE_ USize *_get_size() const {
  108. if (!_ptr) {
  109. return nullptr;
  110. }
  111. return (USize *)((uint8_t *)_ptr - DATA_OFFSET + SIZE_OFFSET);
  112. }
  113. _FORCE_INLINE_ USize _get_alloc_size(USize p_elements) const {
  114. return next_po2(p_elements * sizeof(T));
  115. }
  116. _FORCE_INLINE_ bool _get_alloc_size_checked(USize p_elements, USize *out) const {
  117. if (unlikely(p_elements == 0)) {
  118. *out = 0;
  119. return true;
  120. }
  121. #if defined(__GNUC__) && defined(IS_32_BIT)
  122. USize o;
  123. USize p;
  124. if (__builtin_mul_overflow(p_elements, sizeof(T), &o)) {
  125. *out = 0;
  126. return false;
  127. }
  128. *out = next_po2(o);
  129. if (__builtin_add_overflow(o, static_cast<USize>(32), &p)) {
  130. return false; // No longer allocated here.
  131. }
  132. #else
  133. // Speed is more important than correctness here, do the operations unchecked
  134. // and hope for the best.
  135. *out = _get_alloc_size(p_elements);
  136. #endif
  137. return *out;
  138. }
  139. // Decrements the reference count. Deallocates the backing buffer if needed.
  140. // After this function, _ptr is guaranteed to be NULL.
  141. void _unref();
  142. void _ref(const CowData *p_from);
  143. void _ref(const CowData &p_from);
  144. USize _copy_on_write();
  145. Error _realloc(Size p_alloc_size);
  146. public:
  147. void operator=(const CowData<T> &p_from) { _ref(p_from); }
  148. void operator=(CowData<T> &&p_from) {
  149. if (_ptr == p_from._ptr) {
  150. return;
  151. }
  152. _unref();
  153. _ptr = p_from._ptr;
  154. p_from._ptr = nullptr;
  155. }
  156. _FORCE_INLINE_ T *ptrw() {
  157. _copy_on_write();
  158. return _ptr;
  159. }
  160. _FORCE_INLINE_ const T *ptr() const {
  161. return _ptr;
  162. }
  163. _FORCE_INLINE_ Size size() const {
  164. USize *size = (USize *)_get_size();
  165. if (size) {
  166. return *size;
  167. } else {
  168. return 0;
  169. }
  170. }
  171. _FORCE_INLINE_ void clear() { resize(0); }
  172. _FORCE_INLINE_ bool is_empty() const { return _ptr == nullptr; }
  173. _FORCE_INLINE_ void set(Size p_index, const T &p_elem) {
  174. ERR_FAIL_INDEX(p_index, size());
  175. _copy_on_write();
  176. _ptr[p_index] = p_elem;
  177. }
  178. _FORCE_INLINE_ T &get_m(Size p_index) {
  179. CRASH_BAD_INDEX(p_index, size());
  180. _copy_on_write();
  181. return _ptr[p_index];
  182. }
  183. _FORCE_INLINE_ const T &get(Size p_index) const {
  184. CRASH_BAD_INDEX(p_index, size());
  185. return _ptr[p_index];
  186. }
  187. template <bool p_ensure_zero = false>
  188. Error resize(Size p_size);
  189. _FORCE_INLINE_ void remove_at(Size p_index) {
  190. ERR_FAIL_INDEX(p_index, size());
  191. T *p = ptrw();
  192. Size len = size();
  193. for (Size i = p_index; i < len - 1; i++) {
  194. p[i] = std::move(p[i + 1]);
  195. }
  196. resize(len - 1);
  197. }
  198. Error insert(Size p_pos, const T &p_val) {
  199. Size new_size = size() + 1;
  200. ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);
  201. Error err = resize(new_size);
  202. ERR_FAIL_COND_V(err, err);
  203. T *p = ptrw();
  204. for (Size i = new_size - 1; i > p_pos; i--) {
  205. p[i] = std::move(p[i - 1]);
  206. }
  207. p[p_pos] = p_val;
  208. return OK;
  209. }
  210. _FORCE_INLINE_ operator Span<T>() const { return Span<T>(ptr(), size()); }
  211. _FORCE_INLINE_ Span<T> span() const { return operator Span<T>(); }
  212. _FORCE_INLINE_ CowData() {}
  213. _FORCE_INLINE_ ~CowData() { _unref(); }
  214. _FORCE_INLINE_ CowData(std::initializer_list<T> p_init);
  215. _FORCE_INLINE_ CowData(const CowData<T> &p_from) { _ref(p_from); }
  216. _FORCE_INLINE_ CowData(CowData<T> &&p_from) {
  217. _ptr = p_from._ptr;
  218. p_from._ptr = nullptr;
  219. }
  220. };
  221. template <typename T>
  222. void CowData<T>::_unref() {
  223. if (!_ptr) {
  224. return;
  225. }
  226. SafeNumeric<USize> *refc = _get_refcount();
  227. if (refc->decrement() > 0) {
  228. // Data is still in use elsewhere.
  229. _ptr = nullptr;
  230. return;
  231. }
  232. // Clean up.
  233. // First, invalidate our own reference.
  234. // NOTE: It is required to do so immediately because it must not be observable outside of this
  235. // function after refcount has already been reduced to 0.
  236. // WARNING: It must be done before calling the destructors, because one of them may otherwise
  237. // observe it through a reference to us. In this case, it may try to access the buffer,
  238. // which is illegal after some of the elements in it have already been destructed, and
  239. // may lead to a segmentation fault.
  240. USize current_size = *_get_size();
  241. T *prev_ptr = _ptr;
  242. _ptr = nullptr;
  243. if constexpr (!std::is_trivially_destructible_v<T>) {
  244. for (USize i = 0; i < current_size; ++i) {
  245. prev_ptr[i].~T();
  246. }
  247. }
  248. // free mem
  249. Memory::free_static((uint8_t *)prev_ptr - DATA_OFFSET, false);
  250. }
  251. template <typename T>
  252. typename CowData<T>::USize CowData<T>::_copy_on_write() {
  253. if (!_ptr) {
  254. return 0;
  255. }
  256. SafeNumeric<USize> *refc = _get_refcount();
  257. USize rc = refc->get();
  258. if (unlikely(rc > 1)) {
  259. /* in use by more than me */
  260. USize current_size = *_get_size();
  261. uint8_t *mem_new = (uint8_t *)Memory::alloc_static(_get_alloc_size(current_size) + DATA_OFFSET, false);
  262. ERR_FAIL_NULL_V(mem_new, 0);
  263. SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
  264. USize *_size_ptr = _get_size_ptr(mem_new);
  265. T *_data_ptr = _get_data_ptr(mem_new);
  266. new (_refc_ptr) SafeNumeric<USize>(1); //refcount
  267. *(_size_ptr) = current_size; //size
  268. // initialize new elements
  269. if constexpr (std::is_trivially_copyable_v<T>) {
  270. memcpy((uint8_t *)_data_ptr, _ptr, current_size * sizeof(T));
  271. } else {
  272. for (USize i = 0; i < current_size; i++) {
  273. memnew_placement(&_data_ptr[i], T(_ptr[i]));
  274. }
  275. }
  276. _unref();
  277. _ptr = _data_ptr;
  278. rc = 1;
  279. }
  280. return rc;
  281. }
  282. template <typename T>
  283. template <bool p_ensure_zero>
  284. Error CowData<T>::resize(Size p_size) {
  285. ERR_FAIL_COND_V(p_size < 0, ERR_INVALID_PARAMETER);
  286. Size current_size = size();
  287. if (p_size == current_size) {
  288. return OK;
  289. }
  290. if (p_size == 0) {
  291. // Wants to clean up.
  292. _unref(); // Resets _ptr to nullptr.
  293. return OK;
  294. }
  295. // possibly changing size, copy on write
  296. _copy_on_write();
  297. USize current_alloc_size = _get_alloc_size(current_size);
  298. USize alloc_size;
  299. ERR_FAIL_COND_V(!_get_alloc_size_checked(p_size, &alloc_size), ERR_OUT_OF_MEMORY);
  300. if (p_size > current_size) {
  301. if (alloc_size != current_alloc_size) {
  302. if (current_size == 0) {
  303. // alloc from scratch
  304. uint8_t *mem_new = (uint8_t *)Memory::alloc_static(alloc_size + DATA_OFFSET, false);
  305. ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
  306. SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
  307. USize *_size_ptr = _get_size_ptr(mem_new);
  308. T *_data_ptr = _get_data_ptr(mem_new);
  309. new (_refc_ptr) SafeNumeric<USize>(1); //refcount
  310. *(_size_ptr) = 0; //size, currently none
  311. _ptr = _data_ptr;
  312. } else {
  313. const Error error = _realloc(alloc_size);
  314. if (error) {
  315. return error;
  316. }
  317. }
  318. }
  319. // construct the newly created elements
  320. memnew_arr_placement<p_ensure_zero>(_ptr + current_size, p_size - current_size);
  321. *_get_size() = p_size;
  322. } else if (p_size < current_size) {
  323. if constexpr (!std::is_trivially_destructible_v<T>) {
  324. // deinitialize no longer needed elements
  325. for (USize i = p_size; i < *_get_size(); i++) {
  326. T *t = &_ptr[i];
  327. t->~T();
  328. }
  329. }
  330. if (alloc_size != current_alloc_size) {
  331. const Error error = _realloc(alloc_size);
  332. if (error) {
  333. return error;
  334. }
  335. }
  336. *_get_size() = p_size;
  337. }
  338. return OK;
  339. }
  340. template <typename T>
  341. Error CowData<T>::_realloc(Size p_alloc_size) {
  342. uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, p_alloc_size + DATA_OFFSET, false);
  343. ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
  344. SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
  345. T *_data_ptr = _get_data_ptr(mem_new);
  346. // If we realloc, we're guaranteed to be the only reference.
  347. new (_refc_ptr) SafeNumeric<USize>(1);
  348. _ptr = _data_ptr;
  349. return OK;
  350. }
  351. template <typename T>
  352. void CowData<T>::_ref(const CowData *p_from) {
  353. _ref(*p_from);
  354. }
  355. template <typename T>
  356. void CowData<T>::_ref(const CowData &p_from) {
  357. if (_ptr == p_from._ptr) {
  358. return; // self assign, do nothing.
  359. }
  360. _unref(); // Resets _ptr to nullptr.
  361. if (!p_from._ptr) {
  362. return; //nothing to do
  363. }
  364. if (p_from._get_refcount()->conditional_increment() > 0) { // could reference
  365. _ptr = p_from._ptr;
  366. }
  367. }
  368. template <typename T>
  369. CowData<T>::CowData(std::initializer_list<T> p_init) {
  370. Error err = resize(p_init.size());
  371. if (err != OK) {
  372. return;
  373. }
  374. Size i = 0;
  375. for (const T &element : p_init) {
  376. set(i++, element);
  377. }
  378. }
  379. #if defined(__GNUC__) && !defined(__clang__)
  380. #pragma GCC diagnostic pop
  381. #endif
  382. // Zero-constructing CowData initializes _ptr to nullptr (and thus empty).
  383. template <typename T>
  384. struct is_zero_constructible<CowData<T>> : std::true_type {};