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
34KB

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