Array.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/STLAllocator.h>
  6. #include <Jolt/Core/HashCombine.h>
  7. #ifdef JPH_USE_STD_VECTOR
  8. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  9. #include <vector>
  10. JPH_SUPPRESS_WARNINGS_STD_END
  11. JPH_NAMESPACE_BEGIN
  12. template <class T, class Allocator = STLAllocator<T>> using Array = std::vector<T, Allocator>;
  13. JPH_NAMESPACE_END
  14. #else
  15. JPH_NAMESPACE_BEGIN
  16. /// Simple replacement for std::vector
  17. ///
  18. /// Major differences:
  19. /// - Memory is not initialized to zero (this was causing a lot of page faults when deserializing large MeshShapes / HeightFieldShapes)
  20. /// - Iterators are simple pointers (for now)
  21. /// - No exception safety
  22. /// - No specialization like std::vector<bool> has
  23. /// - Not all functions have been implemented
  24. template <class T, class Allocator = STLAllocator<T>>
  25. class [[nodiscard]] Array : private Allocator
  26. {
  27. public:
  28. using value_type = T;
  29. using allocator_type = Allocator;
  30. using size_type = size_t;
  31. using difference_type = typename Allocator::difference_type;
  32. using pointer = T *;
  33. using const_pointer = const T *;
  34. using reference = T &;
  35. using const_reference = const T &;
  36. using const_iterator = const T *;
  37. using iterator = T *;
  38. private:
  39. /// Move elements from one location to another
  40. inline void move(pointer inDestination, pointer inSource, size_type inCount)
  41. {
  42. if constexpr (std::is_trivially_copyable<T>())
  43. memmove(inDestination, inSource, inCount * sizeof(T));
  44. else
  45. {
  46. if (inDestination < inSource)
  47. {
  48. for (T *destination_end = inDestination + inCount; inDestination < destination_end; ++inDestination, ++inSource)
  49. {
  50. ::new (inDestination) T(std::move(*inSource));
  51. inSource->~T();
  52. }
  53. }
  54. else
  55. {
  56. for (T *destination = inDestination + inCount - 1, *source = inSource + inCount - 1; destination >= inDestination; --destination, --source)
  57. {
  58. ::new (destination) T(std::move(*source));
  59. source->~T();
  60. }
  61. }
  62. }
  63. }
  64. /// Reallocate the data block to inNewCapacity
  65. inline void reallocate(size_type inNewCapacity)
  66. {
  67. JPH_ASSERT(inNewCapacity > 0 && inNewCapacity >= mSize);
  68. pointer pointer;
  69. if constexpr (AllocatorHasReallocate<Allocator>::sValue)
  70. {
  71. // Reallocate data block
  72. pointer = get_allocator().reallocate(mElements, mCapacity, inNewCapacity);
  73. }
  74. else
  75. {
  76. // Copy data to a new location
  77. pointer = get_allocator().allocate(inNewCapacity);
  78. if (mElements != nullptr)
  79. {
  80. move(pointer, mElements, mSize);
  81. get_allocator().deallocate(mElements, mCapacity);
  82. }
  83. }
  84. mElements = pointer;
  85. mCapacity = inNewCapacity;
  86. }
  87. /// Destruct elements [inStart, inEnd - 1]
  88. inline void destruct(size_type inStart, size_type inEnd)
  89. {
  90. if constexpr (!std::is_trivially_destructible<T>())
  91. if (inStart < inEnd)
  92. for (T *element = mElements + inStart, *element_end = mElements + inEnd; element < element_end; ++element)
  93. element->~T();
  94. }
  95. public:
  96. /// Reserve array space
  97. inline void reserve(size_type inNewSize)
  98. {
  99. if (mCapacity < inNewSize)
  100. reallocate(inNewSize);
  101. }
  102. /// Resize array to new length
  103. inline void resize(size_type inNewSize)
  104. {
  105. destruct(inNewSize, mSize);
  106. reserve(inNewSize);
  107. if constexpr (!std::is_trivially_constructible<T>())
  108. for (T *element = mElements + mSize, *element_end = mElements + inNewSize; element < element_end; ++element)
  109. ::new (element) T;
  110. mSize = inNewSize;
  111. }
  112. /// Resize array to new length and initialize all elements with inValue
  113. inline void resize(size_type inNewSize, const T &inValue)
  114. {
  115. JPH_ASSERT(&inValue < mElements || &inValue >= mElements + mSize, "Can't pass an element from the array to resize");
  116. destruct(inNewSize, mSize);
  117. reserve(inNewSize);
  118. for (T *element = mElements + mSize, *element_end = mElements + inNewSize; element < element_end; ++element)
  119. ::new (element) T(inValue);
  120. mSize = inNewSize;
  121. }
  122. /// Destruct all elements and set length to zero
  123. inline void clear()
  124. {
  125. destruct(0, mSize);
  126. mSize = 0;
  127. }
  128. private:
  129. /// Grow the array by at least inAmount elements
  130. inline void grow(size_type inAmount = 1)
  131. {
  132. size_type min_size = mSize + inAmount;
  133. if (min_size > mCapacity)
  134. {
  135. size_type new_capacity = max(min_size, mCapacity * 2);
  136. reserve(new_capacity);
  137. }
  138. }
  139. /// Free memory
  140. inline void free()
  141. {
  142. get_allocator().deallocate(mElements, mCapacity);
  143. mElements = nullptr;
  144. mCapacity = 0;
  145. }
  146. /// Destroy all elements and free memory
  147. inline void destroy()
  148. {
  149. if (mElements != nullptr)
  150. {
  151. clear();
  152. free();
  153. }
  154. }
  155. public:
  156. /// Replace the contents of this array with inBegin .. inEnd
  157. template <class Iterator>
  158. inline void assign(Iterator inBegin, Iterator inEnd)
  159. {
  160. clear();
  161. reserve(size_type(std::distance(inBegin, inEnd)));
  162. for (Iterator element = inBegin; element != inEnd; ++element)
  163. ::new (&mElements[mSize++]) T(*element);
  164. }
  165. /// Replace the contents of this array with inList
  166. inline void assign(std::initializer_list<T> inList)
  167. {
  168. clear();
  169. reserve(size_type(inList.size()));
  170. for (const T &v : inList)
  171. ::new (&mElements[mSize++]) T(v);
  172. }
  173. /// Default constructor
  174. Array() = default;
  175. /// Constructor with allocator
  176. explicit inline Array(const Allocator &inAllocator) :
  177. Allocator(inAllocator)
  178. {
  179. }
  180. /// Constructor with length
  181. explicit inline Array(size_type inLength, const Allocator &inAllocator = { }) :
  182. Allocator(inAllocator)
  183. {
  184. resize(inLength);
  185. }
  186. /// Constructor with length and value
  187. inline Array(size_type inLength, const T &inValue, const Allocator &inAllocator = { }) :
  188. Allocator(inAllocator)
  189. {
  190. resize(inLength, inValue);
  191. }
  192. /// Constructor from initializer list
  193. inline Array(std::initializer_list<T> inList, const Allocator &inAllocator = { }) :
  194. Allocator(inAllocator)
  195. {
  196. assign(inList);
  197. }
  198. /// Constructor from iterator
  199. inline Array(const_iterator inBegin, const_iterator inEnd, const Allocator &inAllocator = { }) :
  200. Allocator(inAllocator)
  201. {
  202. assign(inBegin, inEnd);
  203. }
  204. /// Copy constructor
  205. inline Array(const Array<T, Allocator> &inRHS) :
  206. Allocator(inRHS.get_allocator())
  207. {
  208. assign(inRHS.begin(), inRHS.end());
  209. }
  210. /// Move constructor
  211. inline Array(Array<T, Allocator> &&inRHS) noexcept :
  212. Allocator(std::move(inRHS.get_allocator())),
  213. mSize(inRHS.mSize),
  214. mCapacity(inRHS.mCapacity),
  215. mElements(inRHS.mElements)
  216. {
  217. inRHS.mSize = 0;
  218. inRHS.mCapacity = 0;
  219. inRHS.mElements = nullptr;
  220. }
  221. /// Destruct all elements
  222. inline ~Array()
  223. {
  224. destroy();
  225. }
  226. /// Get the allocator
  227. inline Allocator & get_allocator()
  228. {
  229. return *this;
  230. }
  231. inline const Allocator &get_allocator() const
  232. {
  233. return *this;
  234. }
  235. /// Add element to the back of the array
  236. inline void push_back(const T &inValue)
  237. {
  238. JPH_ASSERT(&inValue < mElements || &inValue >= mElements + mSize, "Can't pass an element from the array to push_back");
  239. grow();
  240. T *element = mElements + mSize++;
  241. ::new (element) T(inValue);
  242. }
  243. inline void push_back(T &&inValue)
  244. {
  245. grow();
  246. T *element = mElements + mSize++;
  247. ::new (element) T(std::move(inValue));
  248. }
  249. /// Construct element at the back of the array
  250. template <class... A>
  251. inline T & emplace_back(A &&... inValue)
  252. {
  253. grow();
  254. T *element = mElements + mSize++;
  255. ::new (element) T(std::forward<A>(inValue)...);
  256. return *element;
  257. }
  258. /// Remove element from the back of the array
  259. inline void pop_back()
  260. {
  261. JPH_ASSERT(mSize > 0);
  262. mElements[--mSize].~T();
  263. }
  264. /// Returns true if there are no elements in the array
  265. inline bool empty() const
  266. {
  267. return mSize == 0;
  268. }
  269. /// Returns amount of elements in the array
  270. inline size_type size() const
  271. {
  272. return mSize;
  273. }
  274. /// Returns maximum amount of elements the array can hold
  275. inline size_type capacity() const
  276. {
  277. return mCapacity;
  278. }
  279. /// Reduce the capacity of the array to match its size
  280. void shrink_to_fit()
  281. {
  282. if (mElements != nullptr)
  283. {
  284. if (mSize == 0)
  285. free();
  286. else if (mCapacity > mSize)
  287. reallocate(mSize);
  288. }
  289. }
  290. /// Swap the contents of two arrays
  291. void swap(Array<T, Allocator> &inRHS) noexcept
  292. {
  293. std::swap(get_allocator(), inRHS.get_allocator());
  294. std::swap(mSize, inRHS.mSize);
  295. std::swap(mCapacity, inRHS.mCapacity);
  296. std::swap(mElements, inRHS.mElements);
  297. }
  298. template <class Iterator>
  299. void insert(const_iterator inPos, Iterator inBegin, Iterator inEnd)
  300. {
  301. size_type num_elements = size_type(std::distance(inBegin, inEnd));
  302. if (num_elements > 0)
  303. {
  304. // After grow() inPos may be invalid
  305. size_type first_element = inPos - mElements;
  306. grow(num_elements);
  307. T *element_begin = mElements + first_element;
  308. T *element_end = element_begin + num_elements;
  309. move(element_end, element_begin, mSize - first_element);
  310. for (T *element = element_begin; element < element_end; ++element, ++inBegin)
  311. ::new (element) T(*inBegin);
  312. mSize += num_elements;
  313. }
  314. }
  315. void insert(const_iterator inPos, const T &inValue)
  316. {
  317. JPH_ASSERT(&inValue < mElements || &inValue >= mElements + mSize, "Can't pass an element from the array to insert");
  318. // After grow() inPos may be invalid
  319. size_type first_element = inPos - mElements;
  320. grow();
  321. T *element = mElements + first_element;
  322. move(element + 1, element, mSize - first_element);
  323. ::new (element) T(inValue);
  324. mSize++;
  325. }
  326. /// Remove one element from the array
  327. void erase(const_iterator inIter)
  328. {
  329. size_type p = size_type(inIter - begin());
  330. JPH_ASSERT(p < mSize);
  331. mElements[p].~T();
  332. if (p + 1 < mSize)
  333. move(mElements + p, mElements + p + 1, mSize - p - 1);
  334. --mSize;
  335. }
  336. /// Remove multiple element from the array
  337. void erase(const_iterator inBegin, const_iterator inEnd)
  338. {
  339. size_type p = size_type(inBegin - begin());
  340. size_type n = size_type(inEnd - inBegin);
  341. JPH_ASSERT(inEnd <= end());
  342. destruct(p, p + n);
  343. if (p + n < mSize)
  344. move(mElements + p, mElements + p + n, mSize - p - n);
  345. mSize -= n;
  346. }
  347. /// Iterators
  348. inline const_iterator begin() const
  349. {
  350. return mElements;
  351. }
  352. inline const_iterator end() const
  353. {
  354. return mElements + mSize;
  355. }
  356. inline const_iterator cbegin() const
  357. {
  358. return mElements;
  359. }
  360. inline const_iterator cend() const
  361. {
  362. return mElements + mSize;
  363. }
  364. inline iterator begin()
  365. {
  366. return mElements;
  367. }
  368. inline iterator end()
  369. {
  370. return mElements + mSize;
  371. }
  372. inline const T * data() const
  373. {
  374. return mElements;
  375. }
  376. inline T * data()
  377. {
  378. return mElements;
  379. }
  380. /// Access element
  381. inline T & operator [] (size_type inIdx)
  382. {
  383. JPH_ASSERT(inIdx < mSize);
  384. return mElements[inIdx];
  385. }
  386. inline const T & operator [] (size_type inIdx) const
  387. {
  388. JPH_ASSERT(inIdx < mSize);
  389. return mElements[inIdx];
  390. }
  391. /// Access element
  392. inline T & at(size_type inIdx)
  393. {
  394. JPH_ASSERT(inIdx < mSize);
  395. return mElements[inIdx];
  396. }
  397. inline const T & at(size_type inIdx) const
  398. {
  399. JPH_ASSERT(inIdx < mSize);
  400. return mElements[inIdx];
  401. }
  402. /// First element in the array
  403. inline const T & front() const
  404. {
  405. JPH_ASSERT(mSize > 0);
  406. return mElements[0];
  407. }
  408. inline T & front()
  409. {
  410. JPH_ASSERT(mSize > 0);
  411. return mElements[0];
  412. }
  413. /// Last element in the array
  414. inline const T & back() const
  415. {
  416. JPH_ASSERT(mSize > 0);
  417. return mElements[mSize - 1];
  418. }
  419. inline T & back()
  420. {
  421. JPH_ASSERT(mSize > 0);
  422. return mElements[mSize - 1];
  423. }
  424. /// Assignment operator
  425. Array<T, Allocator> & operator = (const Array<T, Allocator> &inRHS)
  426. {
  427. if (static_cast<const void *>(this) != static_cast<const void *>(&inRHS))
  428. assign(inRHS.begin(), inRHS.end());
  429. return *this;
  430. }
  431. /// Assignment move operator
  432. Array<T, Allocator> & operator = (Array<T, Allocator> &&inRHS) noexcept
  433. {
  434. if (static_cast<const void *>(this) != static_cast<const void *>(&inRHS))
  435. {
  436. destroy();
  437. get_allocator() = std::move(inRHS.get_allocator());
  438. mSize = inRHS.mSize;
  439. mCapacity = inRHS.mCapacity;
  440. mElements = inRHS.mElements;
  441. inRHS.mSize = 0;
  442. inRHS.mCapacity = 0;
  443. inRHS.mElements = nullptr;
  444. }
  445. return *this;
  446. }
  447. /// Assignment operator
  448. Array<T, Allocator> & operator = (std::initializer_list<T> inRHS)
  449. {
  450. assign(inRHS);
  451. return *this;
  452. }
  453. /// Comparing arrays
  454. bool operator == (const Array<T, Allocator> &inRHS) const
  455. {
  456. if (mSize != inRHS.mSize)
  457. return false;
  458. for (size_type i = 0; i < mSize; ++i)
  459. if (!(mElements[i] == inRHS.mElements[i]))
  460. return false;
  461. return true;
  462. }
  463. bool operator != (const Array<T, Allocator> &inRHS) const
  464. {
  465. if (mSize != inRHS.mSize)
  466. return true;
  467. for (size_type i = 0; i < mSize; ++i)
  468. if (mElements[i] != inRHS.mElements[i])
  469. return true;
  470. return false;
  471. }
  472. /// Get hash for this array
  473. uint64 GetHash() const
  474. {
  475. // Hash length first
  476. uint64 ret = Hash<uint32> { } (uint32(size()));
  477. // Then hash elements
  478. for (const T *element = mElements, *element_end = mElements + mSize; element < element_end; ++element)
  479. HashCombine(ret, *element);
  480. return ret;
  481. }
  482. private:
  483. size_type mSize = 0;
  484. size_type mCapacity = 0;
  485. T * mElements = nullptr;
  486. };
  487. JPH_NAMESPACE_END
  488. JPH_SUPPRESS_WARNING_PUSH
  489. JPH_CLANG_SUPPRESS_WARNING("-Wc++98-compat")
  490. namespace std
  491. {
  492. /// Declare std::hash for Array
  493. template <class T, class Allocator>
  494. struct hash<JPH::Array<T, Allocator>>
  495. {
  496. size_t operator () (const JPH::Array<T, Allocator> &inRHS) const
  497. {
  498. return std::size_t(inRHS.GetHash());
  499. }
  500. };
  501. }
  502. JPH_SUPPRESS_WARNING_POP
  503. #endif // JPH_USE_STD_VECTOR