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.

873 lines
32KB

  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_H_INCLUDED
  22. #define JUCE_REFERENCECOUNTEDARRAY_H_INCLUDED
  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. swapWith (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. swapWith (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. ObjectClass* add (ObjectClass* const newObject) noexcept
  241. {
  242. const ScopedLockType lock (getLock());
  243. data.ensureAllocatedSize (numUsed + 1);
  244. jassert (data.elements != nullptr);
  245. data.elements [numUsed++] = newObject;
  246. if (newObject != nullptr)
  247. newObject->incReferenceCount();
  248. return newObject;
  249. }
  250. /** Inserts a new object into the array at the given index.
  251. If the index is less than 0 or greater than the size of the array, the
  252. element will be added to the end of the array.
  253. Otherwise, it will be inserted into the array, moving all the later elements
  254. along to make room.
  255. This will increase the new object's reference count.
  256. @param indexToInsertAt the index at which the new element should be inserted
  257. @param newObject the new object to add to the array
  258. @see add, addSorted, addIfNotAlreadyThere, set
  259. */
  260. ObjectClass* insert (int indexToInsertAt,
  261. ObjectClass* const newObject) noexcept
  262. {
  263. if (indexToInsertAt >= 0)
  264. {
  265. const ScopedLockType lock (getLock());
  266. if (indexToInsertAt > numUsed)
  267. indexToInsertAt = numUsed;
  268. data.ensureAllocatedSize (numUsed + 1);
  269. jassert (data.elements != nullptr);
  270. ObjectClass** const e = data.elements + indexToInsertAt;
  271. const int numToMove = numUsed - indexToInsertAt;
  272. if (numToMove > 0)
  273. memmove (e + 1, e, sizeof (ObjectClass*) * (size_t) numToMove);
  274. *e = newObject;
  275. if (newObject != nullptr)
  276. newObject->incReferenceCount();
  277. ++numUsed;
  278. return newObject;
  279. }
  280. else
  281. {
  282. return add (newObject);
  283. }
  284. }
  285. /** Appends a new object at the end of the array as long as the array doesn't
  286. already contain it.
  287. If the array already contains a matching object, nothing will be done.
  288. @param newObject the new object to add to the array
  289. */
  290. void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  291. {
  292. const ScopedLockType lock (getLock());
  293. if (! contains (newObject))
  294. add (newObject);
  295. }
  296. /** Replaces an object in the array with a different one.
  297. If the index is less than zero, this method does nothing.
  298. If the index is beyond the end of the array, the new object is added to the end of the array.
  299. The object being added has its reference count increased, and if it's replacing
  300. another object, then that one has its reference count decreased, and may be deleted.
  301. @param indexToChange the index whose value you want to change
  302. @param newObject the new value to set for this index.
  303. @see add, insert, remove
  304. */
  305. void set (const int indexToChange,
  306. ObjectClass* const newObject)
  307. {
  308. if (indexToChange >= 0)
  309. {
  310. const ScopedLockType lock (getLock());
  311. if (newObject != nullptr)
  312. newObject->incReferenceCount();
  313. if (indexToChange < numUsed)
  314. {
  315. if (ObjectClass* o = data.elements [indexToChange])
  316. o->decReferenceCount();
  317. data.elements [indexToChange] = newObject;
  318. }
  319. else
  320. {
  321. data.ensureAllocatedSize (numUsed + 1);
  322. jassert (data.elements != nullptr);
  323. data.elements [numUsed++] = newObject;
  324. }
  325. }
  326. }
  327. /** Adds elements from another array to the end of this array.
  328. @param arrayToAddFrom the array from which to copy the elements
  329. @param startIndex the first element of the other array to start copying from
  330. @param numElementsToAdd how many elements to add from the other array. If this
  331. value is negative or greater than the number of available elements,
  332. all available elements will be copied.
  333. @see add
  334. */
  335. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  336. int startIndex = 0,
  337. int numElementsToAdd = -1) noexcept
  338. {
  339. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  340. {
  341. const ScopedLockType lock2 (getLock());
  342. if (startIndex < 0)
  343. {
  344. jassertfalse;
  345. startIndex = 0;
  346. }
  347. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  348. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  349. if (numElementsToAdd > 0)
  350. {
  351. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  352. while (--numElementsToAdd >= 0)
  353. add (arrayToAddFrom.getUnchecked (startIndex++));
  354. }
  355. }
  356. }
  357. /** Inserts a new object into the array assuming that the array is sorted.
  358. This will use a comparator to find the position at which the new object
  359. should go. If the array isn't sorted, the behaviour of this
  360. method will be unpredictable.
  361. @param comparator the comparator object to use to compare the elements - see the
  362. sort() method for details about this object's form
  363. @param newObject the new object to insert to the array
  364. @returns the index at which the new object was added
  365. @see add, sort
  366. */
  367. template <class ElementComparator>
  368. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  369. {
  370. const ScopedLockType lock (getLock());
  371. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  372. insert (index, newObject);
  373. return index;
  374. }
  375. /** Inserts or replaces an object in the array, assuming it is sorted.
  376. This is similar to addSorted, but if a matching element already exists, then it will be
  377. replaced by the new one, rather than the new one being added as well.
  378. */
  379. template <class ElementComparator>
  380. void addOrReplaceSorted (ElementComparator& comparator,
  381. ObjectClass* newObject) noexcept
  382. {
  383. const ScopedLockType lock (getLock());
  384. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  385. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  386. set (index - 1, newObject); // replace an existing object that matches
  387. else
  388. insert (index, newObject); // no match, so insert the new one
  389. }
  390. /** Finds the index of an object in the array, assuming that the array is sorted.
  391. This will use a comparator to do a binary-chop to find the index of the given
  392. element, if it exists. If the array isn't sorted, the behaviour of this
  393. method will be unpredictable.
  394. @param comparator the comparator to use to compare the elements - see the sort()
  395. method for details about the form this object should take
  396. @param objectToLookFor the object to search for
  397. @returns the index of the element, or -1 if it's not found
  398. @see addSorted, sort
  399. */
  400. template <class ElementComparator>
  401. int indexOfSorted (ElementComparator& comparator,
  402. const ObjectClass* const objectToLookFor) const noexcept
  403. {
  404. (void) comparator;
  405. const ScopedLockType lock (getLock());
  406. int s = 0, e = numUsed;
  407. while (s < e)
  408. {
  409. if (comparator.compareElements (objectToLookFor, data.elements [s]) == 0)
  410. return s;
  411. const int halfway = (s + e) / 2;
  412. if (halfway == s)
  413. break;
  414. if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  415. s = halfway;
  416. else
  417. e = halfway;
  418. }
  419. return -1;
  420. }
  421. //==============================================================================
  422. /** Removes an object from the array.
  423. This will remove the object at a given index and move back all the
  424. subsequent objects to close the gap.
  425. If the index passed in is out-of-range, nothing will happen.
  426. The object that is removed will have its reference count decreased,
  427. and may be deleted if not referenced from elsewhere.
  428. @param indexToRemove the index of the element to remove
  429. @see removeObject, removeRange
  430. */
  431. void remove (const int indexToRemove)
  432. {
  433. const ScopedLockType lock (getLock());
  434. if (isPositiveAndBelow (indexToRemove, numUsed))
  435. {
  436. ObjectClass** const e = data.elements + indexToRemove;
  437. if (ObjectClass* o = *e)
  438. o->decReferenceCount();
  439. --numUsed;
  440. const int numberToShift = numUsed - indexToRemove;
  441. if (numberToShift > 0)
  442. memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numberToShift);
  443. if ((numUsed << 1) < data.numAllocated)
  444. minimiseStorageOverheads();
  445. }
  446. }
  447. /** Removes and returns an object from the array.
  448. This will remove the object at a given index and return it, moving back all
  449. the subsequent objects to close the gap. If the index passed in is out-of-range,
  450. nothing will happen and a null pointer will be returned.
  451. @param indexToRemove the index of the element to remove
  452. @see remove, removeObject, removeRange
  453. */
  454. ObjectClassPtr removeAndReturn (const int indexToRemove)
  455. {
  456. ObjectClassPtr removedItem;
  457. const ScopedLockType lock (getLock());
  458. if (isPositiveAndBelow (indexToRemove, numUsed))
  459. {
  460. ObjectClass** const e = data.elements + indexToRemove;
  461. if (ObjectClass* o = *e)
  462. {
  463. removedItem = o;
  464. o->decReferenceCount();
  465. }
  466. --numUsed;
  467. const int numberToShift = numUsed - indexToRemove;
  468. if (numberToShift > 0)
  469. memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numberToShift);
  470. if ((numUsed << 1) < data.numAllocated)
  471. minimiseStorageOverheads();
  472. }
  473. return removedItem;
  474. }
  475. /** Removes the first occurrence of a specified object from the array.
  476. If the item isn't found, no action is taken. If it is found, it is
  477. removed and has its reference count decreased.
  478. @param objectToRemove the object to try to remove
  479. @see remove, removeRange
  480. */
  481. void removeObject (ObjectClass* const objectToRemove)
  482. {
  483. const ScopedLockType lock (getLock());
  484. remove (indexOf (objectToRemove));
  485. }
  486. /** Removes a range of objects from the array.
  487. This will remove a set of objects, starting from the given index,
  488. and move any subsequent elements down to close the gap.
  489. If the range extends beyond the bounds of the array, it will
  490. be safely clipped to the size of the array.
  491. The objects that are removed will have their reference counts decreased,
  492. and may be deleted if not referenced from elsewhere.
  493. @param startIndex the index of the first object to remove
  494. @param numberToRemove how many objects should be removed
  495. @see remove, removeObject
  496. */
  497. void removeRange (const int startIndex,
  498. const int numberToRemove)
  499. {
  500. const ScopedLockType lock (getLock());
  501. const int start = jlimit (0, numUsed, startIndex);
  502. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  503. if (endIndex > start)
  504. {
  505. int i;
  506. for (i = start; i < endIndex; ++i)
  507. {
  508. if (ObjectClass* o = data.elements[i])
  509. {
  510. o->decReferenceCount();
  511. data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  512. }
  513. }
  514. const int rangeSize = endIndex - start;
  515. ObjectClass** e = data.elements + start;
  516. i = numUsed - endIndex;
  517. numUsed -= rangeSize;
  518. while (--i >= 0)
  519. {
  520. *e = e [rangeSize];
  521. ++e;
  522. }
  523. if ((numUsed << 1) < data.numAllocated)
  524. minimiseStorageOverheads();
  525. }
  526. }
  527. /** Removes the last n objects from the array.
  528. The objects that are removed will have their reference counts decreased,
  529. and may be deleted if not referenced from elsewhere.
  530. @param howManyToRemove how many objects to remove from the end of the array
  531. @see remove, removeObject, removeRange
  532. */
  533. void removeLast (int howManyToRemove = 1)
  534. {
  535. const ScopedLockType lock (getLock());
  536. if (howManyToRemove > numUsed)
  537. howManyToRemove = numUsed;
  538. while (--howManyToRemove >= 0)
  539. remove (numUsed - 1);
  540. }
  541. /** Swaps a pair of objects in the array.
  542. If either of the indexes passed in is out-of-range, nothing will happen,
  543. otherwise the two objects at these positions will be exchanged.
  544. */
  545. void swap (const int index1,
  546. const int index2) noexcept
  547. {
  548. const ScopedLockType lock (getLock());
  549. if (isPositiveAndBelow (index1, numUsed)
  550. && isPositiveAndBelow (index2, numUsed))
  551. {
  552. std::swap (data.elements [index1],
  553. data.elements [index2]);
  554. }
  555. }
  556. /** Moves one of the objects to a different position.
  557. This will move the object to a specified index, shuffling along
  558. any intervening elements as required.
  559. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  560. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  561. @param currentIndex the index of the object to be moved. If this isn't a
  562. valid index, then nothing will be done
  563. @param newIndex the index at which you'd like this object to end up. If this
  564. is less than zero, it will be moved to the end of the array
  565. */
  566. void move (const int currentIndex,
  567. int newIndex) noexcept
  568. {
  569. if (currentIndex != newIndex)
  570. {
  571. const ScopedLockType lock (getLock());
  572. if (isPositiveAndBelow (currentIndex, numUsed))
  573. {
  574. if (! isPositiveAndBelow (newIndex, numUsed))
  575. newIndex = numUsed - 1;
  576. ObjectClass* const value = data.elements [currentIndex];
  577. if (newIndex > currentIndex)
  578. {
  579. memmove (data.elements + currentIndex,
  580. data.elements + currentIndex + 1,
  581. sizeof (ObjectClass*) * (size_t) (newIndex - currentIndex));
  582. }
  583. else
  584. {
  585. memmove (data.elements + newIndex + 1,
  586. data.elements + newIndex,
  587. sizeof (ObjectClass*) * (size_t) (currentIndex - newIndex));
  588. }
  589. data.elements [newIndex] = value;
  590. }
  591. }
  592. }
  593. //==============================================================================
  594. /** This swaps the contents of this array with those of another array.
  595. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  596. because it just swaps their internal pointers.
  597. */
  598. template <class OtherArrayType>
  599. void swapWith (OtherArrayType& otherArray) noexcept
  600. {
  601. const ScopedLockType lock1 (getLock());
  602. const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
  603. data.swapWith (otherArray.data);
  604. std::swap (numUsed, otherArray.numUsed);
  605. }
  606. //==============================================================================
  607. /** Compares this array to another one.
  608. @returns true only if the other array contains the same objects in the same order
  609. */
  610. bool operator== (const ReferenceCountedArray& other) const noexcept
  611. {
  612. const ScopedLockType lock2 (other.getLock());
  613. const ScopedLockType lock1 (getLock());
  614. if (numUsed != other.numUsed)
  615. return false;
  616. for (int i = numUsed; --i >= 0;)
  617. if (data.elements [i] != other.data.elements [i])
  618. return false;
  619. return true;
  620. }
  621. /** Compares this array to another one.
  622. @see operator==
  623. */
  624. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
  625. {
  626. return ! operator== (other);
  627. }
  628. //==============================================================================
  629. /** Sorts the elements in the array.
  630. This will use a comparator object to sort the elements into order. The object
  631. passed must have a method of the form:
  632. @code
  633. int compareElements (ElementType first, ElementType second);
  634. @endcode
  635. ..and this method must return:
  636. - a value of < 0 if the first comes before the second
  637. - a value of 0 if the two objects are equivalent
  638. - a value of > 0 if the second comes before the first
  639. To improve performance, the compareElements() method can be declared as static or const.
  640. @param comparator the comparator to use for comparing elements.
  641. @param retainOrderOfEquivalentItems if this is true, then items
  642. which the comparator says are equivalent will be
  643. kept in the order in which they currently appear
  644. in the array. This is slower to perform, but may
  645. be important in some cases. If it's false, a faster
  646. algorithm is used, but equivalent elements may be
  647. rearranged.
  648. @see sortArray
  649. */
  650. template <class ElementComparator>
  651. void sort (ElementComparator& comparator,
  652. const bool retainOrderOfEquivalentItems = false) const noexcept
  653. {
  654. (void) comparator; // if you pass in an object with a static compareElements() method, this
  655. // avoids getting warning messages about the parameter being unused
  656. const ScopedLockType lock (getLock());
  657. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  658. }
  659. //==============================================================================
  660. /** Reduces the amount of storage being used by the array.
  661. Arrays typically allocate slightly more storage than they need, and after
  662. removing elements, they may have quite a lot of unused space allocated.
  663. This method will reduce the amount of allocated storage to a minimum.
  664. */
  665. void minimiseStorageOverheads() noexcept
  666. {
  667. const ScopedLockType lock (getLock());
  668. data.shrinkToNoMoreThan (numUsed);
  669. }
  670. /** Increases the array's internal storage to hold a minimum number of elements.
  671. Calling this before adding a large known number of elements means that
  672. the array won't have to keep dynamically resizing itself as the elements
  673. are added, and it'll therefore be more efficient.
  674. */
  675. void ensureStorageAllocated (const int minNumElements)
  676. {
  677. const ScopedLockType lock (getLock());
  678. data.ensureAllocatedSize (minNumElements);
  679. }
  680. //==============================================================================
  681. /** Returns the CriticalSection that locks this array.
  682. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  683. an object of ScopedLockType as an RAII lock for it.
  684. */
  685. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  686. /** Returns the type of scoped lock to use for locking this array */
  687. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  688. //==============================================================================
  689. // Note that the swapWithArray method has been replaced by a more flexible templated version,
  690. // and renamed "swapWith" to be more consistent with the names used in other classes.
  691. JUCE_DEPRECATED_WITH_BODY (void swapWithArray (ReferenceCountedArray& other) noexcept, { swapWith (other); })
  692. private:
  693. //==============================================================================
  694. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  695. int numUsed;
  696. };
  697. #endif // JUCE_REFERENCECOUNTEDARRAY_H_INCLUDED