pool_vector.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /**************************************************************************/
  2. /* pool_vector.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 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. int find(const T &p_val, int p_from = 0) const {
  313. const int s = size();
  314. const Read r = read();
  315. if (p_from < 0) {
  316. return -1;
  317. }
  318. for (int i = p_from; i < s; i++) {
  319. if (r[i] == p_val) {
  320. return i;
  321. }
  322. }
  323. return -1;
  324. }
  325. int rfind(const T &p_val, int p_from = -1) const {
  326. const int s = size();
  327. const Read r = read();
  328. if (p_from < 0) {
  329. p_from = s + p_from;
  330. }
  331. if (p_from < 0 || p_from >= s) {
  332. p_from = s - 1;
  333. }
  334. for (int i = p_from; i >= 0; i--) {
  335. if (r[i] == p_val) {
  336. return i;
  337. }
  338. }
  339. return -1;
  340. }
  341. int count(const T &p_val) const {
  342. const int s = size();
  343. const Read r = read();
  344. int amount = 0;
  345. for (int i = 0; i < s; i++) {
  346. if (r[i] == p_val) {
  347. amount++;
  348. }
  349. }
  350. return amount;
  351. }
  352. bool has(const T &p_val) const {
  353. return find(p_val) != -1;
  354. }
  355. inline int size() const;
  356. inline bool empty() const;
  357. T get(int p_index) const;
  358. void set(int p_index, const T &p_val);
  359. void fill(const T &p_val);
  360. void push_back(const T &p_val);
  361. void append(const T &p_val) { push_back(p_val); }
  362. void append_array(const PoolVector<T> &p_arr) {
  363. int ds = p_arr.size();
  364. if (ds == 0) {
  365. return;
  366. }
  367. int bs = size();
  368. resize(bs + ds);
  369. Write w = write();
  370. Read r = p_arr.read();
  371. for (int i = 0; i < ds; i++) {
  372. w[bs + i] = r[i];
  373. }
  374. }
  375. PoolVector<T> subarray(int p_from, int p_to) {
  376. if (p_from < 0) {
  377. p_from = size() + p_from;
  378. }
  379. if (p_to < 0) {
  380. p_to = size() + p_to;
  381. }
  382. ERR_FAIL_INDEX_V(p_from, size(), PoolVector<T>());
  383. ERR_FAIL_INDEX_V(p_to, size(), PoolVector<T>());
  384. PoolVector<T> slice;
  385. int span = 1 + p_to - p_from;
  386. slice.resize(span);
  387. Read r = read();
  388. Write w = slice.write();
  389. for (int i = 0; i < span; ++i) {
  390. w[i] = r[p_from + i];
  391. }
  392. return slice;
  393. }
  394. Error insert(int p_pos, const T &p_val) {
  395. int s = size();
  396. ERR_FAIL_INDEX_V(p_pos, s + 1, ERR_INVALID_PARAMETER);
  397. resize(s + 1);
  398. {
  399. Write w = write();
  400. for (int i = s; i > p_pos; i--) {
  401. w[i] = w[i - 1];
  402. }
  403. w[p_pos] = p_val;
  404. }
  405. return OK;
  406. }
  407. String join(String delimiter) const {
  408. String rs = "";
  409. int s = size();
  410. Read r = read();
  411. for (int i = 0; i < s; i++) {
  412. rs += r[i] + delimiter;
  413. }
  414. rs.erase(rs.length() - delimiter.length(), delimiter.length());
  415. return rs;
  416. }
  417. bool is_locked() const { return alloc && alloc->lock.get() > 0; }
  418. inline T operator[](int p_index) const;
  419. Error resize(int p_size);
  420. Error clear() { return resize(0); }
  421. void invert();
  422. void sort();
  423. void operator=(const PoolVector &p_pool_vector) { _reference(p_pool_vector); }
  424. PoolVector() { alloc = nullptr; }
  425. PoolVector(const PoolVector &p_pool_vector) {
  426. alloc = nullptr;
  427. _reference(p_pool_vector);
  428. }
  429. ~PoolVector() { _unreference(); }
  430. };
  431. template <class T>
  432. int PoolVector<T>::size() const {
  433. return alloc ? alloc->size / sizeof(T) : 0;
  434. }
  435. template <class T>
  436. bool PoolVector<T>::empty() const {
  437. return alloc ? alloc->size == 0 : true;
  438. }
  439. template <class T>
  440. T PoolVector<T>::get(int p_index) const {
  441. return operator[](p_index);
  442. }
  443. template <class T>
  444. void PoolVector<T>::set(int p_index, const T &p_val) {
  445. ERR_FAIL_INDEX(p_index, size());
  446. Write w = write();
  447. w[p_index] = p_val;
  448. }
  449. template <class T>
  450. void PoolVector<T>::fill(const T &p_val) {
  451. Write w = write();
  452. for (int i = 0; i < size(); i++) {
  453. w[i] = p_val;
  454. }
  455. }
  456. template <class T>
  457. void PoolVector<T>::push_back(const T &p_val) {
  458. resize(size() + 1);
  459. set(size() - 1, p_val);
  460. }
  461. template <class T>
  462. T PoolVector<T>::operator[](int p_index) const {
  463. CRASH_BAD_INDEX(p_index, size());
  464. Read r = read();
  465. return r[p_index];
  466. }
  467. template <class T>
  468. Error PoolVector<T>::resize(int p_size) {
  469. ERR_FAIL_COND_V_MSG(p_size < 0, ERR_INVALID_PARAMETER, "Size of PoolVector cannot be negative.");
  470. if (alloc == nullptr) {
  471. if (p_size == 0) {
  472. return OK; //nothing to do here
  473. }
  474. //must allocate something
  475. MemoryPool::alloc_mutex.lock();
  476. if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
  477. MemoryPool::alloc_mutex.unlock();
  478. ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "All memory pool allocations are in use.");
  479. }
  480. //take one from the free list
  481. alloc = MemoryPool::free_list;
  482. MemoryPool::free_list = alloc->free_list;
  483. //increment the used counter
  484. MemoryPool::allocs_used++;
  485. //cleanup the alloc
  486. alloc->size = 0;
  487. alloc->refcount.init();
  488. alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
  489. MemoryPool::alloc_mutex.unlock();
  490. } else {
  491. ERR_FAIL_COND_V_MSG(alloc->lock.get() > 0, ERR_LOCKED, "Can't resize PoolVector if locked."); //can't resize if locked!
  492. }
  493. size_t new_size = sizeof(T) * p_size;
  494. if (alloc->size == new_size) {
  495. return OK; //nothing to do
  496. }
  497. if (p_size == 0) {
  498. _unreference();
  499. return OK;
  500. }
  501. _copy_on_write(); // make it unique
  502. #ifdef DEBUG_ENABLED
  503. MemoryPool::alloc_mutex.lock();
  504. MemoryPool::total_memory -= alloc->size;
  505. MemoryPool::total_memory += new_size;
  506. if (MemoryPool::total_memory > MemoryPool::max_memory) {
  507. MemoryPool::max_memory = MemoryPool::total_memory;
  508. }
  509. MemoryPool::alloc_mutex.unlock();
  510. #endif
  511. int cur_elements = alloc->size / sizeof(T);
  512. if (p_size > cur_elements) {
  513. if (MemoryPool::memory_pool) {
  514. //resize memory pool
  515. //if none, create
  516. //if some resize
  517. } else {
  518. if (alloc->size == 0) {
  519. alloc->mem = memalloc(new_size);
  520. } else {
  521. alloc->mem = memrealloc(alloc->mem, new_size);
  522. }
  523. }
  524. alloc->size = new_size;
  525. Write w = write();
  526. for (int i = cur_elements; i < p_size; i++) {
  527. memnew_placement(&w[i], T);
  528. }
  529. } else {
  530. {
  531. Write w = write();
  532. for (int i = p_size; i < cur_elements; i++) {
  533. w[i].~T();
  534. }
  535. }
  536. if (MemoryPool::memory_pool) {
  537. //resize memory pool
  538. //if none, create
  539. //if some resize
  540. } else {
  541. if (new_size == 0) {
  542. memfree(alloc->mem);
  543. alloc->mem = nullptr;
  544. alloc->size = 0;
  545. MemoryPool::alloc_mutex.lock();
  546. alloc->free_list = MemoryPool::free_list;
  547. MemoryPool::free_list = alloc;
  548. MemoryPool::allocs_used--;
  549. MemoryPool::alloc_mutex.unlock();
  550. } else {
  551. alloc->mem = memrealloc(alloc->mem, new_size);
  552. alloc->size = new_size;
  553. }
  554. }
  555. }
  556. return OK;
  557. }
  558. template <class T>
  559. void PoolVector<T>::invert() {
  560. T temp;
  561. Write w = write();
  562. int s = size();
  563. int half_s = s / 2;
  564. for (int i = 0; i < half_s; i++) {
  565. temp = w[i];
  566. w[i] = w[s - i - 1];
  567. w[s - i - 1] = temp;
  568. }
  569. }
  570. template <class T>
  571. void PoolVector<T>::sort() {
  572. int len = size();
  573. if (len == 0) {
  574. return;
  575. }
  576. Write w = write();
  577. SortArray<T> sorter;
  578. sorter.sort(w.ptr(), len);
  579. }
  580. #endif // POOL_VECTOR_H