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.

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