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.

1089 lines
37KB

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