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.

1299 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. #if JUCE_COMPILER_SUPPORTS_INITIALIZER_LISTS
  112. template <typename TypeToCreateFrom>
  113. Array (const std::initializer_list<TypeToCreateFrom>& items)
  114. {
  115. addArray (items);
  116. }
  117. #endif
  118. /** Destructor. */
  119. ~Array()
  120. {
  121. deleteAllElements();
  122. }
  123. /** Copies another array.
  124. @param other the array to copy
  125. */
  126. Array& operator= (const Array& other)
  127. {
  128. if (this != &other)
  129. {
  130. auto otherCopy (other);
  131. swapWith (otherCopy);
  132. }
  133. return *this;
  134. }
  135. Array& operator= (Array&& other) noexcept
  136. {
  137. const ScopedLockType lock (getLock());
  138. deleteAllElements();
  139. data = static_cast<ArrayAllocationBase<ElementType, TypeOfCriticalSectionToUse>&&> (other.data);
  140. numUsed = other.numUsed;
  141. other.numUsed = 0;
  142. return *this;
  143. }
  144. //==============================================================================
  145. /** Compares this array to another one.
  146. Two arrays are considered equal if they both contain the same set of
  147. elements, in the same order.
  148. @param other the other array to compare with
  149. */
  150. template <class OtherArrayType>
  151. bool operator== (const OtherArrayType& other) const
  152. {
  153. const ScopedLockType lock (getLock());
  154. const typename OtherArrayType::ScopedLockType lock2 (other.getLock());
  155. if (numUsed != other.numUsed)
  156. return false;
  157. for (int i = numUsed; --i >= 0;)
  158. if (! (data.elements[i] == other.data.elements[i]))
  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[] (const 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 ElementType();
  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 (const 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 (const 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 ElementType();
  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 ElementType();
  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 (const 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 (const 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. #if JUCE_COMPILER_SUPPORTS_INITIALIZER_LISTS
  549. template <typename TypeToCreateFrom>
  550. void addArray (const std::initializer_list<TypeToCreateFrom>& items)
  551. {
  552. const ScopedLockType lock (getLock());
  553. data.ensureAllocatedSize (numUsed + (int) items.size());
  554. for (auto& item : items)
  555. {
  556. new (data.elements + numUsed) ElementType (item);
  557. ++numUsed;
  558. }
  559. }
  560. #endif
  561. /** Adds elements from a null-terminated array of pointers to the end of this array.
  562. @param elementsToAdd an array of pointers to some kind of object from which elements
  563. can be constructed. This array must be terminated by a nullptr
  564. @see addArray
  565. */
  566. template <typename Type>
  567. void addNullTerminatedArray (const Type* const* elementsToAdd)
  568. {
  569. int num = 0;
  570. for (auto e = elementsToAdd; *e != nullptr; ++e)
  571. ++num;
  572. addArray (elementsToAdd, num);
  573. }
  574. /** This swaps the contents of this array with those of another array.
  575. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  576. because it just swaps their internal pointers.
  577. */
  578. template <class OtherArrayType>
  579. void swapWith (OtherArrayType& otherArray) noexcept
  580. {
  581. const ScopedLockType lock1 (getLock());
  582. const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
  583. data.swapWith (otherArray.data);
  584. std::swap (numUsed, otherArray.numUsed);
  585. }
  586. /** Adds elements from another array to the end of this array.
  587. @param arrayToAddFrom the array from which to copy the elements
  588. @param startIndex the first element of the other array to start copying from
  589. @param numElementsToAdd how many elements to add from the other array. If this
  590. value is negative or greater than the number of available elements,
  591. all available elements will be copied.
  592. @see add
  593. */
  594. template <class OtherArrayType>
  595. void addArray (const OtherArrayType& arrayToAddFrom,
  596. int startIndex = 0,
  597. int numElementsToAdd = -1)
  598. {
  599. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  600. {
  601. const ScopedLockType lock2 (getLock());
  602. if (startIndex < 0)
  603. {
  604. jassertfalse;
  605. startIndex = 0;
  606. }
  607. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  608. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  609. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  610. while (--numElementsToAdd >= 0)
  611. addAssumingCapacityIsReady (arrayToAddFrom.getUnchecked (startIndex++));
  612. }
  613. }
  614. /** This will enlarge or shrink the array to the given number of elements, by adding
  615. or removing items from its end.
  616. If the array is smaller than the given target size, empty elements will be appended
  617. until its size is as specified. If its size is larger than the target, items will be
  618. removed from its end to shorten it.
  619. */
  620. void resize (const int targetNumItems)
  621. {
  622. jassert (targetNumItems >= 0);
  623. auto numToAdd = targetNumItems - numUsed;
  624. if (numToAdd > 0)
  625. insertMultiple (numUsed, ElementType(), numToAdd);
  626. else if (numToAdd < 0)
  627. removeRange (targetNumItems, -numToAdd);
  628. }
  629. /** Inserts a new element into the array, assuming that the array is sorted.
  630. This will use a comparator to find the position at which the new element
  631. should go. If the array isn't sorted, the behaviour of this
  632. method will be unpredictable.
  633. @param comparator the comparator to use to compare the elements - see the sort()
  634. method for details about the form this object should take
  635. @param newElement the new element to insert to the array
  636. @returns the index at which the new item was added
  637. @see addUsingDefaultSort, add, sort
  638. */
  639. template <class ElementComparator>
  640. int addSorted (ElementComparator& comparator, ParameterType newElement)
  641. {
  642. const ScopedLockType lock (getLock());
  643. auto index = findInsertIndexInSortedArray (comparator, data.elements.get(), newElement, 0, numUsed);
  644. insert (index, newElement);
  645. return index;
  646. }
  647. /** Inserts a new element into the array, assuming that the array is sorted.
  648. This will use the DefaultElementComparator class for sorting, so your ElementType
  649. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  650. method will be unpredictable.
  651. @param newElement the new element to insert to the array
  652. @see addSorted, sort
  653. */
  654. void addUsingDefaultSort (ParameterType newElement)
  655. {
  656. DefaultElementComparator <ElementType> comparator;
  657. addSorted (comparator, newElement);
  658. }
  659. /** Finds the index of an element in the array, assuming that the array is sorted.
  660. This will use a comparator to do a binary-chop to find the index of the given
  661. element, if it exists. If the array isn't sorted, the behaviour of this
  662. method will be unpredictable.
  663. @param comparator the comparator to use to compare the elements - see the sort()
  664. method for details about the form this object should take
  665. @param elementToLookFor the element to search for
  666. @returns the index of the element, or -1 if it's not found
  667. @see addSorted, sort
  668. */
  669. template <typename ElementComparator, typename TargetValueType>
  670. int indexOfSorted (ElementComparator& comparator, TargetValueType elementToLookFor) const
  671. {
  672. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  673. // avoids getting warning messages about the parameter being unused
  674. const ScopedLockType lock (getLock());
  675. for (int s = 0, e = numUsed;;)
  676. {
  677. if (s >= e)
  678. return -1;
  679. if (comparator.compareElements (elementToLookFor, data.elements[s]) == 0)
  680. return s;
  681. auto halfway = (s + e) / 2;
  682. if (halfway == s)
  683. return -1;
  684. if (comparator.compareElements (elementToLookFor, data.elements[halfway]) >= 0)
  685. s = halfway;
  686. else
  687. e = halfway;
  688. }
  689. }
  690. //==============================================================================
  691. /** Removes an element from the array.
  692. This will remove the element at a given index, and move back
  693. all the subsequent elements to close the gap.
  694. If the index passed in is out-of-range, nothing will happen.
  695. @param indexToRemove the index of the element to remove
  696. @see removeAndReturn, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  697. */
  698. void remove (int indexToRemove)
  699. {
  700. const ScopedLockType lock (getLock());
  701. if (isPositiveAndBelow (indexToRemove, numUsed))
  702. {
  703. jassert (data.elements != nullptr);
  704. removeInternal (indexToRemove);
  705. }
  706. }
  707. /** Removes an element from the array.
  708. This will remove the element at a given index, and move back
  709. all the subsequent elements to close the gap.
  710. If the index passed in is out-of-range, nothing will happen.
  711. @param indexToRemove the index of the element to remove
  712. @returns the element that has been removed
  713. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange
  714. */
  715. ElementType removeAndReturn (int indexToRemove)
  716. {
  717. const ScopedLockType lock (getLock());
  718. if (isPositiveAndBelow (indexToRemove, numUsed))
  719. {
  720. jassert (data.elements != nullptr);
  721. ElementType removed (data.elements[indexToRemove]);
  722. removeInternal (indexToRemove);
  723. return removed;
  724. }
  725. return {};
  726. }
  727. /** Removes an element from the array.
  728. This will remove the element pointed to by the given iterator,
  729. and move back all the subsequent elements to close the gap.
  730. If the iterator passed in does not point to an element within the
  731. array, behaviour is undefined.
  732. @param elementToRemove a pointer to the element to remove
  733. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange, removeIf
  734. */
  735. void remove (const ElementType* elementToRemove)
  736. {
  737. jassert (elementToRemove != nullptr);
  738. const ScopedLockType lock (getLock());
  739. jassert (data.elements != nullptr);
  740. auto indexToRemove = (int) (elementToRemove - data.elements);
  741. if (! isPositiveAndBelow (indexToRemove, numUsed))
  742. {
  743. jassertfalse;
  744. return;
  745. }
  746. removeInternal (indexToRemove);
  747. }
  748. /** Removes an item from the array.
  749. This will remove the first occurrence of the given element from the array.
  750. If the item isn't found, no action is taken.
  751. @param valueToRemove the object to try to remove
  752. @see remove, removeRange, removeIf
  753. */
  754. void removeFirstMatchingValue (ParameterType valueToRemove)
  755. {
  756. const ScopedLockType lock (getLock());
  757. auto* e = data.elements.get();
  758. for (int i = 0; i < numUsed; ++i)
  759. {
  760. if (valueToRemove == e[i])
  761. {
  762. removeInternal (i);
  763. break;
  764. }
  765. }
  766. }
  767. /** Removes items from the array.
  768. This will remove all occurrences of the given element from the array.
  769. If no such items are found, no action is taken.
  770. @param valueToRemove the object to try to remove
  771. @return how many objects were removed.
  772. @see remove, removeRange, removeIf
  773. */
  774. int removeAllInstancesOf (ParameterType valueToRemove)
  775. {
  776. int numRemoved = 0;
  777. const ScopedLockType lock (getLock());
  778. for (int i = numUsed; --i >= 0;)
  779. {
  780. if (valueToRemove == data.elements[i])
  781. {
  782. removeInternal (i);
  783. ++numRemoved;
  784. }
  785. }
  786. return numRemoved;
  787. }
  788. /** Removes items from the array.
  789. This will remove all objects from the array that match a condition.
  790. If no such items are found, no action is taken.
  791. @param predicate the condition when to remove an item. Must be a callable
  792. type that takes an ElementType and returns a bool
  793. @return how many objects were removed.
  794. @see remove, removeRange, removeAllInstancesOf
  795. */
  796. template <typename PredicateType>
  797. int removeIf (PredicateType predicate)
  798. {
  799. int numRemoved = 0;
  800. const ScopedLockType lock (getLock());
  801. for (int i = numUsed; --i >= 0;)
  802. {
  803. if (predicate (data.elements[i]))
  804. {
  805. removeInternal (i);
  806. ++numRemoved;
  807. }
  808. }
  809. return numRemoved;
  810. }
  811. /** Removes a range of elements from the array.
  812. This will remove a set of elements, starting from the given index,
  813. and move subsequent elements down to close the gap.
  814. If the range extends beyond the bounds of the array, it will
  815. be safely clipped to the size of the array.
  816. @param startIndex the index of the first element to remove
  817. @param numberToRemove how many elements should be removed
  818. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeIf
  819. */
  820. void removeRange (int startIndex, int numberToRemove)
  821. {
  822. const ScopedLockType lock (getLock());
  823. auto endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  824. startIndex = jlimit (0, numUsed, startIndex);
  825. if (endIndex > startIndex)
  826. {
  827. auto* e = data.elements + startIndex;
  828. numberToRemove = endIndex - startIndex;
  829. for (int i = 0; i < numberToRemove; ++i)
  830. e[i].~ElementType();
  831. auto numToShift = numUsed - endIndex;
  832. if (numToShift > 0)
  833. memmove (e, e + numberToRemove, ((size_t) numToShift) * sizeof (ElementType));
  834. numUsed -= numberToRemove;
  835. minimiseStorageAfterRemoval();
  836. }
  837. }
  838. /** Removes the last n elements from the array.
  839. @param howManyToRemove how many elements to remove from the end of the array
  840. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  841. */
  842. void removeLast (int howManyToRemove = 1)
  843. {
  844. const ScopedLockType lock (getLock());
  845. if (howManyToRemove > numUsed)
  846. howManyToRemove = numUsed;
  847. for (int i = 1; i <= howManyToRemove; ++i)
  848. data.elements[numUsed - i].~ElementType();
  849. numUsed -= howManyToRemove;
  850. minimiseStorageAfterRemoval();
  851. }
  852. /** Removes any elements which are also in another array.
  853. @param otherArray the other array in which to look for elements to remove
  854. @see removeValuesNotIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  855. */
  856. template <class OtherArrayType>
  857. void removeValuesIn (const OtherArrayType& otherArray)
  858. {
  859. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  860. const ScopedLockType lock2 (getLock());
  861. if (this == &otherArray)
  862. {
  863. clear();
  864. }
  865. else
  866. {
  867. if (otherArray.size() > 0)
  868. {
  869. for (int i = numUsed; --i >= 0;)
  870. if (otherArray.contains (data.elements[i]))
  871. removeInternal (i);
  872. }
  873. }
  874. }
  875. /** Removes any elements which are not found in another array.
  876. Only elements which occur in this other array will be retained.
  877. @param otherArray the array in which to look for elements NOT to remove
  878. @see removeValuesIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  879. */
  880. template <class OtherArrayType>
  881. void removeValuesNotIn (const OtherArrayType& otherArray)
  882. {
  883. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  884. const ScopedLockType lock2 (getLock());
  885. if (this != &otherArray)
  886. {
  887. if (otherArray.size() <= 0)
  888. {
  889. clear();
  890. }
  891. else
  892. {
  893. for (int i = numUsed; --i >= 0;)
  894. if (! otherArray.contains (data.elements[i]))
  895. removeInternal (i);
  896. }
  897. }
  898. }
  899. /** Swaps over two elements in the array.
  900. This swaps over the elements found at the two indexes passed in.
  901. If either index is out-of-range, this method will do nothing.
  902. @param index1 index of one of the elements to swap
  903. @param index2 index of the other element to swap
  904. */
  905. void swap (int index1, int index2)
  906. {
  907. const ScopedLockType lock (getLock());
  908. if (isPositiveAndBelow (index1, numUsed)
  909. && isPositiveAndBelow (index2, numUsed))
  910. {
  911. std::swap (data.elements[index1],
  912. data.elements[index2]);
  913. }
  914. }
  915. /** Moves one of the values to a different position.
  916. This will move the value to a specified index, shuffling along
  917. any intervening elements as required.
  918. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  919. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  920. @param currentIndex the index of the value to be moved. If this isn't a
  921. valid index, then nothing will be done
  922. @param newIndex the index at which you'd like this value to end up. If this
  923. is less than zero, the value will be moved to the end
  924. of the array
  925. */
  926. void move (int currentIndex, int newIndex) noexcept
  927. {
  928. if (currentIndex != newIndex)
  929. {
  930. const ScopedLockType lock (getLock());
  931. if (isPositiveAndBelow (currentIndex, numUsed))
  932. {
  933. if (! isPositiveAndBelow (newIndex, numUsed))
  934. newIndex = numUsed - 1;
  935. char tempCopy[sizeof (ElementType)];
  936. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  937. if (newIndex > currentIndex)
  938. {
  939. memmove (data.elements + currentIndex,
  940. data.elements + currentIndex + 1,
  941. sizeof (ElementType) * (size_t) (newIndex - currentIndex));
  942. }
  943. else
  944. {
  945. memmove (data.elements + newIndex + 1,
  946. data.elements + newIndex,
  947. sizeof (ElementType) * (size_t) (currentIndex - newIndex));
  948. }
  949. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  950. }
  951. }
  952. }
  953. //==============================================================================
  954. /** Reduces the amount of storage being used by the array.
  955. Arrays typically allocate slightly more storage than they need, and after
  956. removing elements, they may have quite a lot of unused space allocated.
  957. This method will reduce the amount of allocated storage to a minimum.
  958. */
  959. void minimiseStorageOverheads()
  960. {
  961. const ScopedLockType lock (getLock());
  962. data.shrinkToNoMoreThan (numUsed);
  963. }
  964. /** Increases the array's internal storage to hold a minimum number of elements.
  965. Calling this before adding a large known number of elements means that
  966. the array won't have to keep dynamically resizing itself as the elements
  967. are added, and it'll therefore be more efficient.
  968. */
  969. void ensureStorageAllocated (const int minNumElements)
  970. {
  971. const ScopedLockType lock (getLock());
  972. data.ensureAllocatedSize (minNumElements);
  973. }
  974. //==============================================================================
  975. /** Sorts the array using a default comparison operation.
  976. If the type of your elements isn't supported by the DefaultElementComparator class
  977. then you may need to use the other version of sort, which takes a custom comparator.
  978. */
  979. void sort()
  980. {
  981. DefaultElementComparator<ElementType> comparator;
  982. sort (comparator);
  983. }
  984. /** Sorts the elements in the array.
  985. This will use a comparator object to sort the elements into order. The object
  986. passed must have a method of the form:
  987. @code
  988. int compareElements (ElementType first, ElementType second);
  989. @endcode
  990. ..and this method must return:
  991. - a value of < 0 if the first comes before the second
  992. - a value of 0 if the two objects are equivalent
  993. - a value of > 0 if the second comes before the first
  994. To improve performance, the compareElements() method can be declared as static or const.
  995. @param comparator the comparator to use for comparing elements.
  996. @param retainOrderOfEquivalentItems if this is true, then items
  997. which the comparator says are equivalent will be
  998. kept in the order in which they currently appear
  999. in the array. This is slower to perform, but may
  1000. be important in some cases. If it's false, a faster
  1001. algorithm is used, but equivalent elements may be
  1002. rearranged.
  1003. @see addSorted, indexOfSorted, sortArray
  1004. */
  1005. template <class ElementComparator>
  1006. void sort (ElementComparator& comparator,
  1007. const bool retainOrderOfEquivalentItems = false)
  1008. {
  1009. const ScopedLockType lock (getLock());
  1010. ignoreUnused (comparator); // if you pass in an object with a static compareElements() method, this
  1011. // avoids getting warning messages about the parameter being unused
  1012. sortArray (comparator, data.elements.get(), 0, size() - 1, retainOrderOfEquivalentItems);
  1013. }
  1014. //==============================================================================
  1015. /** Returns the CriticalSection that locks this array.
  1016. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  1017. an object of ScopedLockType as an RAII lock for it.
  1018. */
  1019. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  1020. /** Returns the type of scoped lock to use for locking this array */
  1021. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  1022. //==============================================================================
  1023. #ifndef DOXYGEN
  1024. // Note that the swapWithArray method has been replaced by a more flexible templated version,
  1025. // and renamed "swapWith" to be more consistent with the names used in other classes.
  1026. JUCE_DEPRECATED_WITH_BODY (void swapWithArray (Array& other) noexcept, { swapWith (other); })
  1027. #endif
  1028. private:
  1029. //==============================================================================
  1030. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  1031. int numUsed = 0;
  1032. void removeInternal (const int indexToRemove)
  1033. {
  1034. --numUsed;
  1035. auto* e = data.elements + indexToRemove;
  1036. e->~ElementType();
  1037. auto numberToShift = numUsed - indexToRemove;
  1038. if (numberToShift > 0)
  1039. memmove (e, e + 1, ((size_t) numberToShift) * sizeof (ElementType));
  1040. minimiseStorageAfterRemoval();
  1041. }
  1042. inline void deleteAllElements() noexcept
  1043. {
  1044. for (int i = 0; i < numUsed; ++i)
  1045. data.elements[i].~ElementType();
  1046. }
  1047. void minimiseStorageAfterRemoval()
  1048. {
  1049. if (data.numAllocated > jmax (minimumAllocatedSize, numUsed * 2))
  1050. data.shrinkToNoMoreThan (jmax (numUsed, jmax (minimumAllocatedSize, 64 / (int) sizeof (ElementType))));
  1051. }
  1052. void addAssumingCapacityIsReady (const ElementType& e) { new (data.elements + numUsed++) ElementType (e); }
  1053. void addAssumingCapacityIsReady (ElementType&& e) { new (data.elements + numUsed++) ElementType (static_cast<ElementType&&> (e)); }
  1054. template <typename... OtherElements>
  1055. void addAssumingCapacityIsReady (const ElementType& firstNewElement, OtherElements... otherElements)
  1056. {
  1057. addAssumingCapacityIsReady (firstNewElement);
  1058. addAssumingCapacityIsReady (otherElements...);
  1059. }
  1060. template <typename... OtherElements>
  1061. void addAssumingCapacityIsReady (ElementType&& firstNewElement, OtherElements... otherElements)
  1062. {
  1063. addAssumingCapacityIsReady (static_cast<ElementType&&> (firstNewElement));
  1064. addAssumingCapacityIsReady (otherElements...);
  1065. }
  1066. };
  1067. } // namespace juce