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.

895 lines
33KB

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