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.

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