Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

UnsafeList.cs 75KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. using Unity.Burst;
  9. using Unity.Jobs;
  10. using Unity.Jobs.LowLevel.Unsafe;
  11. using Unity.Mathematics;
  12. namespace Unity.Collections.LowLevel.Unsafe
  13. {
  14. [BurstCompile]
  15. internal unsafe struct UnsafeDisposeJob : IJob
  16. {
  17. [NativeDisableUnsafePtrRestriction]
  18. public void* Ptr;
  19. public AllocatorManager.AllocatorHandle Allocator;
  20. public void Execute()
  21. {
  22. AllocatorManager.Free(Allocator, Ptr);
  23. }
  24. }
  25. [StructLayout(LayoutKind.Sequential)]
  26. internal unsafe struct UntypedUnsafeList
  27. {
  28. #pragma warning disable 169
  29. // <WARNING>
  30. // 'Header' of this struct must binary match `UntypedUnsafeList`, `UnsafeList`, `UnsafePtrList`, and `NativeArray` struct.
  31. [NativeDisableUnsafePtrRestriction]
  32. internal readonly void* Ptr;
  33. internal readonly int m_length;
  34. internal readonly int m_capacity;
  35. internal readonly AllocatorManager.AllocatorHandle Allocator;
  36. internal readonly int padding;
  37. #pragma warning restore 169
  38. }
  39. /// <summary>
  40. /// An unmanaged, resizable list.
  41. /// </summary>
  42. /// <typeparam name="T">The type of the elements.</typeparam>
  43. [DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")]
  44. [DebuggerTypeProxy(typeof(UnsafeListTDebugView<>))]
  45. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  46. [StructLayout(LayoutKind.Sequential)]
  47. public unsafe struct UnsafeList<T>
  48. : INativeDisposable
  49. , INativeList<T>
  50. , IEnumerable<T> // Used by collection initializers.
  51. where T : unmanaged
  52. {
  53. // <WARNING>
  54. // 'Header' of this struct must binary match `UntypedUnsafeList`, `UnsafeList`, `UnsafePtrList`, and `NativeArray` struct.
  55. // Fields must match UntypedUnsafeList structure, please don't reorder and don't insert anything in between first 4 fields
  56. /// <summary>
  57. /// The internal buffer of this list.
  58. /// </summary>
  59. [NativeDisableUnsafePtrRestriction]
  60. public T* Ptr;
  61. /// <summary>
  62. /// The number of elements.
  63. /// </summary>
  64. public int m_length;
  65. /// <summary>
  66. /// The number of elements that can fit in the internal buffer.
  67. /// </summary>
  68. public int m_capacity;
  69. /// <summary>
  70. /// The allocator used to create the internal buffer.
  71. /// </summary>
  72. public AllocatorManager.AllocatorHandle Allocator;
  73. readonly int padding;
  74. /// <summary>
  75. /// The number of elements.
  76. /// </summary>
  77. /// <value>The number of elements.</value>
  78. public int Length
  79. {
  80. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  81. readonly get => CollectionHelper.AssumePositive(m_length);
  82. set
  83. {
  84. if (value > Capacity)
  85. {
  86. Resize(value);
  87. }
  88. else
  89. {
  90. m_length = value;
  91. }
  92. }
  93. }
  94. /// <summary>
  95. /// The number of elements that can fit in the internal buffer.
  96. /// </summary>
  97. /// <value>The number of elements that can fit in the internal buffer.</value>
  98. public int Capacity
  99. {
  100. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  101. readonly get => CollectionHelper.AssumePositive(m_capacity);
  102. set => SetCapacity(value);
  103. }
  104. /// <summary>
  105. /// The element at an index.
  106. /// </summary>
  107. /// <param name="index">An index.</param>
  108. /// <value>The element at the index.</value>
  109. public T this[int index]
  110. {
  111. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  112. get
  113. {
  114. CollectionHelper.CheckIndexInRange(index, m_length);
  115. return Ptr[CollectionHelper.AssumePositive(index)];
  116. }
  117. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  118. set
  119. {
  120. CollectionHelper.CheckIndexInRange(index, m_length);
  121. Ptr[CollectionHelper.AssumePositive(index)] = value;
  122. }
  123. }
  124. /// <summary>
  125. /// Returns a reference to the element at a given index.
  126. /// </summary>
  127. /// <param name="index">The index to access. Must be in the range of [0..Length).</param>
  128. /// <returns>A reference to the element at the index.</returns>
  129. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  130. public ref T ElementAt(int index)
  131. {
  132. CollectionHelper.CheckIndexInRange(index, m_length);
  133. return ref Ptr[CollectionHelper.AssumePositive(index)];
  134. }
  135. /// <summary>
  136. /// Initializes and returns an instance of UnsafeList.
  137. /// </summary>
  138. /// <param name="ptr">An existing byte array to set as the internal buffer.</param>
  139. /// <param name="length">The length.</param>
  140. public UnsafeList(T* ptr, int length) : this()
  141. {
  142. Ptr = ptr;
  143. m_length = length;
  144. m_capacity = length;
  145. Allocator = AllocatorManager.None;
  146. }
  147. /// <summary>
  148. /// Initializes and returns an instance of UnsafeList.
  149. /// </summary>
  150. /// <param name="initialCapacity">The initial capacity of the list.</param>
  151. /// <param name="allocator">The allocator to use.</param>
  152. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  153. public UnsafeList(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  154. {
  155. Ptr = null;
  156. m_length = 0;
  157. m_capacity = 0;
  158. Allocator = allocator;
  159. padding = 0;
  160. SetCapacity(math.max(initialCapacity, 1));
  161. if (options == NativeArrayOptions.ClearMemory && Ptr != null)
  162. {
  163. var sizeOf = sizeof(T);
  164. UnsafeUtility.MemClear(Ptr, Capacity * sizeOf);
  165. }
  166. }
  167. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })]
  168. internal static UnsafeList<T>* Create<U>(int initialCapacity, ref U allocator, NativeArrayOptions options) where U : unmanaged, AllocatorManager.IAllocator
  169. {
  170. UnsafeList<T>* listData = allocator.Allocate(default(UnsafeList<T>), 1);
  171. *listData = new UnsafeList<T>(initialCapacity, allocator.Handle, options);
  172. return listData;
  173. }
  174. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })]
  175. internal static void Destroy<U>(UnsafeList<T>* listData, ref U allocator) where U : unmanaged, AllocatorManager.IAllocator
  176. {
  177. CheckNull(listData);
  178. listData->Dispose(ref allocator);
  179. allocator.Free(listData, sizeof(UnsafeList<T>), UnsafeUtility.AlignOf<UnsafeList<T>>(), 1);
  180. }
  181. /// <summary>
  182. /// Returns a new list.
  183. /// </summary>
  184. /// <param name="initialCapacity">The initial capacity of the list.</param>
  185. /// <param name="allocator">The allocator to use.</param>
  186. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  187. /// <returns>A pointer to the new list.</returns>
  188. public static UnsafeList<T>* Create(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  189. {
  190. UnsafeList<T>* listData = AllocatorManager.Allocate<UnsafeList<T>>(allocator);
  191. *listData = new UnsafeList<T>(initialCapacity, allocator, options);
  192. return listData;
  193. }
  194. /// <summary>
  195. /// Destroys the list.
  196. /// </summary>
  197. /// <param name="listData">The list to destroy.</param>
  198. public static void Destroy(UnsafeList<T>* listData)
  199. {
  200. CheckNull(listData);
  201. var allocator = listData->Allocator;
  202. listData->Dispose();
  203. AllocatorManager.Free(allocator, listData);
  204. }
  205. /// <summary>
  206. /// Whether the list is empty.
  207. /// </summary>
  208. /// <value>True if the list is empty or the list has not been constructed.</value>
  209. public readonly bool IsEmpty
  210. {
  211. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  212. get => !IsCreated || m_length == 0;
  213. }
  214. /// <summary>
  215. /// Whether this list has been allocated (and not yet deallocated).
  216. /// </summary>
  217. /// <value>True if this list has been allocated (and not yet deallocated).</value>
  218. public readonly bool IsCreated
  219. {
  220. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  221. get => Ptr != null;
  222. }
  223. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })]
  224. internal void Dispose<U>(ref U allocator) where U : unmanaged, AllocatorManager.IAllocator
  225. {
  226. allocator.Free(Ptr, m_capacity);
  227. Ptr = null;
  228. m_length = 0;
  229. m_capacity = 0;
  230. }
  231. /// <summary>
  232. /// Releases all resources (memory).
  233. /// </summary>
  234. public void Dispose()
  235. {
  236. if (!IsCreated)
  237. {
  238. return;
  239. }
  240. if (CollectionHelper.ShouldDeallocate(Allocator))
  241. {
  242. AllocatorManager.Free(Allocator, Ptr, m_capacity);
  243. Allocator = AllocatorManager.Invalid;
  244. }
  245. Ptr = null;
  246. m_length = 0;
  247. m_capacity = 0;
  248. }
  249. /// <summary>
  250. /// Creates and schedules a job that frees the memory of this list.
  251. /// </summary>
  252. /// <param name="inputDeps">The dependency for the new job.</param>
  253. /// <returns>The handle of the new job. The job depends upon `inputDeps` and frees the memory of this list.</returns>
  254. public JobHandle Dispose(JobHandle inputDeps)
  255. {
  256. if (!IsCreated)
  257. {
  258. return inputDeps;
  259. }
  260. if (CollectionHelper.ShouldDeallocate(Allocator))
  261. {
  262. var jobHandle = new UnsafeDisposeJob { Ptr = Ptr, Allocator = Allocator }.Schedule(inputDeps);
  263. Ptr = null;
  264. Allocator = AllocatorManager.Invalid;
  265. return jobHandle;
  266. }
  267. Ptr = null;
  268. return inputDeps;
  269. }
  270. /// <summary>
  271. /// Sets the length to 0.
  272. /// </summary>
  273. /// <remarks>Does not change the capacity.</remarks>
  274. public void Clear()
  275. {
  276. m_length = 0;
  277. }
  278. /// <summary>
  279. /// Sets the length, expanding the capacity if necessary.
  280. /// </summary>
  281. /// <param name="length">The new length.</param>
  282. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  283. public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  284. {
  285. var oldLength = m_length;
  286. if (length > Capacity)
  287. {
  288. SetCapacity(length);
  289. }
  290. m_length = length;
  291. if (options == NativeArrayOptions.ClearMemory && oldLength < length)
  292. {
  293. var num = length - oldLength;
  294. byte* ptr = (byte*)Ptr;
  295. var sizeOf = sizeof(T);
  296. UnsafeUtility.MemClear(ptr + oldLength * sizeOf, num * sizeOf);
  297. }
  298. }
  299. void ResizeExact<U>(ref U allocator, int newCapacity) where U : unmanaged, AllocatorManager.IAllocator
  300. {
  301. newCapacity = math.max(0, newCapacity);
  302. CollectionHelper.CheckAllocator(Allocator);
  303. T* newPointer = null;
  304. var alignOf = UnsafeUtility.AlignOf<T>();
  305. var sizeOf = sizeof(T);
  306. if (newCapacity > 0)
  307. {
  308. newPointer = (T*)allocator.Allocate(sizeOf, alignOf, newCapacity);
  309. if (Ptr != null && m_capacity > 0)
  310. {
  311. var itemsToCopy = math.min(newCapacity, Capacity);
  312. var bytesToCopy = itemsToCopy * sizeOf;
  313. UnsafeUtility.MemCpy(newPointer, Ptr, bytesToCopy);
  314. }
  315. }
  316. allocator.Free(Ptr, Capacity);
  317. Ptr = newPointer;
  318. m_capacity = newCapacity;
  319. m_length = math.min(m_length, newCapacity);
  320. }
  321. void ResizeExact(int capacity)
  322. {
  323. ResizeExact(ref Allocator, capacity);
  324. }
  325. void SetCapacity<U>(ref U allocator, int capacity) where U : unmanaged, AllocatorManager.IAllocator
  326. {
  327. CollectionHelper.CheckCapacityInRange(capacity, Length);
  328. var sizeOf = sizeof(T);
  329. var newCapacity = math.max(capacity, CollectionHelper.CacheLineSize / sizeOf);
  330. newCapacity = math.ceilpow2(newCapacity);
  331. if (newCapacity == Capacity)
  332. {
  333. return;
  334. }
  335. ResizeExact(ref allocator, newCapacity);
  336. }
  337. /// <summary>
  338. /// Sets the capacity.
  339. /// </summary>
  340. /// <param name="capacity">The new capacity.</param>
  341. public void SetCapacity(int capacity)
  342. {
  343. SetCapacity(ref Allocator, capacity);
  344. }
  345. /// <summary>
  346. /// Sets the capacity to match the length.
  347. /// </summary>
  348. public void TrimExcess()
  349. {
  350. if (Capacity != m_length)
  351. {
  352. ResizeExact(m_length);
  353. }
  354. }
  355. /// <summary>
  356. /// Adds an element to the end of this list.
  357. /// </summary>
  358. /// <remarks>
  359. /// Increments the length by 1. Never increases the capacity.
  360. /// </remarks>
  361. /// <param name="value">The value to add to the end of the list.</param>
  362. /// <exception cref="InvalidOperationException">Thrown if incrementing the length would exceed the capacity.</exception>
  363. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  364. public void AddNoResize(T value)
  365. {
  366. CheckNoResizeHasEnoughCapacity(1);
  367. UnsafeUtility.WriteArrayElement(Ptr, m_length, value);
  368. m_length += 1;
  369. }
  370. /// <summary>
  371. /// Copies elements from a buffer to the end of this list.
  372. /// </summary>
  373. /// <remarks>
  374. /// Increments the length by `count`. Never increases the capacity.
  375. /// </remarks>
  376. /// <param name="ptr">The buffer to copy from.</param>
  377. /// <param name="count">The number of elements to copy from the buffer.</param>
  378. /// <exception cref="InvalidOperationExceptionv">Thrown if the increased length would exceed the capacity.</exception>
  379. public void AddRangeNoResize(void* ptr, int count)
  380. {
  381. CheckNoResizeHasEnoughCapacity(count);
  382. var sizeOf = sizeof(T);
  383. void* dst = (byte*)Ptr + m_length * sizeOf;
  384. UnsafeUtility.MemCpy(dst, ptr, count * sizeOf);
  385. m_length += count;
  386. }
  387. /// <summary>
  388. /// Copies the elements of another list to the end of this list.
  389. /// </summary>
  390. /// <param name="list">The other list to copy from.</param>
  391. /// <remarks>
  392. /// Increments the length by the length of the other list. Never increases the capacity.
  393. /// </remarks>
  394. /// <exception cref="InvalidOperationException">Thrown if the increased length would exceed the capacity.</exception>
  395. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  396. public void AddRangeNoResize(UnsafeList<T> list)
  397. {
  398. AddRangeNoResize(list.Ptr, CollectionHelper.AssumePositive(list.Length));
  399. }
  400. /// <summary>
  401. /// Adds an element to the end of the list.
  402. /// </summary>
  403. /// <param name="value">The value to add to the end of this list.</param>
  404. /// <remarks>
  405. /// Increments the length by 1. Increases the capacity if necessary.
  406. /// </remarks>
  407. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  408. public void Add(in T value)
  409. {
  410. var idx = m_length;
  411. if (m_length < m_capacity)
  412. {
  413. Ptr[idx] = value;
  414. m_length++;
  415. return;
  416. }
  417. Resize(idx + 1);
  418. Ptr[idx] = value;
  419. }
  420. /// <summary>
  421. /// Copies the elements of a buffer to the end of this list.
  422. /// </summary>
  423. /// <param name="ptr">The buffer to copy from.</param>
  424. /// <param name="count">The number of elements to copy from the buffer.</param>
  425. /// <remarks>
  426. /// Increments the length by `count`. Increases the capacity if necessary.
  427. /// </remarks>
  428. public void AddRange(void* ptr, int count)
  429. {
  430. var idx = m_length;
  431. if (m_length + count > Capacity)
  432. {
  433. Resize(m_length + count);
  434. }
  435. else
  436. {
  437. m_length += count;
  438. }
  439. var sizeOf = sizeof(T);
  440. void* dst = (byte*)Ptr + idx * sizeOf;
  441. UnsafeUtility.MemCpy(dst, ptr, count * sizeOf);
  442. }
  443. /// <summary>
  444. /// Copies the elements of another list to the end of the list.
  445. /// </summary>
  446. /// <param name="list">The list to copy from.</param>
  447. /// <remarks>
  448. /// The length is increased by the length of the other list. Increases the capacity if necessary.
  449. /// </remarks>
  450. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  451. public void AddRange(UnsafeList<T> list)
  452. {
  453. AddRange(list.Ptr, list.Length);
  454. }
  455. /// <summary>
  456. /// Appends value count times to the end of this list.
  457. /// </summary>
  458. /// <param name="value">The value to add to the end of this list.</param>
  459. /// <param name="count">The number of times to replicate the value.</param>
  460. /// <remarks>
  461. /// Length is incremented by count. If necessary, the capacity is increased.
  462. /// </remarks>
  463. public void AddReplicate(in T value, int count)
  464. {
  465. var idx = m_length;
  466. if (m_length + count > Capacity)
  467. {
  468. Resize(m_length + count);
  469. }
  470. else
  471. {
  472. m_length += count;
  473. }
  474. fixed (void* ptr = &value)
  475. {
  476. UnsafeUtility.MemCpyReplicate(Ptr + idx, ptr, UnsafeUtility.SizeOf<T>(), count);
  477. }
  478. }
  479. /// <summary>
  480. /// Shifts elements toward the end of this list, increasing its length.
  481. /// </summary>
  482. /// <remarks>
  483. /// Right-shifts elements in the list so as to create 'free' slots at the beginning or in the middle.
  484. ///
  485. /// The length is increased by `end - begin`. If necessary, the capacity will be increased accordingly.
  486. ///
  487. /// If `end` equals `begin`, the method does nothing.
  488. ///
  489. /// The element at index `begin` will be copied to index `end`, the element at index `begin + 1` will be copied to `end + 1`, and so forth.
  490. ///
  491. /// The indexes `begin` up to `end` are not cleared: they will contain whatever values they held prior.
  492. /// </remarks>
  493. /// <param name="begin">The index of the first element that will be shifted up.</param>
  494. /// <param name="end">The index where the first shifted element will end up.</param>
  495. /// <exception cref="ArgumentException">Thrown if `end &lt; begin`.</exception>
  496. /// <exception cref="ArgumentOutOfRangeException">Thrown if `begin` or `end` are out of bounds.</exception>
  497. public void InsertRangeWithBeginEnd(int begin, int end)
  498. {
  499. CheckBeginEndNoLength(begin, end);
  500. // Because we've checked begin and end in `CheckBeginEnd` above, we can now
  501. // assume they are positive.
  502. begin = CollectionHelper.AssumePositive(begin);
  503. end = CollectionHelper.AssumePositive(end);
  504. int items = end - begin;
  505. if (items < 1)
  506. {
  507. return;
  508. }
  509. var oldLength = m_length;
  510. if (m_length + items > Capacity)
  511. {
  512. Resize(m_length + items);
  513. }
  514. else
  515. {
  516. m_length += items;
  517. }
  518. var itemsToCopy = oldLength - begin;
  519. if (itemsToCopy < 1)
  520. {
  521. return;
  522. }
  523. var sizeOf = sizeof(T);
  524. var bytesToCopy = itemsToCopy * sizeOf;
  525. unsafe
  526. {
  527. byte* ptr = (byte*)Ptr;
  528. byte* dest = ptr + end * sizeOf;
  529. byte* src = ptr + begin * sizeOf;
  530. UnsafeUtility.MemMove(dest, src, bytesToCopy);
  531. }
  532. }
  533. /// <summary>
  534. /// Shifts elements toward the end of this list, increasing its length.
  535. /// </summary>
  536. /// <remarks>
  537. /// Right-shifts elements in the list so as to create 'free' slots at the beginning or in the middle.
  538. ///
  539. /// The length is increased by `count`. If necessary, the capacity will be increased accordingly.
  540. ///
  541. /// If `count` equals `0`, the method does nothing.
  542. ///
  543. /// The element at index `index` will be copied to index `index + count`, the element at index `index + 1` will be copied to `index + count + 1`, and so forth.
  544. ///
  545. /// The indexes `index` up to `index + count` are not cleared: they will contain whatever values they held prior.
  546. /// </remarks>
  547. /// <param name="index">The index of the first element that will be shifted up.</param>
  548. /// <param name="count">The number of elements to insert.</param>
  549. /// <exception cref="ArgumentException">Thrown if `count` is negative.</exception>
  550. /// <exception cref="ArgumentOutOfRangeException">Thrown if `index` is out of bounds.</exception>
  551. public void InsertRange(int index, int count) => InsertRangeWithBeginEnd(index, index + count);
  552. /// <summary>
  553. /// Copies the last element of this list to the specified index. Decrements the length by 1.
  554. /// </summary>
  555. /// <remarks>Useful as a cheap way to remove an element from this list when you don't care about preserving order.</remarks>
  556. /// <param name="index">The index to overwrite with the last element.</param>
  557. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds.</exception>
  558. public void RemoveAtSwapBack(int index)
  559. {
  560. CollectionHelper.CheckIndexInRange(index, m_length);
  561. index = CollectionHelper.AssumePositive(index);
  562. int copyFrom = m_length - 1;
  563. T* dst = (T*)Ptr + index;
  564. T* src = (T*)Ptr + copyFrom;
  565. (*dst) = (*src);
  566. m_length -= 1;
  567. }
  568. /// <summary>
  569. /// Copies the last *N* elements of this list to a range in this list. Decrements the length by *N*.
  570. /// </summary>
  571. /// <remarks>
  572. /// Copies the last `count` elements to the indexes `index` up to `index + count`.
  573. ///
  574. /// Useful as a cheap way to remove elements from a list when you don't care about preserving order.
  575. /// </remarks>
  576. /// <param name="index">The index of the first element to overwrite.</param>
  577. /// <param name="count">The number of elements to copy and remove.</param>
  578. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds</exception>
  579. /// <exception cref="ArgumentOutOfRangeException">Thrown if `count` is negative,
  580. /// or `index + count` exceeds the length.</exception>
  581. public void RemoveRangeSwapBack(int index, int count)
  582. {
  583. CheckIndexCount(index, count);
  584. index = CollectionHelper.AssumePositive(index);
  585. count = CollectionHelper.AssumePositive(count);
  586. if (count > 0)
  587. {
  588. int copyFrom = math.max(m_length - count, index + count);
  589. var sizeOf = sizeof(T);
  590. void* dst = (byte*)Ptr + index * sizeOf;
  591. void* src = (byte*)Ptr + copyFrom * sizeOf;
  592. UnsafeUtility.MemCpy(dst, src, (m_length - copyFrom) * sizeOf);
  593. m_length -= count;
  594. }
  595. }
  596. /// <summary>
  597. /// Removes the element at an index, shifting everything above it down by one. Decrements the length by 1.
  598. /// </summary>
  599. /// <param name="index">The index of the element to remove.</param>
  600. /// <remarks>
  601. /// If you don't care about preserving the order of the elements, <see cref="RemoveAtSwapBack(int)"/> is a more efficient way to remove elements.
  602. /// </remarks>
  603. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds.</exception>
  604. public void RemoveAt(int index)
  605. {
  606. CollectionHelper.CheckIndexInRange(index, m_length);
  607. index = CollectionHelper.AssumePositive(index);
  608. T* dst = Ptr + index;
  609. T* src = dst + 1;
  610. m_length--;
  611. // Because these tend to be smaller (< 1MB), and the cost of jumping context to native and back is
  612. // so high, this consistently optimizes to better code than UnsafeUtility.MemCpy
  613. for (int i = index; i < m_length; i++)
  614. {
  615. *dst++ = *src++;
  616. }
  617. }
  618. /// <summary>
  619. /// Removes *N* elements in a range, shifting everything above the range down by *N*. Decrements the length by *N*.
  620. /// </summary>
  621. /// <param name="index">The index of the first element to remove.</param>
  622. /// <param name="count">The number of elements to remove.</param>
  623. /// <remarks>
  624. /// If you don't care about preserving the order of the elements, `RemoveRangeSwapBackWithBeginEnd`
  625. /// is a more efficient way to remove elements.
  626. /// </remarks>
  627. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds</exception>
  628. /// <exception cref="ArgumentOutOfRangeException">Thrown if `count` is negative,
  629. /// or `index + count` exceeds the length.</exception>
  630. public void RemoveRange(int index, int count)
  631. {
  632. CheckIndexCount(index, count);
  633. index = CollectionHelper.AssumePositive(index);
  634. count = CollectionHelper.AssumePositive(count);
  635. if (count > 0)
  636. {
  637. int copyFrom = math.min(index + count, m_length);
  638. var sizeOf = sizeof(T);
  639. void* dst = (byte*)Ptr + index * sizeOf;
  640. void* src = (byte*)Ptr + copyFrom * sizeOf;
  641. UnsafeUtility.MemCpy(dst, src, (m_length - copyFrom) * sizeOf);
  642. m_length -= count;
  643. }
  644. }
  645. /// <summary>
  646. /// Returns a read only of this list.
  647. /// </summary>
  648. /// <returns>A read only of this list.</returns>
  649. public ReadOnly AsReadOnly()
  650. {
  651. return new ReadOnly(Ptr, Length);
  652. }
  653. /// <summary>
  654. /// A read only for an UnsafeList&lt;T&gt;.
  655. /// </summary>
  656. /// <remarks>
  657. /// Use <see cref="AsReadOnly"/> to create a read only for a list.
  658. /// </remarks>
  659. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  660. public unsafe struct ReadOnly
  661. : IEnumerable<T>
  662. {
  663. /// <summary>
  664. /// The internal buffer of the list.
  665. /// </summary>
  666. [NativeDisableUnsafePtrRestriction]
  667. public readonly T* Ptr;
  668. /// <summary>
  669. /// The number of elements.
  670. /// </summary>
  671. public readonly int Length;
  672. internal ReadOnly(T* ptr, int length)
  673. {
  674. Ptr = ptr;
  675. Length = length;
  676. }
  677. /// <summary>
  678. /// Returns an enumerator over the elements of the list.
  679. /// </summary>
  680. /// <returns>An enumerator over the elements of the list.</returns>
  681. public Enumerator GetEnumerator()
  682. {
  683. return new Enumerator { m_Ptr = Ptr, m_Length = Length, m_Index = -1 };
  684. }
  685. /// <summary>
  686. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  687. /// </summary>
  688. /// <returns>Throws NotImplementedException.</returns>
  689. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  690. IEnumerator IEnumerable.GetEnumerator()
  691. {
  692. throw new NotImplementedException();
  693. }
  694. /// <summary>
  695. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  696. /// </summary>
  697. /// <returns>Throws NotImplementedException.</returns>
  698. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  699. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  700. {
  701. throw new NotImplementedException();
  702. }
  703. }
  704. /// <summary>
  705. /// **Obsolete.** Use <see cref="AsReadOnly"/> instead.
  706. /// </summary>
  707. /// <returns>A parallel reader of this list.</returns>
  708. // [Obsolete("'AsParallelReader' has been deprecated; use 'AsReadOnly' instead. (UnityUpgradable) -> AsReadOnly")]
  709. public ParallelReader AsParallelReader()
  710. {
  711. return new ParallelReader(Ptr, Length);
  712. }
  713. /// <summary>
  714. /// **Obsolete.** Use <see cref="ReadOnly"/> instead.
  715. /// </summary>
  716. /// <remarks>
  717. /// Use <see cref="AsParallelReader"/> to create a parallel reader for a list.
  718. /// </remarks>
  719. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  720. // [Obsolete("'ParallelReader' has been deprecated; use 'ReadOnly' instead. (UnityUpgradable) -> ReadOnly")]
  721. public unsafe struct ParallelReader
  722. {
  723. /// <summary>
  724. /// The internal buffer of the list.
  725. /// </summary>
  726. [NativeDisableUnsafePtrRestriction]
  727. public readonly T* Ptr;
  728. /// <summary>
  729. /// The number of elements.
  730. /// </summary>
  731. public readonly int Length;
  732. internal ParallelReader(T* ptr, int length)
  733. {
  734. Ptr = ptr;
  735. Length = length;
  736. }
  737. }
  738. /// <summary>
  739. /// Returns a parallel writer of this list.
  740. /// </summary>
  741. /// <returns>A parallel writer of this list.</returns>
  742. public ParallelWriter AsParallelWriter()
  743. {
  744. return new ParallelWriter((UnsafeList<T>*)UnsafeUtility.AddressOf(ref this));
  745. }
  746. /// <summary>
  747. /// A parallel writer for an UnsafeList&lt;T&gt;.
  748. /// </summary>
  749. /// <remarks>
  750. /// Use <see cref="AsParallelWriter"/> to create a parallel writer for a list.
  751. /// </remarks>
  752. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  753. public unsafe struct ParallelWriter
  754. {
  755. /// <summary>
  756. /// The data of the list.
  757. /// </summary>
  758. public readonly void* Ptr
  759. {
  760. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  761. get
  762. {
  763. return ListData->Ptr;
  764. }
  765. }
  766. /// <summary>
  767. /// The UnsafeList to write to.
  768. /// </summary>
  769. [NativeDisableUnsafePtrRestriction]
  770. public UnsafeList<T>* ListData;
  771. internal unsafe ParallelWriter(UnsafeList<T>* listData)
  772. {
  773. ListData = listData;
  774. }
  775. /// <summary>
  776. /// Adds an element to the end of the list.
  777. /// </summary>
  778. /// <param name="value">The value to add to the end of the list.</param>
  779. /// <remarks>
  780. /// Increments the length by 1. Never increases the capacity.
  781. /// </remarks>
  782. /// <exception cref="InvalidOperationException">Thrown if incrementing the length would exceed the capacity.</exception>
  783. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  784. public void AddNoResize(T value)
  785. {
  786. var idx = Interlocked.Increment(ref ListData->m_length) - 1;
  787. ListData->CheckNoResizeHasEnoughCapacity(idx, 1);
  788. UnsafeUtility.WriteArrayElement(ListData->Ptr, idx, value);
  789. }
  790. /// <summary>
  791. /// Copies elements from a buffer to the end of the list.
  792. /// </summary>
  793. /// <param name="ptr">The buffer to copy from.</param>
  794. /// <param name="count">The number of elements to copy from the buffer.</param>
  795. /// <remarks>
  796. /// Increments the length by `count`. Never increases the capacity.
  797. /// </remarks>
  798. /// <exception cref="InvalidOperationException">Thrown if the increased length would exceed the capacity.</exception>
  799. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  800. public void AddRangeNoResize(void* ptr, int count)
  801. {
  802. var idx = Interlocked.Add(ref ListData->m_length, count) - count;
  803. ListData->CheckNoResizeHasEnoughCapacity(idx, count);
  804. void* dst = (byte*)ListData->Ptr + idx * sizeof(T);
  805. UnsafeUtility.MemCpy(dst, ptr, count * sizeof(T));
  806. }
  807. /// <summary>
  808. /// Copies the elements of another list to the end of this list.
  809. /// </summary>
  810. /// <param name="list">The other list to copy from.</param>
  811. /// <remarks>
  812. /// Increments the length by the length of the other list. Never increases the capacity.
  813. /// </remarks>
  814. /// <exception cref="InvalidOperationException">Thrown if the increased length would exceed the capacity.</exception>
  815. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  816. public void AddRangeNoResize(UnsafeList<T> list)
  817. {
  818. AddRangeNoResize(list.Ptr, list.Length);
  819. }
  820. }
  821. /// <summary>
  822. /// Copies all elements of specified container to this container.
  823. /// </summary>
  824. /// <param name="other">An container to copy into this container.</param>
  825. public void CopyFrom(in NativeArray<T> other)
  826. {
  827. Resize(other.Length);
  828. UnsafeUtility.MemCpy(Ptr, other.GetUnsafeReadOnlyPtr<T>(), UnsafeUtility.SizeOf<T>() * other.Length);
  829. }
  830. /// <summary>
  831. /// Copies all elements of specified container to this container.
  832. /// </summary>
  833. /// <param name="other">An container to copy into this container.</param>
  834. public void CopyFrom(in UnsafeList<T> other)
  835. {
  836. Resize(other.Length);
  837. UnsafeUtility.MemCpy(Ptr, other.Ptr, UnsafeUtility.SizeOf<T>() * other.Length);
  838. }
  839. /// <summary>
  840. /// Returns an enumerator over the elements of the list.
  841. /// </summary>
  842. /// <returns>An enumerator over the elements of the list.</returns>
  843. public Enumerator GetEnumerator()
  844. {
  845. return new Enumerator { m_Ptr = Ptr, m_Length = Length, m_Index = -1 };
  846. }
  847. /// <summary>
  848. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  849. /// </summary>
  850. /// <returns>Throws NotImplementedException.</returns>
  851. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  852. IEnumerator IEnumerable.GetEnumerator()
  853. {
  854. throw new NotImplementedException();
  855. }
  856. /// <summary>
  857. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  858. /// </summary>
  859. /// <returns>Throws NotImplementedException.</returns>
  860. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  861. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  862. {
  863. throw new NotImplementedException();
  864. }
  865. /// <summary>
  866. /// An enumerator over the elements of a list.
  867. /// </summary>
  868. /// <remarks>
  869. /// In an enumerator's initial state, <see cref="Current"/> is invalid.
  870. /// The first <see cref="MoveNext"/> call advances the enumerator to the first element of the list.
  871. /// </remarks>
  872. public struct Enumerator : IEnumerator<T>
  873. {
  874. internal T* m_Ptr;
  875. internal int m_Length;
  876. internal int m_Index;
  877. /// <summary>
  878. /// Does nothing.
  879. /// </summary>
  880. public void Dispose() { }
  881. /// <summary>
  882. /// Advances the enumerator to the next element of the list.
  883. /// </summary>
  884. /// <remarks>
  885. /// The first `MoveNext` call advances the enumerator to the first element of the list. Before this call, `Current` is not valid to read.
  886. /// </remarks>
  887. /// <returns>True if `Current` is valid to read after the call.</returns>
  888. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  889. public bool MoveNext() => ++m_Index < m_Length;
  890. /// <summary>
  891. /// Resets the enumerator to its initial state.
  892. /// </summary>
  893. public void Reset() => m_Index = -1;
  894. /// <summary>
  895. /// The current element.
  896. /// </summary>
  897. /// <value>The current element.</value>
  898. public T Current
  899. {
  900. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  901. get => m_Ptr[m_Index];
  902. }
  903. object IEnumerator.Current => Current;
  904. }
  905. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  906. internal static void CheckNull(void* listData)
  907. {
  908. if (listData == null)
  909. {
  910. throw new InvalidOperationException("UnsafeList has yet to be created or has been destroyed!");
  911. }
  912. }
  913. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  914. void CheckIndexCount(int index, int count)
  915. {
  916. if (count < 0)
  917. {
  918. throw new ArgumentOutOfRangeException($"Value for count {count} must be positive.");
  919. }
  920. if (index < 0)
  921. {
  922. throw new IndexOutOfRangeException($"Value for index {index} must be positive.");
  923. }
  924. if (index > Length)
  925. {
  926. throw new IndexOutOfRangeException($"Value for index {index} is out of bounds.");
  927. }
  928. if (index + count > Length)
  929. {
  930. throw new ArgumentOutOfRangeException($"Value for count {count} is out of bounds.");
  931. }
  932. }
  933. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  934. void CheckBeginEndNoLength(int begin, int end)
  935. {
  936. if (begin > end)
  937. {
  938. throw new ArgumentException($"Value for begin {begin} index must less or equal to end {end}.");
  939. }
  940. if (begin < 0)
  941. {
  942. throw new ArgumentOutOfRangeException($"Value for begin {begin} must be positive.");
  943. }
  944. }
  945. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  946. void CheckBeginEnd(int begin, int end)
  947. {
  948. CheckBeginEndNoLength(begin, end);
  949. if (begin > Length)
  950. {
  951. throw new ArgumentOutOfRangeException($"Value for begin {begin} is out of bounds.");
  952. }
  953. if (end > Length)
  954. {
  955. throw new ArgumentOutOfRangeException($"Value for end {end} is out of bounds.");
  956. }
  957. }
  958. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  959. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  960. void CheckNoResizeHasEnoughCapacity(int length)
  961. {
  962. CheckNoResizeHasEnoughCapacity(length, Length);
  963. }
  964. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  965. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  966. void CheckNoResizeHasEnoughCapacity(int length, int index)
  967. {
  968. if (Capacity < index + length)
  969. {
  970. throw new InvalidOperationException($"AddNoResize assumes that list capacity is sufficient (Capacity {Capacity}, Length {Length}), requested length {length}!");
  971. }
  972. }
  973. }
  974. /// <summary>
  975. /// Provides extension methods for UnsafeList.
  976. /// </summary>
  977. [GenerateTestsForBurstCompatibility]
  978. public unsafe static class UnsafeListExtensions
  979. {
  980. /// <summary>
  981. /// Finds the index of the first occurrence of a particular value in this list.
  982. /// </summary>
  983. /// <typeparam name="T">The type of elements in this list.</typeparam>
  984. /// <typeparam name="U">The type of value to locate.</typeparam>
  985. /// <param name="list">This list.</param>
  986. /// <param name="value">A value to locate.</param>
  987. /// <returns>The zero-based index of the first occurrence of the value if it is found. Returns -1 if no occurrence is found.</returns>
  988. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
  989. public static int IndexOf<T, U>(this UnsafeList<T> list, U value) where T : unmanaged, IEquatable<U>
  990. {
  991. return NativeArrayExtensions.IndexOf<T, U>(list.Ptr, list.Length, value);
  992. }
  993. /// <summary>
  994. /// Returns true if a particular value is present in this list.
  995. /// </summary>
  996. /// <typeparam name="T">The type of elements in the list.</typeparam>
  997. /// <typeparam name="U">The type of value to locate.</typeparam>
  998. /// <param name="list">This list.</param>
  999. /// <param name="value">The value to locate.</param>
  1000. /// <returns>True if the value is present in this list.</returns>
  1001. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
  1002. public static bool Contains<T, U>(this UnsafeList<T> list, U value) where T : unmanaged, IEquatable<U>
  1003. {
  1004. return list.IndexOf(value) != -1;
  1005. }
  1006. /// <summary>
  1007. /// Finds the index of the first occurrence of a particular value in the list.
  1008. /// </summary>
  1009. /// <typeparam name="T">The type of elements in the list.</typeparam>
  1010. /// <typeparam name="U">The type of value to locate.</typeparam>
  1011. /// <param name="list">This reader of the list.</param>
  1012. /// <param name="value">A value to locate.</param>
  1013. /// <returns>The zero-based index of the first occurrence of the value if it is found. Returns -1 if no occurrence is found.</returns>
  1014. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
  1015. public static int IndexOf<T, U>(this UnsafeList<T>.ReadOnly list, U value) where T : unmanaged, IEquatable<U>
  1016. {
  1017. return NativeArrayExtensions.IndexOf<T, U>(list.Ptr, list.Length, value);
  1018. }
  1019. /// <summary>
  1020. /// Returns true if a particular value is present in the list.
  1021. /// </summary>
  1022. /// <typeparam name="T">The type of elements in the list.</typeparam>
  1023. /// <typeparam name="U">The type of value to locate.</typeparam>
  1024. /// <param name="list">This reader of the list.</param>
  1025. /// <param name="value">The value to locate.</param>
  1026. /// <returns>True if the value is present in the list.</returns>
  1027. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
  1028. public static bool Contains<T, U>(this UnsafeList<T>.ReadOnly list, U value) where T : unmanaged, IEquatable<U>
  1029. {
  1030. return list.IndexOf(value) != -1;
  1031. }
  1032. /// <summary>
  1033. /// **Obsolete.** Use <see cref="UnsafeList{T}.ReadOnly"/> instead.
  1034. /// </summary>
  1035. /// <typeparam name="T">The type of elements in the list.</typeparam>
  1036. /// <typeparam name="U">The type of value to locate.</typeparam>
  1037. /// <param name="list">This reader of the list.</param>
  1038. /// <param name="value">A value to locate.</param>
  1039. /// <returns>The zero-based index of the first occurrence of the value if it is found. Returns -1 if no occurrence is found.</returns>
  1040. // [Obsolete("'UnsafeList<T>.ParallelReader' has been deprecated; use 'UnsafeList<T>.ReadOnly' instead.")]
  1041. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
  1042. public static int IndexOf<T, U>(this UnsafeList<T>.ParallelReader list, U value) where T : unmanaged, IEquatable<U>
  1043. {
  1044. return NativeArrayExtensions.IndexOf<T, U>(list.Ptr, list.Length, value);
  1045. }
  1046. /// <summary>
  1047. /// **Obsolete.** Use <see cref="UnsafeList{T}.ReadOnly"/> instead.
  1048. /// </summary>
  1049. /// <typeparam name="T">The type of elements in the list.</typeparam>
  1050. /// <typeparam name="U">The type of value to locate.</typeparam>
  1051. /// <param name="list">This reader of the list.</param>
  1052. /// <param name="value">The value to locate.</param>
  1053. /// <returns>True if the value is present in the list.</returns>
  1054. // [Obsolete("'UnsafeList<T>.ParallelReader' has been deprecated; use 'UnsafeList<T>.ReadOnly' instead.")]
  1055. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
  1056. public static bool Contains<T, U>(this UnsafeList<T>.ParallelReader list, U value) where T : unmanaged, IEquatable<U>
  1057. {
  1058. return list.IndexOf(value) != -1;
  1059. }
  1060. /// <summary>
  1061. /// Returns true if this container and another have equal length and content.
  1062. /// </summary>
  1063. /// <typeparam name="T">The type of the source container's elements.</typeparam>
  1064. /// <param name="container">The container to compare for equality.</param>
  1065. /// <param name="other">The other container to compare for equality.</param>
  1066. /// <returns>True if the containers have equal length and content.</returns>
  1067. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  1068. public static bool ArraysEqual<T>(this UnsafeList<T> container, in UnsafeList<T> other)
  1069. where T : unmanaged, IEquatable<T>
  1070. {
  1071. if (container.Length != other.Length)
  1072. return false;
  1073. for (int i = 0; i != container.Length; i++)
  1074. {
  1075. if (!container[i].Equals(other[i]))
  1076. return false;
  1077. }
  1078. return true;
  1079. }
  1080. }
  1081. internal sealed class UnsafeListTDebugView<T>
  1082. where T : unmanaged
  1083. {
  1084. UnsafeList<T> Data;
  1085. public UnsafeListTDebugView(UnsafeList<T> data)
  1086. {
  1087. Data = data;
  1088. }
  1089. public unsafe T[] Items
  1090. {
  1091. get
  1092. {
  1093. T[] result = new T[Data.Length];
  1094. for (var i = 0; i < result.Length; ++i)
  1095. {
  1096. result[i] = Data.Ptr[i];
  1097. }
  1098. return result;
  1099. }
  1100. }
  1101. }
  1102. /// <summary>
  1103. /// An unmanaged, resizable list of pointers.
  1104. /// </summary>
  1105. /// <typeparam name="T">The type of pointer element.</typeparam>
  1106. [DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")]
  1107. [DebuggerTypeProxy(typeof(UnsafePtrListDebugView<>))]
  1108. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  1109. [StructLayout(LayoutKind.Sequential)]
  1110. public unsafe struct UnsafePtrList<T>
  1111. : INativeDisposable
  1112. // IIndexable<T> and INativeList<T> can't be implemented because this[index] and ElementAt return T* instead of T.
  1113. , IEnumerable<IntPtr> // Used by collection initializers.
  1114. where T : unmanaged
  1115. {
  1116. // <WARNING>
  1117. // 'Header' of this struct must binary match `UntypedUnsafeList`, `UnsafeList`, `UnsafePtrList`, and `NativeArray` struct.
  1118. // Fields must match UntypedUnsafeList structure, please don't reorder and don't insert anything in between first 4 fields
  1119. /// <summary>
  1120. /// The internal buffer of this list.
  1121. /// </summary>
  1122. [NativeDisableUnsafePtrRestriction]
  1123. public readonly T** Ptr;
  1124. /// <summary>
  1125. /// The number of elements.
  1126. /// </summary>
  1127. public readonly int m_length;
  1128. /// <summary>
  1129. /// The number of elements that can fit in the internal buffer.
  1130. /// </summary>
  1131. public readonly int m_capacity;
  1132. /// <summary>
  1133. /// The allocator used to create the internal buffer.
  1134. /// </summary>
  1135. public readonly AllocatorManager.AllocatorHandle Allocator;
  1136. readonly int padding;
  1137. /// <summary>
  1138. /// The number of elements.
  1139. /// </summary>
  1140. /// <value>The number of elements.</value>
  1141. public int Length
  1142. {
  1143. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1144. readonly get => this.ListDataRO().Length;
  1145. set => this.ListData().Length = value;
  1146. }
  1147. /// <summary>
  1148. /// The number of elements that can fit in the internal buffer.
  1149. /// </summary>
  1150. /// <value>The number of elements that can fit in the internal buffer.</value>
  1151. public int Capacity
  1152. {
  1153. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1154. readonly get => this.ListDataRO().Capacity;
  1155. set => this.ListData().Capacity = value;
  1156. }
  1157. /// <summary>
  1158. /// The element at an index.
  1159. /// </summary>
  1160. /// <param name="index">An index.</param>
  1161. /// <value>The element at the index.</value>
  1162. public T* this[int index]
  1163. {
  1164. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1165. get
  1166. {
  1167. CollectionHelper.CheckIndexInRange(index, Length);
  1168. return Ptr[CollectionHelper.AssumePositive(index)];
  1169. }
  1170. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1171. set
  1172. {
  1173. CollectionHelper.CheckIndexInRange(index, Length);
  1174. Ptr[CollectionHelper.AssumePositive(index)] = value;
  1175. }
  1176. }
  1177. /// <summary>
  1178. /// Returns a reference to the element at a given index.
  1179. /// </summary>
  1180. /// <param name="index">The index to access. Must be in the range of [0..Length).</param>
  1181. /// <returns>A reference to the element at the index.</returns>
  1182. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1183. public ref T* ElementAt(int index)
  1184. {
  1185. CollectionHelper.CheckIndexInRange(index, Length);
  1186. return ref Ptr[CollectionHelper.AssumePositive(index)];
  1187. }
  1188. /// <summary>
  1189. /// Initializes and returns an instance of UnsafePtrList.
  1190. /// </summary>
  1191. /// <param name="ptr">An existing pointer array to set as the internal buffer.</param>
  1192. /// <param name="length">The length.</param>
  1193. public unsafe UnsafePtrList(T** ptr, int length) : this()
  1194. {
  1195. Ptr = ptr;
  1196. m_length = length;
  1197. m_capacity = length;
  1198. Allocator = AllocatorManager.None;
  1199. }
  1200. /// <summary>
  1201. /// Initializes and returns an instance of UnsafePtrList.
  1202. /// </summary>
  1203. /// <param name="initialCapacity">The initial capacity of the list.</param>
  1204. /// <param name="allocator">The allocator to use.</param>
  1205. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  1206. public unsafe UnsafePtrList(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  1207. {
  1208. Ptr = null;
  1209. m_length = 0;
  1210. m_capacity = 0;
  1211. padding = 0;
  1212. Allocator = AllocatorManager.None;
  1213. this.ListData() = new UnsafeList<IntPtr>(initialCapacity, allocator, options);
  1214. }
  1215. /// <summary>
  1216. /// Returns a new list of pointers.
  1217. /// </summary>
  1218. /// <param name="ptr">An existing pointer array to set as the internal buffer.</param>
  1219. /// <param name="length">The length.</param>
  1220. /// <returns>A pointer to the new list.</returns>
  1221. public static UnsafePtrList<T>* Create(T** ptr, int length)
  1222. {
  1223. UnsafePtrList<T>* listData = AllocatorManager.Allocate<UnsafePtrList<T>>(AllocatorManager.Persistent);
  1224. *listData = new UnsafePtrList<T>(ptr, length);
  1225. return listData;
  1226. }
  1227. /// <summary>
  1228. /// Returns a new list of pointers.
  1229. /// </summary>
  1230. /// <param name="initialCapacity">The initial capacity of the list.</param>
  1231. /// <param name="allocator">The allocator to use.</param>
  1232. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  1233. /// <returns>A pointer to the new list.</returns>
  1234. public static UnsafePtrList<T>* Create(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
  1235. {
  1236. UnsafePtrList<T>* listData = AllocatorManager.Allocate<UnsafePtrList<T>>(allocator);
  1237. *listData = new UnsafePtrList<T>(initialCapacity, allocator, options);
  1238. return listData;
  1239. }
  1240. /// <summary>
  1241. /// Destroys the list.
  1242. /// </summary>
  1243. /// <param name="listData">The list to destroy.</param>
  1244. public static void Destroy(UnsafePtrList<T>* listData)
  1245. {
  1246. UnsafeList<IntPtr>.CheckNull(listData);
  1247. var allocator = listData->ListData().Allocator.Value == AllocatorManager.Invalid.Value
  1248. ? AllocatorManager.Persistent
  1249. : listData->ListData().Allocator
  1250. ;
  1251. listData->Dispose();
  1252. AllocatorManager.Free(allocator, listData);
  1253. }
  1254. /// <summary>
  1255. /// Whether the list is empty.
  1256. /// </summary>
  1257. /// <value>True if the list is empty or the list has not been constructed.</value>
  1258. public readonly bool IsEmpty
  1259. {
  1260. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1261. get => !IsCreated || Length == 0;
  1262. }
  1263. /// <summary>
  1264. /// Whether this list has been allocated (and not yet deallocated).
  1265. /// </summary>
  1266. /// <value>True if this list has been allocated (and not yet deallocated).</value>
  1267. public readonly bool IsCreated
  1268. {
  1269. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1270. get => Ptr != null;
  1271. }
  1272. /// <summary>
  1273. /// Releases all resources (memory).
  1274. /// </summary>
  1275. public void Dispose()
  1276. {
  1277. this.ListData().Dispose();
  1278. }
  1279. /// <summary>
  1280. /// Creates and schedules a job that frees the memory of this list.
  1281. /// </summary>
  1282. /// <param name="inputDeps">The dependency for the new job.</param>
  1283. /// <returns>The handle of the new job. The job depends upon `inputDeps` and frees the memory of this list.</returns>
  1284. public JobHandle Dispose(JobHandle inputDeps) => this.ListData().Dispose(inputDeps);
  1285. /// <summary>
  1286. /// Sets the length to 0.
  1287. /// </summary>
  1288. /// <remarks>Does not change the capacity.</remarks>
  1289. public void Clear() => this.ListData().Clear();
  1290. /// <summary>
  1291. /// Sets the length, expanding the capacity if necessary.
  1292. /// </summary>
  1293. /// <param name="length">The new length.</param>
  1294. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  1295. public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) => this.ListData().Resize(length, options);
  1296. /// <summary>
  1297. /// Sets the capacity.
  1298. /// </summary>
  1299. /// <param name="capacity">The new capacity.</param>
  1300. public void SetCapacity(int capacity) => this.ListData().SetCapacity(capacity);
  1301. /// <summary>
  1302. /// Sets the capacity to match the length.
  1303. /// </summary>
  1304. public void TrimExcess() => this.ListData().TrimExcess();
  1305. /// <summary>
  1306. /// Returns the index of the first occurrence of a specific pointer in the list.
  1307. /// </summary>
  1308. /// <param name="ptr">The pointer to search for in the list.</param>
  1309. /// <returns>The index of the first occurrence of the pointer. Returns -1 if it is not found in the list.</returns>
  1310. public int IndexOf(void* ptr)
  1311. {
  1312. for (int i = 0; i < Length; ++i)
  1313. {
  1314. if (Ptr[i] == ptr) return i;
  1315. }
  1316. return -1;
  1317. }
  1318. /// <summary>
  1319. /// Returns true if the list contains at least one occurrence of a specific pointer.
  1320. /// </summary>
  1321. /// <param name="ptr">The pointer to search for in the list.</param>
  1322. /// <returns>True if the list contains at least one occurrence of the pointer.</returns>
  1323. public bool Contains(void* ptr)
  1324. {
  1325. return IndexOf(ptr) != -1;
  1326. }
  1327. /// <summary>
  1328. /// Adds a pointer to the end of this list.
  1329. /// </summary>
  1330. /// <remarks>
  1331. /// Increments the length by 1. Never increases the capacity.
  1332. /// </remarks>
  1333. /// <param name="value">The pointer to add to the end of the list.</param>
  1334. /// <exception cref="InvalidOperationException">Thrown if incrementing the length would exceed the capacity.</exception>
  1335. public void AddNoResize(void* value)
  1336. {
  1337. this.ListData().AddNoResize((IntPtr)value);
  1338. }
  1339. /// <summary>
  1340. /// Copies pointers from a buffer to the end of this list.
  1341. /// </summary>
  1342. /// <remarks>
  1343. /// Increments the length by `count`. Never increases the capacity.
  1344. /// </remarks>
  1345. /// <param name="ptr">The buffer to copy from.</param>
  1346. /// <param name="count">The number of pointers to copy from the buffer.</param>
  1347. /// <exception cref="InvalidOperationException">Thrown if the increased length would exceed the capacity.</exception>
  1348. public void AddRangeNoResize(void** ptr, int count) => this.ListData().AddRangeNoResize(ptr, count);
  1349. /// <summary>
  1350. /// Copies the pointers of another list to the end of this list.
  1351. /// </summary>
  1352. /// <param name="list">The other list to copy from.</param>
  1353. /// <remarks>
  1354. /// Increments the length by the length of the other list. Never increases the capacity.
  1355. /// </remarks>
  1356. /// <exception cref="InvalidOperationException">Thrown if the increased length would exceed the capacity.</exception>
  1357. public void AddRangeNoResize(UnsafePtrList<T> list) => this.ListData().AddRangeNoResize(list.Ptr, list.Length);
  1358. /// <summary>
  1359. /// Adds a pointer to the end of the list.
  1360. /// </summary>
  1361. /// <param name="value">The pointer to add to the end of this list.</param>
  1362. /// <remarks>
  1363. /// Increments the length by 1. Increases the capacity if necessary.
  1364. /// </remarks>
  1365. public void Add(in IntPtr value)
  1366. {
  1367. this.ListData().Add(value);
  1368. }
  1369. /// <summary>
  1370. /// Adds a pointer to the end of the list.
  1371. /// </summary>
  1372. /// <param name="value">The pointer to add to the end of this list.</param>
  1373. /// <remarks>
  1374. /// Increments the length by 1. Increases the capacity if necessary.
  1375. /// </remarks>
  1376. public void Add(void* value)
  1377. {
  1378. this.ListData().Add((IntPtr)value);
  1379. }
  1380. /// <summary>
  1381. /// Adds elements from a buffer to this list.
  1382. /// </summary>
  1383. /// <param name="ptr">A pointer to the buffer.</param>
  1384. /// <param name="length">The number of elements to add to the list.</param>
  1385. public void AddRange(void* ptr, int length) => this.ListData().AddRange(ptr, length);
  1386. /// <summary>
  1387. /// Copies the elements of another list to the end of this list.
  1388. /// </summary>
  1389. /// <param name="list">The other list to copy from.</param>
  1390. /// <remarks>
  1391. /// Increments the length by the length of the other list. Increases the capacity if necessary.
  1392. /// </remarks>
  1393. public void AddRange(UnsafePtrList<T> list) => this.ListData().AddRange(list.ListData());
  1394. /// <summary>
  1395. /// Shifts pointers toward the end of this list, increasing its length.
  1396. /// </summary>
  1397. /// <remarks>
  1398. /// Right-shifts pointers in the list so as to create 'free' slots at the beginning or in the middle.
  1399. ///
  1400. /// The length is increased by `end - begin`. If necessary, the capacity will be increased accordingly.
  1401. ///
  1402. /// If `end` equals `begin`, the method does nothing.
  1403. ///
  1404. /// The pointer at index `begin` will be copied to index `end`, the pointer at index `begin + 1` will be copied to `end + 1`, and so forth.
  1405. ///
  1406. /// The indexes `begin` up to `end` are not cleared: they will contain whatever pointers they held prior.
  1407. /// </remarks>
  1408. /// <param name="begin">The index of the first pointer that will be shifted up.</param>
  1409. /// <param name="end">The index where the first shifted pointer will end up.</param>
  1410. /// <exception cref="ArgumentException">Thrown if `end &lt; begin`.</exception>
  1411. /// <exception cref="ArgumentOutOfRangeException">Thrown if `begin` or `end` are out of bounds.</exception>
  1412. public void InsertRangeWithBeginEnd(int begin, int end) => this.ListData().InsertRangeWithBeginEnd(begin, end);
  1413. /// <summary>
  1414. /// Copies the last pointer of this list to the specified index. Decrements the length by 1.
  1415. /// </summary>
  1416. /// <remarks>Useful as a cheap way to remove a pointer from this list when you don't care about preserving order.</remarks>
  1417. /// <param name="index">The index to overwrite with the last pointer.</param>
  1418. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds.</exception>
  1419. public void RemoveAtSwapBack(int index) => this.ListData().RemoveAtSwapBack(index);
  1420. /// <summary>
  1421. /// Copies the last *N* pointer of this list to a range in this list. Decrements the length by *N*.
  1422. /// </summary>
  1423. /// <remarks>
  1424. /// Copies the last `count` pointers to the indexes `index` up to `index + count`.
  1425. ///
  1426. /// Useful as a cheap way to remove pointers from a list when you don't care about preserving order.
  1427. /// </remarks>
  1428. /// <param name="index">The index of the first pointer to overwrite.</param>
  1429. /// <param name="count">The number of pointers to copy and remove.</param>
  1430. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds</exception>
  1431. /// <exception cref="ArgumentOutOfRangeException">Thrown if `count` is negative,
  1432. /// or `index + count` exceeds the length.</exception>
  1433. public void RemoveRangeSwapBack(int index, int count) => this.ListData().RemoveRangeSwapBack(index, count);
  1434. /// <summary>
  1435. /// Removes the pointer at an index, shifting everything above it down by one. Decrements the length by 1.
  1436. /// </summary>
  1437. /// <param name="index">The index of the pointer to remove.</param>
  1438. /// <remarks>
  1439. /// If you don't care about preserving the order of the pointers, <see cref="RemoveAtSwapBack(int)"/> is a more efficient way to remove pointers.
  1440. /// </remarks>
  1441. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds.</exception>
  1442. public void RemoveAt(int index) => this.ListData().RemoveAt(index);
  1443. /// <summary>
  1444. /// Removes *N* pointers in a range, shifting everything above the range down by *N*. Decrements the length by *N*.
  1445. /// </summary>
  1446. /// <param name="index">The index of the first pointer to remove.</param>
  1447. /// <param name="count">The number of pointers to remove.</param>
  1448. /// <remarks>
  1449. /// If you don't care about preserving the order of the pointers, `RemoveRangeSwapBackWithBeginEnd`
  1450. /// is a more efficient way to remove pointers.
  1451. /// </remarks>
  1452. /// <exception cref="IndexOutOfRangeException">Thrown if `index` is out of bounds</exception>
  1453. /// <exception cref="ArgumentOutOfRangeException">Thrown if `count` is negative,
  1454. /// or `index + count` exceeds the length.</exception>
  1455. public void RemoveRange(int index, int count) => this.ListData().RemoveRange(index, count);
  1456. /// <summary>
  1457. /// This method is not implemented. It will throw NotImplementedException if it is used.
  1458. /// </summary>
  1459. /// <remarks>Use Enumerator GetEnumerator() instead.</remarks>
  1460. /// <returns>Throws NotImplementedException.</returns>
  1461. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  1462. IEnumerator IEnumerable.GetEnumerator()
  1463. {
  1464. throw new NotImplementedException();
  1465. }
  1466. /// <summary>
  1467. /// This method is not implemented. It will throw NotImplementedException if it is used.
  1468. /// </summary>
  1469. /// <remarks>Use Enumerator GetEnumerator() instead.</remarks>
  1470. /// <returns>Throws NotImplementedException.</returns>
  1471. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  1472. IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
  1473. {
  1474. throw new NotImplementedException();
  1475. }
  1476. /// <summary>
  1477. /// Returns a read only of this list.
  1478. /// </summary>
  1479. /// <returns>A read only of this list.</returns>
  1480. public ReadOnly AsReadOnly()
  1481. {
  1482. return new ReadOnly(Ptr, Length);
  1483. }
  1484. /// <summary>
  1485. /// A read only for an UnsafePtrList&lt;T&gt;.
  1486. /// </summary>
  1487. /// <remarks>
  1488. /// Use <see cref="AsReadOnly"/> to create a read only for a list.
  1489. /// </remarks>
  1490. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  1491. public unsafe struct ReadOnly
  1492. {
  1493. /// <summary>
  1494. /// The internal buffer of the list.
  1495. /// </summary>
  1496. [NativeDisableUnsafePtrRestriction]
  1497. public readonly T** Ptr;
  1498. /// <summary>
  1499. /// The number of elements.
  1500. /// </summary>
  1501. public readonly int Length;
  1502. internal ReadOnly(T** ptr, int length)
  1503. {
  1504. Ptr = ptr;
  1505. Length = length;
  1506. }
  1507. /// <summary>
  1508. /// Returns the index of the first occurrence of a specific pointer in the list.
  1509. /// </summary>
  1510. /// <param name="ptr">The pointer to search for in the list.</param>
  1511. /// <returns>The index of the first occurrence of the pointer. Returns -1 if it is not found in the list.</returns>
  1512. public int IndexOf(void* ptr)
  1513. {
  1514. for (int i = 0; i < Length; ++i)
  1515. {
  1516. if (Ptr[i] == ptr) return i;
  1517. }
  1518. return -1;
  1519. }
  1520. /// <summary>
  1521. /// Returns true if the list contains at least one occurrence of a specific pointer.
  1522. /// </summary>
  1523. /// <param name="ptr">The pointer to search for in the list.</param>
  1524. /// <returns>True if the list contains at least one occurrence of the pointer.</returns>
  1525. public bool Contains(void* ptr)
  1526. {
  1527. return IndexOf(ptr) != -1;
  1528. }
  1529. }
  1530. /// <summary>
  1531. /// **Obsolete**. Use <see cref="AsReadOnly"/> instead.
  1532. /// </summary>
  1533. /// <returns>A parallel reader of this list.</returns>
  1534. // [Obsolete("'AsParallelReader' has been deprecated; use 'AsReadOnly' instead. (UnityUpgradable) -> AsReadOnly")]
  1535. public ParallelReader AsParallelReader()
  1536. {
  1537. return new ParallelReader(Ptr, Length);
  1538. }
  1539. /// <summary>
  1540. /// **Obsolete.** Use <see cref="ReadOnly"/> instead.
  1541. /// </summary>
  1542. /// <remarks>
  1543. /// Use <see cref="AsParallelReader"/> to create a parallel reader for a list.
  1544. /// </remarks>
  1545. // [Obsolete("'ParallelReader' has been deprecated; use 'ReadOnly' instead. (UnityUpgradable) -> ReadOnly")]
  1546. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  1547. public unsafe struct ParallelReader
  1548. {
  1549. /// <summary>
  1550. /// The internal buffer of the list.
  1551. /// </summary>
  1552. [NativeDisableUnsafePtrRestriction]
  1553. public readonly T** Ptr;
  1554. /// <summary>
  1555. /// The number of elements.
  1556. /// </summary>
  1557. public readonly int Length;
  1558. internal ParallelReader(T** ptr, int length)
  1559. {
  1560. Ptr = ptr;
  1561. Length = length;
  1562. }
  1563. /// <summary>
  1564. /// Returns the index of the first occurrence of a specific pointer in the list.
  1565. /// </summary>
  1566. /// <param name="ptr">The pointer to search for in the list.</param>
  1567. /// <returns>The index of the first occurrence of the pointer. Returns -1 if it is not found in the list.</returns>
  1568. public int IndexOf(void* ptr)
  1569. {
  1570. for (int i = 0; i < Length; ++i)
  1571. {
  1572. if (Ptr[i] == ptr) return i;
  1573. }
  1574. return -1;
  1575. }
  1576. /// <summary>
  1577. /// Returns true if the list contains at least one occurrence of a specific pointer.
  1578. /// </summary>
  1579. /// <param name="ptr">The pointer to search for in the list.</param>
  1580. /// <returns>True if the list contains at least one occurrence of the pointer.</returns>
  1581. public bool Contains(void* ptr)
  1582. {
  1583. return IndexOf(ptr) != -1;
  1584. }
  1585. }
  1586. /// <summary>
  1587. /// Returns a parallel writer of this list.
  1588. /// </summary>
  1589. /// <returns>A parallel writer of this list.</returns>
  1590. public ParallelWriter AsParallelWriter()
  1591. {
  1592. return new ParallelWriter(Ptr, (UnsafeList<IntPtr>*)UnsafeUtility.AddressOf(ref this));
  1593. }
  1594. /// <summary>
  1595. /// A parallel writer for an UnsafePtrList&lt;T&gt;.
  1596. /// </summary>
  1597. /// <remarks>
  1598. /// Use <see cref="AsParallelWriter"/> to create a parallel writer for a list.
  1599. /// </remarks>
  1600. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  1601. public unsafe struct ParallelWriter
  1602. {
  1603. /// <summary>
  1604. /// The data of the list.
  1605. /// </summary>
  1606. [NativeDisableUnsafePtrRestriction]
  1607. public readonly T** Ptr;
  1608. /// <summary>
  1609. /// The UnsafeList to write to.
  1610. /// </summary>
  1611. [NativeDisableUnsafePtrRestriction]
  1612. public UnsafeList<IntPtr>* ListData;
  1613. internal unsafe ParallelWriter(T** ptr, UnsafeList<IntPtr>* listData)
  1614. {
  1615. Ptr = ptr;
  1616. ListData = listData;
  1617. }
  1618. /// <summary>
  1619. /// Adds a pointer to the end of the list.
  1620. /// </summary>
  1621. /// <param name="value">The pointer to add to the end of the list.</param>
  1622. /// <remarks>
  1623. /// Increments the length by 1. Never increases the capacity.
  1624. /// </remarks>
  1625. /// <exception cref="InvalidOperationException">Thrown if incrementing the length would exceed the capacity.</exception>
  1626. public void AddNoResize(T* value) => ListData->AddNoResize((IntPtr)value);
  1627. /// <summary>
  1628. /// Copies pointers from a buffer to the end of the list.
  1629. /// </summary>
  1630. /// <param name="ptr">The buffer to copy from.</param>
  1631. /// <param name="count">The number of pointers to copy from the buffer.</param>
  1632. /// <remarks>
  1633. /// Increments the length by `count`. Never increases the capacity.
  1634. /// </remarks>
  1635. /// <exception cref="InvalidOperationException">Thrown if the increased length would exceed the capacity.</exception>
  1636. public void AddRangeNoResize(T** ptr, int count) => ListData->AddRangeNoResize(ptr, count);
  1637. /// <summary>
  1638. /// Copies the pointers of another list to the end of this list.
  1639. /// </summary>
  1640. /// <param name="list">The other list to copy from.</param>
  1641. /// <remarks>
  1642. /// Increments the length by the length of the other list. Never increases the capacity.
  1643. /// </remarks>
  1644. /// <exception cref="InvalidOperationException">Thrown if the increased length would exceed the capacity.</exception>
  1645. public void AddRangeNoResize(UnsafePtrList<T> list) => ListData->AddRangeNoResize(list.Ptr, list.Length);
  1646. }
  1647. }
  1648. [GenerateTestsForBurstCompatibility]
  1649. internal static class UnsafePtrListExtensions
  1650. {
  1651. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  1652. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1653. public static ref UnsafeList<IntPtr> ListData<T>(ref this UnsafePtrList<T> from) where T : unmanaged => ref UnsafeUtility.As<UnsafePtrList<T>, UnsafeList<IntPtr>>(ref from);
  1654. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  1655. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1656. public static UnsafeList<IntPtr> ListDataRO<T>(this UnsafePtrList<T> from) where T : unmanaged => UnsafeUtility.As<UnsafePtrList<T>, UnsafeList<IntPtr>>(ref from);
  1657. }
  1658. internal sealed class UnsafePtrListDebugView<T>
  1659. where T : unmanaged
  1660. {
  1661. UnsafePtrList<T> Data;
  1662. public UnsafePtrListDebugView(UnsafePtrList<T> data)
  1663. {
  1664. Data = data;
  1665. }
  1666. public unsafe T*[] Items
  1667. {
  1668. get
  1669. {
  1670. T*[] result = new T*[Data.Length];
  1671. for (var i = 0; i < result.Length; ++i)
  1672. {
  1673. result[i] = Data.Ptr[i];
  1674. }
  1675. return result;
  1676. }
  1677. }
  1678. }
  1679. }