Audio plugin host https://kx.studio/carla
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.

OwnedArray.h 30KB

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