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.

866 lines
32KB

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