cowdata.h 11 KB

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