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.

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