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.

857 lines
30KB

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