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.

1321 lines
48KB

  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. /**
  21. Holds a resizable array of primitive or copy-by-value objects.
  22. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  23. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  24. do so, the class must fulfil these requirements:
  25. - it must have a copy constructor and assignment operator
  26. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  27. objects whose functionality relies on external pointers or references to themselves can not be used.
  28. You can of course have an array of pointers to any kind of object, e.g. Array<MyClass*>, but if
  29. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  30. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  31. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  32. specialised class StringArray, which provides more useful functions.
  33. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  34. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  35. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  36. @tags{Core}
  37. */
  38. template <typename ElementType,
  39. typename TypeOfCriticalSectionToUse = DummyCriticalSection,
  40. int minimumAllocatedSize = 0>
  41. class Array
  42. {
  43. private:
  44. using ParameterType = typename TypeHelpers::ParameterType<ElementType>::type;
  45. public:
  46. //==============================================================================
  47. /** Creates an empty array. */
  48. Array() noexcept
  49. {
  50. }
  51. /** Creates a copy of another array.
  52. @param other the array to copy
  53. */
  54. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  55. {
  56. const ScopedLockType lock (other.getLock());
  57. numUsed = other.numUsed;
  58. data.setAllocatedSize (other.numUsed);
  59. for (int i = 0; i < numUsed; ++i)
  60. new (data.elements + i) ElementType (other.data.elements[i]);
  61. }
  62. Array (Array<ElementType, TypeOfCriticalSectionToUse>&& other) noexcept
  63. : data (static_cast<ArrayAllocationBase<ElementType, TypeOfCriticalSectionToUse>&&> (other.data)),
  64. numUsed (other.numUsed)
  65. {
  66. other.numUsed = 0;
  67. }
  68. /** Initalises from a null-terminated raw array of values.
  69. @param values the array to copy from
  70. */
  71. template <typename TypeToCreateFrom>
  72. explicit Array (const TypeToCreateFrom* values)
  73. {
  74. while (*values != TypeToCreateFrom())
  75. add (*values++);
  76. }
  77. /** Initalises from a raw array of values.
  78. @param values the array to copy from
  79. @param numValues the number of values in the array
  80. */
  81. template <typename TypeToCreateFrom>
  82. Array (const TypeToCreateFrom* values, int numValues) : numUsed (numValues)
  83. {
  84. data.setAllocatedSize (numValues);
  85. for (int i = 0; i < numValues; ++i)
  86. new (data.elements + i) ElementType (values[i]);
  87. }
  88. /** Initalises an Array of size 1 containing a single element. */
  89. Array (const ElementType& singleElementToAdd)
  90. {
  91. add (singleElementToAdd);
  92. }
  93. /** Initalises an Array of size 1 containing a single element. */
  94. Array (ElementType&& singleElementToAdd)
  95. {
  96. add (static_cast<ElementType&&> (singleElementToAdd));
  97. }
  98. /** Initalises an Array from a list of items. */
  99. template <typename... OtherElements>
  100. Array (const ElementType& firstNewElement, OtherElements... otherElements)
  101. {
  102. data.setAllocatedSize (1 + (int) sizeof... (otherElements));
  103. addAssumingCapacityIsReady (firstNewElement, otherElements...);
  104. }
  105. /** Initalises an Array from a list of items. */
  106. template <typename... OtherElements>
  107. Array (ElementType&& firstNewElement, OtherElements... otherElements)
  108. {
  109. data.setAllocatedSize (1 + (int) sizeof... (otherElements));
  110. addAssumingCapacityIsReady (static_cast<ElementType&&> (firstNewElement), otherElements...);
  111. }
  112. template <typename TypeToCreateFrom>
  113. Array (const std::initializer_list<TypeToCreateFrom>& items)
  114. {
  115. addArray (items);
  116. }
  117. /** Destructor. */
  118. ~Array()
  119. {
  120. deleteAllElements();
  121. }
  122. /** Copies another array.
  123. @param other the array to copy
  124. */
  125. Array& operator= (const Array& other)
  126. {
  127. if (this != &other)
  128. {
  129. auto otherCopy (other);
  130. swapWith (otherCopy);
  131. }
  132. return *this;
  133. }
  134. Array& operator= (Array&& other) noexcept
  135. {
  136. const ScopedLockType lock (getLock());
  137. deleteAllElements();
  138. data = static_cast<ArrayAllocationBase<ElementType, TypeOfCriticalSectionToUse>&&> (other.data);
  139. numUsed = other.numUsed;
  140. other.numUsed = 0;
  141. return *this;
  142. }
  143. //==============================================================================
  144. /** Compares this array to another one.
  145. Two arrays are considered equal if they both contain the same set of
  146. elements, in the same order.
  147. @param other the other array to compare with
  148. */
  149. template <class OtherArrayType>
  150. bool operator== (const OtherArrayType& other) const
  151. {
  152. const ScopedLockType lock (getLock());
  153. const typename OtherArrayType::ScopedLockType lock2 (other.getLock());
  154. if (size() != other.size())
  155. return false;
  156. auto e = begin();
  157. for (auto& o : other)
  158. if (! (*e++ == o))
  159. return false;
  160. return true;
  161. }
  162. /** Compares this array to another one.
  163. Two arrays are considered equal if they both contain the same set of
  164. elements, in the same order.
  165. @param other the other array to compare with
  166. */
  167. template <class OtherArrayType>
  168. bool operator!= (const OtherArrayType& other) const
  169. {
  170. return ! operator== (other);
  171. }
  172. //==============================================================================
  173. /** Removes all elements from the array.
  174. This will remove all the elements, and free any storage that the array is
  175. using. To clear the array without freeing the storage, use the clearQuick()
  176. method instead.
  177. @see clearQuick
  178. */
  179. void clear()
  180. {
  181. const ScopedLockType lock (getLock());
  182. deleteAllElements();
  183. data.setAllocatedSize (0);
  184. numUsed = 0;
  185. }
  186. /** Removes all elements from the array without freeing the array's allocated storage.
  187. @see clear
  188. */
  189. void clearQuick()
  190. {
  191. const ScopedLockType lock (getLock());
  192. deleteAllElements();
  193. numUsed = 0;
  194. }
  195. /** Fills the Array with the provided value. */
  196. void fill (const ParameterType& newValue) noexcept
  197. {
  198. const ScopedLockType lock (getLock());
  199. for (auto& e : *this)
  200. e = newValue;
  201. }
  202. //==============================================================================
  203. /** Returns the current number of elements in the array. */
  204. inline int size() const noexcept
  205. {
  206. return numUsed;
  207. }
  208. /** Returns true if the array is empty, false otherwise. */
  209. inline bool isEmpty() const noexcept
  210. {
  211. return numUsed == 0;
  212. }
  213. /** Returns one of the elements in the array.
  214. If the index passed in is beyond the range of valid elements, this
  215. will return a default value.
  216. If you're certain that the index will always be a valid element, you
  217. can call getUnchecked() instead, which is faster.
  218. @param index the index of the element being requested (0 is the first element in the array)
  219. @see getUnchecked, getFirst, getLast
  220. */
  221. ElementType operator[] (int index) const
  222. {
  223. const ScopedLockType lock (getLock());
  224. if (isPositiveAndBelow (index, numUsed))
  225. {
  226. jassert (data.elements != nullptr);
  227. return data.elements[index];
  228. }
  229. // We can't default aggregate initialise here "{}" due to a VS2017 compiler bug
  230. return ElementType();
  231. }
  232. /** Returns one of the elements in the array, without checking the index passed in.
  233. Unlike the operator[] method, this will try to return an element without
  234. checking that the index is within the bounds of the array, so should only
  235. be used when you're confident that it will always be a valid index.
  236. @param index the index of the element being requested (0 is the first element in the array)
  237. @see operator[], getFirst, getLast
  238. */
  239. inline ElementType getUnchecked (int index) const
  240. {
  241. const ScopedLockType lock (getLock());
  242. jassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  243. return data.elements[index];
  244. }
  245. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  246. This is like getUnchecked, but returns a direct reference to the element, so that
  247. you can alter it directly. Obviously this can be dangerous, so only use it when
  248. absolutely necessary.
  249. @param index the index of the element being requested (0 is the first element in the array)
  250. @see operator[], getFirst, getLast
  251. */
  252. inline ElementType& getReference (int index) const noexcept
  253. {
  254. const ScopedLockType lock (getLock());
  255. jassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  256. return data.elements[index];
  257. }
  258. /** Returns the first element in the array, or a default value if the array is empty.
  259. @see operator[], getUnchecked, getLast
  260. */
  261. inline ElementType getFirst() const
  262. {
  263. const ScopedLockType lock (getLock());
  264. if (numUsed > 0)
  265. {
  266. jassert (data.elements != nullptr);
  267. return data.elements[0];
  268. }
  269. return ElementType();
  270. }
  271. /** Returns the last element in the array, or a default value if the array is empty.
  272. @see operator[], getUnchecked, getFirst
  273. */
  274. inline ElementType getLast() const
  275. {
  276. const ScopedLockType lock (getLock());
  277. if (numUsed > 0)
  278. {
  279. jassert (data.elements != nullptr);
  280. return data.elements[numUsed - 1];
  281. }
  282. return ElementType();
  283. }
  284. /** Returns a pointer to the actual array data.
  285. This pointer will only be valid until the next time a non-const method
  286. is called on the array.
  287. */
  288. inline ElementType* getRawDataPointer() noexcept
  289. {
  290. return data.elements;
  291. }
  292. //==============================================================================
  293. /** Returns a pointer to the first element in the array.
  294. This method is provided for compatibility with standard C++ iteration mechanisms.
  295. */
  296. inline ElementType* begin() const noexcept
  297. {
  298. return data.elements;
  299. }
  300. /** Returns a pointer to the element which follows the last element in the array.
  301. This method is provided for compatibility with standard C++ iteration mechanisms.
  302. */
  303. inline ElementType* end() const noexcept
  304. {
  305. #if JUCE_DEBUG
  306. if (data.elements == nullptr || numUsed <= 0) // (to keep static analysers happy)
  307. return data.elements;
  308. #endif
  309. return data.elements + numUsed;
  310. }
  311. //==============================================================================
  312. /** Finds the index of the first element which matches the value passed in.
  313. This will search the array for the given object, and return the index
  314. of its first occurrence. If the object isn't found, the method will return -1.
  315. @param elementToLookFor the value or object to look for
  316. @returns the index of the object, or -1 if it's not found
  317. */
  318. int indexOf (ParameterType elementToLookFor) const
  319. {
  320. const ScopedLockType lock (getLock());
  321. auto e = data.elements.get();
  322. auto endPtr = e + numUsed;
  323. for (; e != endPtr; ++e)
  324. if (elementToLookFor == *e)
  325. return static_cast<int> (e - data.elements.get());
  326. return -1;
  327. }
  328. /** Returns true if the array contains at least one occurrence of an object.
  329. @param elementToLookFor the value or object to look for
  330. @returns true if the item is found
  331. */
  332. bool contains (ParameterType elementToLookFor) const
  333. {
  334. const ScopedLockType lock (getLock());
  335. auto e = data.elements.get();
  336. auto endPtr = e + numUsed;
  337. for (; e != endPtr; ++e)
  338. if (elementToLookFor == *e)
  339. return true;
  340. return false;
  341. }
  342. //==============================================================================
  343. /** Appends a new element at the end of the array.
  344. @param newElement the new object to add to the array
  345. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  346. */
  347. void add (const ElementType& newElement)
  348. {
  349. const ScopedLockType lock (getLock());
  350. data.ensureAllocatedSize (numUsed + 1);
  351. new (data.elements + numUsed++) ElementType (newElement);
  352. }
  353. /** Appends a new element at the end of the array.
  354. @param newElement the new object to add to the array
  355. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  356. */
  357. void add (ElementType&& newElement)
  358. {
  359. const ScopedLockType lock (getLock());
  360. data.ensureAllocatedSize (numUsed + 1);
  361. new (data.elements + numUsed++) ElementType (static_cast<ElementType&&> (newElement));
  362. }
  363. /** Appends multiple new elements at the end of the array. */
  364. template <typename... OtherElements>
  365. void add (const ElementType& firstNewElement, OtherElements... otherElements)
  366. {
  367. const ScopedLockType lock (getLock());
  368. data.ensureAllocatedSize (numUsed + 1 + (int) sizeof... (otherElements));
  369. addAssumingCapacityIsReady (firstNewElement, otherElements...);
  370. }
  371. /** Appends multiple new elements at the end of the array. */
  372. template <typename... OtherElements>
  373. void add (ElementType&& firstNewElement, OtherElements... otherElements)
  374. {
  375. const ScopedLockType lock (getLock());
  376. data.ensureAllocatedSize (numUsed + 1 + (int) sizeof... (otherElements));
  377. addAssumingCapacityIsReady (static_cast<ElementType&&> (firstNewElement), otherElements...);
  378. }
  379. /** Inserts a new element into the array at a given position.
  380. If the index is less than 0 or greater than the size of the array, the
  381. element will be added to the end of the array.
  382. Otherwise, it will be inserted into the array, moving all the later elements
  383. along to make room.
  384. @param indexToInsertAt the index at which the new element should be
  385. inserted (pass in -1 to add it to the end)
  386. @param newElement the new object to add to the array
  387. @see add, addSorted, addUsingDefaultSort, set
  388. */
  389. void insert (int indexToInsertAt, ParameterType newElement)
  390. {
  391. const ScopedLockType lock (getLock());
  392. data.ensureAllocatedSize (numUsed + 1);
  393. jassert (data.elements != nullptr);
  394. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  395. {
  396. auto* insertPos = data.elements + indexToInsertAt;
  397. auto numberToMove = numUsed - indexToInsertAt;
  398. if (numberToMove > 0)
  399. memmove (insertPos + 1, insertPos, ((size_t) numberToMove) * sizeof (ElementType));
  400. new (insertPos) ElementType (newElement);
  401. ++numUsed;
  402. }
  403. else
  404. {
  405. new (data.elements + numUsed++) ElementType (newElement);
  406. }
  407. }
  408. /** Inserts multiple copies of an element into the array at a given position.
  409. If the index is less than 0 or greater than the size of the array, the
  410. element will be added to the end of the array.
  411. Otherwise, it will be inserted into the array, moving all the later elements
  412. along to make room.
  413. @param indexToInsertAt the index at which the new element should be inserted
  414. @param newElement the new object to add to the array
  415. @param numberOfTimesToInsertIt how many copies of the value to insert
  416. @see insert, add, addSorted, set
  417. */
  418. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  419. int numberOfTimesToInsertIt)
  420. {
  421. if (numberOfTimesToInsertIt > 0)
  422. {
  423. const ScopedLockType lock (getLock());
  424. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  425. ElementType* insertPos;
  426. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  427. {
  428. insertPos = data.elements + indexToInsertAt;
  429. auto numberToMove = numUsed - indexToInsertAt;
  430. memmove (insertPos + numberOfTimesToInsertIt, insertPos, ((size_t) numberToMove) * sizeof (ElementType));
  431. }
  432. else
  433. {
  434. insertPos = data.elements + numUsed;
  435. }
  436. numUsed += numberOfTimesToInsertIt;
  437. while (--numberOfTimesToInsertIt >= 0)
  438. {
  439. new (insertPos) ElementType (newElement);
  440. ++insertPos; // NB: this increment is done separately from the
  441. // new statement to avoid a compiler bug in VS2014
  442. }
  443. }
  444. }
  445. /** Inserts an array of values into this array at a given position.
  446. If the index is less than 0 or greater than the size of the array, the
  447. new elements will be added to the end of the array.
  448. Otherwise, they will be inserted into the array, moving all the later elements
  449. along to make room.
  450. @param indexToInsertAt the index at which the first new element should be inserted
  451. @param newElements the new values to add to the array
  452. @param numberOfElements how many items are in the array
  453. @see insert, add, addSorted, set
  454. */
  455. void insertArray (int indexToInsertAt,
  456. const ElementType* newElements,
  457. int numberOfElements)
  458. {
  459. if (numberOfElements > 0)
  460. {
  461. const ScopedLockType lock (getLock());
  462. data.ensureAllocatedSize (numUsed + numberOfElements);
  463. ElementType* insertPos = data.elements;
  464. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  465. {
  466. insertPos += indexToInsertAt;
  467. auto numberToMove = numUsed - indexToInsertAt;
  468. memmove (insertPos + numberOfElements, insertPos, (size_t) numberToMove * sizeof (ElementType));
  469. }
  470. else
  471. {
  472. insertPos += numUsed;
  473. }
  474. numUsed += numberOfElements;
  475. while (--numberOfElements >= 0)
  476. new (insertPos++) ElementType (*newElements++);
  477. }
  478. }
  479. /** Appends a new element at the end of the array as long as the array doesn't
  480. already contain it.
  481. If the array already contains an element that matches the one passed in, nothing
  482. will be done.
  483. @param newElement the new object to add to the array
  484. @return true if the element was added to the array; false otherwise.
  485. */
  486. bool addIfNotAlreadyThere (ParameterType newElement)
  487. {
  488. const ScopedLockType lock (getLock());
  489. if (contains (newElement))
  490. return false;
  491. add (newElement);
  492. return true;
  493. }
  494. /** Replaces an element with a new value.
  495. If the index is less than zero, this method does nothing.
  496. If the index is beyond the end of the array, the item is added to the end of the array.
  497. @param indexToChange the index whose value you want to change
  498. @param newValue the new value to set for this index.
  499. @see add, insert
  500. */
  501. void set (int indexToChange, ParameterType newValue)
  502. {
  503. jassert (indexToChange >= 0);
  504. const ScopedLockType lock (getLock());
  505. if (isPositiveAndBelow (indexToChange, numUsed))
  506. {
  507. jassert (data.elements != nullptr);
  508. data.elements[indexToChange] = newValue;
  509. }
  510. else if (indexToChange >= 0)
  511. {
  512. data.ensureAllocatedSize (numUsed + 1);
  513. new (data.elements + numUsed++) ElementType (newValue);
  514. }
  515. }
  516. /** Replaces an element with a new value without doing any bounds-checking.
  517. This just sets a value directly in the array's internal storage, so you'd
  518. better make sure it's in range!
  519. @param indexToChange the index whose value you want to change
  520. @param newValue the new value to set for this index.
  521. @see set, getUnchecked
  522. */
  523. void setUnchecked (int indexToChange, ParameterType newValue)
  524. {
  525. const ScopedLockType lock (getLock());
  526. jassert (isPositiveAndBelow (indexToChange, numUsed));
  527. data.elements[indexToChange] = newValue;
  528. }
  529. /** Adds elements from an array to the end of this array.
  530. @param elementsToAdd an array of some kind of object from which elements
  531. can be constructed.
  532. @param numElementsToAdd how many elements are in this other array
  533. @see add
  534. */
  535. template <typename Type>
  536. void addArray (const Type* elementsToAdd, int numElementsToAdd)
  537. {
  538. const ScopedLockType lock (getLock());
  539. if (numElementsToAdd > 0)
  540. {
  541. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  542. while (--numElementsToAdd >= 0)
  543. {
  544. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  545. ++numUsed;
  546. }
  547. }
  548. }
  549. template <typename TypeToCreateFrom>
  550. void addArray (const std::initializer_list<TypeToCreateFrom>& items)
  551. {
  552. const ScopedLockType lock (getLock());
  553. data.ensureAllocatedSize (numUsed + (int) items.size());
  554. for (auto& item : items)
  555. {
  556. new (data.elements + numUsed) ElementType (item);
  557. ++numUsed;
  558. }
  559. }
  560. /** Adds elements from a null-terminated array of pointers to the end of this array.
  561. @param elementsToAdd an array of pointers to some kind of object from which elements
  562. can be constructed. This array must be terminated by a nullptr
  563. @see addArray
  564. */
  565. template <typename Type>
  566. void addNullTerminatedArray (const Type* const* elementsToAdd)
  567. {
  568. int num = 0;
  569. for (auto e = elementsToAdd; *e != nullptr; ++e)
  570. ++num;
  571. addArray (elementsToAdd, num);
  572. }
  573. /** This swaps the contents of this array with those of another array.
  574. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  575. because it just swaps their internal pointers.
  576. */
  577. template <class OtherArrayType>
  578. void swapWith (OtherArrayType& otherArray) noexcept
  579. {
  580. const ScopedLockType lock1 (getLock());
  581. const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
  582. data.swapWith (otherArray.data);
  583. std::swap (numUsed, otherArray.numUsed);
  584. }
  585. /** Adds elements from another array to the end of this array.
  586. @param arrayToAddFrom the array from which to copy the elements
  587. @see add
  588. */
  589. template <class OtherArrayType>
  590. void addArray (const OtherArrayType& arrayToAddFrom)
  591. {
  592. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  593. const ScopedLockType lock2 (getLock());
  594. data.ensureAllocatedSize (numUsed + arrayToAddFrom.size());
  595. for (auto& e : arrayToAddFrom)
  596. addAssumingCapacityIsReady (e);
  597. }
  598. /** Adds elements from another array to the end of this array.
  599. @param arrayToAddFrom the array from which to copy the elements
  600. @param startIndex the first element of the other array to start copying from
  601. @param numElementsToAdd how many elements to add from the other array. If this
  602. value is negative or greater than the number of available elements,
  603. all available elements will be copied.
  604. @see add
  605. */
  606. template <class OtherArrayType>
  607. void addArray (const OtherArrayType& arrayToAddFrom,
  608. int startIndex,
  609. int numElementsToAdd = -1)
  610. {
  611. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  612. {
  613. const ScopedLockType lock2 (getLock());
  614. if (startIndex < 0)
  615. {
  616. jassertfalse;
  617. startIndex = 0;
  618. }
  619. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  620. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  621. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  622. while (--numElementsToAdd >= 0)
  623. addAssumingCapacityIsReady (arrayToAddFrom.getUnchecked (startIndex++));
  624. }
  625. }
  626. /** This will enlarge or shrink the array to the given number of elements, by adding
  627. or removing items from its end.
  628. If the array is smaller than the given target size, empty elements will be appended
  629. until its size is as specified. If its size is larger than the target, items will be
  630. removed from its end to shorten it.
  631. */
  632. void resize (int targetNumItems)
  633. {
  634. jassert (targetNumItems >= 0);
  635. auto numToAdd = targetNumItems - numUsed;
  636. if (numToAdd > 0)
  637. insertMultiple (numUsed, ElementType(), numToAdd);
  638. else if (numToAdd < 0)
  639. removeRange (targetNumItems, -numToAdd);
  640. }
  641. /** Inserts a new element into the array, assuming that the array is sorted.
  642. This will use a comparator to find the position at which the new element
  643. should go. If the array isn't sorted, the behaviour of this
  644. method will be unpredictable.
  645. @param comparator the comparator to use to compare the elements - see the sort()
  646. method for details about the form this object should take
  647. @param newElement the new element to insert to the array
  648. @returns the index at which the new item was added
  649. @see addUsingDefaultSort, add, sort
  650. */
  651. template <class ElementComparator>
  652. int addSorted (ElementComparator& comparator, ParameterType newElement)
  653. {
  654. const ScopedLockType lock (getLock());
  655. auto index = findInsertIndexInSortedArray (comparator, data.elements.get(), newElement, 0, numUsed);
  656. insert (index, newElement);
  657. return index;
  658. }
  659. /** Inserts a new element into the array, assuming that the array is sorted.
  660. This will use the DefaultElementComparator class for sorting, so your ElementType
  661. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  662. method will be unpredictable.
  663. @param newElement the new element to insert to the array
  664. @see addSorted, sort
  665. */
  666. void addUsingDefaultSort (ParameterType newElement)
  667. {
  668. DefaultElementComparator <ElementType> comparator;
  669. addSorted (comparator, newElement);
  670. }
  671. /** Finds the index of an element in the array, assuming that the array is sorted.
  672. This will use a comparator to do a binary-chop to find the index of the given
  673. element, if it exists. If the array isn't sorted, the behaviour of this
  674. method will be unpredictable.
  675. @param comparator the comparator to use to compare the elements - see the sort()
  676. method for details about the form this object should take
  677. @param elementToLookFor the element to search for
  678. @returns the index of the element, or -1 if it's not found
  679. @see addSorted, sort
  680. */
  681. template <typename ElementComparator, typename TargetValueType>
  682. int indexOfSorted (ElementComparator& comparator, TargetValueType elementToLookFor) const
  683. {
  684. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  685. // avoids getting warning messages about the parameter being unused
  686. const ScopedLockType lock (getLock());
  687. for (int s = 0, e = numUsed;;)
  688. {
  689. if (s >= e)
  690. return -1;
  691. if (comparator.compareElements (elementToLookFor, data.elements[s]) == 0)
  692. return s;
  693. auto halfway = (s + e) / 2;
  694. if (halfway == s)
  695. return -1;
  696. if (comparator.compareElements (elementToLookFor, data.elements[halfway]) >= 0)
  697. s = halfway;
  698. else
  699. e = halfway;
  700. }
  701. }
  702. //==============================================================================
  703. /** Removes an element from the array.
  704. This will remove the element at a given index, and move back
  705. all the subsequent elements to close the gap.
  706. If the index passed in is out-of-range, nothing will happen.
  707. @param indexToRemove the index of the element to remove
  708. @see removeAndReturn, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  709. */
  710. void remove (int indexToRemove)
  711. {
  712. const ScopedLockType lock (getLock());
  713. if (isPositiveAndBelow (indexToRemove, numUsed))
  714. {
  715. jassert (data.elements != nullptr);
  716. removeInternal (indexToRemove);
  717. }
  718. }
  719. /** Removes an element from the array.
  720. This will remove the element at a given index, and move back
  721. all the subsequent elements to close the gap.
  722. If the index passed in is out-of-range, nothing will happen.
  723. @param indexToRemove the index of the element to remove
  724. @returns the element that has been removed
  725. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange
  726. */
  727. ElementType removeAndReturn (int indexToRemove)
  728. {
  729. const ScopedLockType lock (getLock());
  730. if (isPositiveAndBelow (indexToRemove, numUsed))
  731. {
  732. jassert (data.elements != nullptr);
  733. ElementType removed (data.elements[indexToRemove]);
  734. removeInternal (indexToRemove);
  735. return removed;
  736. }
  737. return ElementType();
  738. }
  739. /** Removes an element from the array.
  740. This will remove the element pointed to by the given iterator,
  741. and move back all the subsequent elements to close the gap.
  742. If the iterator passed in does not point to an element within the
  743. array, behaviour is undefined.
  744. @param elementToRemove a pointer to the element to remove
  745. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange, removeIf
  746. */
  747. void remove (const ElementType* elementToRemove)
  748. {
  749. jassert (elementToRemove != nullptr);
  750. const ScopedLockType lock (getLock());
  751. jassert (data.elements != nullptr);
  752. auto indexToRemove = (int) (elementToRemove - data.elements);
  753. if (! isPositiveAndBelow (indexToRemove, numUsed))
  754. {
  755. jassertfalse;
  756. return;
  757. }
  758. removeInternal (indexToRemove);
  759. }
  760. /** Removes an item from the array.
  761. This will remove the first occurrence of the given element from the array.
  762. If the item isn't found, no action is taken.
  763. @param valueToRemove the object to try to remove
  764. @see remove, removeRange, removeIf
  765. */
  766. void removeFirstMatchingValue (ParameterType valueToRemove)
  767. {
  768. const ScopedLockType lock (getLock());
  769. auto* e = data.elements.get();
  770. for (int i = 0; i < numUsed; ++i)
  771. {
  772. if (valueToRemove == e[i])
  773. {
  774. removeInternal (i);
  775. break;
  776. }
  777. }
  778. }
  779. /** Removes items from the array.
  780. This will remove all occurrences of the given element from the array.
  781. If no such items are found, no action is taken.
  782. @param valueToRemove the object to try to remove
  783. @return how many objects were removed.
  784. @see remove, removeRange, removeIf
  785. */
  786. int removeAllInstancesOf (ParameterType valueToRemove)
  787. {
  788. int numRemoved = 0;
  789. const ScopedLockType lock (getLock());
  790. for (int i = numUsed; --i >= 0;)
  791. {
  792. if (valueToRemove == data.elements[i])
  793. {
  794. removeInternal (i);
  795. ++numRemoved;
  796. }
  797. }
  798. return numRemoved;
  799. }
  800. /** Removes items from the array.
  801. This will remove all objects from the array that match a condition.
  802. If no such items are found, no action is taken.
  803. @param predicate the condition when to remove an item. Must be a callable
  804. type that takes an ElementType and returns a bool
  805. @return how many objects were removed.
  806. @see remove, removeRange, removeAllInstancesOf
  807. */
  808. template <typename PredicateType>
  809. int removeIf (PredicateType&& predicate)
  810. {
  811. int numRemoved = 0;
  812. const ScopedLockType lock (getLock());
  813. for (int i = numUsed; --i >= 0;)
  814. {
  815. if (predicate (data.elements[i]))
  816. {
  817. removeInternal (i);
  818. ++numRemoved;
  819. }
  820. }
  821. return numRemoved;
  822. }
  823. /** Removes a range of elements from the array.
  824. This will remove a set of elements, starting from the given index,
  825. and move subsequent elements down to close the gap.
  826. If the range extends beyond the bounds of the array, it will
  827. be safely clipped to the size of the array.
  828. @param startIndex the index of the first element to remove
  829. @param numberToRemove how many elements should be removed
  830. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeIf
  831. */
  832. void removeRange (int startIndex, int numberToRemove)
  833. {
  834. const ScopedLockType lock (getLock());
  835. auto endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  836. startIndex = jlimit (0, numUsed, startIndex);
  837. if (endIndex > startIndex)
  838. {
  839. auto* e = data.elements + startIndex;
  840. numberToRemove = endIndex - startIndex;
  841. for (int i = 0; i < numberToRemove; ++i)
  842. e[i].~ElementType();
  843. auto numToShift = numUsed - endIndex;
  844. if (numToShift > 0)
  845. memmove (e, e + numberToRemove, ((size_t) numToShift) * sizeof (ElementType));
  846. numUsed -= numberToRemove;
  847. minimiseStorageAfterRemoval();
  848. }
  849. }
  850. /** Removes the last n elements from the array.
  851. @param howManyToRemove how many elements to remove from the end of the array
  852. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  853. */
  854. void removeLast (int howManyToRemove = 1)
  855. {
  856. jassert (howManyToRemove >= 0);
  857. if (howManyToRemove > 0)
  858. {
  859. const ScopedLockType lock (getLock());
  860. if (howManyToRemove > numUsed)
  861. howManyToRemove = numUsed;
  862. for (int i = 1; i <= howManyToRemove; ++i)
  863. data.elements[numUsed - i].~ElementType();
  864. numUsed -= howManyToRemove;
  865. minimiseStorageAfterRemoval();
  866. }
  867. }
  868. /** Removes any elements which are also in another array.
  869. @param otherArray the other array in which to look for elements to remove
  870. @see removeValuesNotIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  871. */
  872. template <class OtherArrayType>
  873. void removeValuesIn (const OtherArrayType& otherArray)
  874. {
  875. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  876. const ScopedLockType lock2 (getLock());
  877. if (this == &otherArray)
  878. {
  879. clear();
  880. }
  881. else
  882. {
  883. if (otherArray.size() > 0)
  884. {
  885. for (int i = numUsed; --i >= 0;)
  886. if (otherArray.contains (data.elements[i]))
  887. removeInternal (i);
  888. }
  889. }
  890. }
  891. /** Removes any elements which are not found in another array.
  892. Only elements which occur in this other array will be retained.
  893. @param otherArray the array in which to look for elements NOT to remove
  894. @see removeValuesIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  895. */
  896. template <class OtherArrayType>
  897. void removeValuesNotIn (const OtherArrayType& otherArray)
  898. {
  899. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  900. const ScopedLockType lock2 (getLock());
  901. if (this != &otherArray)
  902. {
  903. if (otherArray.size() <= 0)
  904. {
  905. clear();
  906. }
  907. else
  908. {
  909. for (int i = numUsed; --i >= 0;)
  910. if (! otherArray.contains (data.elements[i]))
  911. removeInternal (i);
  912. }
  913. }
  914. }
  915. /** Swaps over two elements in the array.
  916. This swaps over the elements found at the two indexes passed in.
  917. If either index is out-of-range, this method will do nothing.
  918. @param index1 index of one of the elements to swap
  919. @param index2 index of the other element to swap
  920. */
  921. void swap (int index1, int index2)
  922. {
  923. const ScopedLockType lock (getLock());
  924. if (isPositiveAndBelow (index1, numUsed)
  925. && isPositiveAndBelow (index2, numUsed))
  926. {
  927. std::swap (data.elements[index1],
  928. data.elements[index2]);
  929. }
  930. }
  931. /** Moves one of the values to a different position.
  932. This will move the value to a specified index, shuffling along
  933. any intervening elements as required.
  934. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  935. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  936. @param currentIndex the index of the value to be moved. If this isn't a
  937. valid index, then nothing will be done
  938. @param newIndex the index at which you'd like this value to end up. If this
  939. is less than zero, the value will be moved to the end
  940. of the array
  941. */
  942. void move (int currentIndex, int newIndex) noexcept
  943. {
  944. if (currentIndex != newIndex)
  945. {
  946. const ScopedLockType lock (getLock());
  947. if (isPositiveAndBelow (currentIndex, numUsed))
  948. {
  949. if (! isPositiveAndBelow (newIndex, numUsed))
  950. newIndex = numUsed - 1;
  951. char tempCopy[sizeof (ElementType)];
  952. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  953. if (newIndex > currentIndex)
  954. {
  955. memmove (data.elements + currentIndex,
  956. data.elements + currentIndex + 1,
  957. sizeof (ElementType) * (size_t) (newIndex - currentIndex));
  958. }
  959. else
  960. {
  961. memmove (data.elements + newIndex + 1,
  962. data.elements + newIndex,
  963. sizeof (ElementType) * (size_t) (currentIndex - newIndex));
  964. }
  965. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  966. }
  967. }
  968. }
  969. //==============================================================================
  970. /** Reduces the amount of storage being used by the array.
  971. Arrays typically allocate slightly more storage than they need, and after
  972. removing elements, they may have quite a lot of unused space allocated.
  973. This method will reduce the amount of allocated storage to a minimum.
  974. */
  975. void minimiseStorageOverheads()
  976. {
  977. const ScopedLockType lock (getLock());
  978. data.shrinkToNoMoreThan (numUsed);
  979. }
  980. /** Increases the array's internal storage to hold a minimum number of elements.
  981. Calling this before adding a large known number of elements means that
  982. the array won't have to keep dynamically resizing itself as the elements
  983. are added, and it'll therefore be more efficient.
  984. */
  985. void ensureStorageAllocated (int minNumElements)
  986. {
  987. const ScopedLockType lock (getLock());
  988. data.ensureAllocatedSize (minNumElements);
  989. }
  990. //==============================================================================
  991. /** Sorts the array using a default comparison operation.
  992. If the type of your elements isn't supported by the DefaultElementComparator class
  993. then you may need to use the other version of sort, which takes a custom comparator.
  994. */
  995. void sort()
  996. {
  997. DefaultElementComparator<ElementType> comparator;
  998. sort (comparator);
  999. }
  1000. /** Sorts the elements in the array.
  1001. This will use a comparator object to sort the elements into order. The object
  1002. passed must have a method of the form:
  1003. @code
  1004. int compareElements (ElementType first, ElementType second);
  1005. @endcode
  1006. ..and this method must return:
  1007. - a value of < 0 if the first comes before the second
  1008. - a value of 0 if the two objects are equivalent
  1009. - a value of > 0 if the second comes before the first
  1010. To improve performance, the compareElements() method can be declared as static or const.
  1011. @param comparator the comparator to use for comparing elements.
  1012. @param retainOrderOfEquivalentItems if this is true, then items
  1013. which the comparator says are equivalent will be
  1014. kept in the order in which they currently appear
  1015. in the array. This is slower to perform, but may
  1016. be important in some cases. If it's false, a faster
  1017. algorithm is used, but equivalent elements may be
  1018. rearranged.
  1019. @see addSorted, indexOfSorted, sortArray
  1020. */
  1021. template <class ElementComparator>
  1022. void sort (ElementComparator& comparator,
  1023. bool retainOrderOfEquivalentItems = false)
  1024. {
  1025. const ScopedLockType lock (getLock());
  1026. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  1027. // avoids getting warning messages about the parameter being unused
  1028. sortArray (comparator, data.elements.get(), 0, size() - 1, retainOrderOfEquivalentItems);
  1029. }
  1030. //==============================================================================
  1031. /** Returns the CriticalSection that locks this array.
  1032. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  1033. an object of ScopedLockType as an RAII lock for it.
  1034. */
  1035. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  1036. /** Returns the type of scoped lock to use for locking this array */
  1037. using ScopedLockType = typename TypeOfCriticalSectionToUse::ScopedLockType;
  1038. //==============================================================================
  1039. #ifndef DOXYGEN
  1040. // Note that the swapWithArray method has been replaced by a more flexible templated version,
  1041. // and renamed "swapWith" to be more consistent with the names used in other classes.
  1042. JUCE_DEPRECATED_WITH_BODY (void swapWithArray (Array& other) noexcept, { swapWith (other); })
  1043. #endif
  1044. private:
  1045. //==============================================================================
  1046. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  1047. int numUsed = 0;
  1048. void removeInternal (int indexToRemove)
  1049. {
  1050. --numUsed;
  1051. auto* e = data.elements + indexToRemove;
  1052. e->~ElementType();
  1053. auto numberToShift = numUsed - indexToRemove;
  1054. if (numberToShift > 0)
  1055. memmove (e, e + 1, ((size_t) numberToShift) * sizeof (ElementType));
  1056. minimiseStorageAfterRemoval();
  1057. }
  1058. inline void deleteAllElements() noexcept
  1059. {
  1060. for (int i = 0; i < numUsed; ++i)
  1061. data.elements[i].~ElementType();
  1062. }
  1063. void minimiseStorageAfterRemoval()
  1064. {
  1065. if (data.numAllocated > jmax (minimumAllocatedSize, numUsed * 2))
  1066. data.shrinkToNoMoreThan (jmax (numUsed, jmax (minimumAllocatedSize, 64 / (int) sizeof (ElementType))));
  1067. }
  1068. void addAssumingCapacityIsReady (const ElementType& e) { new (data.elements + numUsed++) ElementType (e); }
  1069. void addAssumingCapacityIsReady (ElementType&& e) { new (data.elements + numUsed++) ElementType (static_cast<ElementType&&> (e)); }
  1070. template <typename... OtherElements>
  1071. void addAssumingCapacityIsReady (const ElementType& firstNewElement, OtherElements... otherElements)
  1072. {
  1073. addAssumingCapacityIsReady (firstNewElement);
  1074. addAssumingCapacityIsReady (otherElements...);
  1075. }
  1076. template <typename... OtherElements>
  1077. void addAssumingCapacityIsReady (ElementType&& firstNewElement, OtherElements... otherElements)
  1078. {
  1079. addAssumingCapacityIsReady (static_cast<ElementType&&> (firstNewElement));
  1080. addAssumingCapacityIsReady (otherElements...);
  1081. }
  1082. };
  1083. } // namespace juce