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.

779 lines
26KB

  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_REFERENCECOUNTEDARRAY_JUCEHEADER__
  24. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  25. #include "juce_ReferenceCountedObject.h"
  26. #include "juce_ArrayAllocationBase.h"
  27. #include "juce_ElementComparator.h"
  28. #include "../threads/juce_CriticalSection.h"
  29. //==============================================================================
  30. /**
  31. Holds a list of objects derived from ReferenceCountedObject.
  32. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  33. and takes care of incrementing and decrementing their ref counts when they
  34. are added and removed from the array.
  35. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  36. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  37. @see Array, OwnedArray, StringArray
  38. */
  39. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  40. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  41. {
  42. public:
  43. //==============================================================================
  44. /** Creates an empty array.
  45. @param granularity this is the size of increment by which the internal storage
  46. used by the array will grow. Only change it from the default if you know the
  47. array is going to be very big and needs to be able to grow efficiently.
  48. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  49. */
  50. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  51. : ArrayAllocationBase <ObjectClass*> (granularity),
  52. numUsed (0)
  53. {
  54. }
  55. /** Creates a copy of another array */
  56. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  57. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  58. numUsed (other.numUsed)
  59. {
  60. other.lockArray();
  61. this->setAllocatedSize (numUsed);
  62. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  63. for (int i = numUsed; --i >= 0;)
  64. if (this->elements[i] != 0)
  65. this->elements[i]->incReferenceCount();
  66. other.unlockArray();
  67. }
  68. /** Copies another array into this one.
  69. Any existing objects in this array will first be released.
  70. */
  71. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  72. {
  73. if (this != &other)
  74. {
  75. other.lockArray();
  76. lock.enter();
  77. clear();
  78. this->granularity = other.granularity;
  79. this->ensureAllocatedSize (other.numUsed);
  80. numUsed = other.numUsed;
  81. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  82. minimiseStorageOverheads();
  83. for (int i = numUsed; --i >= 0;)
  84. if (this->elements[i] != 0)
  85. this->elements[i]->incReferenceCount();
  86. lock.exit();
  87. other.unlockArray();
  88. }
  89. return *this;
  90. }
  91. /** Destructor.
  92. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  93. */
  94. ~ReferenceCountedArray()
  95. {
  96. clear();
  97. }
  98. //==============================================================================
  99. /** Removes all objects from the array.
  100. Any objects in the array that are not referenced from elsewhere will be deleted.
  101. */
  102. void clear()
  103. {
  104. lock.enter();
  105. while (numUsed > 0)
  106. if (this->elements [--numUsed] != 0)
  107. this->elements [numUsed]->decReferenceCount();
  108. jassert (numUsed == 0);
  109. this->setAllocatedSize (0);
  110. lock.exit();
  111. }
  112. /** Returns the current number of objects in the array. */
  113. inline int size() const throw()
  114. {
  115. return numUsed;
  116. }
  117. /** Returns a pointer to the object at this index in the array.
  118. If the index is out-of-range, this will return a null pointer, (and
  119. it could be null anyway, because it's ok for the array to hold null
  120. pointers as well as objects).
  121. @see getUnchecked
  122. */
  123. inline ObjectClass* operator[] (const int index) const throw()
  124. {
  125. lock.enter();
  126. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  127. ? this->elements [index]
  128. : (ObjectClass*) 0;
  129. lock.exit();
  130. return result;
  131. }
  132. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  133. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  134. it can be used when you're sure the index if always going to be legal.
  135. */
  136. inline ObjectClass* getUnchecked (const int index) const throw()
  137. {
  138. lock.enter();
  139. jassert (((unsigned int) index) < (unsigned int) numUsed);
  140. ObjectClass* const result = this->elements [index];
  141. lock.exit();
  142. return result;
  143. }
  144. /** Returns a pointer to the first object in the array.
  145. This will return a null pointer if the array's empty.
  146. @see getLast
  147. */
  148. inline ObjectClass* getFirst() const throw()
  149. {
  150. lock.enter();
  151. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  152. : (ObjectClass*) 0;
  153. lock.exit();
  154. return result;
  155. }
  156. /** Returns a pointer to the last object in the array.
  157. This will return a null pointer if the array's empty.
  158. @see getFirst
  159. */
  160. inline ObjectClass* getLast() const throw()
  161. {
  162. lock.enter();
  163. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  164. : (ObjectClass*) 0;
  165. lock.exit();
  166. return result;
  167. }
  168. //==============================================================================
  169. /** Finds the index of the first occurrence of an object in the array.
  170. @param objectToLookFor the object to look for
  171. @returns the index at which the object was found, or -1 if it's not found
  172. */
  173. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  174. {
  175. int result = -1;
  176. lock.enter();
  177. ObjectClass** e = this->elements;
  178. for (int i = numUsed; --i >= 0;)
  179. {
  180. if (objectToLookFor == *e)
  181. {
  182. result = (int) (e - this->elements);
  183. break;
  184. }
  185. ++e;
  186. }
  187. lock.exit();
  188. return result;
  189. }
  190. /** Returns true if the array contains a specified object.
  191. @param objectToLookFor the object to look for
  192. @returns true if the object is in the array
  193. */
  194. bool contains (const ObjectClass* const objectToLookFor) const throw()
  195. {
  196. lock.enter();
  197. ObjectClass** e = this->elements;
  198. for (int i = numUsed; --i >= 0;)
  199. {
  200. if (objectToLookFor == *e)
  201. {
  202. lock.exit();
  203. return true;
  204. }
  205. ++e;
  206. }
  207. lock.exit();
  208. return false;
  209. }
  210. /** Appends a new object to the end of the array.
  211. This will increase the new object's reference count.
  212. @param newObject the new object to add to the array
  213. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  214. */
  215. void add (ObjectClass* const newObject) throw()
  216. {
  217. lock.enter();
  218. this->ensureAllocatedSize (numUsed + 1);
  219. this->elements [numUsed++] = newObject;
  220. if (newObject != 0)
  221. newObject->incReferenceCount();
  222. lock.exit();
  223. }
  224. /** Inserts a new object into the array at the given index.
  225. If the index is less than 0 or greater than the size of the array, the
  226. element will be added to the end of the array.
  227. Otherwise, it will be inserted into the array, moving all the later elements
  228. along to make room.
  229. This will increase the new object's reference count.
  230. @param indexToInsertAt the index at which the new element should be inserted
  231. @param newObject the new object to add to the array
  232. @see add, addSorted, addIfNotAlreadyThere, set
  233. */
  234. void insert (int indexToInsertAt,
  235. ObjectClass* const newObject) throw()
  236. {
  237. if (indexToInsertAt >= 0)
  238. {
  239. lock.enter();
  240. if (indexToInsertAt > numUsed)
  241. indexToInsertAt = numUsed;
  242. this->ensureAllocatedSize (numUsed + 1);
  243. ObjectClass** const e = this->elements + indexToInsertAt;
  244. const int numToMove = numUsed - indexToInsertAt;
  245. if (numToMove > 0)
  246. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  247. *e = newObject;
  248. if (newObject != 0)
  249. newObject->incReferenceCount();
  250. ++numUsed;
  251. lock.exit();
  252. }
  253. else
  254. {
  255. add (newObject);
  256. }
  257. }
  258. /** Appends a new object at the end of the array as long as the array doesn't
  259. already contain it.
  260. If the array already contains a matching object, nothing will be done.
  261. @param newObject the new object to add to the array
  262. */
  263. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  264. {
  265. lock.enter();
  266. if (! contains (newObject))
  267. add (newObject);
  268. lock.exit();
  269. }
  270. /** Replaces an object in the array with a different one.
  271. If the index is less than zero, this method does nothing.
  272. If the index is beyond the end of the array, the new object is added to the end of the array.
  273. The object being added has its reference count increased, and if it's replacing
  274. another object, then that one has its reference count decreased, and may be deleted.
  275. @param indexToChange the index whose value you want to change
  276. @param newObject the new value to set for this index.
  277. @see add, insert, remove
  278. */
  279. void set (const int indexToChange,
  280. ObjectClass* const newObject)
  281. {
  282. if (indexToChange >= 0)
  283. {
  284. lock.enter();
  285. if (newObject != 0)
  286. newObject->incReferenceCount();
  287. if (indexToChange < numUsed)
  288. {
  289. if (this->elements [indexToChange] != 0)
  290. this->elements [indexToChange]->decReferenceCount();
  291. this->elements [indexToChange] = newObject;
  292. }
  293. else
  294. {
  295. this->ensureAllocatedSize (numUsed + 1);
  296. this->elements [numUsed++] = newObject;
  297. }
  298. lock.exit();
  299. }
  300. }
  301. /** Adds elements from another array to the end of this array.
  302. @param arrayToAddFrom the array from which to copy the elements
  303. @param startIndex the first element of the other array to start copying from
  304. @param numElementsToAdd how many elements to add from the other array. If this
  305. value is negative or greater than the number of available elements,
  306. all available elements will be copied.
  307. @see add
  308. */
  309. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  310. int startIndex = 0,
  311. int numElementsToAdd = -1) throw()
  312. {
  313. arrayToAddFrom.lockArray();
  314. lock.enter();
  315. if (startIndex < 0)
  316. {
  317. jassertfalse
  318. startIndex = 0;
  319. }
  320. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  321. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  322. if (numElementsToAdd > 0)
  323. {
  324. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  325. while (--numElementsToAdd >= 0)
  326. add (arrayToAddFrom.getUnchecked (startIndex++));
  327. }
  328. lock.exit();
  329. arrayToAddFrom.unlockArray();
  330. }
  331. /** Inserts a new object into the array assuming that the array is sorted.
  332. This will use a comparator to find the position at which the new object
  333. should go. If the array isn't sorted, the behaviour of this
  334. method will be unpredictable.
  335. @param comparator the comparator object to use to compare the elements - see the
  336. sort() method for details about this object's form
  337. @param newObject the new object to insert to the array
  338. @see add, sort
  339. */
  340. template <class ElementComparator>
  341. void addSorted (ElementComparator& comparator,
  342. ObjectClass* newObject) throw()
  343. {
  344. lock.enter();
  345. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  346. lock.exit();
  347. }
  348. //==============================================================================
  349. /** Removes an object from the array.
  350. This will remove the object at a given index and move back all the
  351. subsequent objects to close the gap.
  352. If the index passed in is out-of-range, nothing will happen.
  353. The object that is removed will have its reference count decreased,
  354. and may be deleted if not referenced from elsewhere.
  355. @param indexToRemove the index of the element to remove
  356. @see removeObject, removeRange
  357. */
  358. void remove (const int indexToRemove)
  359. {
  360. lock.enter();
  361. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  362. {
  363. ObjectClass** const e = this->elements + indexToRemove;
  364. if (*e != 0)
  365. (*e)->decReferenceCount();
  366. --numUsed;
  367. const int numberToShift = numUsed - indexToRemove;
  368. if (numberToShift > 0)
  369. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  370. if ((numUsed << 1) < this->numAllocated)
  371. minimiseStorageOverheads();
  372. }
  373. lock.exit();
  374. }
  375. /** Removes the first occurrence of a specified object from the array.
  376. If the item isn't found, no action is taken. If it is found, it is
  377. removed and has its reference count decreased.
  378. @param objectToRemove the object to try to remove
  379. @see remove, removeRange
  380. */
  381. void removeObject (ObjectClass* const objectToRemove)
  382. {
  383. lock.enter();
  384. remove (indexOf (objectToRemove));
  385. lock.exit();
  386. }
  387. /** Removes a range of objects from the array.
  388. This will remove a set of objects, starting from the given index,
  389. and move any subsequent elements down to close the gap.
  390. If the range extends beyond the bounds of the array, it will
  391. be safely clipped to the size of the array.
  392. The objects that are removed will have their reference counts decreased,
  393. and may be deleted if not referenced from elsewhere.
  394. @param startIndex the index of the first object to remove
  395. @param numberToRemove how many objects should be removed
  396. @see remove, removeObject
  397. */
  398. void removeRange (const int startIndex,
  399. const int numberToRemove)
  400. {
  401. lock.enter();
  402. const int start = jlimit (0, numUsed, startIndex);
  403. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  404. if (end > start)
  405. {
  406. int i;
  407. for (i = start; i < end; ++i)
  408. {
  409. if (this->elements[i] != 0)
  410. {
  411. this->elements[i]->decReferenceCount();
  412. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  413. }
  414. }
  415. const int rangeSize = end - start;
  416. ObjectClass** e = this->elements + start;
  417. i = numUsed - end;
  418. numUsed -= rangeSize;
  419. while (--i >= 0)
  420. {
  421. *e = e [rangeSize];
  422. ++e;
  423. }
  424. if ((numUsed << 1) < this->numAllocated)
  425. minimiseStorageOverheads();
  426. }
  427. lock.exit();
  428. }
  429. /** Removes the last n objects from the array.
  430. The objects that are removed will have their reference counts decreased,
  431. and may be deleted if not referenced from elsewhere.
  432. @param howManyToRemove how many objects to remove from the end of the array
  433. @see remove, removeObject, removeRange
  434. */
  435. void removeLast (int howManyToRemove = 1)
  436. {
  437. lock.enter();
  438. if (howManyToRemove > numUsed)
  439. howManyToRemove = numUsed;
  440. while (--howManyToRemove >= 0)
  441. remove (numUsed - 1);
  442. lock.exit();
  443. }
  444. /** Swaps a pair of objects in the array.
  445. If either of the indexes passed in is out-of-range, nothing will happen,
  446. otherwise the two objects at these positions will be exchanged.
  447. */
  448. void swap (const int index1,
  449. const int index2) throw()
  450. {
  451. lock.enter();
  452. if (((unsigned int) index1) < (unsigned int) numUsed
  453. && ((unsigned int) index2) < (unsigned int) numUsed)
  454. {
  455. swapVariables (this->elements [index1],
  456. this->elements [index2]);
  457. }
  458. lock.exit();
  459. }
  460. /** Moves one of the objects to a different position.
  461. This will move the object to a specified index, shuffling along
  462. any intervening elements as required.
  463. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  464. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  465. @param currentIndex the index of the object to be moved. If this isn't a
  466. valid index, then nothing will be done
  467. @param newIndex the index at which you'd like this object to end up. If this
  468. is less than zero, it will be moved to the end of the array
  469. */
  470. void move (const int currentIndex,
  471. int newIndex) throw()
  472. {
  473. if (currentIndex != newIndex)
  474. {
  475. lock.enter();
  476. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  477. {
  478. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  479. newIndex = numUsed - 1;
  480. ObjectClass* const value = this->elements [currentIndex];
  481. if (newIndex > currentIndex)
  482. {
  483. memmove (this->elements + currentIndex,
  484. this->elements + currentIndex + 1,
  485. (newIndex - currentIndex) * sizeof (ObjectClass*));
  486. }
  487. else
  488. {
  489. memmove (this->elements + newIndex + 1,
  490. this->elements + newIndex,
  491. (currentIndex - newIndex) * sizeof (ObjectClass*));
  492. }
  493. this->elements [newIndex] = value;
  494. }
  495. lock.exit();
  496. }
  497. }
  498. //==============================================================================
  499. /** Compares this array to another one.
  500. @returns true only if the other array contains the same objects in the same order
  501. */
  502. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  503. {
  504. other.lockArray();
  505. lock.enter();
  506. bool result = numUsed == other.numUsed;
  507. if (result)
  508. {
  509. for (int i = numUsed; --i >= 0;)
  510. {
  511. if (this->elements [i] != other.elements [i])
  512. {
  513. result = false;
  514. break;
  515. }
  516. }
  517. }
  518. lock.exit();
  519. other.unlockArray();
  520. return result;
  521. }
  522. /** Compares this array to another one.
  523. @see operator==
  524. */
  525. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  526. {
  527. return ! operator== (other);
  528. }
  529. //==============================================================================
  530. /** Sorts the elements in the array.
  531. This will use a comparator object to sort the elements into order. The object
  532. passed must have a method of the form:
  533. @code
  534. int compareElements (ElementType first, ElementType second);
  535. @endcode
  536. ..and this method must return:
  537. - a value of < 0 if the first comes before the second
  538. - a value of 0 if the two objects are equivalent
  539. - a value of > 0 if the second comes before the first
  540. To improve performance, the compareElements() method can be declared as static or const.
  541. @param comparator the comparator to use for comparing elements.
  542. @param retainOrderOfEquivalentItems if this is true, then items
  543. which the comparator says are equivalent will be
  544. kept in the order in which they currently appear
  545. in the array. This is slower to perform, but may
  546. be important in some cases. If it's false, a faster
  547. algorithm is used, but equivalent elements may be
  548. rearranged.
  549. @see sortArray
  550. */
  551. template <class ElementComparator>
  552. void sort (ElementComparator& comparator,
  553. const bool retainOrderOfEquivalentItems = false) const throw()
  554. {
  555. (void) comparator; // if you pass in an object with a static compareElements() method, this
  556. // avoids getting warning messages about the parameter being unused
  557. lock.enter();
  558. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  559. lock.exit();
  560. }
  561. //==============================================================================
  562. /** Reduces the amount of storage being used by the array.
  563. Arrays typically allocate slightly more storage than they need, and after
  564. removing elements, they may have quite a lot of unused space allocated.
  565. This method will reduce the amount of allocated storage to a minimum.
  566. */
  567. void minimiseStorageOverheads() throw()
  568. {
  569. lock.enter();
  570. if (numUsed == 0)
  571. {
  572. this->setAllocatedSize (0);
  573. }
  574. else
  575. {
  576. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  577. if (newAllocation < this->numAllocated)
  578. this->setAllocatedSize (newAllocation);
  579. }
  580. lock.exit();
  581. }
  582. //==============================================================================
  583. /** Locks the array's CriticalSection.
  584. Of course if the type of section used is a DummyCriticalSection, this won't
  585. have any effect.
  586. @see unlockArray
  587. */
  588. void lockArray() const throw()
  589. {
  590. lock.enter();
  591. }
  592. /** Unlocks the array's CriticalSection.
  593. Of course if the type of section used is a DummyCriticalSection, this won't
  594. have any effect.
  595. @see lockArray
  596. */
  597. void unlockArray() const throw()
  598. {
  599. lock.exit();
  600. }
  601. //==============================================================================
  602. juce_UseDebuggingNewOperator
  603. private:
  604. int numUsed;
  605. TypeOfCriticalSectionToUse lock;
  606. };
  607. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__