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