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.

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