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.

1238 lines
45KB

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