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.

1242 lines
45KB

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