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.

1034 lines
37KB

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