cowdata.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. #ifndef COWDATA_H
  31. #define COWDATA_H
  32. #include "core/error/error_macros.h"
  33. #include "core/os/memory.h"
  34. #include "core/templates/safe_refcount.h"
  35. #include <string.h>
  36. #include <initializer_list>
  37. #include <type_traits>
  38. #include <utility>
  39. template <typename T>
  40. class Vector;
  41. class String;
  42. class Char16String;
  43. class CharString;
  44. template <typename T, typename V>
  45. class VMap;
  46. static_assert(std::is_trivially_destructible_v<std::atomic<uint64_t>>);
  47. // Silence a false positive warning (see GH-52119).
  48. #if defined(__GNUC__) && !defined(__clang__)
  49. #pragma GCC diagnostic push
  50. #pragma GCC diagnostic ignored "-Wplacement-new"
  51. #endif
  52. template <typename T>
  53. class CowData {
  54. template <typename TV>
  55. friend class Vector;
  56. friend class String;
  57. friend class Char16String;
  58. friend class CharString;
  59. template <typename TV, typename VV>
  60. friend class VMap;
  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. // Decrements the reference count. Deallocates the backing buffer if needed.
  141. // After this function, _ptr is guaranteed to be NULL.
  142. void _unref();
  143. void _ref(const CowData *p_from);
  144. void _ref(const CowData &p_from);
  145. USize _copy_on_write();
  146. Error _realloc(Size p_alloc_size);
  147. public:
  148. void operator=(const CowData<T> &p_from) { _ref(p_from); }
  149. void operator=(CowData<T> &&p_from) {
  150. if (_ptr == p_from._ptr) {
  151. return;
  152. }
  153. _unref();
  154. _ptr = p_from._ptr;
  155. p_from._ptr = nullptr;
  156. }
  157. _FORCE_INLINE_ T *ptrw() {
  158. _copy_on_write();
  159. return _ptr;
  160. }
  161. _FORCE_INLINE_ const T *ptr() const {
  162. return _ptr;
  163. }
  164. _FORCE_INLINE_ Size size() const {
  165. USize *size = (USize *)_get_size();
  166. if (size) {
  167. return *size;
  168. } else {
  169. return 0;
  170. }
  171. }
  172. _FORCE_INLINE_ void clear() { resize(0); }
  173. _FORCE_INLINE_ bool is_empty() const { return _ptr == nullptr; }
  174. _FORCE_INLINE_ void set(Size p_index, const T &p_elem) {
  175. ERR_FAIL_INDEX(p_index, size());
  176. _copy_on_write();
  177. _ptr[p_index] = p_elem;
  178. }
  179. _FORCE_INLINE_ T &get_m(Size p_index) {
  180. CRASH_BAD_INDEX(p_index, size());
  181. _copy_on_write();
  182. return _ptr[p_index];
  183. }
  184. _FORCE_INLINE_ const T &get(Size p_index) const {
  185. CRASH_BAD_INDEX(p_index, size());
  186. return _ptr[p_index];
  187. }
  188. template <bool p_ensure_zero = false>
  189. Error resize(Size p_size);
  190. _FORCE_INLINE_ void remove_at(Size p_index) {
  191. ERR_FAIL_INDEX(p_index, size());
  192. T *p = ptrw();
  193. Size len = size();
  194. for (Size i = p_index; i < len - 1; i++) {
  195. p[i] = std::move(p[i + 1]);
  196. }
  197. resize(len - 1);
  198. }
  199. Error insert(Size p_pos, const T &p_val) {
  200. Size new_size = size() + 1;
  201. ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);
  202. Error err = resize(new_size);
  203. ERR_FAIL_COND_V(err, err);
  204. T *p = ptrw();
  205. for (Size i = new_size - 1; i > p_pos; i--) {
  206. p[i] = std::move(p[i - 1]);
  207. }
  208. p[p_pos] = p_val;
  209. return OK;
  210. }
  211. Size find(const T &p_val, Size p_from = 0) const;
  212. Size rfind(const T &p_val, Size p_from = -1) const;
  213. Size count(const T &p_val) const;
  214. _FORCE_INLINE_ CowData() {}
  215. _FORCE_INLINE_ ~CowData() { _unref(); }
  216. _FORCE_INLINE_ CowData(std::initializer_list<T> p_init);
  217. _FORCE_INLINE_ CowData(const CowData<T> &p_from) { _ref(p_from); }
  218. _FORCE_INLINE_ CowData(CowData<T> &&p_from) {
  219. _ptr = p_from._ptr;
  220. p_from._ptr = nullptr;
  221. }
  222. };
  223. template <typename T>
  224. void CowData<T>::_unref() {
  225. if (!_ptr) {
  226. return;
  227. }
  228. SafeNumeric<USize> *refc = _get_refcount();
  229. if (refc->decrement() > 0) {
  230. // Data is still in use elsewhere.
  231. _ptr = nullptr;
  232. return;
  233. }
  234. // Clean up.
  235. // First, invalidate our own reference.
  236. // NOTE: It is required to do so immediately because it must not be observable outside of this
  237. // function after refcount has already been reduced to 0.
  238. // WARNING: It must be done before calling the destructors, because one of them may otherwise
  239. // observe it through a reference to us. In this case, it may try to access the buffer,
  240. // which is illegal after some of the elements in it have already been destructed, and
  241. // may lead to a segmentation fault.
  242. USize current_size = *_get_size();
  243. T *prev_ptr = _ptr;
  244. _ptr = nullptr;
  245. if constexpr (!std::is_trivially_destructible_v<T>) {
  246. for (USize i = 0; i < current_size; ++i) {
  247. prev_ptr[i].~T();
  248. }
  249. }
  250. // free mem
  251. Memory::free_static((uint8_t *)prev_ptr - DATA_OFFSET, false);
  252. }
  253. template <typename T>
  254. typename CowData<T>::USize CowData<T>::_copy_on_write() {
  255. if (!_ptr) {
  256. return 0;
  257. }
  258. SafeNumeric<USize> *refc = _get_refcount();
  259. USize rc = refc->get();
  260. if (unlikely(rc > 1)) {
  261. /* in use by more than me */
  262. USize current_size = *_get_size();
  263. uint8_t *mem_new = (uint8_t *)Memory::alloc_static(_get_alloc_size(current_size) + DATA_OFFSET, false);
  264. ERR_FAIL_NULL_V(mem_new, 0);
  265. SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
  266. USize *_size_ptr = _get_size_ptr(mem_new);
  267. T *_data_ptr = _get_data_ptr(mem_new);
  268. new (_refc_ptr) SafeNumeric<USize>(1); //refcount
  269. *(_size_ptr) = current_size; //size
  270. // initialize new elements
  271. if constexpr (std::is_trivially_copyable_v<T>) {
  272. memcpy((uint8_t *)_data_ptr, _ptr, current_size * sizeof(T));
  273. } else {
  274. for (USize i = 0; i < current_size; i++) {
  275. memnew_placement(&_data_ptr[i], T(_ptr[i]));
  276. }
  277. }
  278. _unref();
  279. _ptr = _data_ptr;
  280. rc = 1;
  281. }
  282. return rc;
  283. }
  284. template <typename T>
  285. template <bool p_ensure_zero>
  286. Error CowData<T>::resize(Size p_size) {
  287. ERR_FAIL_COND_V(p_size < 0, ERR_INVALID_PARAMETER);
  288. Size current_size = size();
  289. if (p_size == current_size) {
  290. return OK;
  291. }
  292. if (p_size == 0) {
  293. // Wants to clean up.
  294. _unref(); // Resets _ptr to nullptr.
  295. return OK;
  296. }
  297. // possibly changing size, copy on write
  298. _copy_on_write();
  299. USize current_alloc_size = _get_alloc_size(current_size);
  300. USize alloc_size;
  301. ERR_FAIL_COND_V(!_get_alloc_size_checked(p_size, &alloc_size), ERR_OUT_OF_MEMORY);
  302. if (p_size > current_size) {
  303. if (alloc_size != current_alloc_size) {
  304. if (current_size == 0) {
  305. // alloc from scratch
  306. uint8_t *mem_new = (uint8_t *)Memory::alloc_static(alloc_size + DATA_OFFSET, false);
  307. ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
  308. SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
  309. USize *_size_ptr = _get_size_ptr(mem_new);
  310. T *_data_ptr = _get_data_ptr(mem_new);
  311. new (_refc_ptr) SafeNumeric<USize>(1); //refcount
  312. *(_size_ptr) = 0; //size, currently none
  313. _ptr = _data_ptr;
  314. } else {
  315. const Error error = _realloc(alloc_size);
  316. if (error) {
  317. return error;
  318. }
  319. }
  320. }
  321. // construct the newly created elements
  322. if constexpr (!std::is_trivially_constructible_v<T>) {
  323. for (Size i = *_get_size(); i < p_size; i++) {
  324. memnew_placement(&_ptr[i], T);
  325. }
  326. } else if (p_ensure_zero) {
  327. memset((void *)(_ptr + current_size), 0, (p_size - current_size) * sizeof(T));
  328. }
  329. *_get_size() = p_size;
  330. } else if (p_size < current_size) {
  331. if constexpr (!std::is_trivially_destructible_v<T>) {
  332. // deinitialize no longer needed elements
  333. for (USize i = p_size; i < *_get_size(); i++) {
  334. T *t = &_ptr[i];
  335. t->~T();
  336. }
  337. }
  338. if (alloc_size != current_alloc_size) {
  339. const Error error = _realloc(alloc_size);
  340. if (error) {
  341. return error;
  342. }
  343. }
  344. *_get_size() = p_size;
  345. }
  346. return OK;
  347. }
  348. template <typename T>
  349. Error CowData<T>::_realloc(Size p_alloc_size) {
  350. uint8_t *mem_new = (uint8_t *)Memory::realloc_static(((uint8_t *)_ptr) - DATA_OFFSET, p_alloc_size + DATA_OFFSET, false);
  351. ERR_FAIL_NULL_V(mem_new, ERR_OUT_OF_MEMORY);
  352. SafeNumeric<USize> *_refc_ptr = _get_refcount_ptr(mem_new);
  353. T *_data_ptr = _get_data_ptr(mem_new);
  354. // If we realloc, we're guaranteed to be the only reference.
  355. new (_refc_ptr) SafeNumeric<USize>(1);
  356. _ptr = _data_ptr;
  357. return OK;
  358. }
  359. template <typename T>
  360. typename CowData<T>::Size CowData<T>::find(const T &p_val, Size p_from) const {
  361. Size ret = -1;
  362. if (p_from < 0 || size() == 0) {
  363. return ret;
  364. }
  365. for (Size i = p_from; i < size(); i++) {
  366. if (get(i) == p_val) {
  367. ret = i;
  368. break;
  369. }
  370. }
  371. return ret;
  372. }
  373. template <typename T>
  374. typename CowData<T>::Size CowData<T>::rfind(const T &p_val, Size p_from) const {
  375. const Size s = size();
  376. if (p_from < 0) {
  377. p_from = s + p_from;
  378. }
  379. if (p_from < 0 || p_from >= s) {
  380. p_from = s - 1;
  381. }
  382. for (Size i = p_from; i >= 0; i--) {
  383. if (get(i) == p_val) {
  384. return i;
  385. }
  386. }
  387. return -1;
  388. }
  389. template <typename T>
  390. typename CowData<T>::Size CowData<T>::count(const T &p_val) const {
  391. Size amount = 0;
  392. for (Size i = 0; i < size(); i++) {
  393. if (get(i) == p_val) {
  394. amount++;
  395. }
  396. }
  397. return amount;
  398. }
  399. template <typename T>
  400. void CowData<T>::_ref(const CowData *p_from) {
  401. _ref(*p_from);
  402. }
  403. template <typename T>
  404. void CowData<T>::_ref(const CowData &p_from) {
  405. if (_ptr == p_from._ptr) {
  406. return; // self assign, do nothing.
  407. }
  408. _unref(); // Resets _ptr to nullptr.
  409. if (!p_from._ptr) {
  410. return; //nothing to do
  411. }
  412. if (p_from._get_refcount()->conditional_increment() > 0) { // could reference
  413. _ptr = p_from._ptr;
  414. }
  415. }
  416. template <typename T>
  417. CowData<T>::CowData(std::initializer_list<T> p_init) {
  418. Error err = resize(p_init.size());
  419. if (err != OK) {
  420. return;
  421. }
  422. Size i = 0;
  423. for (const T &element : p_init) {
  424. set(i++, element);
  425. }
  426. }
  427. #if defined(__GNUC__) && !defined(__clang__)
  428. #pragma GCC diagnostic pop
  429. #endif
  430. #endif // COWDATA_H