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.

905 lines
34KB

  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. #ifndef JUCE_OWNEDARRAY_H_INCLUDED
  22. #define JUCE_OWNEDARRAY_H_INCLUDED
  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 (bool deleteObjects = true)
  75. {
  76. const ScopedLockType lock (getLock());
  77. if (deleteObjects)
  78. deleteAllObjects();
  79. data.setAllocatedSize (0);
  80. numUsed = 0;
  81. }
  82. //==============================================================================
  83. /** Clears the array, optionally deleting the objects inside it first. */
  84. void clearQuick (bool deleteObjects)
  85. {
  86. const ScopedLockType lock (getLock());
  87. if (deleteObjects)
  88. deleteAllObjects();
  89. numUsed = 0;
  90. }
  91. //==============================================================================
  92. /** Returns the number of items currently in the array.
  93. @see operator[]
  94. */
  95. inline int size() const noexcept
  96. {
  97. return numUsed;
  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* const 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* const 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. @see set, insert, addIfNotAlreadyThere, addSorted
  217. */
  218. ObjectClass* add (ObjectClass* const newObject) noexcept
  219. {
  220. const ScopedLockType lock (getLock());
  221. data.ensureAllocatedSize (numUsed + 1);
  222. jassert (data.elements != nullptr);
  223. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  224. return const_cast <ObjectClass*> (newObject);
  225. }
  226. /** Inserts a new object into the array at the given index.
  227. Note that the this object will be deleted by the OwnedArray when it
  228. is removed, so be careful not to delete it somewhere else.
  229. If the index is less than 0 or greater than the size of the array, the
  230. element will be added to the end of the array.
  231. Otherwise, it will be inserted into the array, moving all the later elements
  232. along to make room.
  233. Be careful not to add the same object to the array more than once,
  234. as this will obviously cause deletion of dangling pointers.
  235. @param indexToInsertAt the index at which the new element should be inserted
  236. @param newObject the new object to add to the array
  237. @see add, addSorted, addIfNotAlreadyThere, set
  238. */
  239. void insert (int indexToInsertAt,
  240. ObjectClass* const newObject) noexcept
  241. {
  242. if (indexToInsertAt >= 0)
  243. {
  244. const ScopedLockType lock (getLock());
  245. if (indexToInsertAt > numUsed)
  246. indexToInsertAt = numUsed;
  247. data.ensureAllocatedSize (numUsed + 1);
  248. jassert (data.elements != nullptr);
  249. ObjectClass** const e = data.elements + indexToInsertAt;
  250. const int numToMove = numUsed - indexToInsertAt;
  251. if (numToMove > 0)
  252. memmove (e + 1, e, sizeof (ObjectClass*) * (size_t) numToMove);
  253. *e = const_cast <ObjectClass*> (newObject);
  254. ++numUsed;
  255. }
  256. else
  257. {
  258. add (newObject);
  259. }
  260. }
  261. /** Inserts an array of values into this array at a given position.
  262. If the index is less than 0 or greater than the size of the array, the
  263. new elements will be added to the end of the array.
  264. Otherwise, they will be inserted into the array, moving all the later elements
  265. along to make room.
  266. @param indexToInsertAt the index at which the first new element should be inserted
  267. @param newObjects the new values to add to the array
  268. @param numberOfElements how many items are in the array
  269. @see insert, add, addSorted, set
  270. */
  271. void insertArray (int indexToInsertAt,
  272. ObjectClass* const* newObjects,
  273. int numberOfElements)
  274. {
  275. if (numberOfElements > 0)
  276. {
  277. const ScopedLockType lock (getLock());
  278. data.ensureAllocatedSize (numUsed + numberOfElements);
  279. ObjectClass** insertPos = data.elements;
  280. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  281. {
  282. insertPos += indexToInsertAt;
  283. const size_t numberToMove = (size_t) (numUsed - indexToInsertAt);
  284. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ObjectClass*));
  285. }
  286. else
  287. {
  288. insertPos += numUsed;
  289. }
  290. numUsed += numberOfElements;
  291. while (--numberOfElements >= 0)
  292. *insertPos++ = *newObjects++;
  293. }
  294. }
  295. /** Appends a new object at the end of the array as long as the array doesn't
  296. already contain it.
  297. If the array already contains a matching object, nothing will be done.
  298. @param newObject the new object to add to the array
  299. */
  300. void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  301. {
  302. const ScopedLockType lock (getLock());
  303. if (! contains (newObject))
  304. add (newObject);
  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. void set (const int indexToChange,
  317. const ObjectClass* const newObject,
  318. const bool deleteOldElement = true)
  319. {
  320. if (indexToChange >= 0)
  321. {
  322. ScopedPointer<ObjectClass> toDelete;
  323. {
  324. const ScopedLockType lock (getLock());
  325. if (indexToChange < numUsed)
  326. {
  327. if (deleteOldElement)
  328. {
  329. toDelete = data.elements [indexToChange];
  330. if (toDelete == newObject)
  331. toDelete.release();
  332. }
  333. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  334. }
  335. else
  336. {
  337. data.ensureAllocatedSize (numUsed + 1);
  338. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  339. }
  340. }
  341. }
  342. else
  343. {
  344. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  345. // any effect - but since the object is not being added, it may be leaking..
  346. }
  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. {
  408. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  409. ++numUsed;
  410. }
  411. }
  412. /** Inserts a new object into the array assuming that the array is sorted.
  413. This will use a comparator to find the position at which the new object
  414. should go. If the array isn't sorted, the behaviour of this
  415. method will be unpredictable.
  416. @param comparator the comparator to use to compare the elements - see the sort method
  417. for details about this object's structure
  418. @param newObject the new object to insert to the array
  419. @returns the index at which the new object was added
  420. @see add, sort, indexOfSorted
  421. */
  422. template <class ElementComparator>
  423. int addSorted (ElementComparator& comparator, ObjectClass* const newObject) noexcept
  424. {
  425. (void) comparator; // if you pass in an object with a static compareElements() method, this
  426. // avoids getting warning messages about the parameter being unused
  427. const ScopedLockType lock (getLock());
  428. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  429. insert (index, newObject);
  430. return index;
  431. }
  432. /** Finds the index of an object in the array, assuming that the array is sorted.
  433. This will use a comparator to do a binary-chop to find the index of the given
  434. element, if it exists. If the array isn't sorted, the behaviour of this
  435. method will be unpredictable.
  436. @param comparator the comparator to use to compare the elements - see the sort()
  437. method for details about the form this object should take
  438. @param objectToLookFor the object to search for
  439. @returns the index of the element, or -1 if it's not found
  440. @see addSorted, sort
  441. */
  442. template <typename ElementComparator>
  443. int indexOfSorted (ElementComparator& comparator, const ObjectClass* const objectToLookFor) const noexcept
  444. {
  445. (void) comparator;
  446. const ScopedLockType lock (getLock());
  447. int s = 0, e = numUsed;
  448. while (s < e)
  449. {
  450. if (comparator.compareElements (objectToLookFor, data.elements [s]) == 0)
  451. return s;
  452. const int halfway = (s + e) / 2;
  453. if (halfway == s)
  454. break;
  455. if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  456. s = halfway;
  457. else
  458. e = halfway;
  459. }
  460. return -1;
  461. }
  462. //==============================================================================
  463. /** Removes an object from the array.
  464. This will remove the object at a given index (optionally also
  465. deleting it) and move back all the subsequent objects to close the gap.
  466. If the index passed in is out-of-range, nothing will happen.
  467. @param indexToRemove the index of the element to remove
  468. @param deleteObject whether to delete the object that is removed
  469. @see removeObject, removeRange
  470. */
  471. void remove (const int indexToRemove,
  472. const bool deleteObject = true)
  473. {
  474. ScopedPointer<ObjectClass> toDelete;
  475. {
  476. const ScopedLockType lock (getLock());
  477. if (isPositiveAndBelow (indexToRemove, numUsed))
  478. {
  479. ObjectClass** const e = data.elements + indexToRemove;
  480. if (deleteObject)
  481. toDelete = *e;
  482. --numUsed;
  483. const int numToShift = numUsed - indexToRemove;
  484. if (numToShift > 0)
  485. memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numToShift);
  486. }
  487. }
  488. if ((numUsed << 1) < data.numAllocated)
  489. minimiseStorageOverheads();
  490. }
  491. /** Removes and returns an object from the array without deleting it.
  492. This will remove the object at a given index and return it, moving back all
  493. the subsequent objects to close the gap. If the index passed in is out-of-range,
  494. nothing will happen.
  495. @param indexToRemove the index of the element to remove
  496. @see remove, removeObject, removeRange
  497. */
  498. ObjectClass* removeAndReturn (const int indexToRemove)
  499. {
  500. ObjectClass* removedItem = nullptr;
  501. const ScopedLockType lock (getLock());
  502. if (isPositiveAndBelow (indexToRemove, numUsed))
  503. {
  504. ObjectClass** const e = data.elements + indexToRemove;
  505. removedItem = *e;
  506. --numUsed;
  507. const int numToShift = numUsed - indexToRemove;
  508. if (numToShift > 0)
  509. memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numToShift);
  510. if ((numUsed << 1) < data.numAllocated)
  511. minimiseStorageOverheads();
  512. }
  513. return removedItem;
  514. }
  515. /** Removes a specified object from the array.
  516. If the item isn't found, no action is taken.
  517. @param objectToRemove the object to try to remove
  518. @param deleteObject whether to delete the object (if it's found)
  519. @see remove, removeRange
  520. */
  521. void removeObject (const ObjectClass* const objectToRemove,
  522. const bool deleteObject = true)
  523. {
  524. const ScopedLockType lock (getLock());
  525. ObjectClass** const e = data.elements.getData();
  526. for (int i = 0; i < numUsed; ++i)
  527. {
  528. if (objectToRemove == e[i])
  529. {
  530. remove (i, deleteObject);
  531. break;
  532. }
  533. }
  534. }
  535. /** Removes a range of objects from the array.
  536. This will remove a set of objects, starting from the given index,
  537. and move any subsequent elements down to close the gap.
  538. If the range extends beyond the bounds of the array, it will
  539. be safely clipped to the size of the array.
  540. @param startIndex the index of the first object to remove
  541. @param numberToRemove how many objects should be removed
  542. @param deleteObjects whether to delete the objects that get removed
  543. @see remove, removeObject
  544. */
  545. void removeRange (int startIndex,
  546. const int numberToRemove,
  547. const bool deleteObjects = true)
  548. {
  549. const ScopedLockType lock (getLock());
  550. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  551. startIndex = jlimit (0, numUsed, startIndex);
  552. if (endIndex > startIndex)
  553. {
  554. if (deleteObjects)
  555. {
  556. for (int i = startIndex; i < endIndex; ++i)
  557. {
  558. ContainerDeletePolicy<ObjectClass>::destroy (data.elements [i]);
  559. data.elements [i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  560. }
  561. }
  562. const int rangeSize = endIndex - startIndex;
  563. ObjectClass** e = data.elements + startIndex;
  564. int numToShift = numUsed - endIndex;
  565. numUsed -= rangeSize;
  566. while (--numToShift >= 0)
  567. {
  568. *e = e [rangeSize];
  569. ++e;
  570. }
  571. if ((numUsed << 1) < data.numAllocated)
  572. minimiseStorageOverheads();
  573. }
  574. }
  575. /** Removes the last n objects from the array.
  576. @param howManyToRemove how many objects to remove from the end of the array
  577. @param deleteObjects whether to also delete the objects that are removed
  578. @see remove, removeObject, removeRange
  579. */
  580. void removeLast (int howManyToRemove = 1,
  581. const bool deleteObjects = true)
  582. {
  583. const ScopedLockType lock (getLock());
  584. if (howManyToRemove >= numUsed)
  585. clear (deleteObjects);
  586. else
  587. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  588. }
  589. /** Swaps a pair of objects in the array.
  590. If either of the indexes passed in is out-of-range, nothing will happen,
  591. otherwise the two objects at these positions will be exchanged.
  592. */
  593. void swap (const int index1,
  594. const int index2) noexcept
  595. {
  596. const ScopedLockType lock (getLock());
  597. if (isPositiveAndBelow (index1, numUsed)
  598. && isPositiveAndBelow (index2, numUsed))
  599. {
  600. std::swap (data.elements [index1],
  601. data.elements [index2]);
  602. }
  603. }
  604. /** Moves one of the objects to a different position.
  605. This will move the object to a specified index, shuffling along
  606. any intervening elements as required.
  607. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  608. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  609. @param currentIndex the index of the object to be moved. If this isn't a
  610. valid index, then nothing will be done
  611. @param newIndex the index at which you'd like this object to end up. If this
  612. is less than zero, it will be moved to the end of the array
  613. */
  614. void move (const int currentIndex,
  615. int newIndex) noexcept
  616. {
  617. if (currentIndex != newIndex)
  618. {
  619. const ScopedLockType lock (getLock());
  620. if (isPositiveAndBelow (currentIndex, numUsed))
  621. {
  622. if (! isPositiveAndBelow (newIndex, numUsed))
  623. newIndex = numUsed - 1;
  624. ObjectClass* const value = data.elements [currentIndex];
  625. if (newIndex > currentIndex)
  626. {
  627. memmove (data.elements + currentIndex,
  628. data.elements + currentIndex + 1,
  629. sizeof (ObjectClass*) * (size_t) (newIndex - currentIndex));
  630. }
  631. else
  632. {
  633. memmove (data.elements + newIndex + 1,
  634. data.elements + newIndex,
  635. sizeof (ObjectClass*) * (size_t) (currentIndex - newIndex));
  636. }
  637. data.elements [newIndex] = value;
  638. }
  639. }
  640. }
  641. /** This swaps the contents of this array with those of another array.
  642. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  643. because it just swaps their internal pointers.
  644. */
  645. template <class OtherArrayType>
  646. void swapWith (OtherArrayType& otherArray) noexcept
  647. {
  648. const ScopedLockType lock1 (getLock());
  649. const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
  650. data.swapWith (otherArray.data);
  651. std::swap (numUsed, otherArray.numUsed);
  652. }
  653. //==============================================================================
  654. /** Reduces the amount of storage being used by the array.
  655. Arrays typically allocate slightly more storage than they need, and after
  656. removing elements, they may have quite a lot of unused space allocated.
  657. This method will reduce the amount of allocated storage to a minimum.
  658. */
  659. void minimiseStorageOverheads() noexcept
  660. {
  661. const ScopedLockType lock (getLock());
  662. data.shrinkToNoMoreThan (numUsed);
  663. }
  664. /** Increases the array's internal storage to hold a minimum number of elements.
  665. Calling this before adding a large known number of elements means that
  666. the array won't have to keep dynamically resizing itself as the elements
  667. are added, and it'll therefore be more efficient.
  668. */
  669. void ensureStorageAllocated (const int minNumElements) noexcept
  670. {
  671. const ScopedLockType lock (getLock());
  672. data.ensureAllocatedSize (minNumElements);
  673. }
  674. //==============================================================================
  675. /** Sorts the elements in the array.
  676. This will use a comparator object to sort the elements into order. The object
  677. passed must have a method of the form:
  678. @code
  679. int compareElements (ElementType first, ElementType second);
  680. @endcode
  681. ..and this method must return:
  682. - a value of < 0 if the first comes before the second
  683. - a value of 0 if the two objects are equivalent
  684. - a value of > 0 if the second comes before the first
  685. To improve performance, the compareElements() method can be declared as static or const.
  686. @param comparator the comparator to use for comparing elements.
  687. @param retainOrderOfEquivalentItems if this is true, then items
  688. which the comparator says are equivalent will be
  689. kept in the order in which they currently appear
  690. in the array. This is slower to perform, but may
  691. be important in some cases. If it's false, a faster
  692. algorithm is used, but equivalent elements may be
  693. rearranged.
  694. @see sortArray, indexOfSorted
  695. */
  696. template <class ElementComparator>
  697. void sort (ElementComparator& comparator,
  698. const bool retainOrderOfEquivalentItems = false) const noexcept
  699. {
  700. (void) comparator; // if you pass in an object with a static compareElements() method, this
  701. // avoids getting warning messages about the parameter being unused
  702. const ScopedLockType lock (getLock());
  703. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  704. }
  705. //==============================================================================
  706. /** Returns the CriticalSection that locks this array.
  707. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  708. an object of ScopedLockType as an RAII lock for it.
  709. */
  710. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  711. /** Returns the type of scoped lock to use for locking this array */
  712. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  713. //==============================================================================
  714. #ifndef DOXYGEN
  715. // Note that the swapWithArray method has been replaced by a more flexible templated version,
  716. // and renamed "swapWith" to be more consistent with the names used in other classes.
  717. JUCE_DEPRECATED_WITH_BODY (void swapWithArray (OwnedArray& other) noexcept, { swapWith (other); })
  718. #endif
  719. private:
  720. //==============================================================================
  721. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  722. int numUsed;
  723. void deleteAllObjects()
  724. {
  725. while (numUsed > 0)
  726. ContainerDeletePolicy<ObjectClass>::destroy (data.elements [--numUsed]);
  727. }
  728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray)
  729. };
  730. #endif // JUCE_OWNEDARRAY_H_INCLUDED