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.

1143 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. {
  57. CARLA_SAFE_ASSERT_RETURN(data.setAllocatedSize (other.numUsed),);
  58. numUsed = other.numUsed;
  59. for (int i = 0; i < numUsed; ++i)
  60. new (data.elements + i) ElementType (other.data.elements[i]);
  61. }
  62. #if WATER_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) noexcept : numUsed (0)
  75. {
  76. while (*values != TypeToCreateFrom())
  77. {
  78. CARLA_SAFE_ASSERT_BREAK(add (*values++));
  79. }
  80. }
  81. /** Initalises from a C array of values.
  82. @param values the array to copy from
  83. @param numValues the number of values in the array
  84. */
  85. template <typename TypeToCreateFrom>
  86. Array (const TypeToCreateFrom* values, int numValues) noexcept : numUsed (numValues)
  87. {
  88. CARLA_SAFE_ASSERT_RETURN(data.setAllocatedSize (numValues),);
  89. for (int i = 0; i < numValues; ++i)
  90. new (data.elements + i) ElementType (values[i]);
  91. }
  92. /** Destructor. */
  93. ~Array() noexcept
  94. {
  95. deleteAllElements();
  96. }
  97. /** Copies another array.
  98. @param other the array to copy
  99. */
  100. Array& operator= (const Array& other) noexcept
  101. {
  102. if (this != &other)
  103. {
  104. Array<ElementType> otherCopy (other);
  105. swapWith (otherCopy);
  106. }
  107. return *this;
  108. }
  109. #if WATER_COMPILER_SUPPORTS_MOVE_SEMANTICS
  110. Array& operator= (Array&& other) noexcept
  111. {
  112. deleteAllElements();
  113. data = static_cast<ArrayAllocationBase<ElementType>&&> (other.data);
  114. numUsed = other.numUsed;
  115. other.numUsed = 0;
  116. return *this;
  117. }
  118. #endif
  119. //==============================================================================
  120. /** Compares this array to another one.
  121. Two arrays are considered equal if they both contain the same set of
  122. elements, in the same order.
  123. @param other the other array to compare with
  124. */
  125. template <class OtherArrayType>
  126. bool operator== (const OtherArrayType& other) const
  127. {
  128. if (numUsed != other.numUsed)
  129. return false;
  130. for (int i = numUsed; --i >= 0;)
  131. if (! (data.elements [i] == other.data.elements [i]))
  132. return false;
  133. return true;
  134. }
  135. /** Compares this array to another one.
  136. Two arrays are considered equal if they both contain the same set of
  137. elements, in the same order.
  138. @param other the other array to compare with
  139. */
  140. template <class OtherArrayType>
  141. bool operator!= (const OtherArrayType& other) const
  142. {
  143. return ! operator== (other);
  144. }
  145. //==============================================================================
  146. /** Removes all elements from the array.
  147. This will remove all the elements, and free any storage that the array is
  148. using. To clear the array without freeing the storage, use the clearQuick()
  149. method instead.
  150. @see clearQuick
  151. */
  152. void clear() noexcept
  153. {
  154. deleteAllElements();
  155. data.setAllocatedSize (0);
  156. numUsed = 0;
  157. }
  158. /** Removes all elements from the array without freeing the array's allocated storage.
  159. @see clear
  160. */
  161. void clearQuick() noexcept
  162. {
  163. deleteAllElements();
  164. numUsed = 0;
  165. }
  166. //==============================================================================
  167. /** Returns the current number of elements in the array. */
  168. inline int size() const noexcept
  169. {
  170. return numUsed;
  171. }
  172. /** Returns true if the array is empty, false otherwise. */
  173. inline bool isEmpty() const noexcept
  174. {
  175. return size() == 0;
  176. }
  177. /** Returns one of the elements in the array.
  178. If the index passed in is beyond the range of valid elements, this
  179. will return a default value.
  180. If you're certain that the index will always be a valid element, you
  181. can call getUnchecked() instead, which is faster.
  182. @param index the index of the element being requested (0 is the first element in the array)
  183. @see getUnchecked, getFirst, getLast
  184. */
  185. ElementType operator[] (const int index) const
  186. {
  187. if (isPositiveAndBelow (index, numUsed))
  188. {
  189. jassert (data.elements != nullptr);
  190. return data.elements [index];
  191. }
  192. return ElementType();
  193. }
  194. /** Returns one of the elements in the array, without checking the index passed in.
  195. Unlike the operator[] method, this will try to return an element without
  196. checking that the index is within the bounds of the array, so should only
  197. be used when you're confident that it will always be a valid index.
  198. @param index the index of the element being requested (0 is the first element in the array)
  199. @see operator[], getFirst, getLast
  200. */
  201. inline ElementType getUnchecked (const int index) const
  202. {
  203. jassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  204. return data.elements [index];
  205. }
  206. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  207. This is like getUnchecked, but returns a direct reference to the element, so that
  208. you can alter it directly. Obviously this can be dangerous, so only use it when
  209. absolutely necessary.
  210. @param index the index of the element being requested (0 is the first element in the array)
  211. @see operator[], getFirst, getLast
  212. */
  213. inline ElementType& getReference (const int index) const noexcept
  214. {
  215. jassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  216. return data.elements [index];
  217. }
  218. /** Returns the first element in the array, or a default value if the array is empty.
  219. @see operator[], getUnchecked, getLast
  220. */
  221. inline ElementType getFirst() const
  222. {
  223. if (numUsed > 0)
  224. {
  225. jassert (data.elements != nullptr);
  226. return data.elements[0];
  227. }
  228. return ElementType();
  229. }
  230. /** Returns the last element in the array, or a default value if the array is empty.
  231. @see operator[], getUnchecked, getFirst
  232. */
  233. inline ElementType getLast() const
  234. {
  235. if (numUsed > 0)
  236. {
  237. jassert (data.elements != nullptr);
  238. return data.elements[numUsed - 1];
  239. }
  240. return ElementType();
  241. }
  242. /** Returns a pointer to the actual array data.
  243. This pointer will only be valid until the next time a non-const method
  244. is called on the array.
  245. */
  246. inline ElementType* getRawDataPointer() noexcept
  247. {
  248. return data.elements;
  249. }
  250. //==============================================================================
  251. /** Returns a pointer to the first element in the array.
  252. This method is provided for compatibility with standard C++ iteration mechanisms.
  253. */
  254. inline ElementType* begin() const noexcept
  255. {
  256. return data.elements;
  257. }
  258. /** Returns a pointer to the element which follows the last element in the array.
  259. This method is provided for compatibility with standard C++ iteration mechanisms.
  260. */
  261. inline ElementType* end() const noexcept
  262. {
  263. #ifdef DEBUG
  264. if (data.elements == nullptr || numUsed <= 0) // (to keep static analysers happy)
  265. return data.elements;
  266. #endif
  267. return data.elements + numUsed;
  268. }
  269. //==============================================================================
  270. /** Finds the index of the first element which matches the value passed in.
  271. This will search the array for the given object, and return the index
  272. of its first occurrence. If the object isn't found, the method will return -1.
  273. @param elementToLookFor the value or object to look for
  274. @returns the index of the object, or -1 if it's not found
  275. */
  276. int indexOf (ParameterType elementToLookFor) const
  277. {
  278. const ElementType* e = data.elements.getData();
  279. const ElementType* const end_ = e + numUsed;
  280. for (; e != end_; ++e)
  281. if (elementToLookFor == *e)
  282. return static_cast<int> (e - data.elements.getData());
  283. return -1;
  284. }
  285. /** Returns true if the array contains at least one occurrence of an object.
  286. @param elementToLookFor the value or object to look for
  287. @returns true if the item is found
  288. */
  289. bool contains (ParameterType elementToLookFor) const
  290. {
  291. const ElementType* e = data.elements.getData();
  292. const ElementType* const end_ = e + numUsed;
  293. for (; e != end_; ++e)
  294. if (elementToLookFor == *e)
  295. return true;
  296. return false;
  297. }
  298. //==============================================================================
  299. /** Appends a new element at the end of the array.
  300. @param newElement the new object to add to the array
  301. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  302. */
  303. bool add (const ElementType& newElement) noexcept
  304. {
  305. if (! data.ensureAllocatedSize (numUsed + 1))
  306. return false;
  307. new (data.elements + numUsed++) ElementType (newElement);
  308. return true;
  309. }
  310. #if WATER_COMPILER_SUPPORTS_MOVE_SEMANTICS
  311. /** Appends a new element at the end of the array.
  312. @param newElement the new object to add to the array
  313. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  314. */
  315. bool add (ElementType&& newElement) noexcept
  316. {
  317. if (! data.ensureAllocatedSize (numUsed + 1))
  318. return false;
  319. new (data.elements + numUsed++) ElementType (static_cast<ElementType&&> (newElement));
  320. return true;
  321. }
  322. #endif
  323. /** Inserts a new element into the array at a given position.
  324. If the index is less than 0 or greater than the size of the array, the
  325. element will be added to the end of the array.
  326. Otherwise, it will be inserted into the array, moving all the later elements
  327. along to make room.
  328. @param indexToInsertAt the index at which the new element should be
  329. inserted (pass in -1 to add it to the end)
  330. @param newElement the new object to add to the array
  331. @see add, addSorted, addUsingDefaultSort, set
  332. */
  333. bool insert (int indexToInsertAt, ParameterType newElement) noexcept
  334. {
  335. if (! data.ensureAllocatedSize (numUsed + 1))
  336. return false;
  337. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  338. {
  339. ElementType* const insertPos = data.elements + indexToInsertAt;
  340. const int numberToMove = numUsed - indexToInsertAt;
  341. if (numberToMove > 0)
  342. std::memmove (insertPos + 1, insertPos, ((size_t) numberToMove) * sizeof (ElementType));
  343. new (insertPos) ElementType (newElement);
  344. ++numUsed;
  345. }
  346. else
  347. {
  348. new (data.elements + numUsed++) ElementType (newElement);
  349. }
  350. return true;
  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. return add (newElement);
  433. }
  434. /** Replaces an element with a new value.
  435. If the index is less than zero, this method does nothing.
  436. If the index is beyond the end of the array, the item is added to the end of the array.
  437. @param indexToChange the index whose value you want to change
  438. @param newValue the new value to set for this index.
  439. @see add, insert
  440. */
  441. void set (const int indexToChange, ParameterType newValue)
  442. {
  443. jassert (indexToChange >= 0);
  444. if (isPositiveAndBelow (indexToChange, numUsed))
  445. {
  446. jassert (data.elements != nullptr);
  447. data.elements [indexToChange] = newValue;
  448. }
  449. else if (indexToChange >= 0)
  450. {
  451. data.ensureAllocatedSize (numUsed + 1);
  452. new (data.elements + numUsed++) ElementType (newValue);
  453. }
  454. }
  455. /** Replaces an element with a new value without doing any bounds-checking.
  456. This just sets a value directly in the array's internal storage, so you'd
  457. better make sure it's in range!
  458. @param indexToChange the index whose value you want to change
  459. @param newValue the new value to set for this index.
  460. @see set, getUnchecked
  461. */
  462. void setUnchecked (const int indexToChange, ParameterType newValue)
  463. {
  464. jassert (isPositiveAndBelow (indexToChange, numUsed));
  465. data.elements [indexToChange] = newValue;
  466. }
  467. /** Adds elements from an array to the end of this array.
  468. @param elementsToAdd an array of some kind of object from which elements
  469. can be constructed.
  470. @param numElementsToAdd how many elements are in this other array
  471. @see add
  472. */
  473. template <typename Type>
  474. void addArray (const Type* elementsToAdd, int numElementsToAdd)
  475. {
  476. if (numElementsToAdd > 0)
  477. {
  478. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  479. while (--numElementsToAdd >= 0)
  480. {
  481. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  482. ++numUsed;
  483. }
  484. }
  485. }
  486. /** Adds elements from a null-terminated array of pointers to the end of this array.
  487. @param elementsToAdd an array of pointers to some kind of object from which elements
  488. can be constructed. This array must be terminated by a nullptr
  489. @see addArray
  490. */
  491. template <typename Type>
  492. void addNullTerminatedArray (const Type* const* elementsToAdd)
  493. {
  494. int num = 0;
  495. for (const Type* const* e = elementsToAdd; *e != nullptr; ++e)
  496. ++num;
  497. addArray (elementsToAdd, num);
  498. }
  499. /** This swaps the contents of this array with those of another array.
  500. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  501. because it just swaps their internal pointers.
  502. */
  503. template <class OtherArrayType>
  504. void swapWith (OtherArrayType& otherArray) noexcept
  505. {
  506. data.swapWith (otherArray.data);
  507. std::swap (numUsed, otherArray.numUsed);
  508. }
  509. /** Adds elements from another array to the end of this array.
  510. @param arrayToAddFrom the array from which to copy the elements
  511. @param startIndex the first element of the other array to start copying from
  512. @param numElementsToAdd how many elements to add from the other array. If this
  513. value is negative or greater than the number of available elements,
  514. all available elements will be copied.
  515. @see add
  516. */
  517. template <class OtherArrayType>
  518. void addArray (const OtherArrayType& arrayToAddFrom,
  519. int startIndex = 0,
  520. int numElementsToAdd = -1)
  521. {
  522. if (startIndex < 0)
  523. {
  524. jassertfalse;
  525. startIndex = 0;
  526. }
  527. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  528. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  529. while (--numElementsToAdd >= 0)
  530. add (arrayToAddFrom.getUnchecked (startIndex++));
  531. }
  532. /** This will enlarge or shrink the array to the given number of elements, by adding
  533. or removing items from its end.
  534. If the array is smaller than the given target size, empty elements will be appended
  535. until its size is as specified. If its size is larger than the target, items will be
  536. removed from its end to shorten it.
  537. */
  538. void resize (const int targetNumItems)
  539. {
  540. jassert (targetNumItems >= 0);
  541. const int numToAdd = targetNumItems - numUsed;
  542. if (numToAdd > 0)
  543. insertMultiple (numUsed, ElementType(), numToAdd);
  544. else if (numToAdd < 0)
  545. removeRange (targetNumItems, -numToAdd);
  546. }
  547. /** Inserts a new element into the array, assuming that the array is sorted.
  548. This will use a comparator to find the position at which the new element
  549. should go. If the array isn't sorted, the behaviour of this
  550. method will be unpredictable.
  551. @param comparator the comparator to use to compare the elements - see the sort()
  552. method for details about the form this object should take
  553. @param newElement the new element to insert to the array
  554. @returns the index at which the new item was added
  555. @see addUsingDefaultSort, add, sort
  556. */
  557. template <class ElementComparator>
  558. int addSorted (ElementComparator& comparator, ParameterType newElement)
  559. {
  560. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  561. insert (index, newElement);
  562. return index;
  563. }
  564. /** Inserts a new element into the array, assuming that the array is sorted.
  565. This will use the DefaultElementComparator class for sorting, so your ElementType
  566. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  567. method will be unpredictable.
  568. @param newElement the new element to insert to the array
  569. @see addSorted, sort
  570. */
  571. void addUsingDefaultSort (ParameterType newElement)
  572. {
  573. DefaultElementComparator <ElementType> comparator;
  574. addSorted (comparator, newElement);
  575. }
  576. /** Finds the index of an element in the array, assuming that the array is sorted.
  577. This will use a comparator to do a binary-chop to find the index of the given
  578. element, if it exists. If the array isn't sorted, the behaviour of this
  579. method will be unpredictable.
  580. @param comparator the comparator to use to compare the elements - see the sort()
  581. method for details about the form this object should take
  582. @param elementToLookFor the element to search for
  583. @returns the index of the element, or -1 if it's not found
  584. @see addSorted, sort
  585. */
  586. template <typename ElementComparator, typename TargetValueType>
  587. int indexOfSorted (ElementComparator& comparator, TargetValueType elementToLookFor) const
  588. {
  589. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  590. // avoids getting warning messages about the parameter being unused
  591. for (int s = 0, e = numUsed;;)
  592. {
  593. if (s >= e)
  594. return -1;
  595. if (comparator.compareElements (elementToLookFor, data.elements [s]) == 0)
  596. return s;
  597. const int halfway = (s + e) / 2;
  598. if (halfway == s)
  599. return -1;
  600. if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  601. s = halfway;
  602. else
  603. e = halfway;
  604. }
  605. }
  606. //==============================================================================
  607. /** Removes an element from the array.
  608. This will remove the element at a given index, and move back
  609. all the subsequent elements to close the gap.
  610. If the index passed in is out-of-range, nothing will happen.
  611. @param indexToRemove the index of the element to remove
  612. @see removeAndReturn, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  613. */
  614. void remove (int indexToRemove)
  615. {
  616. if (isPositiveAndBelow (indexToRemove, numUsed))
  617. {
  618. jassert (data.elements != nullptr);
  619. removeInternal (indexToRemove);
  620. }
  621. }
  622. /** Removes an element from the array.
  623. This will remove the element at a given index, and move back
  624. all the subsequent elements to close the gap.
  625. If the index passed in is out-of-range, nothing will happen.
  626. @param indexToRemove the index of the element to remove
  627. @returns the element that has been removed
  628. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange
  629. */
  630. ElementType removeAndReturn (const int indexToRemove)
  631. {
  632. if (isPositiveAndBelow (indexToRemove, numUsed))
  633. {
  634. jassert (data.elements != nullptr);
  635. ElementType removed (data.elements[indexToRemove]);
  636. removeInternal (indexToRemove);
  637. return removed;
  638. }
  639. return ElementType();
  640. }
  641. /** Removes an element from the array.
  642. This will remove the element pointed to by the given iterator,
  643. and move back all the subsequent elements to close the gap.
  644. If the iterator passed in does not point to an element within the
  645. array, behaviour is undefined.
  646. @param elementToRemove a pointer to the element to remove
  647. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange, removeIf
  648. */
  649. void remove (const ElementType* elementToRemove)
  650. {
  651. jassert (elementToRemove != nullptr);
  652. jassert (data.elements != nullptr);
  653. const int indexToRemove = int (elementToRemove - data.elements);
  654. if (! isPositiveAndBelow (indexToRemove, numUsed))
  655. {
  656. jassertfalse;
  657. return;
  658. }
  659. removeInternal (indexToRemove);
  660. }
  661. /** Removes an item from the array.
  662. This will remove the first occurrence of the given element from the array.
  663. If the item isn't found, no action is taken.
  664. @param valueToRemove the object to try to remove
  665. @see remove, removeRange, removeIf
  666. */
  667. void removeFirstMatchingValue (ParameterType valueToRemove)
  668. {
  669. ElementType* const e = data.elements;
  670. for (int i = 0; i < numUsed; ++i)
  671. {
  672. if (valueToRemove == e[i])
  673. {
  674. removeInternal (i);
  675. break;
  676. }
  677. }
  678. }
  679. /** Removes items from the array.
  680. This will remove all occurrences of the given element from the array.
  681. If no such items are found, no action is taken.
  682. @param valueToRemove the object to try to remove
  683. @return how many objects were removed.
  684. @see remove, removeRange, removeIf
  685. */
  686. int removeAllInstancesOf (ParameterType valueToRemove)
  687. {
  688. int numRemoved = 0;
  689. for (int i = numUsed; --i >= 0;)
  690. {
  691. if (valueToRemove == data.elements[i])
  692. {
  693. removeInternal (i);
  694. ++numRemoved;
  695. }
  696. }
  697. return numRemoved;
  698. }
  699. /** Removes items from the array.
  700. This will remove all objects from the array that match a condition.
  701. If no such items are found, no action is taken.
  702. @param predicate the condition when to remove an item. Must be a callable
  703. type that takes an ElementType and returns a bool
  704. @return how many objects were removed.
  705. @see remove, removeRange, removeAllInstancesOf
  706. */
  707. template <typename PredicateType>
  708. int removeIf (PredicateType predicate)
  709. {
  710. int numRemoved = 0;
  711. for (int i = numUsed; --i >= 0;)
  712. {
  713. if (predicate (data.elements[i]) == true)
  714. {
  715. removeInternal (i);
  716. ++numRemoved;
  717. }
  718. }
  719. return numRemoved;
  720. }
  721. /** Removes a range of elements from the array.
  722. This will remove a set of elements, starting from the given index,
  723. and move subsequent elements down to close the gap.
  724. If the range extends beyond the bounds of the array, it will
  725. be safely clipped to the size of the array.
  726. @param startIndex the index of the first element to remove
  727. @param numberToRemove how many elements should be removed
  728. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeIf
  729. */
  730. void removeRange (int startIndex, int numberToRemove)
  731. {
  732. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  733. startIndex = jlimit (0, numUsed, startIndex);
  734. if (endIndex > startIndex)
  735. {
  736. ElementType* const e = data.elements + startIndex;
  737. numberToRemove = endIndex - startIndex;
  738. for (int i = 0; i < numberToRemove; ++i)
  739. e[i].~ElementType();
  740. const int numToShift = numUsed - endIndex;
  741. if (numToShift > 0)
  742. memmove (e, e + numberToRemove, ((size_t) numToShift) * sizeof (ElementType));
  743. numUsed -= numberToRemove;
  744. minimiseStorageAfterRemoval();
  745. }
  746. }
  747. /** Removes the last n elements from the array.
  748. @param howManyToRemove how many elements to remove from the end of the array
  749. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  750. */
  751. void removeLast (int howManyToRemove = 1)
  752. {
  753. if (howManyToRemove > numUsed)
  754. howManyToRemove = numUsed;
  755. for (int i = 1; i <= howManyToRemove; ++i)
  756. data.elements [numUsed - i].~ElementType();
  757. numUsed -= howManyToRemove;
  758. minimiseStorageAfterRemoval();
  759. }
  760. /** Removes any elements which are also in another array.
  761. @param otherArray the other array in which to look for elements to remove
  762. @see removeValuesNotIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  763. */
  764. template <class OtherArrayType>
  765. void removeValuesIn (const OtherArrayType& otherArray)
  766. {
  767. if (this == &otherArray)
  768. {
  769. clear();
  770. }
  771. else
  772. {
  773. if (otherArray.size() > 0)
  774. {
  775. for (int i = numUsed; --i >= 0;)
  776. if (otherArray.contains (data.elements [i]))
  777. removeInternal (i);
  778. }
  779. }
  780. }
  781. /** Removes any elements which are not found in another array.
  782. Only elements which occur in this other array will be retained.
  783. @param otherArray the array in which to look for elements NOT to remove
  784. @see removeValuesIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  785. */
  786. template <class OtherArrayType>
  787. void removeValuesNotIn (const OtherArrayType& otherArray)
  788. {
  789. if (this != &otherArray)
  790. {
  791. if (otherArray.size() <= 0)
  792. {
  793. clear();
  794. }
  795. else
  796. {
  797. for (int i = numUsed; --i >= 0;)
  798. if (! otherArray.contains (data.elements [i]))
  799. removeInternal (i);
  800. }
  801. }
  802. }
  803. /** Swaps over two elements in the array.
  804. This swaps over the elements found at the two indexes passed in.
  805. If either index is out-of-range, this method will do nothing.
  806. @param index1 index of one of the elements to swap
  807. @param index2 index of the other element to swap
  808. */
  809. void swap (const int index1,
  810. const int index2)
  811. {
  812. if (isPositiveAndBelow (index1, numUsed)
  813. && isPositiveAndBelow (index2, numUsed))
  814. {
  815. std::swap (data.elements [index1],
  816. data.elements [index2]);
  817. }
  818. }
  819. /** Moves one of the values to a different position.
  820. This will move the value to a specified index, shuffling along
  821. any intervening elements as required.
  822. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  823. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  824. @param currentIndex the index of the value to be moved. If this isn't a
  825. valid index, then nothing will be done
  826. @param newIndex the index at which you'd like this value to end up. If this
  827. is less than zero, the value will be moved to the end
  828. of the array
  829. */
  830. void move (const int currentIndex, int newIndex) noexcept
  831. {
  832. if (currentIndex != newIndex)
  833. {
  834. if (isPositiveAndBelow (currentIndex, numUsed))
  835. {
  836. if (! isPositiveAndBelow (newIndex, numUsed))
  837. newIndex = numUsed - 1;
  838. char tempCopy [sizeof (ElementType)];
  839. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  840. if (newIndex > currentIndex)
  841. {
  842. memmove (data.elements + currentIndex,
  843. data.elements + currentIndex + 1,
  844. sizeof (ElementType) * (size_t) (newIndex - currentIndex));
  845. }
  846. else
  847. {
  848. memmove (data.elements + newIndex + 1,
  849. data.elements + newIndex,
  850. sizeof (ElementType) * (size_t) (currentIndex - newIndex));
  851. }
  852. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  853. }
  854. }
  855. }
  856. //==============================================================================
  857. /** Reduces the amount of storage being used by the array.
  858. Arrays typically allocate slightly more storage than they need, and after
  859. removing elements, they may have quite a lot of unused space allocated.
  860. This method will reduce the amount of allocated storage to a minimum.
  861. */
  862. bool minimiseStorageOverheads() noexcept
  863. {
  864. return data.shrinkToNoMoreThan (numUsed);
  865. }
  866. /** Increases the array's internal storage to hold a minimum number of elements.
  867. Calling this before adding a large known number of elements means that
  868. the array won't have to keep dynamically resizing itself as the elements
  869. are added, and it'll therefore be more efficient.
  870. */
  871. bool ensureStorageAllocated (const int minNumElements) noexcept
  872. {
  873. return data.ensureAllocatedSize (minNumElements);
  874. }
  875. //==============================================================================
  876. /** Sorts the array using a default comparison operation.
  877. If the type of your elements isn't supported by the DefaultElementComparator class
  878. then you may need to use the other version of sort, which takes a custom comparator.
  879. */
  880. void sort()
  881. {
  882. DefaultElementComparator<ElementType> comparator;
  883. sort (comparator);
  884. }
  885. /** Sorts the elements in the array.
  886. This will use a comparator object to sort the elements into order. The object
  887. passed must have a method of the form:
  888. @code
  889. int compareElements (ElementType first, ElementType second);
  890. @endcode
  891. ..and this method must return:
  892. - a value of < 0 if the first comes before the second
  893. - a value of 0 if the two objects are equivalent
  894. - a value of > 0 if the second comes before the first
  895. To improve performance, the compareElements() method can be declared as static or const.
  896. @param comparator the comparator to use for comparing elements.
  897. @param retainOrderOfEquivalentItems if this is true, then items
  898. which the comparator says are equivalent will be
  899. kept in the order in which they currently appear
  900. in the array. This is slower to perform, but may
  901. be important in some cases. If it's false, a faster
  902. algorithm is used, but equivalent elements may be
  903. rearranged.
  904. @see addSorted, indexOfSorted, sortArray
  905. */
  906. template <class ElementComparator>
  907. void sort (ElementComparator& comparator,
  908. const bool retainOrderOfEquivalentItems = false)
  909. {
  910. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  911. // avoids getting warning messages about the parameter being unused
  912. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  913. }
  914. private:
  915. //==============================================================================
  916. ArrayAllocationBase <ElementType> data;
  917. int numUsed;
  918. void removeInternal (const int indexToRemove)
  919. {
  920. --numUsed;
  921. ElementType* const e = data.elements + indexToRemove;
  922. e->~ElementType();
  923. const int numberToShift = numUsed - indexToRemove;
  924. if (numberToShift > 0)
  925. memmove (e, e + 1, ((size_t) numberToShift) * sizeof (ElementType));
  926. minimiseStorageAfterRemoval();
  927. }
  928. inline void deleteAllElements() noexcept
  929. {
  930. for (int i = 0; i < numUsed; ++i)
  931. data.elements[i].~ElementType();
  932. }
  933. void minimiseStorageAfterRemoval()
  934. {
  935. if (data.numAllocated > jmax (minimumAllocatedSize, numUsed * 2))
  936. data.shrinkToNoMoreThan (jmax (numUsed, jmax (minimumAllocatedSize, 64 / (int) sizeof (ElementType))));
  937. }
  938. };
  939. }
  940. #endif // WATER_ARRAY_H_INCLUDED