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.

898 lines
33KB

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