pool_vector.h 14 KB

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