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.

924 lines
33KB

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