juce_Array.h 43 KB

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