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
33KB

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