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.

Array.h 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2019 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_ARRAY_H_INCLUDED
  21. #define WATER_ARRAY_H_INCLUDED
  22. #include "../containers/ArrayAllocationBase.h"
  23. #include "../containers/ElementComparator.h"
  24. namespace water {
  25. //==============================================================================
  26. /**
  27. Holds a resizable array of primitive or copy-by-value objects.
  28. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  29. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  30. do so, the class must fulfil these requirements:
  31. - it must have a copy constructor and assignment operator
  32. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  33. objects whose functionality relies on external pointers or references to themselves can not be used.
  34. You can of course have an array of pointers to any kind of object, e.g. Array<MyClass*>, but if
  35. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  36. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  37. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  38. specialised class StringArray, which provides more useful functions.
  39. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  40. */
  41. template <typename ElementType, size_t minimumAllocatedSize = 0>
  42. class Array
  43. {
  44. private:
  45. typedef PARAMETER_TYPE (ElementType) ParameterType;
  46. public:
  47. //==============================================================================
  48. /** Creates an empty array. */
  49. Array() noexcept
  50. : data(),
  51. numUsed(0)
  52. {
  53. }
  54. /** Creates a copy of another array.
  55. @param other the array to copy
  56. */
  57. Array (const Array<ElementType>& other) noexcept
  58. : data(),
  59. numUsed(0)
  60. {
  61. CARLA_SAFE_ASSERT_RETURN(data.setAllocatedSize (other.numUsed),);
  62. numUsed = other.numUsed;
  63. for (int i = 0; i < numUsed; ++i)
  64. new (data.elements + i) ElementType (other.data.elements[i]);
  65. }
  66. /** Initalises from a null-terminated C array of values.
  67. @param values the array to copy from
  68. */
  69. template <typename TypeToCreateFrom>
  70. explicit Array (const TypeToCreateFrom* values) noexcept : numUsed (0)
  71. {
  72. while (*values != TypeToCreateFrom())
  73. {
  74. CARLA_SAFE_ASSERT_BREAK(add (*values++));
  75. }
  76. }
  77. /** Initalises from a C array of values.
  78. @param values the array to copy from
  79. @param numValues the number of values in the array
  80. */
  81. template <typename TypeToCreateFrom>
  82. Array (const TypeToCreateFrom* values, int numValues) noexcept : numUsed (numValues)
  83. {
  84. CARLA_SAFE_ASSERT_RETURN(data.setAllocatedSize (numValues),);
  85. for (int i = 0; i < numValues; ++i)
  86. new (data.elements + i) ElementType (values[i]);
  87. }
  88. /** Destructor. */
  89. ~Array() noexcept
  90. {
  91. deleteAllElements();
  92. }
  93. /** Copies another array.
  94. @param other the array to copy
  95. */
  96. Array& operator= (const Array& other) noexcept
  97. {
  98. if (this != &other)
  99. {
  100. Array<ElementType> otherCopy (other);
  101. swapWith (otherCopy);
  102. }
  103. return *this;
  104. }
  105. //==============================================================================
  106. /** Compares this array to another one.
  107. Two arrays are considered equal if they both contain the same set of
  108. elements, in the same order.
  109. @param other the other array to compare with
  110. */
  111. template <class OtherArrayType>
  112. bool operator== (const OtherArrayType& other) const
  113. {
  114. if (numUsed != other.numUsed)
  115. return false;
  116. for (int i = numUsed; --i >= 0;)
  117. if (! (data.elements [i] == other.data.elements [i]))
  118. return false;
  119. return true;
  120. }
  121. /** Compares this array to another one.
  122. Two arrays are considered equal if they both contain the same set of
  123. elements, in the same order.
  124. @param other the other array to compare with
  125. */
  126. template <class OtherArrayType>
  127. bool operator!= (const OtherArrayType& other) const
  128. {
  129. return ! operator== (other);
  130. }
  131. //==============================================================================
  132. /** Removes all elements from the array.
  133. This will remove all the elements, and free any storage that the array is
  134. using. To clear the array without freeing the storage, use the clearQuick()
  135. method instead.
  136. @see clearQuick
  137. */
  138. void clear() noexcept
  139. {
  140. deleteAllElements();
  141. data.setAllocatedSize (0);
  142. numUsed = 0;
  143. }
  144. /** Removes all elements from the array without freeing the array's allocated storage.
  145. @see clear
  146. */
  147. void clearQuick() noexcept
  148. {
  149. deleteAllElements();
  150. numUsed = 0;
  151. }
  152. //==============================================================================
  153. /** Returns the current number of elements in the array. */
  154. inline int size() const noexcept
  155. {
  156. return numUsed;
  157. }
  158. /** Returns true if the array is empty, false otherwise. */
  159. inline bool isEmpty() const noexcept
  160. {
  161. return size() == 0;
  162. }
  163. /** Returns one of the elements in the array.
  164. If the index passed in is beyond the range of valid elements, this
  165. will return a default value.
  166. If you're certain that the index will always be a valid element, you
  167. can call getUnchecked() instead, which is faster.
  168. @param index the index of the element being requested (0 is the first element in the array)
  169. @see getUnchecked, getFirst, getLast
  170. */
  171. ElementType operator[] (const int index) const
  172. {
  173. if (isPositiveAndBelow (index, numUsed))
  174. {
  175. wassert (data.elements != nullptr);
  176. return data.elements [index];
  177. }
  178. return ElementType();
  179. }
  180. /** Returns one of the elements in the array, without checking the index passed in.
  181. Unlike the operator[] method, this will try to return an element without
  182. checking that the index is within the bounds of the array, so should only
  183. be used when you're confident that it will always be a valid index.
  184. @param index the index of the element being requested (0 is the first element in the array)
  185. @see operator[], getFirst, getLast
  186. */
  187. inline ElementType getUnchecked (const int index) const
  188. {
  189. wassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  190. return data.elements [index];
  191. }
  192. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  193. This is like getUnchecked, but returns a direct reference to the element, so that
  194. you can alter it directly. Obviously this can be dangerous, so only use it when
  195. absolutely necessary.
  196. @param index the index of the element being requested (0 is the first element in the array)
  197. @see operator[], getFirst, getLast
  198. */
  199. inline ElementType& getReference (const int index) const noexcept
  200. {
  201. wassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  202. return data.elements [index];
  203. }
  204. /** Returns the first element in the array, or a default value if the array is empty.
  205. @see operator[], getUnchecked, getLast
  206. */
  207. inline ElementType getFirst() const
  208. {
  209. if (numUsed > 0)
  210. {
  211. wassert (data.elements != nullptr);
  212. return data.elements[0];
  213. }
  214. return ElementType();
  215. }
  216. /** Returns the last element in the array, or a default value if the array is empty.
  217. @see operator[], getUnchecked, getFirst
  218. */
  219. inline ElementType getLast() const
  220. {
  221. if (numUsed > 0)
  222. {
  223. wassert (data.elements != nullptr);
  224. return data.elements[numUsed - 1];
  225. }
  226. return ElementType();
  227. }
  228. /** Returns a pointer to the actual array data.
  229. This pointer will only be valid until the next time a non-const method
  230. is called on the array.
  231. */
  232. inline ElementType* getRawDataPointer() noexcept
  233. {
  234. return data.elements;
  235. }
  236. //==============================================================================
  237. /** Returns a pointer to the first element in the array.
  238. This method is provided for compatibility with standard C++ iteration mechanisms.
  239. */
  240. inline ElementType* begin() const noexcept
  241. {
  242. return data.elements;
  243. }
  244. /** Returns a pointer to the element which follows the last element in the array.
  245. This method is provided for compatibility with standard C++ iteration mechanisms.
  246. */
  247. inline ElementType* end() const noexcept
  248. {
  249. #ifdef DEBUG
  250. if (data.elements == nullptr || numUsed <= 0) // (to keep static analysers happy)
  251. return data.elements;
  252. #endif
  253. return data.elements + numUsed;
  254. }
  255. //==============================================================================
  256. /** Finds the index of the first element which matches the value passed in.
  257. This will search the array for the given object, and return the index
  258. of its first occurrence. If the object isn't found, the method will return -1.
  259. @param elementToLookFor the value or object to look for
  260. @returns the index of the object, or -1 if it's not found
  261. */
  262. int indexOf (ParameterType elementToLookFor) const
  263. {
  264. const ElementType* e = data.elements.getData();
  265. const ElementType* const end_ = e + numUsed;
  266. for (; e != end_; ++e)
  267. if (elementToLookFor == *e)
  268. return static_cast<int> (e - data.elements.getData());
  269. return -1;
  270. }
  271. /** Returns true if the array contains at least one occurrence of an object.
  272. @param elementToLookFor the value or object to look for
  273. @returns true if the item is found
  274. */
  275. bool contains (ParameterType elementToLookFor) const
  276. {
  277. const ElementType* e = data.elements.getData();
  278. const ElementType* const end_ = e + numUsed;
  279. for (; e != end_; ++e)
  280. if (elementToLookFor == *e)
  281. return true;
  282. return false;
  283. }
  284. //==============================================================================
  285. /** Appends a new element at the end of the array.
  286. @param newElement the new object to add to the array
  287. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  288. */
  289. bool add (const ElementType& newElement) noexcept
  290. {
  291. if (! data.ensureAllocatedSize (static_cast<size_t>(numUsed + 1)))
  292. return false;
  293. new (data.elements + numUsed++) ElementType (newElement);
  294. return true;
  295. }
  296. /** Inserts a new element into the array at a given position.
  297. If the index is less than 0 or greater than the size of the array, the
  298. element will be added to the end of the array.
  299. Otherwise, it will be inserted into the array, moving all the later elements
  300. along to make room.
  301. @param indexToInsertAt the index at which the new element should be
  302. inserted (pass in -1 to add it to the end)
  303. @param newElement the new object to add to the array
  304. @see add, addSorted, addUsingDefaultSort, set
  305. */
  306. bool insert (int indexToInsertAt, ParameterType newElement) noexcept
  307. {
  308. if (! data.ensureAllocatedSize (numUsed + 1))
  309. return false;
  310. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  311. {
  312. ElementType* const insertPos = data.elements + indexToInsertAt;
  313. const int numberToMove = numUsed - indexToInsertAt;
  314. if (numberToMove > 0)
  315. data.moveMemory (insertPos + 1, insertPos, numberToMove);
  316. new (insertPos) ElementType (newElement);
  317. ++numUsed;
  318. }
  319. else
  320. {
  321. new (data.elements + numUsed++) ElementType (newElement);
  322. }
  323. return true;
  324. }
  325. /** Inserts multiple copies of an element into the array at a given position.
  326. If the index is less than 0 or greater than the size of the array, the
  327. element will be added to the end of the array.
  328. Otherwise, it will be inserted into the array, moving all the later elements
  329. along to make room.
  330. @param indexToInsertAt the index at which the new element should be inserted
  331. @param newElement the new object to add to the array
  332. @param numberOfTimesToInsertIt how many copies of the value to insert
  333. @see insert, add, addSorted, set
  334. */
  335. bool insertMultiple (int indexToInsertAt, ParameterType newElement,
  336. int numberOfTimesToInsertIt)
  337. {
  338. if (numberOfTimesToInsertIt > 0)
  339. {
  340. if (! data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt))
  341. return false;
  342. ElementType* insertPos;
  343. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  344. {
  345. insertPos = data.elements + indexToInsertAt;
  346. const int numberToMove = numUsed - indexToInsertAt;
  347. data.moveMemory (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove);
  348. }
  349. else
  350. {
  351. insertPos = data.elements + numUsed;
  352. }
  353. numUsed += numberOfTimesToInsertIt;
  354. while (--numberOfTimesToInsertIt >= 0)
  355. {
  356. new (insertPos) ElementType (newElement);
  357. ++insertPos; // NB: this increment is done separately from the
  358. // new statement to avoid a compiler bug in VS2014
  359. }
  360. }
  361. return true;
  362. }
  363. #if 0
  364. /** Inserts an array of values into this array at a given position.
  365. If the index is less than 0 or greater than the size of the array, the
  366. new elements will be added to the end of the array.
  367. Otherwise, they will be inserted into the array, moving all the later elements
  368. along to make room.
  369. @param indexToInsertAt the index at which the first new element should be inserted
  370. @param newElements the new values to add to the array
  371. @param numberOfElements how many items are in the array
  372. @see insert, add, addSorted, set
  373. */
  374. bool insertArray (int indexToInsertAt,
  375. const ElementType* newElements,
  376. int numberOfElements)
  377. {
  378. if (numberOfElements > 0)
  379. {
  380. if (! data.ensureAllocatedSize (numUsed + numberOfElements))
  381. return false;
  382. ElementType* insertPos = data.elements;
  383. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  384. {
  385. insertPos += indexToInsertAt;
  386. const int numberToMove = numUsed - indexToInsertAt;
  387. std::memmove (insertPos + numberOfElements, insertPos, (size_t) numberToMove * sizeof (ElementType));
  388. }
  389. else
  390. {
  391. insertPos += numUsed;
  392. }
  393. numUsed += numberOfElements;
  394. while (--numberOfElements >= 0)
  395. new (insertPos++) ElementType (*newElements++);
  396. }
  397. return true;
  398. }
  399. #endif
  400. /** Appends a new element at the end of the array as long as the array doesn't
  401. already contain it.
  402. If the array already contains an element that matches the one passed in, nothing
  403. will be done.
  404. @param newElement the new object to add to the array
  405. @return true if the element was added to the array; false otherwise.
  406. */
  407. bool addIfNotAlreadyThere (ParameterType newElement)
  408. {
  409. if (contains (newElement))
  410. return false;
  411. return add (newElement);
  412. }
  413. /** Replaces an element with a new value.
  414. If the index is less than zero, this method does nothing.
  415. If the index is beyond the end of the array, the item is added to the end of the array.
  416. @param indexToChange the index whose value you want to change
  417. @param newValue the new value to set for this index.
  418. @see add, insert
  419. */
  420. void set (const int indexToChange, ParameterType newValue)
  421. {
  422. wassert (indexToChange >= 0);
  423. if (isPositiveAndBelow (indexToChange, numUsed))
  424. {
  425. wassert (data.elements != nullptr);
  426. data.elements [indexToChange] = newValue;
  427. }
  428. else if (indexToChange >= 0)
  429. {
  430. data.ensureAllocatedSize (numUsed + 1);
  431. new (data.elements + numUsed++) ElementType (newValue);
  432. }
  433. }
  434. /** Replaces an element with a new value without doing any bounds-checking.
  435. This just sets a value directly in the array's internal storage, so you'd
  436. better make sure it's in range!
  437. @param indexToChange the index whose value you want to change
  438. @param newValue the new value to set for this index.
  439. @see set, getUnchecked
  440. */
  441. void setUnchecked (const int indexToChange, ParameterType newValue)
  442. {
  443. wassert (isPositiveAndBelow (indexToChange, numUsed));
  444. data.elements [indexToChange] = newValue;
  445. }
  446. /** Adds elements from an array to the end of this array.
  447. @param elementsToAdd an array of some kind of object from which elements
  448. can be constructed.
  449. @param numElementsToAdd how many elements are in this other array
  450. @see add
  451. */
  452. template <typename Type>
  453. void addArray (const Type* elementsToAdd, int numElementsToAdd)
  454. {
  455. if (numElementsToAdd > 0)
  456. {
  457. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  458. while (--numElementsToAdd >= 0)
  459. {
  460. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  461. ++numUsed;
  462. }
  463. }
  464. }
  465. /** Adds elements from a null-terminated array of pointers to the end of this array.
  466. @param elementsToAdd an array of pointers to some kind of object from which elements
  467. can be constructed. This array must be terminated by a nullptr
  468. @see addArray
  469. */
  470. template <typename Type>
  471. void addNullTerminatedArray (const Type* const* elementsToAdd)
  472. {
  473. int num = 0;
  474. for (const Type* const* e = elementsToAdd; *e != nullptr; ++e)
  475. ++num;
  476. addArray (elementsToAdd, num);
  477. }
  478. /** This swaps the contents of this array with those of another array.
  479. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  480. because it just swaps their internal pointers.
  481. */
  482. template <class OtherArrayType>
  483. void swapWith (OtherArrayType& otherArray) noexcept
  484. {
  485. data.swapWith (otherArray.data);
  486. std::swap (numUsed, otherArray.numUsed);
  487. }
  488. /** Adds elements from another array to the end of this array.
  489. @param arrayToAddFrom the array from which to copy the elements
  490. @param startIndex the first element of the other array to start copying from
  491. @param numElementsToAdd how many elements to add from the other array. If this
  492. value is negative or greater than the number of available elements,
  493. all available elements will be copied.
  494. @see add
  495. */
  496. template <class OtherArrayType>
  497. void addArray (const OtherArrayType& arrayToAddFrom,
  498. int startIndex = 0,
  499. int numElementsToAdd = -1)
  500. {
  501. if (startIndex < 0)
  502. {
  503. wassertfalse;
  504. startIndex = 0;
  505. }
  506. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  507. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  508. while (--numElementsToAdd >= 0)
  509. add (arrayToAddFrom.getUnchecked (startIndex++));
  510. }
  511. /** This will enlarge or shrink the array to the given number of elements, by adding
  512. or removing items from its end.
  513. If the array is smaller than the given target size, empty elements will be appended
  514. until its size is as specified. If its size is larger than the target, items will be
  515. removed from its end to shorten it.
  516. */
  517. void resize (const int targetNumItems)
  518. {
  519. wassert (targetNumItems >= 0);
  520. const int numToAdd = targetNumItems - numUsed;
  521. if (numToAdd > 0)
  522. insertMultiple (numUsed, ElementType(), numToAdd);
  523. else if (numToAdd < 0)
  524. removeRange (targetNumItems, -numToAdd);
  525. }
  526. /** Inserts a new element into the array, assuming that the array is sorted.
  527. This will use a comparator to find the position at which the new element
  528. should go. If the array isn't sorted, the behaviour of this
  529. method will be unpredictable.
  530. @param comparator the comparator to use to compare the elements - see the sort()
  531. method for details about the form this object should take
  532. @param newElement the new element to insert to the array
  533. @returns the index at which the new item was added
  534. @see addUsingDefaultSort, add, sort
  535. */
  536. template <class ElementComparator>
  537. int addSorted (ElementComparator& comparator, ParameterType newElement)
  538. {
  539. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  540. insert (index, newElement);
  541. return index;
  542. }
  543. /** Inserts a new element into the array, assuming that the array is sorted.
  544. This will use the DefaultElementComparator class for sorting, so your ElementType
  545. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  546. method will be unpredictable.
  547. @param newElement the new element to insert to the array
  548. @see addSorted, sort
  549. */
  550. void addUsingDefaultSort (ParameterType newElement)
  551. {
  552. DefaultElementComparator <ElementType> comparator;
  553. addSorted (comparator, newElement);
  554. }
  555. /** Finds the index of an element in the array, assuming that the array is sorted.
  556. This will use a comparator to do a binary-chop to find the index of the given
  557. element, if it exists. If the array isn't sorted, the behaviour of this
  558. method will be unpredictable.
  559. @param comparator the comparator to use to compare the elements - see the sort()
  560. method for details about the form this object should take
  561. @param elementToLookFor the element to search for
  562. @returns the index of the element, or -1 if it's not found
  563. @see addSorted, sort
  564. */
  565. template <typename ElementComparator, typename TargetValueType>
  566. int indexOfSorted (ElementComparator& comparator, TargetValueType elementToLookFor) const
  567. {
  568. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  569. // avoids getting warning messages about the parameter being unused
  570. for (int s = 0, e = numUsed;;)
  571. {
  572. if (s >= e)
  573. return -1;
  574. if (comparator.compareElements (elementToLookFor, data.elements [s]) == 0)
  575. return s;
  576. const int halfway = (s + e) / 2;
  577. if (halfway == s)
  578. return -1;
  579. if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  580. s = halfway;
  581. else
  582. e = halfway;
  583. }
  584. }
  585. //==============================================================================
  586. /** Removes an element from the array.
  587. This will remove the element at a given index, and move back
  588. all the subsequent elements to close the gap.
  589. If the index passed in is out-of-range, nothing will happen.
  590. @param indexToRemove the index of the element to remove
  591. @see removeAndReturn, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  592. */
  593. void remove (int indexToRemove)
  594. {
  595. if (isPositiveAndBelow (indexToRemove, numUsed))
  596. {
  597. wassert (data.elements != nullptr);
  598. removeInternal (indexToRemove);
  599. }
  600. }
  601. /** Removes an element from the array.
  602. This will remove the element at a given index, and move back
  603. all the subsequent elements to close the gap.
  604. If the index passed in is out-of-range, nothing will happen.
  605. @param indexToRemove the index of the element to remove
  606. @returns the element that has been removed
  607. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange
  608. */
  609. ElementType removeAndReturn (const int indexToRemove)
  610. {
  611. if (isPositiveAndBelow (indexToRemove, numUsed))
  612. {
  613. wassert (data.elements != nullptr);
  614. ElementType removed (data.elements[indexToRemove]);
  615. removeInternal (indexToRemove);
  616. return removed;
  617. }
  618. return ElementType();
  619. }
  620. /** Removes an element from the array.
  621. This will remove the element pointed to by the given iterator,
  622. and move back all the subsequent elements to close the gap.
  623. If the iterator passed in does not point to an element within the
  624. array, behaviour is undefined.
  625. @param elementToRemove a pointer to the element to remove
  626. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange, removeIf
  627. */
  628. void remove (const ElementType* elementToRemove)
  629. {
  630. wassert (elementToRemove != nullptr);
  631. wassert (data.elements != nullptr);
  632. const int indexToRemove = int (elementToRemove - data.elements);
  633. if (! isPositiveAndBelow (indexToRemove, numUsed))
  634. {
  635. wassertfalse;
  636. return;
  637. }
  638. removeInternal (indexToRemove);
  639. }
  640. /** Removes an item from the array.
  641. This will remove the first occurrence of the given element from the array.
  642. If the item isn't found, no action is taken.
  643. @param valueToRemove the object to try to remove
  644. @see remove, removeRange, removeIf
  645. */
  646. void removeFirstMatchingValue (ParameterType valueToRemove)
  647. {
  648. ElementType* const e = data.elements;
  649. for (int i = 0; i < numUsed; ++i)
  650. {
  651. if (valueToRemove == e[i])
  652. {
  653. removeInternal (i);
  654. break;
  655. }
  656. }
  657. }
  658. /** Removes items from the array.
  659. This will remove all occurrences of the given element from the array.
  660. If no such items are found, no action is taken.
  661. @param valueToRemove the object to try to remove
  662. @return how many objects were removed.
  663. @see remove, removeRange, removeIf
  664. */
  665. int removeAllInstancesOf (ParameterType valueToRemove)
  666. {
  667. int numRemoved = 0;
  668. for (int i = numUsed; --i >= 0;)
  669. {
  670. if (valueToRemove == data.elements[i])
  671. {
  672. removeInternal (i);
  673. ++numRemoved;
  674. }
  675. }
  676. return numRemoved;
  677. }
  678. /** Removes items from the array.
  679. This will remove all objects from the array that match a condition.
  680. If no such items are found, no action is taken.
  681. @param predicate the condition when to remove an item. Must be a callable
  682. type that takes an ElementType and returns a bool
  683. @return how many objects were removed.
  684. @see remove, removeRange, removeAllInstancesOf
  685. */
  686. template <typename PredicateType>
  687. int removeIf (PredicateType predicate)
  688. {
  689. int numRemoved = 0;
  690. for (int i = numUsed; --i >= 0;)
  691. {
  692. if (predicate (data.elements[i]) == true)
  693. {
  694. removeInternal (i);
  695. ++numRemoved;
  696. }
  697. }
  698. return numRemoved;
  699. }
  700. /** Removes a range of elements from the array.
  701. This will remove a set of elements, starting from the given index,
  702. and move subsequent elements down to close the gap.
  703. If the range extends beyond the bounds of the array, it will
  704. be safely clipped to the size of the array.
  705. @param startIndex the index of the first element to remove
  706. @param numberToRemove how many elements should be removed
  707. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeIf
  708. */
  709. void removeRange (int startIndex, int numberToRemove)
  710. {
  711. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  712. startIndex = jlimit (0, numUsed, startIndex);
  713. numberToRemove = endIndex - startIndex;
  714. if (numberToRemove > 0)
  715. {
  716. #if 1
  717. ElementType* const e = data.elements + startIndex;
  718. const int numToShift = numUsed - endIndex;
  719. if (numToShift > 0)
  720. data.moveMemory (e, e + numberToRemove, numToShift);
  721. for (int i = 0; i < numberToRemove; ++i)
  722. e[numToShift + i].~ElementType();
  723. #else
  724. ElementType* dst = data.elements + startIndex;
  725. ElementType* src = dst + numberToRemove;
  726. const int numToShift = numUsed - endIndex;
  727. for (int i = 0; i < numToShift; ++i)
  728. data.moveElement (dst++, std::move (*(src++)));
  729. for (int i = 0; i < numberToRemove; ++i)
  730. (dst++)->~ElementType();
  731. #endif
  732. numUsed -= numberToRemove;
  733. minimiseStorageAfterRemoval();
  734. }
  735. }
  736. /** Removes the last n elements from the array.
  737. @param howManyToRemove how many elements to remove from the end of the array
  738. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  739. */
  740. void removeLast (int howManyToRemove = 1)
  741. {
  742. if (howManyToRemove > numUsed)
  743. howManyToRemove = numUsed;
  744. for (int i = 1; i <= howManyToRemove; ++i)
  745. data.elements [numUsed - i].~ElementType();
  746. numUsed -= howManyToRemove;
  747. minimiseStorageAfterRemoval();
  748. }
  749. /** Removes any elements which are also in another array.
  750. @param otherArray the other array in which to look for elements to remove
  751. @see removeValuesNotIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  752. */
  753. template <class OtherArrayType>
  754. void removeValuesIn (const OtherArrayType& otherArray)
  755. {
  756. if (this == &otherArray)
  757. {
  758. clear();
  759. }
  760. else
  761. {
  762. if (otherArray.size() > 0)
  763. {
  764. for (int i = numUsed; --i >= 0;)
  765. if (otherArray.contains (data.elements [i]))
  766. removeInternal (i);
  767. }
  768. }
  769. }
  770. /** Removes any elements which are not found in another array.
  771. Only elements which occur in this other array will be retained.
  772. @param otherArray the array in which to look for elements NOT to remove
  773. @see removeValuesIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  774. */
  775. template <class OtherArrayType>
  776. void removeValuesNotIn (const OtherArrayType& otherArray)
  777. {
  778. if (this != &otherArray)
  779. {
  780. if (otherArray.size() <= 0)
  781. {
  782. clear();
  783. }
  784. else
  785. {
  786. for (int i = numUsed; --i >= 0;)
  787. if (! otherArray.contains (data.elements [i]))
  788. removeInternal (i);
  789. }
  790. }
  791. }
  792. /** Swaps over two elements in the array.
  793. This swaps over the elements found at the two indexes passed in.
  794. If either index is out-of-range, this method will do nothing.
  795. @param index1 index of one of the elements to swap
  796. @param index2 index of the other element to swap
  797. */
  798. void swap (const int index1,
  799. const int index2)
  800. {
  801. if (isPositiveAndBelow (index1, numUsed)
  802. && isPositiveAndBelow (index2, numUsed))
  803. {
  804. std::swap (data.elements [index1],
  805. data.elements [index2]);
  806. }
  807. }
  808. //==============================================================================
  809. /** Reduces the amount of storage being used by the array.
  810. Arrays typically allocate slightly more storage than they need, and after
  811. removing elements, they may have quite a lot of unused space allocated.
  812. This method will reduce the amount of allocated storage to a minimum.
  813. */
  814. bool minimiseStorageOverheads() noexcept
  815. {
  816. return data.shrinkToNoMoreThan (numUsed);
  817. }
  818. /** Increases the array's internal storage to hold a minimum number of elements.
  819. Calling this before adding a large known number of elements means that
  820. the array won't have to keep dynamically resizing itself as the elements
  821. are added, and it'll therefore be more efficient.
  822. */
  823. bool ensureStorageAllocated (const int minNumElements) noexcept
  824. {
  825. return data.ensureAllocatedSize (minNumElements);
  826. }
  827. //==============================================================================
  828. /** Sorts the array using a default comparison operation.
  829. If the type of your elements isn't supported by the DefaultElementComparator class
  830. then you may need to use the other version of sort, which takes a custom comparator.
  831. */
  832. void sort()
  833. {
  834. DefaultElementComparator<ElementType> comparator;
  835. sort (comparator);
  836. }
  837. /** Sorts the elements in the array.
  838. This will use a comparator object to sort the elements into order. The object
  839. passed must have a method of the form:
  840. @code
  841. int compareElements (ElementType first, ElementType second);
  842. @endcode
  843. ..and this method must return:
  844. - a value of < 0 if the first comes before the second
  845. - a value of 0 if the two objects are equivalent
  846. - a value of > 0 if the second comes before the first
  847. To improve performance, the compareElements() method can be declared as static or const.
  848. @param comparator the comparator to use for comparing elements.
  849. @param retainOrderOfEquivalentItems if this is true, then items
  850. which the comparator says are equivalent will be
  851. kept in the order in which they currently appear
  852. in the array. This is slower to perform, but may
  853. be important in some cases. If it's false, a faster
  854. algorithm is used, but equivalent elements may be
  855. rearranged.
  856. @see addSorted, indexOfSorted, sortArray
  857. */
  858. template <class ElementComparator>
  859. void sort (ElementComparator& comparator,
  860. const bool retainOrderOfEquivalentItems = false)
  861. {
  862. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  863. // avoids getting warning messages about the parameter being unused
  864. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  865. }
  866. private:
  867. //==============================================================================
  868. ArrayAllocationBase <ElementType> data;
  869. int numUsed;
  870. void removeInternal (const int indexToRemove)
  871. {
  872. --numUsed;
  873. ElementType* const e = data.elements + indexToRemove;
  874. e->~ElementType();
  875. const int numberToShift = numUsed - indexToRemove;
  876. if (numberToShift > 0)
  877. data.moveMemory (e, e + 1, static_cast<size_t>(numberToShift));
  878. minimiseStorageAfterRemoval();
  879. }
  880. inline void deleteAllElements() noexcept
  881. {
  882. for (int i = 0; i < numUsed; ++i)
  883. data.elements[i].~ElementType();
  884. }
  885. void minimiseStorageAfterRemoval()
  886. {
  887. CARLA_SAFE_ASSERT_RETURN(numUsed >= 0,);
  888. const size_t snumUsed = static_cast<size_t>(numUsed);
  889. if (data.numAllocated > jmax (minimumAllocatedSize, snumUsed * 2U))
  890. data.shrinkToNoMoreThan (jmax (snumUsed, jmax (minimumAllocatedSize, 64U / sizeof (ElementType))));
  891. }
  892. };
  893. }
  894. #endif // WATER_ARRAY_H_INCLUDED