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.

597 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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) const noexcept
  113. {
  114. jassert (elements != nullptr);
  115. jassert (isPositiveAndBelow (index, numUsed));
  116. return elements[index];
  117. }
  118. inline ElementType getValueWithDefault (const int index) const noexcept
  119. {
  120. return isPositiveAndBelow (index, numUsed) ? elements[index] : ElementType();
  121. }
  122. inline ElementType getFirst() const noexcept
  123. {
  124. return numUsed > 0 ? elements[0] : ElementType();
  125. }
  126. inline ElementType getLast() const noexcept
  127. {
  128. return numUsed > 0 ? elements[numUsed - 1] : ElementType();
  129. }
  130. //==============================================================================
  131. inline ElementType* begin() const noexcept
  132. {
  133. return elements;
  134. }
  135. inline ElementType* end() const noexcept
  136. {
  137. return elements + numUsed;
  138. }
  139. inline ElementType* data() const noexcept
  140. {
  141. return elements;
  142. }
  143. inline int size() const noexcept
  144. {
  145. return numUsed;
  146. }
  147. inline int capacity() const noexcept
  148. {
  149. return numAllocated;
  150. }
  151. //==============================================================================
  152. void setAllocatedSize (int numElements)
  153. {
  154. jassert (numElements >= numUsed);
  155. if (numAllocated != numElements)
  156. {
  157. if (numElements > 0)
  158. setAllocatedSizeInternal (numElements);
  159. else
  160. elements.free();
  161. }
  162. numAllocated = numElements;
  163. }
  164. void ensureAllocatedSize (int minNumElements)
  165. {
  166. if (minNumElements > numAllocated)
  167. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  168. jassert (numAllocated <= 0 || elements != nullptr);
  169. }
  170. void shrinkToNoMoreThan (int maxNumElements)
  171. {
  172. if (maxNumElements < numAllocated)
  173. setAllocatedSize (maxNumElements);
  174. }
  175. void clear()
  176. {
  177. for (int i = 0; i < numUsed; ++i)
  178. elements[i].~ElementType();
  179. numUsed = 0;
  180. }
  181. //==============================================================================
  182. void swapWith (ArrayBase& other) noexcept
  183. {
  184. elements.swapWith (other.elements);
  185. std::swap (numAllocated, other.numAllocated);
  186. std::swap (numUsed, other.numUsed);
  187. }
  188. //==============================================================================
  189. void add (const ElementType& newElement)
  190. {
  191. checkSourceIsNotAMember (&newElement);
  192. ensureAllocatedSize (numUsed + 1);
  193. addAssumingCapacityIsReady (newElement);
  194. }
  195. void add (ElementType&& newElement)
  196. {
  197. checkSourceIsNotAMember (&newElement);
  198. ensureAllocatedSize (numUsed + 1);
  199. addAssumingCapacityIsReady (std::move (newElement));
  200. }
  201. template <typename... OtherElements>
  202. void add (const ElementType& firstNewElement, OtherElements... otherElements)
  203. {
  204. checkSourceIsNotAMember (&firstNewElement);
  205. ensureAllocatedSize (numUsed + 1 + (int) sizeof... (otherElements));
  206. addAssumingCapacityIsReady (firstNewElement, otherElements...);
  207. }
  208. template <typename... OtherElements>
  209. void add (ElementType&& firstNewElement, OtherElements... otherElements)
  210. {
  211. checkSourceIsNotAMember (&firstNewElement);
  212. ensureAllocatedSize (numUsed + 1 + (int) sizeof... (otherElements));
  213. addAssumingCapacityIsReady (std::move (firstNewElement), otherElements...);
  214. }
  215. //==============================================================================
  216. template <typename Type>
  217. void addArray (const Type* elementsToAdd, int numElementsToAdd)
  218. {
  219. ensureAllocatedSize (numUsed + numElementsToAdd);
  220. addArrayInternal (elementsToAdd, numElementsToAdd);
  221. numUsed += numElementsToAdd;
  222. }
  223. template <typename TypeToCreateFrom>
  224. void addArray (const std::initializer_list<TypeToCreateFrom>& items)
  225. {
  226. ensureAllocatedSize (numUsed + (int) items.size());
  227. for (auto& item : items)
  228. new (elements + numUsed++) ElementType (item);
  229. }
  230. template <class OtherArrayType>
  231. void addArray (const OtherArrayType& arrayToAddFrom)
  232. {
  233. jassert ((const void*) this != (const void*) &arrayToAddFrom); // can't add from our own elements!
  234. ensureAllocatedSize (numUsed + (int) arrayToAddFrom.size());
  235. for (auto& e : arrayToAddFrom)
  236. addAssumingCapacityIsReady (e);
  237. }
  238. template <class OtherArrayType>
  239. typename std::enable_if<! std::is_pointer<OtherArrayType>::value, int>::type
  240. addArray (const OtherArrayType& arrayToAddFrom,
  241. int startIndex, int numElementsToAdd = -1)
  242. {
  243. jassert ((const void*) this != (const void*) &arrayToAddFrom); // can't add from our own elements!
  244. if (startIndex < 0)
  245. {
  246. jassertfalse;
  247. startIndex = 0;
  248. }
  249. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > (int) arrayToAddFrom.size())
  250. numElementsToAdd = (int) arrayToAddFrom.size() - startIndex;
  251. addArray (arrayToAddFrom.data() + startIndex, numElementsToAdd);
  252. return numElementsToAdd;
  253. }
  254. //==============================================================================
  255. void insert (int indexToInsertAt, ParameterType newElement, int numberOfTimesToInsertIt)
  256. {
  257. checkSourceIsNotAMember (&newElement);
  258. auto* space = createInsertSpace (indexToInsertAt, numberOfTimesToInsertIt);
  259. for (int i = 0; i < numberOfTimesToInsertIt; ++i)
  260. new (space++) ElementType (newElement);
  261. numUsed += numberOfTimesToInsertIt;
  262. }
  263. void insertArray (int indexToInsertAt, const ElementType* newElements, int numberOfElements)
  264. {
  265. auto* space = createInsertSpace (indexToInsertAt, numberOfElements);
  266. for (int i = 0; i < numberOfElements; ++i)
  267. new (space++) ElementType (*(newElements++));
  268. numUsed += numberOfElements;
  269. }
  270. //==============================================================================
  271. void removeElements (int indexToRemoveAt, int numElementsToRemove)
  272. {
  273. jassert (indexToRemoveAt >= 0);
  274. jassert (numElementsToRemove >= 0);
  275. jassert (indexToRemoveAt + numElementsToRemove <= numUsed);
  276. if (numElementsToRemove > 0)
  277. {
  278. removeElementsInternal (indexToRemoveAt, numElementsToRemove);
  279. numUsed -= numElementsToRemove;
  280. }
  281. }
  282. //==============================================================================
  283. void swap (int index1, int index2)
  284. {
  285. if (isPositiveAndBelow (index1, numUsed)
  286. && isPositiveAndBelow (index2, numUsed))
  287. {
  288. std::swap (elements[index1],
  289. elements[index2]);
  290. }
  291. }
  292. //==============================================================================
  293. void move (int currentIndex, int newIndex) noexcept
  294. {
  295. if (isPositiveAndBelow (currentIndex, numUsed))
  296. {
  297. if (! isPositiveAndBelow (newIndex, numUsed))
  298. newIndex = numUsed - 1;
  299. moveInternal (currentIndex, newIndex);
  300. }
  301. }
  302. private:
  303. //==============================================================================
  304. template <typename T>
  305. #if defined(__GNUC__) && __GNUC__ < 5 && ! defined(__clang__)
  306. using IsTriviallyCopyable = std::is_scalar<T>;
  307. #else
  308. using IsTriviallyCopyable = std::is_trivially_copyable<T>;
  309. #endif
  310. template <typename T>
  311. using TriviallyCopyableVoid = typename std::enable_if<IsTriviallyCopyable<T>::value, void>::type;
  312. template <typename T>
  313. using NonTriviallyCopyableVoid = typename std::enable_if<! IsTriviallyCopyable<T>::value, void>::type;
  314. //==============================================================================
  315. template <typename T = ElementType>
  316. TriviallyCopyableVoid<T> addArrayInternal (const ElementType* otherElements, int numElements)
  317. {
  318. memcpy (elements + numUsed, otherElements, (size_t) numElements * sizeof (ElementType));
  319. }
  320. template <typename Type, typename T = ElementType>
  321. TriviallyCopyableVoid<T> addArrayInternal (const Type* otherElements, int numElements)
  322. {
  323. auto* start = elements + numUsed;
  324. while (--numElements >= 0)
  325. new (start++) ElementType (*(otherElements++));
  326. }
  327. template <typename Type, typename T = ElementType>
  328. NonTriviallyCopyableVoid<T> addArrayInternal (const Type* otherElements, int numElements)
  329. {
  330. auto* start = elements + numUsed;
  331. while (--numElements >= 0)
  332. new (start++) ElementType (*(otherElements++));
  333. }
  334. //==============================================================================
  335. template <typename T = ElementType>
  336. TriviallyCopyableVoid<T> setAllocatedSizeInternal (int numElements)
  337. {
  338. elements.realloc ((size_t) numElements);
  339. }
  340. template <typename T = ElementType>
  341. NonTriviallyCopyableVoid<T> setAllocatedSizeInternal (int numElements)
  342. {
  343. HeapBlock<ElementType> newElements (numElements);
  344. for (int i = 0; i < numUsed; ++i)
  345. {
  346. new (newElements + i) ElementType (std::move (elements[i]));
  347. elements[i].~ElementType();
  348. }
  349. elements = std::move (newElements);
  350. }
  351. //==============================================================================
  352. ElementType* createInsertSpace (int indexToInsertAt, int numElements)
  353. {
  354. ensureAllocatedSize (numUsed + numElements);
  355. if (! isPositiveAndBelow (indexToInsertAt, numUsed))
  356. return elements + numUsed;
  357. createInsertSpaceInternal (indexToInsertAt, numElements);
  358. return elements + indexToInsertAt;
  359. }
  360. template <typename T = ElementType>
  361. TriviallyCopyableVoid<T> createInsertSpaceInternal (int indexToInsertAt, int numElements)
  362. {
  363. auto* start = elements + indexToInsertAt;
  364. auto numElementsToShift = numUsed - indexToInsertAt;
  365. memmove (start + numElements, start, (size_t) numElementsToShift * sizeof (ElementType));
  366. }
  367. template <typename T = ElementType>
  368. NonTriviallyCopyableVoid<T> createInsertSpaceInternal (int indexToInsertAt, int numElements)
  369. {
  370. auto* end = elements + numUsed;
  371. auto* newEnd = end + numElements;
  372. auto numElementsToShift = numUsed - indexToInsertAt;
  373. for (int i = 0; i < numElementsToShift; ++i)
  374. {
  375. new (--newEnd) ElementType (std::move (*(--end)));
  376. end->~ElementType();
  377. }
  378. }
  379. //==============================================================================
  380. template <typename T = ElementType>
  381. TriviallyCopyableVoid<T> removeElementsInternal (int indexToRemoveAt, int numElementsToRemove)
  382. {
  383. auto* start = elements + indexToRemoveAt;
  384. auto numElementsToShift = numUsed - (indexToRemoveAt + numElementsToRemove);
  385. memmove (start, start + numElementsToRemove, (size_t) numElementsToShift * sizeof (ElementType));
  386. }
  387. template <typename T = ElementType>
  388. NonTriviallyCopyableVoid<T> removeElementsInternal (int indexToRemoveAt, int numElementsToRemove)
  389. {
  390. auto numElementsToShift = numUsed - (indexToRemoveAt + numElementsToRemove);
  391. auto* destination = elements + indexToRemoveAt;
  392. auto* source = destination + numElementsToRemove;
  393. for (int i = 0; i < numElementsToShift; ++i)
  394. moveAssignElement (destination++, std::move (*(source++)));
  395. for (int i = 0; i < numElementsToRemove; ++i)
  396. (destination++)->~ElementType();
  397. }
  398. //==============================================================================
  399. template <typename T = ElementType>
  400. TriviallyCopyableVoid<T> moveInternal (int currentIndex, int newIndex) noexcept
  401. {
  402. char tempCopy[sizeof (ElementType)];
  403. memcpy (tempCopy, elements + currentIndex, sizeof (ElementType));
  404. if (newIndex > currentIndex)
  405. {
  406. memmove (elements + currentIndex,
  407. elements + currentIndex + 1,
  408. sizeof (ElementType) * (size_t) (newIndex - currentIndex));
  409. }
  410. else
  411. {
  412. memmove (elements + newIndex + 1,
  413. elements + newIndex,
  414. sizeof (ElementType) * (size_t) (currentIndex - newIndex));
  415. }
  416. memcpy (elements + newIndex, tempCopy, sizeof (ElementType));
  417. }
  418. template <typename T = ElementType>
  419. NonTriviallyCopyableVoid<T> moveInternal (int currentIndex, int newIndex) noexcept
  420. {
  421. auto* e = elements + currentIndex;
  422. ElementType tempCopy (std::move (*e));
  423. auto delta = newIndex - currentIndex;
  424. if (delta > 0)
  425. {
  426. for (int i = 0; i < delta; ++i)
  427. {
  428. moveAssignElement (e, std::move (*(e + 1)));
  429. ++e;
  430. }
  431. }
  432. else
  433. {
  434. for (int i = 0; i < -delta; ++i)
  435. {
  436. moveAssignElement (e, std::move (*(e - 1)));
  437. --e;
  438. }
  439. }
  440. moveAssignElement (e, std::move (tempCopy));
  441. }
  442. //==============================================================================
  443. void addAssumingCapacityIsReady (const ElementType& element) { new (elements + numUsed++) ElementType (element); }
  444. void addAssumingCapacityIsReady (ElementType&& element) { new (elements + numUsed++) ElementType (std::move (element)); }
  445. template <typename... OtherElements>
  446. void addAssumingCapacityIsReady (const ElementType& firstNewElement, OtherElements... otherElements)
  447. {
  448. addAssumingCapacityIsReady (firstNewElement);
  449. addAssumingCapacityIsReady (otherElements...);
  450. }
  451. template <typename... OtherElements>
  452. void addAssumingCapacityIsReady (ElementType&& firstNewElement, OtherElements... otherElements)
  453. {
  454. addAssumingCapacityIsReady (std::move (firstNewElement));
  455. addAssumingCapacityIsReady (otherElements...);
  456. }
  457. //==============================================================================
  458. template <typename T = ElementType>
  459. typename std::enable_if<std::is_move_assignable<T>::value, void>::type
  460. moveAssignElement (ElementType* destination, ElementType&& source)
  461. {
  462. *destination = std::move (source);
  463. }
  464. template <typename T = ElementType>
  465. typename std::enable_if<! std::is_move_assignable<T>::value, void>::type
  466. moveAssignElement (ElementType* destination, ElementType&& source)
  467. {
  468. destination->~ElementType();
  469. new (destination) ElementType (std::move (source));
  470. }
  471. void checkSourceIsNotAMember (const ElementType* element)
  472. {
  473. // when you pass a reference to an existing element into a method like add() which
  474. // may need to reallocate the array to make more space, the incoming reference may
  475. // be deleted indirectly during the reallocation operation! To work around this,
  476. // make a local copy of the item you're trying to add (and maybe use std::move to
  477. // move it into the add() method to avoid any extra overhead)
  478. jassert (element < begin() || element >= end());
  479. ignoreUnused (element);
  480. }
  481. //==============================================================================
  482. HeapBlock<ElementType> elements;
  483. int numAllocated = 0, numUsed = 0;
  484. template <class OtherElementType, class OtherCriticalSection>
  485. friend class ArrayBase;
  486. JUCE_DECLARE_NON_COPYABLE (ArrayBase)
  487. };
  488. } // namespace juce