juce_ReferenceCountedArray.h 33 KB

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