The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

870 lines
32KB

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