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.

871 lines
33KB

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