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.

861 lines
31KB

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