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.

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