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.

1151 lines
42KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. /**
  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 fulfill 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, std::forward<OtherElements> (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), std::forward<OtherElements> (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) noexcept
  222. {
  223. const ScopedLockType lock (getLock());
  224. return values[index];
  225. }
  226. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  227. This is like getUnchecked, but returns a direct reference to the element. Obviously
  228. this can be dangerous, so only use it when absolutely necessary.
  229. @param index the index of the element being requested (0 is the first element in the array)
  230. @see operator[], getFirst, getLast
  231. */
  232. inline const ElementType& getReference (int index) const noexcept
  233. {
  234. const ScopedLockType lock (getLock());
  235. return values[index];
  236. }
  237. /** Returns the first element in the array, or a default value if the array is empty.
  238. @see operator[], getUnchecked, getLast
  239. */
  240. inline ElementType getFirst() const noexcept
  241. {
  242. const ScopedLockType lock (getLock());
  243. return values.getFirst();
  244. }
  245. /** Returns the last element in the array, or a default value if the array is empty.
  246. @see operator[], getUnchecked, getFirst
  247. */
  248. inline ElementType getLast() const noexcept
  249. {
  250. const ScopedLockType lock (getLock());
  251. return values.getLast();
  252. }
  253. /** Returns a pointer to the actual array data.
  254. This pointer will only be valid until the next time a non-const method
  255. is called on the array.
  256. */
  257. inline ElementType* getRawDataPointer() noexcept
  258. {
  259. return values.begin();
  260. }
  261. /** Returns a pointer to the actual array data.
  262. This pointer will only be valid until the next time a non-const method
  263. is called on the array.
  264. */
  265. inline const ElementType* getRawDataPointer() const noexcept
  266. {
  267. return values.begin();
  268. }
  269. //==============================================================================
  270. /** Returns a pointer to the first element in the array.
  271. This method is provided for compatibility with standard C++ iteration mechanisms.
  272. */
  273. inline ElementType* begin() noexcept
  274. {
  275. return values.begin();
  276. }
  277. /** Returns a pointer to the first element in the array.
  278. This method is provided for compatibility with standard C++ iteration mechanisms.
  279. */
  280. inline const ElementType* begin() const noexcept
  281. {
  282. return values.begin();
  283. }
  284. /** Returns a pointer to the element which follows the last element in the array.
  285. This method is provided for compatibility with standard C++ iteration mechanisms.
  286. */
  287. inline ElementType* end() noexcept
  288. {
  289. return values.end();
  290. }
  291. /** Returns a pointer to the element which follows the last element in the array.
  292. This method is provided for compatibility with standard C++ iteration mechanisms.
  293. */
  294. inline const ElementType* end() const noexcept
  295. {
  296. return values.end();
  297. }
  298. /** Returns a pointer to the first element in the array.
  299. This method is provided for compatibility with the standard C++ containers.
  300. */
  301. inline ElementType* data() noexcept
  302. {
  303. return begin();
  304. }
  305. /** Returns a pointer to the first element in the array.
  306. This method is provided for compatibility with the standard C++ containers.
  307. */
  308. inline const ElementType* data() const noexcept
  309. {
  310. return begin();
  311. }
  312. //==============================================================================
  313. /** Finds the index of the first element which matches the value passed in.
  314. This will search the array for the given object, and return the index
  315. of its first occurrence. If the object isn't found, the method will return -1.
  316. @param elementToLookFor the value or object to look for
  317. @returns the index of the object, or -1 if it's not found
  318. */
  319. int indexOf (ParameterType elementToLookFor) const
  320. {
  321. const ScopedLockType lock (getLock());
  322. auto e = values.begin();
  323. auto endPtr = values.end();
  324. for (; e != endPtr; ++e)
  325. if (elementToLookFor == *e)
  326. return static_cast<int> (e - values.begin());
  327. return -1;
  328. }
  329. /** Returns true if the array contains at least one occurrence of an object.
  330. @param elementToLookFor the value or object to look for
  331. @returns true if the item is found
  332. */
  333. bool contains (ParameterType elementToLookFor) const
  334. {
  335. const ScopedLockType lock (getLock());
  336. auto e = values.begin();
  337. auto endPtr = values.end();
  338. for (; e != endPtr; ++e)
  339. if (elementToLookFor == *e)
  340. return true;
  341. return false;
  342. }
  343. //==============================================================================
  344. /** Appends a new element at the end of the array.
  345. @param newElement the new object to add to the array
  346. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  347. */
  348. void add (const ElementType& newElement)
  349. {
  350. const ScopedLockType lock (getLock());
  351. values.add (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. values.add (std::move (newElement));
  361. }
  362. /** Appends multiple new elements at the end of the array. */
  363. template <typename... OtherElements>
  364. void add (const ElementType& firstNewElement, OtherElements&&... otherElements)
  365. {
  366. const ScopedLockType lock (getLock());
  367. values.add (firstNewElement, std::forward<OtherElements> (otherElements)...);
  368. }
  369. /** Appends multiple new elements at the end of the array. */
  370. template <typename... OtherElements>
  371. void add (ElementType&& firstNewElement, OtherElements&&... otherElements)
  372. {
  373. const ScopedLockType lock (getLock());
  374. values.add (std::move (firstNewElement), std::forward<OtherElements> (otherElements)...);
  375. }
  376. /** Inserts a new element into the array at a given position.
  377. If the index is less than 0 or greater than the size of the array, the
  378. element will be added to the end of the array.
  379. Otherwise, it will be inserted into the array, moving all the later elements
  380. along to make room.
  381. @param indexToInsertAt the index at which the new element should be
  382. inserted (pass in -1 to add it to the end)
  383. @param newElement the new object to add to the array
  384. @see add, addSorted, addUsingDefaultSort, set
  385. */
  386. void insert (int indexToInsertAt, ParameterType newElement)
  387. {
  388. const ScopedLockType lock (getLock());
  389. values.insert (indexToInsertAt, newElement, 1);
  390. }
  391. /** Inserts multiple copies of an element into the array at a given position.
  392. If the index is less than 0 or greater than the size of the array, the
  393. element will be added to the end of the array.
  394. Otherwise, it will be inserted into the array, moving all the later elements
  395. along to make room.
  396. @param indexToInsertAt the index at which the new element should be inserted
  397. @param newElement the new object to add to the array
  398. @param numberOfTimesToInsertIt how many copies of the value to insert
  399. @see insert, add, addSorted, set
  400. */
  401. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  402. int numberOfTimesToInsertIt)
  403. {
  404. if (numberOfTimesToInsertIt > 0)
  405. {
  406. const ScopedLockType lock (getLock());
  407. values.insert (indexToInsertAt, newElement, numberOfTimesToInsertIt);
  408. }
  409. }
  410. /** Inserts an array of values into this array at a given position.
  411. If the index is less than 0 or greater than the size of the array, the
  412. new elements will be added to the end of the array.
  413. Otherwise, they will be inserted into the array, moving all the later elements
  414. along to make room.
  415. @param indexToInsertAt the index at which the first new element should be inserted
  416. @param newElements the new values to add to the array
  417. @param numberOfElements how many items are in the array
  418. @see insert, add, addSorted, set
  419. */
  420. void insertArray (int indexToInsertAt,
  421. const ElementType* newElements,
  422. int numberOfElements)
  423. {
  424. if (numberOfElements > 0)
  425. {
  426. const ScopedLockType lock (getLock());
  427. values.insertArray (indexToInsertAt, newElements, numberOfElements);
  428. }
  429. }
  430. /** Appends a new element at the end of the array as long as the array doesn't
  431. already contain it.
  432. If the array already contains an element that matches the one passed in, nothing
  433. will be done.
  434. @param newElement the new object to add to the array
  435. @return true if the element was added to the array; false otherwise.
  436. */
  437. bool addIfNotAlreadyThere (ParameterType newElement)
  438. {
  439. const ScopedLockType lock (getLock());
  440. if (contains (newElement))
  441. return false;
  442. add (newElement);
  443. return true;
  444. }
  445. /** Replaces an element with a new value.
  446. If the index is less than zero, this method does nothing.
  447. If the index is beyond the end of the array, the item is added to the end of the array.
  448. @param indexToChange the index whose value you want to change
  449. @param newValue the new value to set for this index.
  450. @see add, insert
  451. */
  452. void set (int indexToChange, ParameterType newValue)
  453. {
  454. if (indexToChange >= 0)
  455. {
  456. const ScopedLockType lock (getLock());
  457. if (indexToChange < values.size())
  458. values[indexToChange] = newValue;
  459. else
  460. values.add (newValue);
  461. }
  462. else
  463. {
  464. jassertfalse;
  465. }
  466. }
  467. /** Replaces an element with a new value without doing any bounds-checking.
  468. This just sets a value directly in the array's internal storage, so you'd
  469. better make sure it's in range!
  470. @param indexToChange the index whose value you want to change
  471. @param newValue the new value to set for this index.
  472. @see set, getUnchecked
  473. */
  474. void setUnchecked (int indexToChange, ParameterType newValue)
  475. {
  476. const ScopedLockType lock (getLock());
  477. jassert (isPositiveAndBelow (indexToChange, values.size()));
  478. values[indexToChange] = newValue;
  479. }
  480. /** Adds elements from an array to the end of this array.
  481. @param elementsToAdd an array of some kind of object from which elements
  482. can be constructed.
  483. @param numElementsToAdd how many elements are in this other array
  484. @see add
  485. */
  486. template <typename Type>
  487. void addArray (const Type* elementsToAdd, int numElementsToAdd)
  488. {
  489. const ScopedLockType lock (getLock());
  490. if (numElementsToAdd > 0)
  491. values.addArray (elementsToAdd, numElementsToAdd);
  492. }
  493. template <typename TypeToCreateFrom>
  494. void addArray (const std::initializer_list<TypeToCreateFrom>& items)
  495. {
  496. const ScopedLockType lock (getLock());
  497. values.addArray (items);
  498. }
  499. /** Adds elements from a null-terminated array of pointers to the end of this array.
  500. @param elementsToAdd an array of pointers to some kind of object from which elements
  501. can be constructed. This array must be terminated by a nullptr
  502. @see addArray
  503. */
  504. template <typename Type>
  505. void addNullTerminatedArray (const Type* const* elementsToAdd)
  506. {
  507. int num = 0;
  508. for (auto e = elementsToAdd; *e != nullptr; ++e)
  509. ++num;
  510. addArray (elementsToAdd, num);
  511. }
  512. /** This swaps the contents of this array with those of another array.
  513. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  514. because it just swaps their internal pointers.
  515. */
  516. template <class OtherArrayType>
  517. void swapWith (OtherArrayType& otherArray) noexcept
  518. {
  519. const ScopedLockType lock1 (getLock());
  520. const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
  521. values.swapWith (otherArray.values);
  522. }
  523. /** Adds elements from another array to the end of this array.
  524. @param arrayToAddFrom the array from which to copy the elements
  525. @see add
  526. */
  527. template <class OtherArrayType>
  528. void addArray (const OtherArrayType& arrayToAddFrom)
  529. {
  530. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  531. const ScopedLockType lock2 (getLock());
  532. values.addArray (arrayToAddFrom);
  533. }
  534. /** Adds elements from another array to the end of this array.
  535. @param arrayToAddFrom the array from which to copy the elements
  536. @param startIndex the first element of the other array to start copying from
  537. @param numElementsToAdd how many elements to add from the other array. If this
  538. value is negative or greater than the number of available elements,
  539. all available elements will be copied.
  540. @see add
  541. */
  542. template <class OtherArrayType>
  543. typename std::enable_if<! std::is_pointer<OtherArrayType>::value, void>::type
  544. addArray (const OtherArrayType& arrayToAddFrom,
  545. int startIndex,
  546. int numElementsToAdd = -1)
  547. {
  548. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  549. const ScopedLockType lock2 (getLock());
  550. values.addArray (arrayToAddFrom, startIndex, numElementsToAdd);
  551. }
  552. /** This will enlarge or shrink the array to the given number of elements, by adding
  553. or removing items from its end.
  554. If the array is smaller than the given target size, empty elements will be appended
  555. until its size is as specified. If its size is larger than the target, items will be
  556. removed from its end to shorten it.
  557. */
  558. void resize (int targetNumItems)
  559. {
  560. jassert (targetNumItems >= 0);
  561. auto numToAdd = targetNumItems - values.size();
  562. if (numToAdd > 0)
  563. insertMultiple (values.size(), ElementType(), numToAdd);
  564. else if (numToAdd < 0)
  565. removeRange (targetNumItems, -numToAdd);
  566. }
  567. /** Inserts a new element into the array, assuming that the array is sorted.
  568. This will use a comparator to find the position at which the new element
  569. should go. If the array isn't sorted, the behaviour of this
  570. method will be unpredictable.
  571. @param comparator the comparator to use to compare the elements - see the sort()
  572. method for details about the form this object should take
  573. @param newElement the new element to insert to the array
  574. @returns the index at which the new item was added
  575. @see addUsingDefaultSort, add, sort
  576. */
  577. template <class ElementComparator>
  578. int addSorted (ElementComparator& comparator, ParameterType newElement)
  579. {
  580. const ScopedLockType lock (getLock());
  581. auto index = findInsertIndexInSortedArray (comparator, values.begin(), newElement, 0, values.size());
  582. insert (index, newElement);
  583. return index;
  584. }
  585. /** Inserts a new element into the array, assuming that the array is sorted.
  586. This will use the DefaultElementComparator class for sorting, so your ElementType
  587. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  588. method will be unpredictable.
  589. @param newElement the new element to insert to the array
  590. @see addSorted, sort
  591. */
  592. void addUsingDefaultSort (ParameterType newElement)
  593. {
  594. DefaultElementComparator <ElementType> comparator;
  595. addSorted (comparator, newElement);
  596. }
  597. /** Finds the index of an element in the array, assuming that the array is sorted.
  598. This will use a comparator to do a binary-chop to find the index of the given
  599. element, if it exists. If the array isn't sorted, the behaviour of this
  600. method will be unpredictable.
  601. @param comparator the comparator to use to compare the elements - see the sort()
  602. method for details about the form this object should take
  603. @param elementToLookFor the element to search for
  604. @returns the index of the element, or -1 if it's not found
  605. @see addSorted, sort
  606. */
  607. template <typename ElementComparator, typename TargetValueType>
  608. int indexOfSorted (ElementComparator& comparator, TargetValueType elementToLookFor) const
  609. {
  610. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  611. // avoids getting warning messages about the parameter being unused
  612. const ScopedLockType lock (getLock());
  613. for (int s = 0, e = values.size();;)
  614. {
  615. if (s >= e)
  616. return -1;
  617. if (comparator.compareElements (elementToLookFor, values[s]) == 0)
  618. return s;
  619. auto halfway = (s + e) / 2;
  620. if (halfway == s)
  621. return -1;
  622. if (comparator.compareElements (elementToLookFor, values[halfway]) >= 0)
  623. s = halfway;
  624. else
  625. e = halfway;
  626. }
  627. }
  628. //==============================================================================
  629. /** Removes an element from the array.
  630. This will remove the element at a given index, and move back
  631. all the subsequent elements to close the gap.
  632. If the index passed in is out-of-range, nothing will happen.
  633. @param indexToRemove the index of the element to remove
  634. @see removeAndReturn, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  635. */
  636. void remove (int indexToRemove)
  637. {
  638. const ScopedLockType lock (getLock());
  639. if (isPositiveAndBelow (indexToRemove, values.size()))
  640. removeInternal (indexToRemove);
  641. }
  642. /** Removes an element from the array.
  643. This will remove the element at a given index, and move back
  644. all the subsequent elements to close the gap.
  645. If the index passed in is out-of-range, nothing will happen.
  646. @param indexToRemove the index of the element to remove
  647. @returns the element that has been removed
  648. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange
  649. */
  650. ElementType removeAndReturn (int indexToRemove)
  651. {
  652. const ScopedLockType lock (getLock());
  653. if (isPositiveAndBelow (indexToRemove, values.size()))
  654. {
  655. ElementType removed (values[indexToRemove]);
  656. removeInternal (indexToRemove);
  657. return removed;
  658. }
  659. return ElementType();
  660. }
  661. /** Removes an element from the array.
  662. This will remove the element pointed to by the given iterator,
  663. and move back all the subsequent elements to close the gap.
  664. If the iterator passed in does not point to an element within the
  665. array, behaviour is undefined.
  666. @param elementToRemove a pointer to the element to remove
  667. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange, removeIf
  668. */
  669. void remove (const ElementType* elementToRemove)
  670. {
  671. jassert (elementToRemove != nullptr);
  672. const ScopedLockType lock (getLock());
  673. jassert (values.begin() != nullptr);
  674. auto indexToRemove = (int) (elementToRemove - values.begin());
  675. if (! isPositiveAndBelow (indexToRemove, values.size()))
  676. {
  677. jassertfalse;
  678. return;
  679. }
  680. removeInternal (indexToRemove);
  681. }
  682. /** Removes an item from the array.
  683. This will remove the first occurrence of the given element from the array.
  684. If the item isn't found, no action is taken.
  685. @param valueToRemove the object to try to remove
  686. @see remove, removeRange, removeIf
  687. */
  688. void removeFirstMatchingValue (ParameterType valueToRemove)
  689. {
  690. const ScopedLockType lock (getLock());
  691. auto* e = values.begin();
  692. for (int i = 0; i < values.size(); ++i)
  693. {
  694. if (valueToRemove == e[i])
  695. {
  696. removeInternal (i);
  697. break;
  698. }
  699. }
  700. }
  701. /** Removes items from the array.
  702. This will remove all occurrences of the given element from the array.
  703. If no such items are found, no action is taken.
  704. @param valueToRemove the object to try to remove
  705. @return how many objects were removed.
  706. @see remove, removeRange, removeIf
  707. */
  708. int removeAllInstancesOf (ParameterType valueToRemove)
  709. {
  710. int numRemoved = 0;
  711. const ScopedLockType lock (getLock());
  712. for (int i = values.size(); --i >= 0;)
  713. {
  714. if (valueToRemove == values[i])
  715. {
  716. removeInternal (i);
  717. ++numRemoved;
  718. }
  719. }
  720. return numRemoved;
  721. }
  722. /** Removes items from the array.
  723. This will remove all objects from the array that match a condition.
  724. If no such items are found, no action is taken.
  725. @param predicate the condition when to remove an item. Must be a callable
  726. type that takes an ElementType and returns a bool
  727. @return how many objects were removed.
  728. @see remove, removeRange, removeAllInstancesOf
  729. */
  730. template <typename PredicateType>
  731. int removeIf (PredicateType&& predicate)
  732. {
  733. int numRemoved = 0;
  734. const ScopedLockType lock (getLock());
  735. for (int i = values.size(); --i >= 0;)
  736. {
  737. if (predicate (values[i]))
  738. {
  739. removeInternal (i);
  740. ++numRemoved;
  741. }
  742. }
  743. return numRemoved;
  744. }
  745. /** Removes a range of elements from the array.
  746. This will remove a set of elements, starting from the given index,
  747. and move subsequent elements down to close the gap.
  748. If the range extends beyond the bounds of the array, it will
  749. be safely clipped to the size of the array.
  750. @param startIndex the index of the first element to remove
  751. @param numberToRemove how many elements should be removed
  752. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeIf
  753. */
  754. void removeRange (int startIndex, int numberToRemove)
  755. {
  756. const ScopedLockType lock (getLock());
  757. auto endIndex = jlimit (0, values.size(), startIndex + numberToRemove);
  758. startIndex = jlimit (0, values.size(), startIndex);
  759. numberToRemove = endIndex - startIndex;
  760. if (numberToRemove > 0)
  761. {
  762. values.removeElements (startIndex, numberToRemove);
  763. minimiseStorageAfterRemoval();
  764. }
  765. }
  766. /** Removes the last n elements from the array.
  767. @param howManyToRemove how many elements to remove from the end of the array
  768. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  769. */
  770. void removeLast (int howManyToRemove = 1)
  771. {
  772. jassert (howManyToRemove >= 0);
  773. if (howManyToRemove > 0)
  774. {
  775. const ScopedLockType lock (getLock());
  776. if (howManyToRemove > values.size())
  777. howManyToRemove = values.size();
  778. values.removeElements (values.size() - howManyToRemove, howManyToRemove);
  779. minimiseStorageAfterRemoval();
  780. }
  781. }
  782. /** Removes any elements which are also in another array.
  783. @param otherArray the other array in which to look for elements to remove
  784. @see removeValuesNotIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  785. */
  786. template <class OtherArrayType>
  787. void removeValuesIn (const OtherArrayType& otherArray)
  788. {
  789. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  790. const ScopedLockType lock2 (getLock());
  791. if (this == &otherArray)
  792. {
  793. clear();
  794. }
  795. else
  796. {
  797. if (otherArray.size() > 0)
  798. {
  799. for (int i = values.size(); --i >= 0;)
  800. if (otherArray.contains (values[i]))
  801. removeInternal (i);
  802. }
  803. }
  804. }
  805. /** Removes any elements which are not found in another array.
  806. Only elements which occur in this other array will be retained.
  807. @param otherArray the array in which to look for elements NOT to remove
  808. @see removeValuesIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  809. */
  810. template <class OtherArrayType>
  811. void removeValuesNotIn (const OtherArrayType& otherArray)
  812. {
  813. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  814. const ScopedLockType lock2 (getLock());
  815. if (this != &otherArray)
  816. {
  817. if (otherArray.size() <= 0)
  818. {
  819. clear();
  820. }
  821. else
  822. {
  823. for (int i = values.size(); --i >= 0;)
  824. if (! otherArray.contains (values[i]))
  825. removeInternal (i);
  826. }
  827. }
  828. }
  829. /** Swaps over two elements in the array.
  830. This swaps over the elements found at the two indexes passed in.
  831. If either index is out-of-range, this method will do nothing.
  832. @param index1 index of one of the elements to swap
  833. @param index2 index of the other element to swap
  834. */
  835. void swap (int index1, int index2)
  836. {
  837. const ScopedLockType lock (getLock());
  838. values.swap (index1, index2);
  839. }
  840. /** Moves one of the values to a different position.
  841. This will move the value to a specified index, shuffling along
  842. any intervening elements as required.
  843. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  844. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  845. @param currentIndex the index of the value to be moved. If this isn't a
  846. valid index, then nothing will be done
  847. @param newIndex the index at which you'd like this value to end up. If this
  848. is less than zero, the value will be moved to the end
  849. of the array
  850. */
  851. void move (int currentIndex, int newIndex) noexcept
  852. {
  853. if (currentIndex != newIndex)
  854. {
  855. const ScopedLockType lock (getLock());
  856. values.move (currentIndex, newIndex);
  857. }
  858. }
  859. //==============================================================================
  860. /** Reduces the amount of storage being used by the array.
  861. Arrays typically allocate slightly more storage than they need, and after
  862. removing elements, they may have quite a lot of unused space allocated.
  863. This method will reduce the amount of allocated storage to a minimum.
  864. */
  865. void minimiseStorageOverheads()
  866. {
  867. const ScopedLockType lock (getLock());
  868. values.shrinkToNoMoreThan (values.size());
  869. }
  870. /** Increases the array's internal storage to hold a minimum number of elements.
  871. Calling this before adding a large known number of elements means that
  872. the array won't have to keep dynamically resizing itself as the elements
  873. are added, and it'll therefore be more efficient.
  874. */
  875. void ensureStorageAllocated (int minNumElements)
  876. {
  877. const ScopedLockType lock (getLock());
  878. values.ensureAllocatedSize (minNumElements);
  879. }
  880. //==============================================================================
  881. /** Sorts the array using a default comparison operation.
  882. If the type of your elements isn't supported by the DefaultElementComparator class
  883. then you may need to use the other version of sort, which takes a custom comparator.
  884. */
  885. void sort()
  886. {
  887. DefaultElementComparator<ElementType> comparator;
  888. sort (comparator);
  889. }
  890. /** Sorts the elements in the array.
  891. This will use a comparator object to sort the elements into order. The object
  892. passed must have a method of the form:
  893. @code
  894. int compareElements (ElementType first, ElementType second);
  895. @endcode
  896. ..and this method must return:
  897. - a value of < 0 if the first comes before the second
  898. - a value of 0 if the two objects are equivalent
  899. - a value of > 0 if the second comes before the first
  900. To improve performance, the compareElements() method can be declared as static or const.
  901. @param comparator the comparator to use for comparing elements.
  902. @param retainOrderOfEquivalentItems if this is true, then items
  903. which the comparator says are equivalent will be
  904. kept in the order in which they currently appear
  905. in the array. This is slower to perform, but may
  906. be important in some cases. If it's false, a faster
  907. algorithm is used, but equivalent elements may be
  908. rearranged.
  909. @see addSorted, indexOfSorted, sortArray
  910. */
  911. template <class ElementComparator>
  912. void sort (ElementComparator& comparator,
  913. bool retainOrderOfEquivalentItems = false)
  914. {
  915. const ScopedLockType lock (getLock());
  916. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  917. // avoids getting warning messages about the parameter being unused
  918. sortArray (comparator, values.begin(), 0, size() - 1, retainOrderOfEquivalentItems);
  919. }
  920. //==============================================================================
  921. /** Returns the CriticalSection that locks this array.
  922. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  923. an object of ScopedLockType as an RAII lock for it.
  924. */
  925. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return values; }
  926. /** Returns the type of scoped lock to use for locking this array */
  927. using ScopedLockType = typename TypeOfCriticalSectionToUse::ScopedLockType;
  928. //==============================================================================
  929. #ifndef DOXYGEN
  930. // Note that the swapWithArray method has been replaced by a more flexible templated version,
  931. // and renamed "swapWith" to be more consistent with the names used in other classes.
  932. JUCE_DEPRECATED_WITH_BODY (void swapWithArray (Array& other) noexcept, { swapWith (other); })
  933. #endif
  934. private:
  935. //==============================================================================
  936. ArrayBase<ElementType, TypeOfCriticalSectionToUse> values;
  937. void removeInternal (int indexToRemove)
  938. {
  939. values.removeElements (indexToRemove, 1);
  940. minimiseStorageAfterRemoval();
  941. }
  942. void minimiseStorageAfterRemoval()
  943. {
  944. if (values.capacity() > jmax (minimumAllocatedSize, values.size() * 2))
  945. values.shrinkToNoMoreThan (jmax (values.size(), jmax (minimumAllocatedSize, 64 / (int) sizeof (ElementType))));
  946. }
  947. };
  948. } // namespace juce