cowdata.h 10 KB

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