Audio plugin host https://kx.studio/carla
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.

1156 lines
41KB

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