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.

986 lines
36KB

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