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.

1138 lines
42KB

  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. */
  182. inline int size() const noexcept
  183. {
  184. return numUsed;
  185. }
  186. /** Returns one of the elements in the array.
  187. If the index passed in is beyond the range of valid elements, this
  188. will return a default value.
  189. If you're certain that the index will always be a valid element, you
  190. can call getUnchecked() instead, which is faster.
  191. @param index the index of the element being requested (0 is the first element in the array)
  192. @see getUnchecked, getFirst, getLast
  193. */
  194. ElementType operator[] (const int index) const
  195. {
  196. const ScopedLockType lock (getLock());
  197. if (isPositiveAndBelow (index, numUsed))
  198. {
  199. jassert (data.elements != nullptr);
  200. return data.elements [index];
  201. }
  202. return ElementType();
  203. }
  204. /** Returns one of the elements in the array, without checking the index passed in.
  205. Unlike the operator[] method, this will try to return an element without
  206. checking that the index is within the bounds of the array, so should only
  207. be used when you're confident that it will always be a valid index.
  208. @param index the index of the element being requested (0 is the first element in the array)
  209. @see operator[], getFirst, getLast
  210. */
  211. inline ElementType getUnchecked (const int index) const
  212. {
  213. const ScopedLockType lock (getLock());
  214. jassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  215. return data.elements [index];
  216. }
  217. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  218. This is like getUnchecked, but returns a direct reference to the element, so that
  219. you can alter it directly. Obviously this can be dangerous, so only use it when
  220. absolutely necessary.
  221. @param index the index of the element being requested (0 is the first element in the array)
  222. @see operator[], getFirst, getLast
  223. */
  224. inline ElementType& getReference (const int index) const noexcept
  225. {
  226. const ScopedLockType lock (getLock());
  227. jassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr);
  228. return data.elements [index];
  229. }
  230. /** Returns the first element in the array, or a default value if the array is empty.
  231. @see operator[], getUnchecked, getLast
  232. */
  233. inline ElementType getFirst() const
  234. {
  235. const ScopedLockType lock (getLock());
  236. if (numUsed > 0)
  237. {
  238. jassert (data.elements != nullptr);
  239. return data.elements[0];
  240. }
  241. return ElementType();
  242. }
  243. /** Returns the last element in the array, or a default value if the array is empty.
  244. @see operator[], getUnchecked, getFirst
  245. */
  246. inline ElementType getLast() const
  247. {
  248. const ScopedLockType lock (getLock());
  249. if (numUsed > 0)
  250. {
  251. jassert (data.elements != nullptr);
  252. return data.elements[numUsed - 1];
  253. }
  254. return ElementType();
  255. }
  256. /** Returns a pointer to the actual array data.
  257. This pointer will only be valid until the next time a non-const method
  258. is called on the array.
  259. */
  260. inline ElementType* getRawDataPointer() noexcept
  261. {
  262. return data.elements;
  263. }
  264. //==============================================================================
  265. /** Returns a pointer to the first element in the array.
  266. This method is provided for compatibility with standard C++ iteration mechanisms.
  267. */
  268. inline ElementType* begin() const noexcept
  269. {
  270. return data.elements;
  271. }
  272. /** Returns a pointer to the element which follows the last element in the array.
  273. This method is provided for compatibility with standard C++ iteration mechanisms.
  274. */
  275. inline ElementType* end() const noexcept
  276. {
  277. #if JUCE_DEBUG
  278. if (data.elements == nullptr || numUsed <= 0) // (to keep static analysers happy)
  279. return data.elements;
  280. #endif
  281. return data.elements + numUsed;
  282. }
  283. //==============================================================================
  284. /** Finds the index of the first element which matches the value passed in.
  285. This will search the array for the given object, and return the index
  286. of its first occurrence. If the object isn't found, the method will return -1.
  287. @param elementToLookFor the value or object to look for
  288. @returns the index of the object, or -1 if it's not found
  289. */
  290. int indexOf (ParameterType elementToLookFor) const
  291. {
  292. const ScopedLockType lock (getLock());
  293. const ElementType* e = data.elements.getData();
  294. const ElementType* const end_ = e + numUsed;
  295. for (; e != end_; ++e)
  296. if (elementToLookFor == *e)
  297. return static_cast <int> (e - data.elements.getData());
  298. return -1;
  299. }
  300. /** Returns true if the array contains at least one occurrence of an object.
  301. @param elementToLookFor the value or object to look for
  302. @returns true if the item is found
  303. */
  304. bool contains (ParameterType elementToLookFor) const
  305. {
  306. const ScopedLockType lock (getLock());
  307. const ElementType* e = data.elements.getData();
  308. const ElementType* const end_ = e + numUsed;
  309. for (; e != end_; ++e)
  310. if (elementToLookFor == *e)
  311. return true;
  312. return false;
  313. }
  314. //==============================================================================
  315. /** Appends a new element at the end of the array.
  316. @param newElement the new object to add to the array
  317. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  318. */
  319. void add (const ElementType& newElement)
  320. {
  321. const ScopedLockType lock (getLock());
  322. data.ensureAllocatedSize (numUsed + 1);
  323. new (data.elements + numUsed++) ElementType (newElement);
  324. }
  325. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  326. /** Appends a new element at the end of the array.
  327. @param newElement the new object to add to the array
  328. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  329. */
  330. void add (ElementType&& newElement)
  331. {
  332. const ScopedLockType lock (getLock());
  333. data.ensureAllocatedSize (numUsed + 1);
  334. new (data.elements + numUsed++) ElementType (static_cast<ElementType&&> (newElement));
  335. }
  336. #endif
  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, 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. */
  443. void addIfNotAlreadyThere (ParameterType newElement)
  444. {
  445. const ScopedLockType lock (getLock());
  446. if (! contains (newElement))
  447. add (newElement);
  448. }
  449. /** Replaces an element with a new value.
  450. If the index is less than zero, this method does nothing.
  451. If the index is beyond the end of the array, the item is added to the end of the array.
  452. @param indexToChange the index whose value you want to change
  453. @param newValue the new value to set for this index.
  454. @see add, insert
  455. */
  456. void set (const int indexToChange, ParameterType newValue)
  457. {
  458. jassert (indexToChange >= 0);
  459. const ScopedLockType lock (getLock());
  460. if (isPositiveAndBelow (indexToChange, numUsed))
  461. {
  462. jassert (data.elements != nullptr);
  463. data.elements [indexToChange] = newValue;
  464. }
  465. else if (indexToChange >= 0)
  466. {
  467. data.ensureAllocatedSize (numUsed + 1);
  468. new (data.elements + numUsed++) ElementType (newValue);
  469. }
  470. }
  471. /** Replaces an element with a new value without doing any bounds-checking.
  472. This just sets a value directly in the array's internal storage, so you'd
  473. better make sure it's in range!
  474. @param indexToChange the index whose value you want to change
  475. @param newValue the new value to set for this index.
  476. @see set, getUnchecked
  477. */
  478. void setUnchecked (const int indexToChange, ParameterType newValue)
  479. {
  480. const ScopedLockType lock (getLock());
  481. jassert (isPositiveAndBelow (indexToChange, numUsed));
  482. data.elements [indexToChange] = newValue;
  483. }
  484. /** Adds elements from an array to the end of this array.
  485. @param elementsToAdd an array of some kind of object from which elements
  486. can be constructed.
  487. @param numElementsToAdd how many elements are in this other array
  488. @see add
  489. */
  490. template <typename Type>
  491. void addArray (const Type* elementsToAdd, int numElementsToAdd)
  492. {
  493. const ScopedLockType lock (getLock());
  494. if (numElementsToAdd > 0)
  495. {
  496. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  497. while (--numElementsToAdd >= 0)
  498. {
  499. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  500. ++numUsed;
  501. }
  502. }
  503. }
  504. #if JUCE_COMPILER_SUPPORTS_INITIALIZER_LISTS
  505. template <typename TypeToCreateFrom>
  506. void addArray (const std::initializer_list<TypeToCreateFrom>& items)
  507. {
  508. const ScopedLockType lock (getLock());
  509. data.ensureAllocatedSize (numUsed + (int) items.size());
  510. for (auto& item : items)
  511. {
  512. new (data.elements + numUsed) ElementType (item);
  513. ++numUsed;
  514. }
  515. }
  516. #endif
  517. /** Adds elements from a null-terminated array of pointers to the end of this array.
  518. @param elementsToAdd an array of pointers to some kind of object from which elements
  519. can be constructed. This array must be terminated by a nullptr
  520. @see addArray
  521. */
  522. template <typename Type>
  523. void addNullTerminatedArray (const Type* const* elementsToAdd)
  524. {
  525. int num = 0;
  526. for (const Type* const* e = elementsToAdd; *e != nullptr; ++e)
  527. ++num;
  528. addArray (elementsToAdd, num);
  529. }
  530. /** This swaps the contents of this array with those of another array.
  531. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  532. because it just swaps their internal pointers.
  533. */
  534. template <class OtherArrayType>
  535. void swapWith (OtherArrayType& otherArray) noexcept
  536. {
  537. const ScopedLockType lock1 (getLock());
  538. const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
  539. data.swapWith (otherArray.data);
  540. std::swap (numUsed, otherArray.numUsed);
  541. }
  542. /** Adds elements from another array to the end of this array.
  543. @param arrayToAddFrom the array from which to copy the elements
  544. @param startIndex the first element of the other array to start copying from
  545. @param numElementsToAdd how many elements to add from the other array. If this
  546. value is negative or greater than the number of available elements,
  547. all available elements will be copied.
  548. @see add
  549. */
  550. template <class OtherArrayType>
  551. void addArray (const OtherArrayType& arrayToAddFrom,
  552. int startIndex = 0,
  553. int numElementsToAdd = -1)
  554. {
  555. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  556. {
  557. const ScopedLockType lock2 (getLock());
  558. if (startIndex < 0)
  559. {
  560. jassertfalse;
  561. startIndex = 0;
  562. }
  563. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  564. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  565. while (--numElementsToAdd >= 0)
  566. add (arrayToAddFrom.getUnchecked (startIndex++));
  567. }
  568. }
  569. /** This will enlarge or shrink the array to the given number of elements, by adding
  570. or removing items from its end.
  571. If the array is smaller than the given target size, empty elements will be appended
  572. until its size is as specified. If its size is larger than the target, items will be
  573. removed from its end to shorten it.
  574. */
  575. void resize (const int targetNumItems)
  576. {
  577. jassert (targetNumItems >= 0);
  578. const int numToAdd = targetNumItems - numUsed;
  579. if (numToAdd > 0)
  580. insertMultiple (numUsed, ElementType(), numToAdd);
  581. else if (numToAdd < 0)
  582. removeRange (targetNumItems, -numToAdd);
  583. }
  584. /** Inserts a new element into the array, assuming that the array is sorted.
  585. This will use a comparator to find the position at which the new element
  586. should go. If the array isn't sorted, the behaviour of this
  587. method will be unpredictable.
  588. @param comparator the comparator to use to compare the elements - see the sort()
  589. method for details about the form this object should take
  590. @param newElement the new element to insert to the array
  591. @returns the index at which the new item was added
  592. @see addUsingDefaultSort, add, sort
  593. */
  594. template <class ElementComparator>
  595. int addSorted (ElementComparator& comparator, ParameterType newElement)
  596. {
  597. const ScopedLockType lock (getLock());
  598. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  599. insert (index, newElement);
  600. return index;
  601. }
  602. /** Inserts a new element into the array, assuming that the array is sorted.
  603. This will use the DefaultElementComparator class for sorting, so your ElementType
  604. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  605. method will be unpredictable.
  606. @param newElement the new element to insert to the array
  607. @see addSorted, sort
  608. */
  609. void addUsingDefaultSort (ParameterType newElement)
  610. {
  611. DefaultElementComparator <ElementType> comparator;
  612. addSorted (comparator, newElement);
  613. }
  614. /** Finds the index of an element in the array, assuming that the array is sorted.
  615. This will use a comparator to do a binary-chop to find the index of the given
  616. element, if it exists. If the array isn't sorted, the behaviour of this
  617. method will be unpredictable.
  618. @param comparator the comparator to use to compare the elements - see the sort()
  619. method for details about the form this object should take
  620. @param elementToLookFor the element to search for
  621. @returns the index of the element, or -1 if it's not found
  622. @see addSorted, sort
  623. */
  624. template <typename ElementComparator, typename TargetValueType>
  625. int indexOfSorted (ElementComparator& comparator, TargetValueType elementToLookFor) const
  626. {
  627. (void) comparator; // if you pass in an object with a static compareElements() method, this
  628. // avoids getting warning messages about the parameter being unused
  629. const ScopedLockType lock (getLock());
  630. for (int s = 0, e = numUsed;;)
  631. {
  632. if (s >= e)
  633. return -1;
  634. if (comparator.compareElements (elementToLookFor, data.elements [s]) == 0)
  635. return s;
  636. const int halfway = (s + e) / 2;
  637. if (halfway == s)
  638. return -1;
  639. if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  640. s = halfway;
  641. else
  642. e = halfway;
  643. }
  644. }
  645. //==============================================================================
  646. /** Removes an element from the array.
  647. This will remove the element at a given index, and move back
  648. all the subsequent elements to close the gap.
  649. If the index passed in is out-of-range, nothing will happen.
  650. @param indexToRemove the index of the element to remove
  651. @returns the element that has been removed
  652. @see removeFirstMatchingValue, removeAllInstancesOf, removeRange
  653. */
  654. ElementType remove (const int indexToRemove)
  655. {
  656. const ScopedLockType lock (getLock());
  657. if (isPositiveAndBelow (indexToRemove, numUsed))
  658. {
  659. jassert (data.elements != nullptr);
  660. ElementType removed (data.elements[indexToRemove]);
  661. removeInternal (indexToRemove);
  662. return removed;
  663. }
  664. return ElementType();
  665. }
  666. /** Removes an item from the array.
  667. This will remove the first occurrence of the given element from the array.
  668. If the item isn't found, no action is taken.
  669. @param valueToRemove the object to try to remove
  670. @see remove, removeRange
  671. */
  672. void removeFirstMatchingValue (ParameterType valueToRemove)
  673. {
  674. const ScopedLockType lock (getLock());
  675. ElementType* const e = data.elements;
  676. for (int i = 0; i < numUsed; ++i)
  677. {
  678. if (valueToRemove == e[i])
  679. {
  680. removeInternal (i);
  681. break;
  682. }
  683. }
  684. }
  685. /** Removes an item from the array.
  686. This will remove all occurrences of the given element from the array.
  687. If no such items are found, no action is taken.
  688. @param valueToRemove the object to try to remove
  689. @see remove, removeRange
  690. */
  691. void removeAllInstancesOf (ParameterType valueToRemove)
  692. {
  693. const ScopedLockType lock (getLock());
  694. for (int i = numUsed; --i >= 0;)
  695. if (valueToRemove == data.elements[i])
  696. removeInternal (i);
  697. }
  698. /** Removes a range of elements from the array.
  699. This will remove a set of elements, starting from the given index,
  700. and move subsequent elements down to close the gap.
  701. If the range extends beyond the bounds of the array, it will
  702. be safely clipped to the size of the array.
  703. @param startIndex the index of the first element to remove
  704. @param numberToRemove how many elements should be removed
  705. @see remove, removeFirstMatchingValue, removeAllInstancesOf
  706. */
  707. void removeRange (int startIndex, int numberToRemove)
  708. {
  709. const ScopedLockType lock (getLock());
  710. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  711. startIndex = jlimit (0, numUsed, startIndex);
  712. if (endIndex > startIndex)
  713. {
  714. ElementType* const e = data.elements + startIndex;
  715. numberToRemove = endIndex - startIndex;
  716. for (int i = 0; i < numberToRemove; ++i)
  717. e[i].~ElementType();
  718. const int numToShift = numUsed - endIndex;
  719. if (numToShift > 0)
  720. memmove (e, e + numberToRemove, ((size_t) numToShift) * sizeof (ElementType));
  721. numUsed -= numberToRemove;
  722. minimiseStorageAfterRemoval();
  723. }
  724. }
  725. /** Removes the last n elements from the array.
  726. @param howManyToRemove how many elements to remove from the end of the array
  727. @see remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  728. */
  729. void removeLast (int howManyToRemove = 1)
  730. {
  731. const ScopedLockType lock (getLock());
  732. if (howManyToRemove > numUsed)
  733. howManyToRemove = numUsed;
  734. for (int i = 1; i <= howManyToRemove; ++i)
  735. data.elements [numUsed - i].~ElementType();
  736. numUsed -= howManyToRemove;
  737. minimiseStorageAfterRemoval();
  738. }
  739. /** Removes any elements which are also in another array.
  740. @param otherArray the other array in which to look for elements to remove
  741. @see removeValuesNotIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  742. */
  743. template <class OtherArrayType>
  744. void removeValuesIn (const OtherArrayType& otherArray)
  745. {
  746. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  747. const ScopedLockType lock2 (getLock());
  748. if (this == &otherArray)
  749. {
  750. clear();
  751. }
  752. else
  753. {
  754. if (otherArray.size() > 0)
  755. {
  756. for (int i = numUsed; --i >= 0;)
  757. if (otherArray.contains (data.elements [i]))
  758. removeInternal (i);
  759. }
  760. }
  761. }
  762. /** Removes any elements which are not found in another array.
  763. Only elements which occur in this other array will be retained.
  764. @param otherArray the array in which to look for elements NOT to remove
  765. @see removeValuesIn, remove, removeFirstMatchingValue, removeAllInstancesOf, removeRange
  766. */
  767. template <class OtherArrayType>
  768. void removeValuesNotIn (const OtherArrayType& otherArray)
  769. {
  770. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  771. const ScopedLockType lock2 (getLock());
  772. if (this != &otherArray)
  773. {
  774. if (otherArray.size() <= 0)
  775. {
  776. clear();
  777. }
  778. else
  779. {
  780. for (int i = numUsed; --i >= 0;)
  781. if (! otherArray.contains (data.elements [i]))
  782. removeInternal (i);
  783. }
  784. }
  785. }
  786. /** Swaps over two elements in the array.
  787. This swaps over the elements found at the two indexes passed in.
  788. If either index is out-of-range, this method will do nothing.
  789. @param index1 index of one of the elements to swap
  790. @param index2 index of the other element to swap
  791. */
  792. void swap (const int index1,
  793. const int index2)
  794. {
  795. const ScopedLockType lock (getLock());
  796. if (isPositiveAndBelow (index1, numUsed)
  797. && isPositiveAndBelow (index2, numUsed))
  798. {
  799. std::swap (data.elements [index1],
  800. data.elements [index2]);
  801. }
  802. }
  803. /** Moves one of the values to a different position.
  804. This will move the value to a specified index, shuffling along
  805. any intervening elements as required.
  806. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  807. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  808. @param currentIndex the index of the value to be moved. If this isn't a
  809. valid index, then nothing will be done
  810. @param newIndex the index at which you'd like this value to end up. If this
  811. is less than zero, the value will be moved to the end
  812. of the array
  813. */
  814. void move (const int currentIndex, int newIndex) noexcept
  815. {
  816. if (currentIndex != newIndex)
  817. {
  818. const ScopedLockType lock (getLock());
  819. if (isPositiveAndBelow (currentIndex, numUsed))
  820. {
  821. if (! isPositiveAndBelow (newIndex, numUsed))
  822. newIndex = numUsed - 1;
  823. char tempCopy [sizeof (ElementType)];
  824. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  825. if (newIndex > currentIndex)
  826. {
  827. memmove (data.elements + currentIndex,
  828. data.elements + currentIndex + 1,
  829. sizeof (ElementType) * (size_t) (newIndex - currentIndex));
  830. }
  831. else
  832. {
  833. memmove (data.elements + newIndex + 1,
  834. data.elements + newIndex,
  835. sizeof (ElementType) * (size_t) (currentIndex - newIndex));
  836. }
  837. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  838. }
  839. }
  840. }
  841. //==============================================================================
  842. /** Reduces the amount of storage being used by the array.
  843. Arrays typically allocate slightly more storage than they need, and after
  844. removing elements, they may have quite a lot of unused space allocated.
  845. This method will reduce the amount of allocated storage to a minimum.
  846. */
  847. void minimiseStorageOverheads()
  848. {
  849. const ScopedLockType lock (getLock());
  850. data.shrinkToNoMoreThan (numUsed);
  851. }
  852. /** Increases the array's internal storage to hold a minimum number of elements.
  853. Calling this before adding a large known number of elements means that
  854. the array won't have to keep dynamically resizing itself as the elements
  855. are added, and it'll therefore be more efficient.
  856. */
  857. void ensureStorageAllocated (const int minNumElements)
  858. {
  859. const ScopedLockType lock (getLock());
  860. data.ensureAllocatedSize (minNumElements);
  861. }
  862. //==============================================================================
  863. /** Sorts the elements in the array.
  864. This will use a comparator object to sort the elements into order. The object
  865. passed must have a method of the form:
  866. @code
  867. int compareElements (ElementType first, ElementType second);
  868. @endcode
  869. ..and this method must return:
  870. - a value of < 0 if the first comes before the second
  871. - a value of 0 if the two objects are equivalent
  872. - a value of > 0 if the second comes before the first
  873. To improve performance, the compareElements() method can be declared as static or const.
  874. @param comparator the comparator to use for comparing elements.
  875. @param retainOrderOfEquivalentItems if this is true, then items
  876. which the comparator says are equivalent will be
  877. kept in the order in which they currently appear
  878. in the array. This is slower to perform, but may
  879. be important in some cases. If it's false, a faster
  880. algorithm is used, but equivalent elements may be
  881. rearranged.
  882. @see addSorted, indexOfSorted, sortArray
  883. */
  884. template <class ElementComparator>
  885. void sort (ElementComparator& comparator,
  886. const bool retainOrderOfEquivalentItems = false) const
  887. {
  888. const ScopedLockType lock (getLock());
  889. (void) comparator; // if you pass in an object with a static compareElements() method, this
  890. // avoids getting warning messages about the parameter being unused
  891. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  892. }
  893. //==============================================================================
  894. /** Returns the CriticalSection that locks this array.
  895. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  896. an object of ScopedLockType as an RAII lock for it.
  897. */
  898. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  899. /** Returns the type of scoped lock to use for locking this array */
  900. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  901. //==============================================================================
  902. #ifndef DOXYGEN
  903. // Note that the swapWithArray method has been replaced by a more flexible templated version,
  904. // and renamed "swapWith" to be more consistent with the names used in other classes.
  905. JUCE_DEPRECATED_WITH_BODY (void swapWithArray (Array& other) noexcept, { swapWith (other); })
  906. #endif
  907. private:
  908. //==============================================================================
  909. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  910. int numUsed;
  911. void removeInternal (const int indexToRemove)
  912. {
  913. --numUsed;
  914. ElementType* const e = data.elements + indexToRemove;
  915. e->~ElementType();
  916. const int numberToShift = numUsed - indexToRemove;
  917. if (numberToShift > 0)
  918. memmove (e, e + 1, ((size_t) numberToShift) * sizeof (ElementType));
  919. minimiseStorageAfterRemoval();
  920. }
  921. inline void deleteAllElements() noexcept
  922. {
  923. for (int i = 0; i < numUsed; ++i)
  924. data.elements[i].~ElementType();
  925. }
  926. void minimiseStorageAfterRemoval()
  927. {
  928. if (data.numAllocated > jmax (minimumAllocatedSize, numUsed * 2))
  929. data.shrinkToNoMoreThan (jmax (numUsed, jmax (minimumAllocatedSize, 64 / (int) sizeof (ElementType))));
  930. }
  931. };
  932. #endif // JUCE_ARRAY_H_INCLUDED