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.

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