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.

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