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.

868 lines
32KB

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