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.

884 lines
33KB

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