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.

1288 lines
47KB

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