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.

1104 lines
40KB

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