The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

619 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. /**
  20. A basic object container.
  21. This class isn't really for public use - it's used by the other
  22. array classes, but might come in handy for some purposes.
  23. It inherits from a critical section class to allow the arrays to use
  24. the "empty base class optimisation" pattern to reduce their footprint.
  25. @see Array, OwnedArray, ReferenceCountedArray
  26. @tags{Core}
  27. */
  28. template <class ElementType, class TypeOfCriticalSectionToUse>
  29. class ArrayBase : public TypeOfCriticalSectionToUse
  30. {
  31. private:
  32. using ParameterType = typename TypeHelpers::ParameterType<ElementType>::type;
  33. template <class OtherElementType, class OtherCriticalSection>
  34. using AllowConversion = typename std::enable_if<! std::is_same<std::tuple<ElementType, TypeOfCriticalSectionToUse>,
  35. std::tuple<OtherElementType, OtherCriticalSection>>::value>::type;
  36. public:
  37. //==============================================================================
  38. ArrayBase() = default;
  39. ~ArrayBase()
  40. {
  41. clear();
  42. }
  43. ArrayBase (ArrayBase&& other) noexcept
  44. : elements (std::move (other.elements)),
  45. numAllocated (other.numAllocated),
  46. numUsed (other.numUsed)
  47. {
  48. other.numAllocated = 0;
  49. other.numUsed = 0;
  50. }
  51. ArrayBase& operator= (ArrayBase&& other) noexcept
  52. {
  53. if (this != &other)
  54. {
  55. auto tmp (std::move (other));
  56. swapWith (tmp);
  57. }
  58. return *this;
  59. }
  60. /** Converting move constructor.
  61. Only enabled when the other array has a different type to this one.
  62. If you see a compile error here, it's probably because you're attempting a conversion that
  63. HeapBlock won't allow.
  64. */
  65. template <class OtherElementType,
  66. class OtherCriticalSection,
  67. typename = AllowConversion<OtherElementType, OtherCriticalSection>>
  68. ArrayBase (ArrayBase<OtherElementType, OtherCriticalSection>&& other) noexcept
  69. : elements (std::move (other.elements)),
  70. numAllocated (other.numAllocated),
  71. numUsed (other.numUsed)
  72. {
  73. other.numAllocated = 0;
  74. other.numUsed = 0;
  75. }
  76. /** Converting move assignment operator.
  77. Only enabled when the other array has a different type to this one.
  78. If you see a compile error here, it's probably because you're attempting a conversion that
  79. HeapBlock won't allow.
  80. */
  81. template <class OtherElementType,
  82. class OtherCriticalSection,
  83. typename = AllowConversion<OtherElementType, OtherCriticalSection>>
  84. ArrayBase& operator= (ArrayBase<OtherElementType, OtherCriticalSection>&& other) noexcept
  85. {
  86. // No need to worry about assignment to *this, because 'other' must be of a different type.
  87. elements = std::move (other.elements);
  88. numAllocated = other.numAllocated;
  89. numUsed = other.numUsed;
  90. other.numAllocated = 0;
  91. other.numUsed = 0;
  92. return *this;
  93. }
  94. //==============================================================================
  95. template <class OtherArrayType>
  96. bool operator== (const OtherArrayType& other) const noexcept
  97. {
  98. if (size() != (int) other.size())
  99. return false;
  100. auto* e = begin();
  101. for (auto& o : other)
  102. if (! (*e++ == o))
  103. return false;
  104. return true;
  105. }
  106. template <class OtherArrayType>
  107. bool operator!= (const OtherArrayType& other) const noexcept
  108. {
  109. return ! operator== (other);
  110. }
  111. //==============================================================================
  112. inline ElementType& operator[] (const int index) noexcept
  113. {
  114. jassert (elements != nullptr);
  115. jassert (isPositiveAndBelow (index, numUsed));
  116. return elements[index];
  117. }
  118. inline const ElementType& operator[] (const int index) const noexcept
  119. {
  120. jassert (elements != nullptr);
  121. jassert (isPositiveAndBelow (index, numUsed));
  122. return elements[index];
  123. }
  124. inline ElementType getValueWithDefault (const int index) const noexcept
  125. {
  126. return isPositiveAndBelow (index, numUsed) ? elements[index] : ElementType();
  127. }
  128. inline ElementType getFirst() const noexcept
  129. {
  130. return numUsed > 0 ? elements[0] : ElementType();
  131. }
  132. inline ElementType getLast() const noexcept
  133. {
  134. return numUsed > 0 ? elements[numUsed - 1] : ElementType();
  135. }
  136. //==============================================================================
  137. inline ElementType* begin() noexcept
  138. {
  139. return elements;
  140. }
  141. inline const ElementType* begin() const noexcept
  142. {
  143. return elements;
  144. }
  145. inline ElementType* end() noexcept
  146. {
  147. return elements + numUsed;
  148. }
  149. inline const ElementType* end() const noexcept
  150. {
  151. return elements + numUsed;
  152. }
  153. inline ElementType* data() noexcept
  154. {
  155. return elements;
  156. }
  157. inline const ElementType* data() const noexcept
  158. {
  159. return elements;
  160. }
  161. inline int size() const noexcept
  162. {
  163. return numUsed;
  164. }
  165. inline int capacity() const noexcept
  166. {
  167. return numAllocated;
  168. }
  169. //==============================================================================
  170. void setAllocatedSize (int numElements)
  171. {
  172. jassert (numElements >= numUsed);
  173. if (numAllocated != numElements)
  174. {
  175. if (numElements > 0)
  176. setAllocatedSizeInternal (numElements);
  177. else
  178. elements.free();
  179. }
  180. numAllocated = numElements;
  181. }
  182. void ensureAllocatedSize (int minNumElements)
  183. {
  184. if (minNumElements > numAllocated)
  185. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  186. jassert (numAllocated <= 0 || elements != nullptr);
  187. }
  188. void shrinkToNoMoreThan (int maxNumElements)
  189. {
  190. if (maxNumElements < numAllocated)
  191. setAllocatedSize (maxNumElements);
  192. }
  193. void clear()
  194. {
  195. for (int i = 0; i < numUsed; ++i)
  196. elements[i].~ElementType();
  197. numUsed = 0;
  198. }
  199. //==============================================================================
  200. void swapWith (ArrayBase& other) noexcept
  201. {
  202. elements.swapWith (other.elements);
  203. std::swap (numAllocated, other.numAllocated);
  204. std::swap (numUsed, other.numUsed);
  205. }
  206. //==============================================================================
  207. void add (const ElementType& newElement)
  208. {
  209. checkSourceIsNotAMember (&newElement);
  210. ensureAllocatedSize (numUsed + 1);
  211. addAssumingCapacityIsReady (newElement);
  212. }
  213. void add (ElementType&& newElement)
  214. {
  215. checkSourceIsNotAMember (&newElement);
  216. ensureAllocatedSize (numUsed + 1);
  217. addAssumingCapacityIsReady (std::move (newElement));
  218. }
  219. template <typename... OtherElements>
  220. void add (const ElementType& firstNewElement, OtherElements... otherElements)
  221. {
  222. checkSourceIsNotAMember (&firstNewElement);
  223. ensureAllocatedSize (numUsed + 1 + (int) sizeof... (otherElements));
  224. addAssumingCapacityIsReady (firstNewElement, otherElements...);
  225. }
  226. template <typename... OtherElements>
  227. void add (ElementType&& firstNewElement, OtherElements... otherElements)
  228. {
  229. checkSourceIsNotAMember (&firstNewElement);
  230. ensureAllocatedSize (numUsed + 1 + (int) sizeof... (otherElements));
  231. addAssumingCapacityIsReady (std::move (firstNewElement), otherElements...);
  232. }
  233. //==============================================================================
  234. template <typename Type>
  235. void addArray (const Type* elementsToAdd, int numElementsToAdd)
  236. {
  237. ensureAllocatedSize (numUsed + numElementsToAdd);
  238. addArrayInternal (elementsToAdd, numElementsToAdd);
  239. numUsed += numElementsToAdd;
  240. }
  241. template <typename TypeToCreateFrom>
  242. void addArray (const std::initializer_list<TypeToCreateFrom>& items)
  243. {
  244. ensureAllocatedSize (numUsed + (int) items.size());
  245. for (auto& item : items)
  246. new (elements + numUsed++) ElementType (item);
  247. }
  248. template <class OtherArrayType>
  249. void addArray (const OtherArrayType& arrayToAddFrom)
  250. {
  251. jassert ((const void*) this != (const void*) &arrayToAddFrom); // can't add from our own elements!
  252. ensureAllocatedSize (numUsed + (int) arrayToAddFrom.size());
  253. for (auto& e : arrayToAddFrom)
  254. addAssumingCapacityIsReady (e);
  255. }
  256. template <class OtherArrayType>
  257. typename std::enable_if<! std::is_pointer<OtherArrayType>::value, int>::type
  258. addArray (const OtherArrayType& arrayToAddFrom,
  259. int startIndex, int numElementsToAdd = -1)
  260. {
  261. jassert ((const void*) this != (const void*) &arrayToAddFrom); // can't add from our own elements!
  262. if (startIndex < 0)
  263. {
  264. jassertfalse;
  265. startIndex = 0;
  266. }
  267. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > (int) arrayToAddFrom.size())
  268. numElementsToAdd = (int) arrayToAddFrom.size() - startIndex;
  269. addArray (arrayToAddFrom.data() + startIndex, numElementsToAdd);
  270. return numElementsToAdd;
  271. }
  272. //==============================================================================
  273. void insert (int indexToInsertAt, ParameterType newElement, int numberOfTimesToInsertIt)
  274. {
  275. checkSourceIsNotAMember (&newElement);
  276. auto* space = createInsertSpace (indexToInsertAt, numberOfTimesToInsertIt);
  277. for (int i = 0; i < numberOfTimesToInsertIt; ++i)
  278. new (space++) ElementType (newElement);
  279. numUsed += numberOfTimesToInsertIt;
  280. }
  281. void insertArray (int indexToInsertAt, const ElementType* newElements, int numberOfElements)
  282. {
  283. auto* space = createInsertSpace (indexToInsertAt, numberOfElements);
  284. for (int i = 0; i < numberOfElements; ++i)
  285. new (space++) ElementType (*(newElements++));
  286. numUsed += numberOfElements;
  287. }
  288. //==============================================================================
  289. void removeElements (int indexToRemoveAt, int numElementsToRemove)
  290. {
  291. jassert (indexToRemoveAt >= 0);
  292. jassert (numElementsToRemove >= 0);
  293. jassert (indexToRemoveAt + numElementsToRemove <= numUsed);
  294. if (numElementsToRemove > 0)
  295. {
  296. removeElementsInternal (indexToRemoveAt, numElementsToRemove);
  297. numUsed -= numElementsToRemove;
  298. }
  299. }
  300. //==============================================================================
  301. void swap (int index1, int index2)
  302. {
  303. if (isPositiveAndBelow (index1, numUsed)
  304. && isPositiveAndBelow (index2, numUsed))
  305. {
  306. std::swap (elements[index1],
  307. elements[index2]);
  308. }
  309. }
  310. //==============================================================================
  311. void move (int currentIndex, int newIndex) noexcept
  312. {
  313. if (isPositiveAndBelow (currentIndex, numUsed))
  314. {
  315. if (! isPositiveAndBelow (newIndex, numUsed))
  316. newIndex = numUsed - 1;
  317. moveInternal (currentIndex, newIndex);
  318. }
  319. }
  320. private:
  321. //==============================================================================
  322. template <typename T>
  323. #if defined(__GNUC__) && __GNUC__ < 5 && ! defined(__clang__)
  324. using IsTriviallyCopyable = std::is_scalar<T>;
  325. #else
  326. using IsTriviallyCopyable = std::is_trivially_copyable<T>;
  327. #endif
  328. template <typename T>
  329. using TriviallyCopyableVoid = typename std::enable_if<IsTriviallyCopyable<T>::value, void>::type;
  330. template <typename T>
  331. using NonTriviallyCopyableVoid = typename std::enable_if<! IsTriviallyCopyable<T>::value, void>::type;
  332. //==============================================================================
  333. template <typename T = ElementType>
  334. TriviallyCopyableVoid<T> addArrayInternal (const ElementType* otherElements, int numElements)
  335. {
  336. memcpy (elements + numUsed, otherElements, (size_t) numElements * sizeof (ElementType));
  337. }
  338. template <typename Type, typename T = ElementType>
  339. TriviallyCopyableVoid<T> addArrayInternal (const Type* otherElements, int numElements)
  340. {
  341. auto* start = elements + numUsed;
  342. while (--numElements >= 0)
  343. new (start++) ElementType (*(otherElements++));
  344. }
  345. template <typename Type, typename T = ElementType>
  346. NonTriviallyCopyableVoid<T> addArrayInternal (const Type* otherElements, int numElements)
  347. {
  348. auto* start = elements + numUsed;
  349. while (--numElements >= 0)
  350. new (start++) ElementType (*(otherElements++));
  351. }
  352. //==============================================================================
  353. template <typename T = ElementType>
  354. TriviallyCopyableVoid<T> setAllocatedSizeInternal (int numElements)
  355. {
  356. elements.realloc ((size_t) numElements);
  357. }
  358. template <typename T = ElementType>
  359. NonTriviallyCopyableVoid<T> setAllocatedSizeInternal (int numElements)
  360. {
  361. HeapBlock<ElementType> newElements (numElements);
  362. for (int i = 0; i < numUsed; ++i)
  363. {
  364. new (newElements + i) ElementType (std::move (elements[i]));
  365. elements[i].~ElementType();
  366. }
  367. elements = std::move (newElements);
  368. }
  369. //==============================================================================
  370. ElementType* createInsertSpace (int indexToInsertAt, int numElements)
  371. {
  372. ensureAllocatedSize (numUsed + numElements);
  373. if (! isPositiveAndBelow (indexToInsertAt, numUsed))
  374. return elements + numUsed;
  375. createInsertSpaceInternal (indexToInsertAt, numElements);
  376. return elements + indexToInsertAt;
  377. }
  378. template <typename T = ElementType>
  379. TriviallyCopyableVoid<T> createInsertSpaceInternal (int indexToInsertAt, int numElements)
  380. {
  381. auto* start = elements + indexToInsertAt;
  382. auto numElementsToShift = numUsed - indexToInsertAt;
  383. memmove (start + numElements, start, (size_t) numElementsToShift * sizeof (ElementType));
  384. }
  385. template <typename T = ElementType>
  386. NonTriviallyCopyableVoid<T> createInsertSpaceInternal (int indexToInsertAt, int numElements)
  387. {
  388. auto* end = elements + numUsed;
  389. auto* newEnd = end + numElements;
  390. auto numElementsToShift = numUsed - indexToInsertAt;
  391. for (int i = 0; i < numElementsToShift; ++i)
  392. {
  393. new (--newEnd) ElementType (std::move (*(--end)));
  394. end->~ElementType();
  395. }
  396. }
  397. //==============================================================================
  398. template <typename T = ElementType>
  399. TriviallyCopyableVoid<T> removeElementsInternal (int indexToRemoveAt, int numElementsToRemove)
  400. {
  401. auto* start = elements + indexToRemoveAt;
  402. auto numElementsToShift = numUsed - (indexToRemoveAt + numElementsToRemove);
  403. memmove (start, start + numElementsToRemove, (size_t) numElementsToShift * sizeof (ElementType));
  404. }
  405. template <typename T = ElementType>
  406. NonTriviallyCopyableVoid<T> removeElementsInternal (int indexToRemoveAt, int numElementsToRemove)
  407. {
  408. auto numElementsToShift = numUsed - (indexToRemoveAt + numElementsToRemove);
  409. auto* destination = elements + indexToRemoveAt;
  410. auto* source = destination + numElementsToRemove;
  411. for (int i = 0; i < numElementsToShift; ++i)
  412. moveAssignElement (destination++, std::move (*(source++)));
  413. for (int i = 0; i < numElementsToRemove; ++i)
  414. (destination++)->~ElementType();
  415. }
  416. //==============================================================================
  417. template <typename T = ElementType>
  418. TriviallyCopyableVoid<T> moveInternal (int currentIndex, int newIndex) noexcept
  419. {
  420. char tempCopy[sizeof (ElementType)];
  421. memcpy (tempCopy, elements + currentIndex, sizeof (ElementType));
  422. if (newIndex > currentIndex)
  423. {
  424. memmove (elements + currentIndex,
  425. elements + currentIndex + 1,
  426. (size_t) (newIndex - currentIndex) * sizeof (ElementType));
  427. }
  428. else
  429. {
  430. memmove (elements + newIndex + 1,
  431. elements + newIndex,
  432. (size_t) (currentIndex - newIndex) * sizeof (ElementType));
  433. }
  434. memcpy (elements + newIndex, tempCopy, sizeof (ElementType));
  435. }
  436. template <typename T = ElementType>
  437. NonTriviallyCopyableVoid<T> moveInternal (int currentIndex, int newIndex) noexcept
  438. {
  439. auto* e = elements + currentIndex;
  440. ElementType tempCopy (std::move (*e));
  441. auto delta = newIndex - currentIndex;
  442. if (delta > 0)
  443. {
  444. for (int i = 0; i < delta; ++i)
  445. {
  446. moveAssignElement (e, std::move (*(e + 1)));
  447. ++e;
  448. }
  449. }
  450. else
  451. {
  452. for (int i = 0; i < -delta; ++i)
  453. {
  454. moveAssignElement (e, std::move (*(e - 1)));
  455. --e;
  456. }
  457. }
  458. moveAssignElement (e, std::move (tempCopy));
  459. }
  460. //==============================================================================
  461. void addAssumingCapacityIsReady (const ElementType& element) { new (elements + numUsed++) ElementType (element); }
  462. void addAssumingCapacityIsReady (ElementType&& element) { new (elements + numUsed++) ElementType (std::move (element)); }
  463. template <typename... OtherElements>
  464. void addAssumingCapacityIsReady (const ElementType& firstNewElement, OtherElements... otherElements)
  465. {
  466. addAssumingCapacityIsReady (firstNewElement);
  467. addAssumingCapacityIsReady (otherElements...);
  468. }
  469. template <typename... OtherElements>
  470. void addAssumingCapacityIsReady (ElementType&& firstNewElement, OtherElements... otherElements)
  471. {
  472. addAssumingCapacityIsReady (std::move (firstNewElement));
  473. addAssumingCapacityIsReady (otherElements...);
  474. }
  475. //==============================================================================
  476. template <typename T = ElementType>
  477. typename std::enable_if<std::is_move_assignable<T>::value, void>::type
  478. moveAssignElement (ElementType* destination, ElementType&& source)
  479. {
  480. *destination = std::move (source);
  481. }
  482. template <typename T = ElementType>
  483. typename std::enable_if<! std::is_move_assignable<T>::value, void>::type
  484. moveAssignElement (ElementType* destination, ElementType&& source)
  485. {
  486. destination->~ElementType();
  487. new (destination) ElementType (std::move (source));
  488. }
  489. void checkSourceIsNotAMember (const ElementType* element)
  490. {
  491. // when you pass a reference to an existing element into a method like add() which
  492. // may need to reallocate the array to make more space, the incoming reference may
  493. // be deleted indirectly during the reallocation operation! To work around this,
  494. // make a local copy of the item you're trying to add (and maybe use std::move to
  495. // move it into the add() method to avoid any extra overhead)
  496. jassert (element < begin() || element >= end());
  497. ignoreUnused (element);
  498. }
  499. //==============================================================================
  500. HeapBlock<ElementType> elements;
  501. int numAllocated = 0, numUsed = 0;
  502. template <class OtherElementType, class OtherCriticalSection>
  503. friend class ArrayBase;
  504. JUCE_DECLARE_NON_COPYABLE (ArrayBase)
  505. };
  506. } // namespace juce