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.

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