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.

1047 lines
38KB

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