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.

1270 lines
46KB

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