cowdata.hpp 13 KB

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