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.

908 lines
33KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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() noexcept
  203. {
  204. return values.begin();
  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* const* begin() const noexcept
  210. {
  211. return values.begin();
  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() noexcept
  217. {
  218. return values.end();
  219. }
  220. /** Returns a pointer to the element which follows the last element in the array.
  221. This method is provided for compatibility with standard C++ iteration mechanisms.
  222. */
  223. inline ObjectClass* const* end() const noexcept
  224. {
  225. return values.end();
  226. }
  227. /** Returns a pointer to the first element in the array.
  228. This method is provided for compatibility with the standard C++ containers.
  229. */
  230. inline ObjectClass** data() noexcept
  231. {
  232. return begin();
  233. }
  234. /** Returns a pointer to the first element in the array.
  235. This method is provided for compatibility with the standard C++ containers.
  236. */
  237. inline ObjectClass* const* data() const noexcept
  238. {
  239. return begin();
  240. }
  241. //==============================================================================
  242. /** Finds the index of the first occurrence of an object in the array.
  243. @param objectToLookFor the object to look for
  244. @returns the index at which the object was found, or -1 if it's not found
  245. */
  246. int indexOf (const ObjectClass* objectToLookFor) const noexcept
  247. {
  248. const ScopedLockType lock (getLock());
  249. auto* e = values.begin();
  250. auto* endPointer = values.end();
  251. while (e != endPointer)
  252. {
  253. if (objectToLookFor == *e)
  254. return static_cast<int> (e - values.begin());
  255. ++e;
  256. }
  257. return -1;
  258. }
  259. /** Finds the index of the first occurrence of an object in the array.
  260. @param objectToLookFor the object to look for
  261. @returns the index at which the object was found, or -1 if it's not found
  262. */
  263. int indexOf (const ObjectClassPtr& objectToLookFor) const noexcept { return indexOf (objectToLookFor.get()); }
  264. /** Returns true if the array contains a specified object.
  265. @param objectToLookFor the object to look for
  266. @returns true if the object is in the array
  267. */
  268. bool contains (const ObjectClass* objectToLookFor) const noexcept
  269. {
  270. const ScopedLockType lock (getLock());
  271. auto* e = values.begin();
  272. auto* endPointer = values.end();
  273. while (e != endPointer)
  274. {
  275. if (objectToLookFor == *e)
  276. return true;
  277. ++e;
  278. }
  279. return false;
  280. }
  281. /** Returns true if the array contains a specified object.
  282. @param objectToLookFor the object to look for
  283. @returns true if the object is in the array
  284. */
  285. bool contains (const ObjectClassPtr& objectToLookFor) const noexcept { return contains (objectToLookFor.get()); }
  286. /** Appends a new object to the end of the array.
  287. This will increase the new object's reference count.
  288. @param newObject the new object to add to the array
  289. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  290. */
  291. ObjectClass* add (ObjectClass* newObject)
  292. {
  293. const ScopedLockType lock (getLock());
  294. values.add (newObject);
  295. if (newObject != nullptr)
  296. newObject->incReferenceCount();
  297. return newObject;
  298. }
  299. /** Appends a new object to the end of the array.
  300. This will increase the new object's reference count.
  301. @param newObject the new object to add to the array
  302. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  303. */
  304. ObjectClass* add (const ObjectClassPtr& newObject) { return add (newObject.get()); }
  305. /** Inserts a new object into the array at the given index.
  306. If the index is less than 0 or greater than the size of the array, the
  307. element will be added to the end of the array.
  308. Otherwise, it will be inserted into the array, moving all the later elements
  309. along to make room.
  310. This will increase the new object's reference count.
  311. @param indexToInsertAt the index at which the new element should be inserted
  312. @param newObject the new object to add to the array
  313. @see add, addSorted, addIfNotAlreadyThere, set
  314. */
  315. ObjectClass* insert (int indexToInsertAt, ObjectClass* newObject)
  316. {
  317. values.insert (indexToInsertAt, newObject, 1);
  318. if (newObject != nullptr)
  319. newObject->incReferenceCount();
  320. return newObject;
  321. }
  322. /** Inserts a new object into the array at the given index.
  323. If the index is less than 0 or greater than the size of the array, the
  324. element will be added to the end of the array.
  325. Otherwise, it will be inserted into the array, moving all the later elements
  326. along to make room.
  327. This will increase the new object's reference count.
  328. @param indexToInsertAt the index at which the new element should be inserted
  329. @param newObject the new object to add to the array
  330. @see add, addSorted, addIfNotAlreadyThere, set
  331. */
  332. ObjectClass* insert (int indexToInsertAt, const ObjectClassPtr& newObject) { return insert (indexToInsertAt, newObject.get()); }
  333. /** Appends a new object at the end of the array as long as the array doesn't
  334. already contain it.
  335. If the array already contains a matching object, nothing will be done.
  336. @param newObject the new object to add to the array
  337. @returns true if the object has been added, false otherwise
  338. */
  339. bool addIfNotAlreadyThere (ObjectClass* newObject)
  340. {
  341. const ScopedLockType lock (getLock());
  342. if (contains (newObject))
  343. return false;
  344. add (newObject);
  345. return true;
  346. }
  347. /** Appends a new object at the end of the array as long as the array doesn't
  348. already contain it.
  349. If the array already contains a matching object, nothing will be done.
  350. @param newObject the new object to add to the array
  351. @returns true if the object has been added, false otherwise
  352. */
  353. bool addIfNotAlreadyThere (const ObjectClassPtr& newObject) { return addIfNotAlreadyThere (newObject.get()); }
  354. /** Replaces an object in the array with a different one.
  355. If the index is less than zero, this method does nothing.
  356. If the index is beyond the end of the array, the new object is added to the end of the array.
  357. The object being added has its reference count increased, and if it's replacing
  358. another object, then that one has its reference count decreased, and may be deleted.
  359. @param indexToChange the index whose value you want to change
  360. @param newObject the new value to set for this index.
  361. @see add, insert, remove
  362. */
  363. void set (int indexToChange, ObjectClass* newObject)
  364. {
  365. if (indexToChange >= 0)
  366. {
  367. const ScopedLockType lock (getLock());
  368. if (newObject != nullptr)
  369. newObject->incReferenceCount();
  370. if (indexToChange < values.size())
  371. {
  372. auto* e = values[indexToChange];
  373. values[indexToChange] = newObject;
  374. releaseObject (e);
  375. }
  376. else
  377. {
  378. values.add (newObject);
  379. }
  380. }
  381. }
  382. /** Replaces an object in the array with a different one.
  383. If the index is less than zero, this method does nothing.
  384. If the index is beyond the end of the array, the new object is added to the end of the array.
  385. The object being added has its reference count increased, and if it's replacing
  386. another object, then that one has its reference count decreased, and may be deleted.
  387. @param indexToChange the index whose value you want to change
  388. @param newObject the new value to set for this index.
  389. @see add, insert, remove
  390. */
  391. void set (int indexToChange, const ObjectClassPtr& newObject) { set (indexToChange, newObject.get()); }
  392. /** Adds elements from another array to the end of this array.
  393. @param arrayToAddFrom the array from which to copy the elements
  394. @param startIndex the first element of the other array to start copying from
  395. @param numElementsToAdd how many elements to add from the other array. If this
  396. value is negative or greater than the number of available elements,
  397. all available elements will be copied.
  398. @see add
  399. */
  400. void addArray (const ReferenceCountedArray& arrayToAddFrom,
  401. int startIndex = 0,
  402. int numElementsToAdd = -1) noexcept
  403. {
  404. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  405. {
  406. const ScopedLockType lock2 (getLock());
  407. auto numElementsAdded = values.addArray (arrayToAddFrom.values, startIndex, numElementsToAdd);
  408. auto** e = values.end();
  409. for (int i = 0; i < numElementsAdded; ++i)
  410. (*(--e))->incReferenceCount();
  411. }
  412. }
  413. /** Inserts a new object into the array assuming that the array is sorted.
  414. This will use a comparator to find the position at which the new object
  415. should go. If the array isn't sorted, the behaviour of this
  416. method will be unpredictable.
  417. @param comparator the comparator object to use to compare the elements - see the
  418. sort() method for details about this object's form
  419. @param newObject the new object to insert to the array
  420. @returns the index at which the new object was added
  421. @see add, sort
  422. */
  423. template <class ElementComparator>
  424. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  425. {
  426. const ScopedLockType lock (getLock());
  427. auto index = findInsertIndexInSortedArray (comparator, values.begin(), newObject, 0, values.size());
  428. insert (index, newObject);
  429. return index;
  430. }
  431. /** Inserts or replaces an object in the array, assuming it is sorted.
  432. This is similar to addSorted, but if a matching element already exists, then it will be
  433. replaced by the new one, rather than the new one being added as well.
  434. */
  435. template <class ElementComparator>
  436. void addOrReplaceSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  437. {
  438. const ScopedLockType lock (getLock());
  439. auto index = findInsertIndexInSortedArray (comparator, values.begin(), newObject, 0, values.size());
  440. if (index > 0 && comparator.compareElements (newObject, values[index - 1]) == 0)
  441. set (index - 1, newObject); // replace an existing object that matches
  442. else
  443. insert (index, newObject); // no match, so insert the new one
  444. }
  445. /** Finds the index of an object in the array, assuming that the array is sorted.
  446. This will use a comparator to do a binary-chop to find the index of the given
  447. element, if it exists. If the array isn't sorted, the behaviour of this
  448. method will be unpredictable.
  449. @param comparator the comparator to use to compare the elements - see the sort()
  450. method for details about the form this object should take
  451. @param objectToLookFor the object to search for
  452. @returns the index of the element, or -1 if it's not found
  453. @see addSorted, sort
  454. */
  455. template <class ElementComparator>
  456. int indexOfSorted (ElementComparator& comparator,
  457. const ObjectClass* objectToLookFor) const noexcept
  458. {
  459. ignoreUnused (comparator);
  460. const ScopedLockType lock (getLock());
  461. int s = 0, e = values.size();
  462. while (s < e)
  463. {
  464. if (comparator.compareElements (objectToLookFor, values[s]) == 0)
  465. return s;
  466. auto halfway = (s + e) / 2;
  467. if (halfway == s)
  468. break;
  469. if (comparator.compareElements (objectToLookFor, values[halfway]) >= 0)
  470. s = halfway;
  471. else
  472. e = halfway;
  473. }
  474. return -1;
  475. }
  476. //==============================================================================
  477. /** Removes an object from the array.
  478. This will remove the object at a given index and move back all the
  479. subsequent objects to close the gap.
  480. If the index passed in is out-of-range, nothing will happen.
  481. The object that is removed will have its reference count decreased,
  482. and may be deleted if not referenced from elsewhere.
  483. @param indexToRemove the index of the element to remove
  484. @see removeObject, removeRange
  485. */
  486. void remove (int indexToRemove)
  487. {
  488. const ScopedLockType lock (getLock());
  489. if (isPositiveAndBelow (indexToRemove, values.size()))
  490. {
  491. auto* e = *(values.begin() + indexToRemove);
  492. values.removeElements (indexToRemove, 1);
  493. releaseObject (e);
  494. if ((values.size() << 1) < values.capacity())
  495. minimiseStorageOverheads();
  496. }
  497. }
  498. /** Removes and returns an object from the array.
  499. This will remove the object at a given index and return it, moving back all
  500. the subsequent objects to close the gap. If the index passed in is out-of-range,
  501. nothing will happen and a null pointer will be returned.
  502. @param indexToRemove the index of the element to remove
  503. @see remove, removeObject, removeRange
  504. */
  505. ObjectClassPtr removeAndReturn (int indexToRemove)
  506. {
  507. ObjectClassPtr removedItem;
  508. const ScopedLockType lock (getLock());
  509. if (isPositiveAndBelow (indexToRemove, values.size()))
  510. {
  511. auto* e = *(values.begin() + indexToRemove);
  512. removedItem = e;
  513. values.removeElements (indexToRemove, 1);
  514. releaseObject (e);
  515. if ((values.size() << 1) < values.capacity())
  516. minimiseStorageOverheads();
  517. }
  518. return removedItem;
  519. }
  520. /** Removes the first occurrence of a specified object from the array.
  521. If the item isn't found, no action is taken. If it is found, it is
  522. removed and has its reference count decreased.
  523. @param objectToRemove the object to try to remove
  524. @see remove, removeRange
  525. */
  526. void removeObject (ObjectClass* objectToRemove)
  527. {
  528. const ScopedLockType lock (getLock());
  529. remove (indexOf (objectToRemove));
  530. }
  531. /** Removes the first occurrence of a specified object from the array.
  532. If the item isn't found, no action is taken. If it is found, it is
  533. removed and has its reference count decreased.
  534. @param objectToRemove the object to try to remove
  535. @see remove, removeRange
  536. */
  537. void removeObject (const ObjectClassPtr& objectToRemove) { removeObject (objectToRemove.get()); }
  538. /** Removes a range of objects from the array.
  539. This will remove a set of objects, starting from the given index,
  540. and move any subsequent elements down to close the gap.
  541. If the range extends beyond the bounds of the array, it will
  542. be safely clipped to the size of the array.
  543. The objects that are removed will have their reference counts decreased,
  544. and may be deleted if not referenced from elsewhere.
  545. @param startIndex the index of the first object to remove
  546. @param numberToRemove how many objects should be removed
  547. @see remove, removeObject
  548. */
  549. void removeRange (int startIndex,
  550. int numberToRemove)
  551. {
  552. const ScopedLockType lock (getLock());
  553. startIndex = jlimit (0, values.size(), startIndex);
  554. auto endIndex = jlimit (0, values.size(), startIndex + numberToRemove);
  555. numberToRemove = endIndex - startIndex;
  556. if (numberToRemove > 0)
  557. {
  558. Array<ObjectClass*> objectsToRemove;
  559. objectsToRemove.addArray (values.begin() + startIndex, numberToRemove);
  560. values.removeElements (startIndex, numberToRemove);
  561. for (auto& o : objectsToRemove)
  562. releaseObject (o);
  563. if ((values.size() << 1) < values.capacity())
  564. minimiseStorageOverheads();
  565. }
  566. }
  567. /** Removes the last n objects from the array.
  568. The objects that are removed will have their reference counts decreased,
  569. and may be deleted if not referenced from elsewhere.
  570. @param howManyToRemove how many objects to remove from the end of the array
  571. @see remove, removeObject, removeRange
  572. */
  573. void removeLast (int howManyToRemove = 1)
  574. {
  575. const ScopedLockType lock (getLock());
  576. if (howManyToRemove > values.size())
  577. howManyToRemove = values.size();
  578. while (--howManyToRemove >= 0)
  579. remove (values.size() - 1);
  580. }
  581. /** Swaps a pair of objects in the array.
  582. If either of the indexes passed in is out-of-range, nothing will happen,
  583. otherwise the two objects at these positions will be exchanged.
  584. */
  585. void swap (int index1, int index2) noexcept
  586. {
  587. const ScopedLockType lock (getLock());
  588. if (isPositiveAndBelow (index1, values.size())
  589. && isPositiveAndBelow (index2, values.size()))
  590. {
  591. std::swap (values[index1], values[index2]);
  592. }
  593. }
  594. /** Moves one of the objects to a different position.
  595. This will move the object to a specified index, shuffling along
  596. any intervening elements as required.
  597. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  598. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  599. @param currentIndex the index of the object to be moved. If this isn't a
  600. valid index, then nothing will be done
  601. @param newIndex the index at which you'd like this object to end up. If this
  602. is less than zero, it will be moved to the end of the array
  603. */
  604. void move (int currentIndex, int newIndex) noexcept
  605. {
  606. if (currentIndex != newIndex)
  607. {
  608. const ScopedLockType lock (getLock());
  609. values.move (currentIndex, newIndex);
  610. }
  611. }
  612. //==============================================================================
  613. /** This swaps the contents of this array with those of another array.
  614. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  615. because it just swaps their internal pointers.
  616. */
  617. template <class OtherArrayType>
  618. void swapWith (OtherArrayType& otherArray) noexcept
  619. {
  620. const ScopedLockType lock1 (getLock());
  621. const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
  622. values.swapWith (otherArray.values);
  623. }
  624. //==============================================================================
  625. /** Compares this array to another one.
  626. @returns true only if the other array contains the same objects in the same order
  627. */
  628. bool operator== (const ReferenceCountedArray& other) const noexcept
  629. {
  630. const ScopedLockType lock2 (other.getLock());
  631. const ScopedLockType lock1 (getLock());
  632. return values == other.values;
  633. }
  634. /** Compares this array to another one.
  635. @see operator==
  636. */
  637. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
  638. {
  639. return ! operator== (other);
  640. }
  641. //==============================================================================
  642. /** Sorts the elements in the array.
  643. This will use a comparator object to sort the elements into order. The object
  644. passed must have a method of the form:
  645. @code
  646. int compareElements (ElementType first, ElementType second);
  647. @endcode
  648. ..and this method must return:
  649. - a value of < 0 if the first comes before the second
  650. - a value of 0 if the two objects are equivalent
  651. - a value of > 0 if the second comes before the first
  652. To improve performance, the compareElements() method can be declared as static or const.
  653. @param comparator the comparator to use for comparing elements.
  654. @param retainOrderOfEquivalentItems if this is true, then items
  655. which the comparator says are equivalent will be
  656. kept in the order in which they currently appear
  657. in the array. This is slower to perform, but may
  658. be important in some cases. If it's false, a faster
  659. algorithm is used, but equivalent elements may be
  660. rearranged.
  661. @see sortArray
  662. */
  663. template <class ElementComparator>
  664. void sort (ElementComparator& comparator,
  665. bool retainOrderOfEquivalentItems = false) noexcept
  666. {
  667. // If you pass in an object with a static compareElements() method, this
  668. // avoids getting warning messages about the parameter being unused
  669. ignoreUnused (comparator);
  670. const ScopedLockType lock (getLock());
  671. sortArray (comparator, values.begin(), 0, values.size() - 1, retainOrderOfEquivalentItems);
  672. }
  673. //==============================================================================
  674. /** Reduces the amount of storage being used by the array.
  675. Arrays typically allocate slightly more storage than they need, and after
  676. removing elements, they may have quite a lot of unused space allocated.
  677. This method will reduce the amount of allocated storage to a minimum.
  678. */
  679. void minimiseStorageOverheads() noexcept
  680. {
  681. const ScopedLockType lock (getLock());
  682. values.shrinkToNoMoreThan (values.size());
  683. }
  684. /** Increases the array's internal storage to hold a minimum number of elements.
  685. Calling this before adding a large known number of elements means that
  686. the array won't have to keep dynamically resizing itself as the elements
  687. are added, and it'll therefore be more efficient.
  688. */
  689. void ensureStorageAllocated (const int minNumElements)
  690. {
  691. const ScopedLockType lock (getLock());
  692. values.ensureAllocatedSize (minNumElements);
  693. }
  694. //==============================================================================
  695. /** Returns the CriticalSection that locks this array.
  696. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  697. an object of ScopedLockType as an RAII lock for it.
  698. */
  699. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return values; }
  700. /** Returns the type of scoped lock to use for locking this array */
  701. using ScopedLockType = typename TypeOfCriticalSectionToUse::ScopedLockType;
  702. //==============================================================================
  703. #ifndef DOXYGEN
  704. // Note that the swapWithArray method has been replaced by a more flexible templated version,
  705. // and renamed "swapWith" to be more consistent with the names used in other classes.
  706. JUCE_DEPRECATED_WITH_BODY (void swapWithArray (ReferenceCountedArray& other) noexcept, { swapWith (other); })
  707. #endif
  708. private:
  709. //==============================================================================
  710. ArrayBase<ObjectClass*, TypeOfCriticalSectionToUse> values;
  711. void releaseAllObjects()
  712. {
  713. auto i = values.size();
  714. while (--i >= 0)
  715. {
  716. auto* e = values[i];
  717. values.removeElements (i, 1);
  718. releaseObject (e);
  719. }
  720. }
  721. static void releaseObject (ObjectClass* o)
  722. {
  723. if (o != nullptr && o->decReferenceCountWithoutDeleting())
  724. ContainerDeletePolicy<ObjectClass>::destroy (o);
  725. }
  726. };
  727. } // namespace juce