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.

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