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.

1113 lines
39KB

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