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.

972 lines
35KB

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