pool_vector.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /*************************************************************************/
  2. /* pool_vector.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 POOL_VECTOR_H
  31. #define POOL_VECTOR_H
  32. #include "core/os/memory.h"
  33. #include "core/os/mutex.h"
  34. #include "core/os/rw_lock.h"
  35. #include "core/pool_allocator.h"
  36. #include "core/safe_refcount.h"
  37. #include "core/ustring.h"
  38. struct MemoryPool {
  39. //avoid accessing these directly, must be public for template access
  40. static PoolAllocator *memory_pool;
  41. static uint8_t *pool_memory;
  42. static size_t *pool_size;
  43. struct Alloc {
  44. SafeRefCount refcount;
  45. SafeNumeric<uint32_t> lock;
  46. void *mem;
  47. PoolAllocator::ID pool_id;
  48. size_t size;
  49. Alloc *free_list;
  50. Alloc() :
  51. lock(0),
  52. mem(nullptr),
  53. pool_id(POOL_ALLOCATOR_INVALID_ID),
  54. size(0),
  55. free_list(nullptr) {
  56. }
  57. };
  58. static Alloc *allocs;
  59. static Alloc *free_list;
  60. static uint32_t alloc_count;
  61. static uint32_t allocs_used;
  62. static Mutex alloc_mutex;
  63. static size_t total_memory;
  64. static size_t max_memory;
  65. static void setup(uint32_t p_max_allocs = (1 << 16));
  66. static void cleanup();
  67. };
  68. template <class T>
  69. class PoolVector {
  70. MemoryPool::Alloc *alloc;
  71. void _copy_on_write() {
  72. if (!alloc) {
  73. return;
  74. }
  75. // ERR_FAIL_COND(alloc->lock>0); should not be illegal to lock this for copy on write, as it's a copy on write after all
  76. // Refcount should not be zero, otherwise it's a misuse of COW
  77. if (alloc->refcount.get() == 1) {
  78. return; //nothing to do
  79. }
  80. //must allocate something
  81. MemoryPool::alloc_mutex.lock();
  82. if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
  83. MemoryPool::alloc_mutex.unlock();
  84. ERR_FAIL_MSG("All memory pool allocations are in use, can't COW.");
  85. }
  86. MemoryPool::Alloc *old_alloc = alloc;
  87. //take one from the free list
  88. alloc = MemoryPool::free_list;
  89. MemoryPool::free_list = alloc->free_list;
  90. //increment the used counter
  91. MemoryPool::allocs_used++;
  92. //copy the alloc data
  93. alloc->size = old_alloc->size;
  94. alloc->refcount.init();
  95. alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
  96. alloc->lock.set(0);
  97. #ifdef DEBUG_ENABLED
  98. MemoryPool::total_memory += alloc->size;
  99. if (MemoryPool::total_memory > MemoryPool::max_memory) {
  100. MemoryPool::max_memory = MemoryPool::total_memory;
  101. }
  102. #endif
  103. MemoryPool::alloc_mutex.unlock();
  104. if (MemoryPool::memory_pool) {
  105. } else {
  106. alloc->mem = memalloc(alloc->size);
  107. }
  108. {
  109. Write w;
  110. w._ref(alloc);
  111. Read r;
  112. r._ref(old_alloc);
  113. int cur_elements = alloc->size / sizeof(T);
  114. T *dst = (T *)w.ptr();
  115. const T *src = (const T *)r.ptr();
  116. for (int i = 0; i < cur_elements; i++) {
  117. memnew_placement(&dst[i], T(src[i]));
  118. }
  119. }
  120. if (old_alloc->refcount.unref()) {
  121. //this should never happen but..
  122. #ifdef DEBUG_ENABLED
  123. MemoryPool::alloc_mutex.lock();
  124. MemoryPool::total_memory -= old_alloc->size;
  125. MemoryPool::alloc_mutex.unlock();
  126. #endif
  127. {
  128. Write w;
  129. w._ref(old_alloc);
  130. int cur_elements = old_alloc->size / sizeof(T);
  131. T *elems = (T *)w.ptr();
  132. for (int i = 0; i < cur_elements; i++) {
  133. elems[i].~T();
  134. }
  135. }
  136. if (MemoryPool::memory_pool) {
  137. //resize memory pool
  138. //if none, create
  139. //if some resize
  140. } else {
  141. memfree(old_alloc->mem);
  142. old_alloc->mem = nullptr;
  143. old_alloc->size = 0;
  144. MemoryPool::alloc_mutex.lock();
  145. old_alloc->free_list = MemoryPool::free_list;
  146. MemoryPool::free_list = old_alloc;
  147. MemoryPool::allocs_used--;
  148. MemoryPool::alloc_mutex.unlock();
  149. }
  150. }
  151. }
  152. void _reference(const PoolVector &p_pool_vector) {
  153. if (alloc == p_pool_vector.alloc) {
  154. return;
  155. }
  156. _unreference();
  157. if (!p_pool_vector.alloc) {
  158. return;
  159. }
  160. if (p_pool_vector.alloc->refcount.ref()) {
  161. alloc = p_pool_vector.alloc;
  162. }
  163. }
  164. void _unreference() {
  165. if (!alloc) {
  166. return;
  167. }
  168. if (!alloc->refcount.unref()) {
  169. alloc = nullptr;
  170. return;
  171. }
  172. //must be disposed!
  173. {
  174. int cur_elements = alloc->size / sizeof(T);
  175. // Don't use write() here because it could otherwise provoke COW,
  176. // which is not desirable here because we are destroying the last reference anyways
  177. Write w;
  178. // Reference to still prevent other threads from touching the alloc
  179. w._ref(alloc);
  180. for (int i = 0; i < cur_elements; i++) {
  181. w[i].~T();
  182. }
  183. }
  184. #ifdef DEBUG_ENABLED
  185. MemoryPool::alloc_mutex.lock();
  186. MemoryPool::total_memory -= alloc->size;
  187. MemoryPool::alloc_mutex.unlock();
  188. #endif
  189. if (MemoryPool::memory_pool) {
  190. //resize memory pool
  191. //if none, create
  192. //if some resize
  193. } else {
  194. memfree(alloc->mem);
  195. alloc->mem = nullptr;
  196. alloc->size = 0;
  197. MemoryPool::alloc_mutex.lock();
  198. alloc->free_list = MemoryPool::free_list;
  199. MemoryPool::free_list = alloc;
  200. MemoryPool::allocs_used--;
  201. MemoryPool::alloc_mutex.unlock();
  202. }
  203. alloc = nullptr;
  204. }
  205. public:
  206. class Access {
  207. friend class PoolVector;
  208. protected:
  209. MemoryPool::Alloc *alloc;
  210. T *mem;
  211. _FORCE_INLINE_ void _ref(MemoryPool::Alloc *p_alloc) {
  212. alloc = p_alloc;
  213. if (alloc) {
  214. if (alloc->lock.increment() == 1) {
  215. if (MemoryPool::memory_pool) {
  216. //lock it and get mem
  217. }
  218. }
  219. mem = (T *)alloc->mem;
  220. }
  221. }
  222. _FORCE_INLINE_ void _unref() {
  223. if (alloc) {
  224. if (alloc->lock.decrement() == 0) {
  225. if (MemoryPool::memory_pool) {
  226. //put mem back
  227. }
  228. }
  229. mem = nullptr;
  230. alloc = nullptr;
  231. }
  232. }
  233. Access() {
  234. alloc = nullptr;
  235. mem = nullptr;
  236. }
  237. public:
  238. virtual ~Access() {
  239. _unref();
  240. }
  241. void release() {
  242. _unref();
  243. }
  244. };
  245. class Read : public Access {
  246. public:
  247. _FORCE_INLINE_ const T &operator[](int p_index) const { return this->mem[p_index]; }
  248. _FORCE_INLINE_ const T *ptr() const { return this->mem; }
  249. void operator=(const Read &p_read) {
  250. if (this->alloc == p_read.alloc) {
  251. return;
  252. }
  253. this->_unref();
  254. this->_ref(p_read.alloc);
  255. }
  256. Read(const Read &p_read) {
  257. this->_ref(p_read.alloc);
  258. }
  259. Read() {}
  260. };
  261. class Write : public Access {
  262. public:
  263. _FORCE_INLINE_ T &operator[](int p_index) const { return this->mem[p_index]; }
  264. _FORCE_INLINE_ T *ptr() const { return this->mem; }
  265. void operator=(const Write &p_read) {
  266. if (this->alloc == p_read.alloc) {
  267. return;
  268. }
  269. this->_unref();
  270. this->_ref(p_read.alloc);
  271. }
  272. Write(const Write &p_read) {
  273. this->_ref(p_read.alloc);
  274. }
  275. Write() {}
  276. };
  277. Read read() const {
  278. Read r;
  279. if (alloc) {
  280. r._ref(alloc);
  281. }
  282. return r;
  283. }
  284. Write write() {
  285. Write w;
  286. if (alloc) {
  287. _copy_on_write(); //make sure there is only one being accessed
  288. w._ref(alloc);
  289. }
  290. return w;
  291. }
  292. template <class MC>
  293. void fill_with(const MC &p_mc) {
  294. int c = p_mc.size();
  295. resize(c);
  296. Write w = write();
  297. int idx = 0;
  298. for (const typename MC::Element *E = p_mc.front(); E; E = E->next()) {
  299. w[idx++] = E->get();
  300. }
  301. }
  302. void remove(int p_index) {
  303. int s = size();
  304. ERR_FAIL_INDEX(p_index, s);
  305. Write w = write();
  306. for (int i = p_index; i < s - 1; i++) {
  307. w[i] = w[i + 1];
  308. };
  309. w = Write();
  310. resize(s - 1);
  311. }
  312. inline int size() const;
  313. inline bool empty() const;
  314. T get(int p_index) const;
  315. void set(int p_index, const T &p_val);
  316. void push_back(const T &p_val);
  317. void append(const T &p_val) { push_back(p_val); }
  318. void append_array(const PoolVector<T> &p_arr) {
  319. int ds = p_arr.size();
  320. if (ds == 0) {
  321. return;
  322. }
  323. int bs = size();
  324. resize(bs + ds);
  325. Write w = write();
  326. Read r = p_arr.read();
  327. for (int i = 0; i < ds; i++) {
  328. w[bs + i] = r[i];
  329. }
  330. }
  331. PoolVector<T> subarray(int p_from, int p_to) {
  332. if (p_from < 0) {
  333. p_from = size() + p_from;
  334. }
  335. if (p_to < 0) {
  336. p_to = size() + p_to;
  337. }
  338. ERR_FAIL_INDEX_V(p_from, size(), PoolVector<T>());
  339. ERR_FAIL_INDEX_V(p_to, size(), PoolVector<T>());
  340. PoolVector<T> slice;
  341. int span = 1 + p_to - p_from;
  342. slice.resize(span);
  343. Read r = read();
  344. Write w = slice.write();
  345. for (int i = 0; i < span; ++i) {
  346. w[i] = r[p_from + i];
  347. }
  348. return slice;
  349. }
  350. Error insert(int p_pos, const T &p_val) {
  351. int s = size();
  352. ERR_FAIL_INDEX_V(p_pos, s + 1, ERR_INVALID_PARAMETER);
  353. resize(s + 1);
  354. {
  355. Write w = write();
  356. for (int i = s; i > p_pos; i--) {
  357. w[i] = w[i - 1];
  358. }
  359. w[p_pos] = p_val;
  360. }
  361. return OK;
  362. }
  363. String join(String delimiter) {
  364. String rs = "";
  365. int s = size();
  366. Read r = read();
  367. for (int i = 0; i < s; i++) {
  368. rs += r[i] + delimiter;
  369. }
  370. rs.erase(rs.length() - delimiter.length(), delimiter.length());
  371. return rs;
  372. }
  373. bool is_locked() const { return alloc && alloc->lock.get() > 0; }
  374. inline T operator[](int p_index) const;
  375. Error resize(int p_size);
  376. void invert();
  377. void operator=(const PoolVector &p_pool_vector) { _reference(p_pool_vector); }
  378. PoolVector() { alloc = nullptr; }
  379. PoolVector(const PoolVector &p_pool_vector) {
  380. alloc = nullptr;
  381. _reference(p_pool_vector);
  382. }
  383. ~PoolVector() { _unreference(); }
  384. };
  385. template <class T>
  386. int PoolVector<T>::size() const {
  387. return alloc ? alloc->size / sizeof(T) : 0;
  388. }
  389. template <class T>
  390. bool PoolVector<T>::empty() const {
  391. return alloc ? alloc->size == 0 : true;
  392. }
  393. template <class T>
  394. T PoolVector<T>::get(int p_index) const {
  395. return operator[](p_index);
  396. }
  397. template <class T>
  398. void PoolVector<T>::set(int p_index, const T &p_val) {
  399. ERR_FAIL_INDEX(p_index, size());
  400. Write w = write();
  401. w[p_index] = p_val;
  402. }
  403. template <class T>
  404. void PoolVector<T>::push_back(const T &p_val) {
  405. resize(size() + 1);
  406. set(size() - 1, p_val);
  407. }
  408. template <class T>
  409. T PoolVector<T>::operator[](int p_index) const {
  410. CRASH_BAD_INDEX(p_index, size());
  411. Read r = read();
  412. return r[p_index];
  413. }
  414. template <class T>
  415. Error PoolVector<T>::resize(int p_size) {
  416. ERR_FAIL_COND_V_MSG(p_size < 0, ERR_INVALID_PARAMETER, "Size of PoolVector cannot be negative.");
  417. if (alloc == nullptr) {
  418. if (p_size == 0) {
  419. return OK; //nothing to do here
  420. }
  421. //must allocate something
  422. MemoryPool::alloc_mutex.lock();
  423. if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
  424. MemoryPool::alloc_mutex.unlock();
  425. ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "All memory pool allocations are in use.");
  426. }
  427. //take one from the free list
  428. alloc = MemoryPool::free_list;
  429. MemoryPool::free_list = alloc->free_list;
  430. //increment the used counter
  431. MemoryPool::allocs_used++;
  432. //cleanup the alloc
  433. alloc->size = 0;
  434. alloc->refcount.init();
  435. alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
  436. MemoryPool::alloc_mutex.unlock();
  437. } else {
  438. ERR_FAIL_COND_V_MSG(alloc->lock.get() > 0, ERR_LOCKED, "Can't resize PoolVector if locked."); //can't resize if locked!
  439. }
  440. size_t new_size = sizeof(T) * p_size;
  441. if (alloc->size == new_size) {
  442. return OK; //nothing to do
  443. }
  444. if (p_size == 0) {
  445. _unreference();
  446. return OK;
  447. }
  448. _copy_on_write(); // make it unique
  449. #ifdef DEBUG_ENABLED
  450. MemoryPool::alloc_mutex.lock();
  451. MemoryPool::total_memory -= alloc->size;
  452. MemoryPool::total_memory += new_size;
  453. if (MemoryPool::total_memory > MemoryPool::max_memory) {
  454. MemoryPool::max_memory = MemoryPool::total_memory;
  455. }
  456. MemoryPool::alloc_mutex.unlock();
  457. #endif
  458. int cur_elements = alloc->size / sizeof(T);
  459. if (p_size > cur_elements) {
  460. if (MemoryPool::memory_pool) {
  461. //resize memory pool
  462. //if none, create
  463. //if some resize
  464. } else {
  465. if (alloc->size == 0) {
  466. alloc->mem = memalloc(new_size);
  467. } else {
  468. alloc->mem = memrealloc(alloc->mem, new_size);
  469. }
  470. }
  471. alloc->size = new_size;
  472. Write w = write();
  473. for (int i = cur_elements; i < p_size; i++) {
  474. memnew_placement(&w[i], T);
  475. }
  476. } else {
  477. {
  478. Write w = write();
  479. for (int i = p_size; i < cur_elements; i++) {
  480. w[i].~T();
  481. }
  482. }
  483. if (MemoryPool::memory_pool) {
  484. //resize memory pool
  485. //if none, create
  486. //if some resize
  487. } else {
  488. if (new_size == 0) {
  489. memfree(alloc->mem);
  490. alloc->mem = nullptr;
  491. alloc->size = 0;
  492. MemoryPool::alloc_mutex.lock();
  493. alloc->free_list = MemoryPool::free_list;
  494. MemoryPool::free_list = alloc;
  495. MemoryPool::allocs_used--;
  496. MemoryPool::alloc_mutex.unlock();
  497. } else {
  498. alloc->mem = memrealloc(alloc->mem, new_size);
  499. alloc->size = new_size;
  500. }
  501. }
  502. }
  503. return OK;
  504. }
  505. template <class T>
  506. void PoolVector<T>::invert() {
  507. T temp;
  508. Write w = write();
  509. int s = size();
  510. int half_s = s / 2;
  511. for (int i = 0; i < half_s; i++) {
  512. temp = w[i];
  513. w[i] = w[s - i - 1];
  514. w[s - i - 1] = temp;
  515. }
  516. }
  517. #endif // POOL_VECTOR_H