dvector.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /*************************************************************************/
  2. /* dvector.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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 DVECTOR_H
  31. #define DVECTOR_H
  32. #include "os/copymem.h"
  33. #include "os/memory.h"
  34. #include "os/rw_lock.h"
  35. #include "pool_allocator.h"
  36. #include "safe_refcount.h"
  37. #include "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. uint32_t lock;
  46. void *mem;
  47. PoolAllocator::ID pool_id;
  48. size_t size;
  49. Alloc *free_list;
  50. Alloc() {
  51. mem = NULL;
  52. lock = 0;
  53. pool_id = POOL_ALLOCATOR_INVALID_ID;
  54. size = 0;
  55. free_list = NULL;
  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. /**
  69. @author Juan Linietsky <reduzio@gmail.com>
  70. */
  71. template <class T>
  72. class PoolVector {
  73. MemoryPool::Alloc *alloc;
  74. void _copy_on_write() {
  75. if (!alloc)
  76. return;
  77. // 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
  78. // Refcount should not be zero, otherwise it's a misuse of COW
  79. if (alloc->refcount.get() == 1)
  80. return; //nothing to do
  81. //must allocate something
  82. MemoryPool::alloc_mutex->lock();
  83. if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
  84. MemoryPool::alloc_mutex->unlock();
  85. ERR_EXPLAINC("All memory pool allocations are in use, can't COW.");
  86. ERR_FAIL();
  87. }
  88. MemoryPool::Alloc *old_alloc = alloc;
  89. //take one from the free list
  90. alloc = MemoryPool::free_list;
  91. MemoryPool::free_list = alloc->free_list;
  92. //increment the used counter
  93. MemoryPool::allocs_used++;
  94. //copy the alloc data
  95. alloc->size = old_alloc->size;
  96. alloc->refcount.init();
  97. alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
  98. alloc->lock = 0;
  99. #ifdef DEBUG_ENABLED
  100. MemoryPool::total_memory += alloc->size;
  101. if (MemoryPool::total_memory > MemoryPool::max_memory) {
  102. MemoryPool::max_memory = MemoryPool::total_memory;
  103. }
  104. #endif
  105. MemoryPool::alloc_mutex->unlock();
  106. if (MemoryPool::memory_pool) {
  107. } else {
  108. alloc->mem = memalloc(alloc->size);
  109. }
  110. {
  111. Write w;
  112. w._ref(alloc);
  113. Read r;
  114. r._ref(old_alloc);
  115. int cur_elements = alloc->size / sizeof(T);
  116. T *dst = (T *)w.ptr();
  117. const T *src = (const T *)r.ptr();
  118. for (int i = 0; i < cur_elements; i++) {
  119. memnew_placement(&dst[i], T(src[i]));
  120. }
  121. }
  122. if (old_alloc->refcount.unref() == true) {
  123. //this should never happen but..
  124. #ifdef DEBUG_ENABLED
  125. MemoryPool::alloc_mutex->lock();
  126. MemoryPool::total_memory -= old_alloc->size;
  127. MemoryPool::alloc_mutex->unlock();
  128. #endif
  129. {
  130. Write w;
  131. w._ref(old_alloc);
  132. int cur_elements = old_alloc->size / sizeof(T);
  133. T *elems = (T *)w.ptr();
  134. for (int i = 0; i < cur_elements; i++) {
  135. elems[i].~T();
  136. }
  137. }
  138. if (MemoryPool::memory_pool) {
  139. //resize memory pool
  140. //if none, create
  141. //if some resize
  142. } else {
  143. memfree(old_alloc->mem);
  144. old_alloc->mem = NULL;
  145. old_alloc->size = 0;
  146. MemoryPool::alloc_mutex->lock();
  147. old_alloc->free_list = MemoryPool::free_list;
  148. MemoryPool::free_list = old_alloc;
  149. MemoryPool::allocs_used--;
  150. MemoryPool::alloc_mutex->unlock();
  151. }
  152. }
  153. }
  154. void _reference(const PoolVector &p_dvector) {
  155. if (alloc == p_dvector.alloc)
  156. return;
  157. _unreference();
  158. if (!p_dvector.alloc) {
  159. return;
  160. }
  161. if (p_dvector.alloc->refcount.ref()) {
  162. alloc = p_dvector.alloc;
  163. }
  164. }
  165. void _unreference() {
  166. if (!alloc)
  167. return;
  168. if (alloc->refcount.unref() == false) {
  169. alloc = NULL;
  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 = NULL;
  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 = NULL;
  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 (atomic_increment(&alloc->lock) == 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 (atomic_decrement(&alloc->lock) == 0) {
  225. if (MemoryPool::memory_pool) {
  226. //put mem back
  227. }
  228. }
  229. mem = NULL;
  230. alloc = NULL;
  231. }
  232. }
  233. Access() {
  234. alloc = NULL;
  235. mem = NULL;
  236. }
  237. public:
  238. virtual ~Access() {
  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 acessed
  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. T get(int p_index) const;
  309. void set(int p_index, const T &p_val);
  310. void push_back(const T &p_val);
  311. void append(const T &p_val) { push_back(p_val); }
  312. void append_array(const PoolVector<T> &p_arr) {
  313. int ds = p_arr.size();
  314. if (ds == 0)
  315. return;
  316. int bs = size();
  317. resize(bs + ds);
  318. Write w = write();
  319. Read r = p_arr.read();
  320. for (int i = 0; i < ds; i++)
  321. w[bs + i] = r[i];
  322. }
  323. PoolVector<T> subarray(int p_from, int p_to) {
  324. if (p_from < 0) {
  325. p_from = size() + p_from;
  326. }
  327. if (p_to < 0) {
  328. p_to = size() + p_to;
  329. }
  330. CRASH_BAD_INDEX(p_from, size());
  331. CRASH_BAD_INDEX(p_to, size());
  332. PoolVector<T> slice;
  333. int span = 1 + p_to - p_from;
  334. slice.resize(span);
  335. Read r = read();
  336. Write w = slice.write();
  337. for (int i = 0; i < span; ++i) {
  338. w[i] = r[p_from + i];
  339. }
  340. return slice;
  341. }
  342. Error insert(int p_pos, const T &p_val) {
  343. int s = size();
  344. ERR_FAIL_INDEX_V(p_pos, s + 1, ERR_INVALID_PARAMETER);
  345. resize(s + 1);
  346. {
  347. Write w = write();
  348. for (int i = s; i > p_pos; i--)
  349. w[i] = w[i - 1];
  350. w[p_pos] = p_val;
  351. }
  352. return OK;
  353. }
  354. String join(String delimiter) {
  355. String rs = "";
  356. int s = size();
  357. Read r = read();
  358. for (int i = 0; i < s; i++) {
  359. rs += r[i] + delimiter;
  360. }
  361. rs.erase(rs.length() - delimiter.length(), delimiter.length());
  362. return rs;
  363. }
  364. bool is_locked() const { return alloc && alloc->lock > 0; }
  365. inline const T operator[](int p_index) const;
  366. Error resize(int p_size);
  367. void invert();
  368. void operator=(const PoolVector &p_dvector) { _reference(p_dvector); }
  369. PoolVector() { alloc = NULL; }
  370. PoolVector(const PoolVector &p_dvector) {
  371. alloc = NULL;
  372. _reference(p_dvector);
  373. }
  374. ~PoolVector() { _unreference(); }
  375. };
  376. template <class T>
  377. int PoolVector<T>::size() const {
  378. return alloc ? alloc->size / sizeof(T) : 0;
  379. }
  380. template <class T>
  381. T PoolVector<T>::get(int p_index) const {
  382. return operator[](p_index);
  383. }
  384. template <class T>
  385. void PoolVector<T>::set(int p_index, const T &p_val) {
  386. if (p_index < 0 || p_index >= size()) {
  387. ERR_FAIL_COND(p_index < 0 || p_index >= size());
  388. }
  389. Write w = write();
  390. w[p_index] = p_val;
  391. }
  392. template <class T>
  393. void PoolVector<T>::push_back(const T &p_val) {
  394. resize(size() + 1);
  395. set(size() - 1, p_val);
  396. }
  397. template <class T>
  398. const T PoolVector<T>::operator[](int p_index) const {
  399. CRASH_BAD_INDEX(p_index, size());
  400. Read r = read();
  401. return r[p_index];
  402. }
  403. template <class T>
  404. Error PoolVector<T>::resize(int p_size) {
  405. if (alloc == NULL) {
  406. if (p_size == 0)
  407. return OK; //nothing to do here
  408. //must allocate something
  409. MemoryPool::alloc_mutex->lock();
  410. if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
  411. MemoryPool::alloc_mutex->unlock();
  412. ERR_EXPLAINC("All memory pool allocations are in use.");
  413. ERR_FAIL_V(ERR_OUT_OF_MEMORY);
  414. }
  415. //take one from the free list
  416. alloc = MemoryPool::free_list;
  417. MemoryPool::free_list = alloc->free_list;
  418. //increment the used counter
  419. MemoryPool::allocs_used++;
  420. //cleanup the alloc
  421. alloc->size = 0;
  422. alloc->refcount.init();
  423. alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
  424. MemoryPool::alloc_mutex->unlock();
  425. } else {
  426. ERR_FAIL_COND_V(alloc->lock > 0, ERR_LOCKED); //can't resize if locked!
  427. }
  428. size_t new_size = sizeof(T) * p_size;
  429. if (alloc->size == new_size)
  430. return OK; //nothing to do
  431. if (p_size == 0) {
  432. _unreference();
  433. return OK;
  434. }
  435. _copy_on_write(); // make it unique
  436. #ifdef DEBUG_ENABLED
  437. MemoryPool::alloc_mutex->lock();
  438. MemoryPool::total_memory -= alloc->size;
  439. MemoryPool::total_memory += new_size;
  440. if (MemoryPool::total_memory > MemoryPool::max_memory) {
  441. MemoryPool::max_memory = MemoryPool::total_memory;
  442. }
  443. MemoryPool::alloc_mutex->unlock();
  444. #endif
  445. int cur_elements = alloc->size / sizeof(T);
  446. if (p_size > cur_elements) {
  447. if (MemoryPool::memory_pool) {
  448. //resize memory pool
  449. //if none, create
  450. //if some resize
  451. } else {
  452. if (alloc->size == 0) {
  453. alloc->mem = memalloc(new_size);
  454. } else {
  455. alloc->mem = memrealloc(alloc->mem, new_size);
  456. }
  457. }
  458. alloc->size = new_size;
  459. Write w = write();
  460. for (int i = cur_elements; i < p_size; i++) {
  461. memnew_placement(&w[i], T);
  462. }
  463. } else {
  464. {
  465. Write w = write();
  466. for (int i = p_size; i < cur_elements; i++) {
  467. w[i].~T();
  468. }
  469. }
  470. if (MemoryPool::memory_pool) {
  471. //resize memory pool
  472. //if none, create
  473. //if some resize
  474. } else {
  475. if (new_size == 0) {
  476. memfree(alloc->mem);
  477. alloc->mem = NULL;
  478. alloc->size = 0;
  479. MemoryPool::alloc_mutex->lock();
  480. alloc->free_list = MemoryPool::free_list;
  481. MemoryPool::free_list = alloc;
  482. MemoryPool::allocs_used--;
  483. MemoryPool::alloc_mutex->unlock();
  484. } else {
  485. alloc->mem = memrealloc(alloc->mem, new_size);
  486. alloc->size = new_size;
  487. }
  488. }
  489. }
  490. return OK;
  491. }
  492. template <class T>
  493. void PoolVector<T>::invert() {
  494. T temp;
  495. Write w = write();
  496. int s = size();
  497. int half_s = s / 2;
  498. for (int i = 0; i < half_s; i++) {
  499. temp = w[i];
  500. w[i] = w[s - i - 1];
  501. w[s - i - 1] = temp;
  502. }
  503. }
  504. #endif