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.

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