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.

1144 lines
41KB

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