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.

1063 lines
39KB

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