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.

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