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.

1113 lines
41KB

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