cowdata.hpp 14 KB

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