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.

921 lines
33KB

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