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.

856 lines
30KB

  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_REFERENCECOUNTEDARRAY_H_INCLUDED
  21. #define WATER_REFERENCECOUNTEDARRAY_H_INCLUDED
  22. #include "../memory/ReferenceCountedObject.h"
  23. namespace water {
  24. //==============================================================================
  25. /**
  26. Holds a list of objects derived from ReferenceCountedObject, or which implement basic
  27. reference-count handling methods.
  28. The template parameter specifies the class of the object you want to point to - the easiest
  29. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject
  30. or SingleThreadedReferenceCountedObject, but if you need to, you can roll your own reference-countable
  31. class by implementing a set of methods called incReferenceCount(), decReferenceCount(), and
  32. decReferenceCountWithoutDeleting(). See ReferenceCountedObject for examples of how these methods
  33. should behave.
  34. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  35. and takes care of incrementing and decrementing their ref counts when they
  36. are added and removed from the array.
  37. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  38. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  39. @see Array, OwnedArray, StringArray
  40. */
  41. template <class ObjectClass>
  42. class ReferenceCountedArray
  43. {
  44. public:
  45. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  46. //==============================================================================
  47. /** Creates an empty array.
  48. @see ReferenceCountedObject, Array, OwnedArray
  49. */
  50. ReferenceCountedArray() noexcept
  51. : numUsed (0)
  52. {
  53. }
  54. /** Creates a copy of another array */
  55. ReferenceCountedArray (const ReferenceCountedArray& other) noexcept
  56. {
  57. numUsed = other.size();
  58. data.setAllocatedSize (numUsed);
  59. memcpy (data.elements, other.getRawDataPointer(), (size_t) numUsed * sizeof (ObjectClass*));
  60. for (int i = numUsed; --i >= 0;)
  61. if (ObjectClass* o = data.elements[i])
  62. o->incReferenceCount();
  63. }
  64. /** Creates a copy of another array */
  65. template <class OtherObjectClass>
  66. ReferenceCountedArray (const ReferenceCountedArray<OtherObjectClass>& other) noexcept
  67. {
  68. numUsed = other.size();
  69. data.setAllocatedSize (numUsed);
  70. memcpy (data.elements, other.getRawDataPointer(), numUsed * sizeof (ObjectClass*));
  71. for (int i = numUsed; --i >= 0;)
  72. if (ObjectClass* o = data.elements[i])
  73. o->incReferenceCount();
  74. }
  75. /** Copies another array into this one.
  76. Any existing objects in this array will first be released.
  77. */
  78. ReferenceCountedArray& operator= (const ReferenceCountedArray& other) noexcept
  79. {
  80. ReferenceCountedArray otherCopy (other);
  81. swapWith (otherCopy);
  82. return *this;
  83. }
  84. /** Copies another array into this one.
  85. Any existing objects in this array will first be released.
  86. */
  87. template <class OtherObjectClass>
  88. ReferenceCountedArray<ObjectClass>& operator= (const ReferenceCountedArray<OtherObjectClass>& other) noexcept
  89. {
  90. ReferenceCountedArray<ObjectClass> otherCopy (other);
  91. swapWith (otherCopy);
  92. return *this;
  93. }
  94. /** Destructor.
  95. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  96. */
  97. ~ReferenceCountedArray()
  98. {
  99. releaseAllObjects();
  100. }
  101. //==============================================================================
  102. /** Removes all objects from the array.
  103. Any objects in the array that whose reference counts drop to zero will be deleted.
  104. */
  105. void clear()
  106. {
  107. releaseAllObjects();
  108. data.setAllocatedSize (0);
  109. }
  110. /** Removes all objects from the array without freeing the array's allocated storage.
  111. Any objects in the array that whose reference counts drop to zero will be deleted.
  112. @see clear
  113. */
  114. void clearQuick()
  115. {
  116. releaseAllObjects();
  117. }
  118. /** Returns the current number of objects in the array. */
  119. inline int size() const noexcept
  120. {
  121. return numUsed;
  122. }
  123. /** Returns true if the array is empty, false otherwise. */
  124. inline bool isEmpty() const noexcept
  125. {
  126. return size() == 0;
  127. }
  128. /** Returns a pointer to the object at this index in the array.
  129. If the index is out-of-range, this will return a null pointer, (and
  130. it could be null anyway, because it's ok for the array to hold null
  131. pointers as well as objects).
  132. @see getUnchecked
  133. */
  134. inline ObjectClassPtr operator[] (const int index) const noexcept
  135. {
  136. return getObjectPointer (index);
  137. }
  138. /** Returns a pointer to the object at this index in the array, without checking
  139. whether the index is in-range.
  140. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  141. it can be used when you're sure the index is always going to be legal.
  142. */
  143. inline ObjectClassPtr getUnchecked (const int index) const noexcept
  144. {
  145. return getObjectPointerUnchecked (index);
  146. }
  147. /** Returns a raw pointer to the object at this index in the array.
  148. If the index is out-of-range, this will return a null pointer, (and
  149. it could be null anyway, because it's ok for the array to hold null
  150. pointers as well as objects).
  151. @see getUnchecked
  152. */
  153. inline ObjectClass* getObjectPointer (const int index) const noexcept
  154. {
  155. if (isPositiveAndBelow (index, numUsed))
  156. {
  157. wassert (data.elements != nullptr);
  158. return data.elements [index];
  159. }
  160. return ObjectClassPtr();
  161. }
  162. /** Returns a raw pointer to the object at this index in the array, without checking
  163. whether the index is in-range.
  164. */
  165. inline ObjectClass* getObjectPointerUnchecked (const int index) const noexcept
  166. {
  167. wassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  168. return data.elements [index];
  169. }
  170. /** Returns a pointer to the first object in the array.
  171. This will return a null pointer if the array's empty.
  172. @see getLast
  173. */
  174. inline ObjectClassPtr getFirst() const noexcept
  175. {
  176. if (numUsed > 0)
  177. {
  178. wassert (data.elements != nullptr);
  179. return data.elements [0];
  180. }
  181. return ObjectClassPtr();
  182. }
  183. /** Returns a pointer to the last object in the array.
  184. This will return a null pointer if the array's empty.
  185. @see getFirst
  186. */
  187. inline ObjectClassPtr getLast() const noexcept
  188. {
  189. if (numUsed > 0)
  190. {
  191. wassert (data.elements != nullptr);
  192. return data.elements [numUsed - 1];
  193. }
  194. return ObjectClassPtr();
  195. }
  196. /** Returns a pointer to the actual array data.
  197. This pointer will only be valid until the next time a non-const method
  198. is called on the array.
  199. */
  200. inline ObjectClass** getRawDataPointer() const noexcept
  201. {
  202. return data.elements;
  203. }
  204. //==============================================================================
  205. /** Returns a pointer to the first element in the array.
  206. This method is provided for compatibility with standard C++ iteration mechanisms.
  207. */
  208. inline ObjectClass** begin() const noexcept
  209. {
  210. return data.elements;
  211. }
  212. /** Returns a pointer to the element which follows the last element in the array.
  213. This method is provided for compatibility with standard C++ iteration mechanisms.
  214. */
  215. inline ObjectClass** end() const noexcept
  216. {
  217. return data.elements + numUsed;
  218. }
  219. //==============================================================================
  220. /** Finds the index of the first occurrence of an object in the array.
  221. @param objectToLookFor the object to look for
  222. @returns the index at which the object was found, or -1 if it's not found
  223. */
  224. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  225. {
  226. ObjectClass** e = data.elements.getData();
  227. ObjectClass** const endPointer = e + numUsed;
  228. while (e != endPointer)
  229. {
  230. if (objectToLookFor == *e)
  231. return static_cast<int> (e - data.elements.getData());
  232. ++e;
  233. }
  234. return -1;
  235. }
  236. /** Returns true if the array contains a specified object.
  237. @param objectToLookFor the object to look for
  238. @returns true if the object is in the array
  239. */
  240. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  241. {
  242. ObjectClass** e = data.elements.getData();
  243. ObjectClass** const endPointer = e + numUsed;
  244. while (e != endPointer)
  245. {
  246. if (objectToLookFor == *e)
  247. return true;
  248. ++e;
  249. }
  250. return false;
  251. }
  252. /** Appends a new object to the end of the array.
  253. This will increase the new object's reference count.
  254. @param newObject the new object to add to the array
  255. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  256. */
  257. ObjectClass* add (ObjectClass* const newObject) noexcept
  258. {
  259. data.ensureAllocatedSize (numUsed + 1);
  260. wassert (data.elements != nullptr);
  261. data.elements [numUsed++] = newObject;
  262. if (newObject != nullptr)
  263. newObject->incReferenceCount();
  264. return newObject;
  265. }
  266. /** Inserts a new object into the array at the given index.
  267. If the index is less than 0 or greater than the size of the array, the
  268. element will be added to the end of the array.
  269. Otherwise, it will be inserted into the array, moving all the later elements
  270. along to make room.
  271. This will increase the new object's reference count.
  272. @param indexToInsertAt the index at which the new element should be inserted
  273. @param newObject the new object to add to the array
  274. @see add, addSorted, addIfNotAlreadyThere, set
  275. */
  276. ObjectClass* insert (int indexToInsertAt,
  277. ObjectClass* const newObject) noexcept
  278. {
  279. if (indexToInsertAt < 0)
  280. return add (newObject);
  281. if (indexToInsertAt > numUsed)
  282. indexToInsertAt = numUsed;
  283. data.ensureAllocatedSize (numUsed + 1);
  284. wassert (data.elements != nullptr);
  285. ObjectClass** const e = data.elements + indexToInsertAt;
  286. const int numToMove = numUsed - indexToInsertAt;
  287. if (numToMove > 0)
  288. memmove (e + 1, e, sizeof (ObjectClass*) * (size_t) numToMove);
  289. *e = newObject;
  290. if (newObject != nullptr)
  291. newObject->incReferenceCount();
  292. ++numUsed;
  293. return newObject;
  294. }
  295. /** Appends a new object at the end of the array as long as the array doesn't
  296. already contain it.
  297. If the array already contains a matching object, nothing will be done.
  298. @param newObject the new object to add to the array
  299. @returns true if the object has been added, false otherwise
  300. */
  301. bool addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  302. {
  303. if (contains (newObject))
  304. return false;
  305. add (newObject);
  306. return true;
  307. }
  308. /** Replaces an object in the array with a different one.
  309. If the index is less than zero, this method does nothing.
  310. If the index is beyond the end of the array, the new object is added to the end of the array.
  311. The object being added has its reference count increased, and if it's replacing
  312. another object, then that one has its reference count decreased, and may be deleted.
  313. @param indexToChange the index whose value you want to change
  314. @param newObject the new value to set for this index.
  315. @see add, insert, remove
  316. */
  317. void set (const int indexToChange,
  318. ObjectClass* const newObject)
  319. {
  320. if (indexToChange >= 0)
  321. {
  322. if (newObject != nullptr)
  323. newObject->incReferenceCount();
  324. if (indexToChange < numUsed)
  325. {
  326. if (ObjectClass* o = data.elements [indexToChange])
  327. releaseObject (o);
  328. data.elements [indexToChange] = newObject;
  329. }
  330. else
  331. {
  332. data.ensureAllocatedSize (numUsed + 1);
  333. wassert (data.elements != nullptr);
  334. data.elements [numUsed++] = newObject;
  335. }
  336. }
  337. }
  338. /** Adds elements from another array to the end of this array.
  339. @param arrayToAddFrom the array from which to copy the elements
  340. @param startIndex the first element of the other array to start copying from
  341. @param numElementsToAdd how many elements to add from the other array. If this
  342. value is negative or greater than the number of available elements,
  343. all available elements will be copied.
  344. @see add
  345. */
  346. void addArray (const ReferenceCountedArray<ObjectClass>& arrayToAddFrom,
  347. int startIndex = 0,
  348. int numElementsToAdd = -1) noexcept
  349. {
  350. if (startIndex < 0)
  351. {
  352. wassertfalse;
  353. startIndex = 0;
  354. }
  355. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  356. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  357. if (numElementsToAdd > 0)
  358. {
  359. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  360. while (--numElementsToAdd >= 0)
  361. add (arrayToAddFrom.getUnchecked (startIndex++));
  362. }
  363. }
  364. /** Inserts a new object into the array assuming that the array is sorted.
  365. This will use a comparator to find the position at which the new object
  366. should go. If the array isn't sorted, the behaviour of this
  367. method will be unpredictable.
  368. @param comparator the comparator object to use to compare the elements - see the
  369. sort() method for details about this object's form
  370. @param newObject the new object to insert to the array
  371. @returns the index at which the new object was added
  372. @see add, sort
  373. */
  374. template <class ElementComparator>
  375. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  376. {
  377. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  378. insert (index, newObject);
  379. return index;
  380. }
  381. /** Inserts or replaces an object in the array, assuming it is sorted.
  382. This is similar to addSorted, but if a matching element already exists, then it will be
  383. replaced by the new one, rather than the new one being added as well.
  384. */
  385. template <class ElementComparator>
  386. void addOrReplaceSorted (ElementComparator& comparator,
  387. ObjectClass* newObject) noexcept
  388. {
  389. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  390. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  391. set (index - 1, newObject); // replace an existing object that matches
  392. else
  393. insert (index, newObject); // no match, so insert the new one
  394. }
  395. /** Finds the index of an object in the array, assuming that the array is sorted.
  396. This will use a comparator to do a binary-chop to find the index of the given
  397. element, if it exists. If the array isn't sorted, the behaviour of this
  398. method will be unpredictable.
  399. @param comparator the comparator to use to compare the elements - see the sort()
  400. method for details about the form this object should take
  401. @param objectToLookFor the object to search for
  402. @returns the index of the element, or -1 if it's not found
  403. @see addSorted, sort
  404. */
  405. template <class ElementComparator>
  406. int indexOfSorted (ElementComparator& comparator,
  407. const ObjectClass* const objectToLookFor) const noexcept
  408. {
  409. ignoreUnused (comparator);
  410. int s = 0, e = numUsed;
  411. while (s < e)
  412. {
  413. if (comparator.compareElements (objectToLookFor, data.elements [s]) == 0)
  414. return s;
  415. const int halfway = (s + e) / 2;
  416. if (halfway == s)
  417. break;
  418. if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  419. s = halfway;
  420. else
  421. e = halfway;
  422. }
  423. return -1;
  424. }
  425. //==============================================================================
  426. /** Removes an object from the array.
  427. This will remove the object at a given index and move back all the
  428. subsequent objects to close the gap.
  429. If the index passed in is out-of-range, nothing will happen.
  430. The object that is removed will have its reference count decreased,
  431. and may be deleted if not referenced from elsewhere.
  432. @param indexToRemove the index of the element to remove
  433. @see removeObject, removeRange
  434. */
  435. void remove (const int indexToRemove)
  436. {
  437. if (isPositiveAndBelow (indexToRemove, numUsed))
  438. {
  439. ObjectClass** const e = data.elements + indexToRemove;
  440. if (ObjectClass* o = *e)
  441. releaseObject (o);
  442. --numUsed;
  443. const int numberToShift = numUsed - indexToRemove;
  444. if (numberToShift > 0)
  445. std::memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numberToShift);
  446. if ((numUsed << 1) < static_cast<int>(data.numAllocated))
  447. minimiseStorageOverheads();
  448. }
  449. }
  450. /** Removes and returns an object from the array.
  451. This will remove the object at a given index and return it, moving back all
  452. the subsequent objects to close the gap. If the index passed in is out-of-range,
  453. nothing will happen and a null pointer will be returned.
  454. @param indexToRemove the index of the element to remove
  455. @see remove, removeObject, removeRange
  456. */
  457. ObjectClassPtr removeAndReturn (const int indexToRemove)
  458. {
  459. ObjectClassPtr removedItem;
  460. if (isPositiveAndBelow (indexToRemove, numUsed))
  461. {
  462. ObjectClass** const e = data.elements + indexToRemove;
  463. if (ObjectClass* o = *e)
  464. {
  465. removedItem = o;
  466. releaseObject (o);
  467. }
  468. --numUsed;
  469. const int numberToShift = numUsed - indexToRemove;
  470. if (numberToShift > 0)
  471. memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numberToShift);
  472. if ((numUsed << 1) < data.numAllocated)
  473. minimiseStorageOverheads();
  474. }
  475. return removedItem;
  476. }
  477. /** Removes the first occurrence of a specified object from the array.
  478. If the item isn't found, no action is taken. If it is found, it is
  479. removed and has its reference count decreased.
  480. @param objectToRemove the object to try to remove
  481. @see remove, removeRange
  482. */
  483. void removeObject (ObjectClass* const objectToRemove)
  484. {
  485. remove (indexOf (objectToRemove));
  486. }
  487. /** Removes a range of objects from the array.
  488. This will remove a set of objects, starting from the given index,
  489. and move any subsequent elements down to close the gap.
  490. If the range extends beyond the bounds of the array, it will
  491. be safely clipped to the size of the array.
  492. The objects that are removed will have their reference counts decreased,
  493. and may be deleted if not referenced from elsewhere.
  494. @param startIndex the index of the first object to remove
  495. @param numberToRemove how many objects should be removed
  496. @see remove, removeObject
  497. */
  498. void removeRange (const int startIndex,
  499. const int numberToRemove)
  500. {
  501. const int start = jlimit (0, numUsed, startIndex);
  502. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  503. if (endIndex > start)
  504. {
  505. int i;
  506. for (i = start; i < endIndex; ++i)
  507. {
  508. if (ObjectClass* o = data.elements[i])
  509. {
  510. releaseObject (o);
  511. data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  512. }
  513. }
  514. const int rangeSize = endIndex - start;
  515. ObjectClass** e = data.elements + start;
  516. i = numUsed - endIndex;
  517. numUsed -= rangeSize;
  518. while (--i >= 0)
  519. {
  520. *e = e [rangeSize];
  521. ++e;
  522. }
  523. if ((numUsed << 1) < data.numAllocated)
  524. minimiseStorageOverheads();
  525. }
  526. }
  527. /** Removes the last n objects from the array.
  528. The objects that are removed will have their reference counts decreased,
  529. and may be deleted if not referenced from elsewhere.
  530. @param howManyToRemove how many objects to remove from the end of the array
  531. @see remove, removeObject, removeRange
  532. */
  533. void removeLast (int howManyToRemove = 1)
  534. {
  535. if (howManyToRemove > numUsed)
  536. howManyToRemove = numUsed;
  537. while (--howManyToRemove >= 0)
  538. remove (numUsed - 1);
  539. }
  540. /** Swaps a pair of objects in the array.
  541. If either of the indexes passed in is out-of-range, nothing will happen,
  542. otherwise the two objects at these positions will be exchanged.
  543. */
  544. void swap (const int index1,
  545. const int index2) noexcept
  546. {
  547. if (isPositiveAndBelow (index1, numUsed)
  548. && isPositiveAndBelow (index2, numUsed))
  549. {
  550. std::swap (data.elements [index1],
  551. data.elements [index2]);
  552. }
  553. }
  554. /** Moves one of the objects to a different position.
  555. This will move the object to a specified index, shuffling along
  556. any intervening elements as required.
  557. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  558. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  559. @param currentIndex the index of the object to be moved. If this isn't a
  560. valid index, then nothing will be done
  561. @param newIndex the index at which you'd like this object to end up. If this
  562. is less than zero, it will be moved to the end of the array
  563. */
  564. void move (const int currentIndex,
  565. int newIndex) noexcept
  566. {
  567. if (currentIndex != newIndex)
  568. {
  569. if (isPositiveAndBelow (currentIndex, numUsed))
  570. {
  571. if (! isPositiveAndBelow (newIndex, numUsed))
  572. newIndex = numUsed - 1;
  573. ObjectClass* const value = data.elements [currentIndex];
  574. if (newIndex > currentIndex)
  575. {
  576. memmove (data.elements + currentIndex,
  577. data.elements + currentIndex + 1,
  578. sizeof (ObjectClass*) * (size_t) (newIndex - currentIndex));
  579. }
  580. else
  581. {
  582. memmove (data.elements + newIndex + 1,
  583. data.elements + newIndex,
  584. sizeof (ObjectClass*) * (size_t) (currentIndex - newIndex));
  585. }
  586. data.elements [newIndex] = value;
  587. }
  588. }
  589. }
  590. //==============================================================================
  591. /** This swaps the contents of this array with those of another array.
  592. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  593. because it just swaps their internal pointers.
  594. */
  595. template <class OtherArrayType>
  596. void swapWith (OtherArrayType& otherArray) noexcept
  597. {
  598. data.swapWith (otherArray.data);
  599. std::swap (numUsed, otherArray.numUsed);
  600. }
  601. //==============================================================================
  602. /** Compares this array to another one.
  603. @returns true only if the other array contains the same objects in the same order
  604. */
  605. bool operator== (const ReferenceCountedArray& other) const noexcept
  606. {
  607. if (numUsed != other.numUsed)
  608. return false;
  609. for (int i = numUsed; --i >= 0;)
  610. if (data.elements [i] != other.data.elements [i])
  611. return false;
  612. return true;
  613. }
  614. /** Compares this array to another one.
  615. @see operator==
  616. */
  617. bool operator!= (const ReferenceCountedArray<ObjectClass>& other) const noexcept
  618. {
  619. return ! operator== (other);
  620. }
  621. //==============================================================================
  622. /** Sorts the elements in the array.
  623. This will use a comparator object to sort the elements into order. The object
  624. passed must have a method of the form:
  625. @code
  626. int compareElements (ElementType first, ElementType second);
  627. @endcode
  628. ..and this method must return:
  629. - a value of < 0 if the first comes before the second
  630. - a value of 0 if the two objects are equivalent
  631. - a value of > 0 if the second comes before the first
  632. To improve performance, the compareElements() method can be declared as static or const.
  633. @param comparator the comparator to use for comparing elements.
  634. @param retainOrderOfEquivalentItems if this is true, then items
  635. which the comparator says are equivalent will be
  636. kept in the order in which they currently appear
  637. in the array. This is slower to perform, but may
  638. be important in some cases. If it's false, a faster
  639. algorithm is used, but equivalent elements may be
  640. rearranged.
  641. @see sortArray
  642. */
  643. template <class ElementComparator>
  644. void sort (ElementComparator& comparator,
  645. const bool retainOrderOfEquivalentItems = false) const noexcept
  646. {
  647. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  648. // avoids getting warning messages about the parameter being unused
  649. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  650. }
  651. //==============================================================================
  652. /** Reduces the amount of storage being used by the array.
  653. Arrays typically allocate slightly more storage than they need, and after
  654. removing elements, they may have quite a lot of unused space allocated.
  655. This method will reduce the amount of allocated storage to a minimum.
  656. */
  657. void minimiseStorageOverheads() noexcept
  658. {
  659. data.shrinkToNoMoreThan (numUsed);
  660. }
  661. /** Increases the array's internal storage to hold a minimum number of elements.
  662. Calling this before adding a large known number of elements means that
  663. the array won't have to keep dynamically resizing itself as the elements
  664. are added, and it'll therefore be more efficient.
  665. */
  666. void ensureStorageAllocated (const int minNumElements)
  667. {
  668. data.ensureAllocatedSize (minNumElements);
  669. }
  670. private:
  671. //==============================================================================
  672. ArrayAllocationBase <ObjectClass*> data;
  673. int numUsed;
  674. void releaseAllObjects()
  675. {
  676. while (numUsed > 0)
  677. if (ObjectClass* o = data.elements [--numUsed])
  678. releaseObject (o);
  679. wassert (numUsed == 0);
  680. }
  681. static void releaseObject (ObjectClass* o)
  682. {
  683. if (o->decReferenceCountWithoutDeleting())
  684. delete o;
  685. }
  686. };
  687. }
  688. #endif // WATER_REFERENCECOUNTEDARRAY_H_INCLUDED