Няма описание
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Threading;
  4. using Unity.Collections.LowLevel.Unsafe;
  5. using Unity.Burst;
  6. using Unity.Jobs;
  7. using Unity.Jobs.LowLevel.Unsafe;
  8. using System.Diagnostics;
  9. using System.Runtime.CompilerServices;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. namespace Unity.Collections
  13. {
  14. [StructLayout(LayoutKind.Sequential)]
  15. unsafe struct UnsafeQueueBlockHeader
  16. {
  17. public UnsafeQueueBlockHeader* m_NextBlock;
  18. public int m_NumItems;
  19. }
  20. [StructLayout(LayoutKind.Sequential)]
  21. [GenerateTestsForBurstCompatibility]
  22. internal unsafe struct UnsafeQueueBlockPoolData
  23. {
  24. internal IntPtr m_FirstBlock;
  25. internal int m_NumBlocks;
  26. internal int m_MaxBlocks;
  27. internal const int m_BlockSize = 16 * 1024;
  28. internal int m_AllocLock;
  29. public UnsafeQueueBlockHeader* AllocateBlock()
  30. {
  31. // There can only ever be a single thread allocating an entry from the free list since it needs to
  32. // access the content of the block (the next pointer) before doing the CAS.
  33. // If there was no lock thread A could read the next pointer, thread B could quickly allocate
  34. // the same block then free it with another next pointer before thread A performs the CAS which
  35. // leads to an invalid free list potentially causing memory corruption.
  36. // Having multiple threads freeing data concurrently to each other while another thread is allocating
  37. // is no problems since there is only ever a single thread modifying global data in that case.
  38. while (Interlocked.CompareExchange(ref m_AllocLock, 1, 0) != 0)
  39. {
  40. }
  41. UnsafeQueueBlockHeader* checkBlock = (UnsafeQueueBlockHeader*)m_FirstBlock;
  42. UnsafeQueueBlockHeader* block;
  43. do
  44. {
  45. block = checkBlock;
  46. if (block == null)
  47. {
  48. Interlocked.Exchange(ref m_AllocLock, 0);
  49. Interlocked.Increment(ref m_NumBlocks);
  50. block = (UnsafeQueueBlockHeader*)Memory.Unmanaged.Allocate(m_BlockSize, 16, Allocator.Persistent);
  51. return block;
  52. }
  53. checkBlock = (UnsafeQueueBlockHeader*)Interlocked.CompareExchange(ref m_FirstBlock, (IntPtr)block->m_NextBlock, (IntPtr)block);
  54. }
  55. while (checkBlock != block);
  56. Interlocked.Exchange(ref m_AllocLock, 0);
  57. return block;
  58. }
  59. public void FreeBlock(UnsafeQueueBlockHeader* block)
  60. {
  61. if (m_NumBlocks > m_MaxBlocks)
  62. {
  63. if (Interlocked.Decrement(ref m_NumBlocks) + 1 > m_MaxBlocks)
  64. {
  65. Memory.Unmanaged.Free(block, Allocator.Persistent);
  66. return;
  67. }
  68. Interlocked.Increment(ref m_NumBlocks);
  69. }
  70. UnsafeQueueBlockHeader* checkBlock = (UnsafeQueueBlockHeader*)m_FirstBlock;
  71. UnsafeQueueBlockHeader* nextPtr;
  72. do
  73. {
  74. nextPtr = checkBlock;
  75. block->m_NextBlock = checkBlock;
  76. checkBlock = (UnsafeQueueBlockHeader*)Interlocked.CompareExchange(ref m_FirstBlock, (IntPtr)block, (IntPtr)checkBlock);
  77. }
  78. while (checkBlock != nextPtr);
  79. }
  80. }
  81. internal unsafe class UnsafeQueueBlockPool
  82. {
  83. static readonly SharedStatic<IntPtr> Data = SharedStatic<IntPtr>.GetOrCreate<UnsafeQueueBlockPool>();
  84. internal static UnsafeQueueBlockPoolData* GetQueueBlockPool()
  85. {
  86. var pData = (UnsafeQueueBlockPoolData**)Data.UnsafeDataPointer;
  87. var data = *pData;
  88. if (data == null)
  89. {
  90. data = (UnsafeQueueBlockPoolData*)Memory.Unmanaged.Allocate(UnsafeUtility.SizeOf<UnsafeQueueBlockPoolData>(), 8, Allocator.Persistent);
  91. *pData = data;
  92. data->m_NumBlocks = data->m_MaxBlocks = 256;
  93. data->m_AllocLock = 0;
  94. // Allocate MaxBlocks items
  95. UnsafeQueueBlockHeader* prev = null;
  96. for (int i = 0; i < data->m_MaxBlocks; ++i)
  97. {
  98. UnsafeQueueBlockHeader* block = (UnsafeQueueBlockHeader*)Memory.Unmanaged.Allocate(UnsafeQueueBlockPoolData.m_BlockSize, 16, Allocator.Persistent);
  99. block->m_NextBlock = prev;
  100. prev = block;
  101. }
  102. data->m_FirstBlock = (IntPtr)prev;
  103. AppDomainOnDomainUnload();
  104. }
  105. return data;
  106. }
  107. [BurstDiscard]
  108. static void AppDomainOnDomainUnload()
  109. {
  110. AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;
  111. }
  112. static void OnDomainUnload(object sender, EventArgs e)
  113. {
  114. var pData = (UnsafeQueueBlockPoolData**)Data.UnsafeDataPointer;
  115. var data = *pData;
  116. while (data->m_FirstBlock != IntPtr.Zero)
  117. {
  118. UnsafeQueueBlockHeader* block = (UnsafeQueueBlockHeader*)data->m_FirstBlock;
  119. data->m_FirstBlock = (IntPtr)block->m_NextBlock;
  120. Memory.Unmanaged.Free(block, Allocator.Persistent);
  121. --data->m_NumBlocks;
  122. }
  123. Memory.Unmanaged.Free(data, Allocator.Persistent);
  124. *pData = null;
  125. }
  126. }
  127. [StructLayout(LayoutKind.Sequential)]
  128. [GenerateTestsForBurstCompatibility]
  129. internal unsafe struct UnsafeQueueData
  130. {
  131. public IntPtr m_FirstBlock;
  132. public IntPtr m_LastBlock;
  133. public int m_MaxItems;
  134. public int m_CurrentRead;
  135. public byte* m_CurrentWriteBlockTLS;
  136. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  137. internal UnsafeQueueBlockHeader* GetCurrentWriteBlockTLS(int threadIndex)
  138. {
  139. var data = (UnsafeQueueBlockHeader**)&m_CurrentWriteBlockTLS[threadIndex * JobsUtility.CacheLineSize];
  140. return *data;
  141. }
  142. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  143. internal void SetCurrentWriteBlockTLS(int threadIndex, UnsafeQueueBlockHeader* currentWriteBlock)
  144. {
  145. var data = (UnsafeQueueBlockHeader**)&m_CurrentWriteBlockTLS[threadIndex * JobsUtility.CacheLineSize];
  146. *data = currentWriteBlock;
  147. }
  148. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  149. public static UnsafeQueueBlockHeader* AllocateWriteBlockMT<T>(UnsafeQueueData* data, UnsafeQueueBlockPoolData* pool, int threadIndex) where T : unmanaged
  150. {
  151. UnsafeQueueBlockHeader* currentWriteBlock = data->GetCurrentWriteBlockTLS(threadIndex);
  152. if (currentWriteBlock != null)
  153. {
  154. if (currentWriteBlock->m_NumItems != data->m_MaxItems)
  155. {
  156. return currentWriteBlock;
  157. }
  158. currentWriteBlock = null;
  159. }
  160. currentWriteBlock = pool->AllocateBlock();
  161. currentWriteBlock->m_NextBlock = null;
  162. currentWriteBlock->m_NumItems = 0;
  163. UnsafeQueueBlockHeader* prevLast = (UnsafeQueueBlockHeader*)Interlocked.Exchange(ref data->m_LastBlock, (IntPtr)currentWriteBlock);
  164. if (prevLast == null)
  165. {
  166. data->m_FirstBlock = (IntPtr)currentWriteBlock;
  167. }
  168. else
  169. {
  170. prevLast->m_NextBlock = currentWriteBlock;
  171. }
  172. data->SetCurrentWriteBlockTLS(threadIndex, currentWriteBlock);
  173. return currentWriteBlock;
  174. }
  175. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  176. public unsafe static void AllocateQueue<T>(AllocatorManager.AllocatorHandle label, out UnsafeQueueData* outBuf) where T : unmanaged
  177. {
  178. #if UNITY_2022_2_14F1_OR_NEWER
  179. int maxThreadCount = JobsUtility.ThreadIndexCount;
  180. #else
  181. int maxThreadCount = JobsUtility.MaxJobThreadCount;
  182. #endif
  183. var queueDataSize = CollectionHelper.Align(UnsafeUtility.SizeOf<UnsafeQueueData>(), JobsUtility.CacheLineSize);
  184. var data = (UnsafeQueueData*)Memory.Unmanaged.Allocate(
  185. queueDataSize
  186. + JobsUtility.CacheLineSize * maxThreadCount
  187. , JobsUtility.CacheLineSize
  188. , label
  189. );
  190. data->m_CurrentWriteBlockTLS = (((byte*)data) + queueDataSize);
  191. data->m_FirstBlock = IntPtr.Zero;
  192. data->m_LastBlock = IntPtr.Zero;
  193. data->m_MaxItems = (UnsafeQueueBlockPoolData.m_BlockSize - UnsafeUtility.SizeOf<UnsafeQueueBlockHeader>()) / UnsafeUtility.SizeOf<T>();
  194. data->m_CurrentRead = 0;
  195. for (int threadIndex = 0; threadIndex < maxThreadCount; ++threadIndex)
  196. {
  197. data->SetCurrentWriteBlockTLS(threadIndex, null);
  198. }
  199. outBuf = data;
  200. }
  201. public unsafe static void DeallocateQueue(UnsafeQueueData* data, UnsafeQueueBlockPoolData* pool, AllocatorManager.AllocatorHandle allocation)
  202. {
  203. UnsafeQueueBlockHeader* firstBlock = (UnsafeQueueBlockHeader*)data->m_FirstBlock;
  204. while (firstBlock != null)
  205. {
  206. UnsafeQueueBlockHeader* next = firstBlock->m_NextBlock;
  207. pool->FreeBlock(firstBlock);
  208. firstBlock = next;
  209. }
  210. Memory.Unmanaged.Free(data, allocation);
  211. }
  212. }
  213. /// <summary>
  214. /// An unmanaged queue.
  215. /// </summary>
  216. /// <typeparam name="T">The type of the elements.</typeparam>
  217. [StructLayout(LayoutKind.Sequential)]
  218. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  219. public unsafe struct UnsafeQueue<T>
  220. : INativeDisposable
  221. where T : unmanaged
  222. {
  223. [NativeDisableUnsafePtrRestriction]
  224. internal UnsafeQueueData* m_Buffer;
  225. [NativeDisableUnsafePtrRestriction]
  226. internal UnsafeQueueBlockPoolData* m_QueuePool;
  227. internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
  228. /// <summary>
  229. /// Initializes and returns an instance of UnsafeQueue.
  230. /// </summary>
  231. /// <param name="allocator">The allocator to use.</param>
  232. public UnsafeQueue(AllocatorManager.AllocatorHandle allocator)
  233. {
  234. m_QueuePool = UnsafeQueueBlockPool.GetQueueBlockPool();
  235. m_AllocatorLabel = allocator;
  236. UnsafeQueueData.AllocateQueue<T>(allocator, out m_Buffer);
  237. }
  238. internal static UnsafeQueue<T>* Alloc(AllocatorManager.AllocatorHandle allocator)
  239. {
  240. UnsafeQueue<T>* data = (UnsafeQueue<T>*)Memory.Unmanaged.Allocate(sizeof(UnsafeQueue<T>), UnsafeUtility.AlignOf<UnsafeQueue<T>>(), allocator);
  241. return data;
  242. }
  243. internal static void Free(UnsafeQueue<T>* data)
  244. {
  245. if (data == null)
  246. {
  247. throw new InvalidOperationException("UnsafeQueue has yet to be created or has been destroyed!");
  248. }
  249. var allocator = data->m_AllocatorLabel;
  250. data->Dispose();
  251. Memory.Unmanaged.Free(data, allocator);
  252. }
  253. /// <summary>
  254. /// Returns true if this queue is empty.
  255. /// </summary>
  256. /// <returns>True if this queue has no items or if the queue has not been constructed.</returns>
  257. public readonly bool IsEmpty()
  258. {
  259. if (IsCreated)
  260. {
  261. int count = 0;
  262. var currentRead = m_Buffer->m_CurrentRead;
  263. for (UnsafeQueueBlockHeader* block = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock
  264. ; block != null
  265. ; block = block->m_NextBlock
  266. )
  267. {
  268. count += block->m_NumItems;
  269. if (count > currentRead)
  270. {
  271. return false;
  272. }
  273. }
  274. return count == currentRead;
  275. }
  276. return true;
  277. }
  278. /// <summary>
  279. /// Returns the current number of elements in this queue.
  280. /// </summary>
  281. /// <remarks>Note that getting the count requires traversing the queue's internal linked list of blocks.
  282. /// Where possible, cache this value instead of reading the property repeatedly.</remarks>
  283. /// <returns>The current number of elements in this queue.</returns>
  284. public readonly int Count
  285. {
  286. get
  287. {
  288. int count = 0;
  289. for (UnsafeQueueBlockHeader* block = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock
  290. ; block != null
  291. ; block = block->m_NextBlock
  292. )
  293. {
  294. count += block->m_NumItems;
  295. }
  296. return count - m_Buffer->m_CurrentRead;
  297. }
  298. }
  299. internal static int PersistentMemoryBlockCount
  300. {
  301. get { return UnsafeQueueBlockPool.GetQueueBlockPool()->m_MaxBlocks; }
  302. set { Interlocked.Exchange(ref UnsafeQueueBlockPool.GetQueueBlockPool()->m_MaxBlocks, value); }
  303. }
  304. internal static int MemoryBlockSize
  305. {
  306. get { return UnsafeQueueBlockPoolData.m_BlockSize; }
  307. }
  308. /// <summary>
  309. /// Returns the element at the end of this queue without removing it.
  310. /// </summary>
  311. /// <returns>The element at the end of this queue.</returns>
  312. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  313. public T Peek()
  314. {
  315. CheckNotEmpty();
  316. UnsafeQueueBlockHeader* firstBlock = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock;
  317. return UnsafeUtility.ReadArrayElement<T>(firstBlock + 1, m_Buffer->m_CurrentRead);
  318. }
  319. /// <summary>
  320. /// Adds an element at the front of this queue.
  321. /// </summary>
  322. /// <param name="value">The value to be enqueued.</param>
  323. public void Enqueue(T value)
  324. {
  325. UnsafeQueueBlockHeader* writeBlock = UnsafeQueueData.AllocateWriteBlockMT<T>(m_Buffer, m_QueuePool, 0);
  326. UnsafeUtility.WriteArrayElement(writeBlock + 1, writeBlock->m_NumItems, value);
  327. ++writeBlock->m_NumItems;
  328. }
  329. /// <summary>
  330. /// Removes and returns the element at the end of this queue.
  331. /// </summary>
  332. /// <exception cref="InvalidOperationException">Thrown if this queue is empty.</exception>
  333. /// <returns>The element at the end of this queue.</returns>
  334. public T Dequeue()
  335. {
  336. if (!TryDequeue(out T item))
  337. {
  338. ThrowEmpty();
  339. }
  340. return item;
  341. }
  342. /// <summary>
  343. /// Removes and outputs the element at the end of this queue.
  344. /// </summary>
  345. /// <param name="item">Outputs the removed element.</param>
  346. /// <returns>True if this queue was not empty.</returns>
  347. public bool TryDequeue(out T item)
  348. {
  349. UnsafeQueueBlockHeader* firstBlock = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock;
  350. if (firstBlock != null)
  351. {
  352. var currentRead = m_Buffer->m_CurrentRead++;
  353. var numItems = firstBlock->m_NumItems;
  354. item = UnsafeUtility.ReadArrayElement<T>(firstBlock + 1, currentRead);
  355. if (currentRead + 1 >= numItems)
  356. {
  357. m_Buffer->m_CurrentRead = 0;
  358. m_Buffer->m_FirstBlock = (IntPtr)firstBlock->m_NextBlock;
  359. if (m_Buffer->m_FirstBlock == IntPtr.Zero)
  360. {
  361. m_Buffer->m_LastBlock = IntPtr.Zero;
  362. }
  363. #if UNITY_2022_2_14F1_OR_NEWER
  364. int maxThreadCount = JobsUtility.ThreadIndexCount;
  365. #else
  366. int maxThreadCount = JobsUtility.MaxJobThreadCount;
  367. #endif
  368. for (int threadIndex = 0; threadIndex < maxThreadCount; ++threadIndex)
  369. {
  370. if (m_Buffer->GetCurrentWriteBlockTLS(threadIndex) == firstBlock)
  371. {
  372. m_Buffer->SetCurrentWriteBlockTLS(threadIndex, null);
  373. }
  374. }
  375. m_QueuePool->FreeBlock(firstBlock);
  376. }
  377. return true;
  378. }
  379. item = default(T);
  380. return false;
  381. }
  382. /// <summary>
  383. /// Returns an array containing a copy of this queue's content.
  384. /// </summary>
  385. /// <param name="allocator">The allocator to use.</param>
  386. /// <returns>An array containing a copy of this queue's content. The elements are ordered in the same order they were
  387. /// enqueued, *e.g.* the earliest enqueued element is copied to index 0 of the array.</returns>
  388. public NativeArray<T> ToArray(AllocatorManager.AllocatorHandle allocator)
  389. {
  390. UnsafeQueueBlockHeader* firstBlock = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock;
  391. var outputArray = CollectionHelper.CreateNativeArray<T>(Count, allocator, NativeArrayOptions.UninitializedMemory);
  392. UnsafeQueueBlockHeader* currentBlock = firstBlock;
  393. var arrayPtr = (byte*)outputArray.GetUnsafePtr();
  394. int size = UnsafeUtility.SizeOf<T>();
  395. int dstOffset = 0;
  396. int srcOffset = m_Buffer->m_CurrentRead * size;
  397. int srcOffsetElements = m_Buffer->m_CurrentRead;
  398. while (currentBlock != null)
  399. {
  400. int bytesToCopy = (currentBlock->m_NumItems - srcOffsetElements) * size;
  401. UnsafeUtility.MemCpy(arrayPtr + dstOffset, (byte*)(currentBlock + 1) + srcOffset, bytesToCopy);
  402. srcOffset = srcOffsetElements = 0;
  403. dstOffset += bytesToCopy;
  404. currentBlock = currentBlock->m_NextBlock;
  405. }
  406. return outputArray;
  407. }
  408. /// <summary>
  409. /// Removes all elements of this queue.
  410. /// </summary>
  411. public void Clear()
  412. {
  413. UnsafeQueueBlockHeader* firstBlock = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock;
  414. while (firstBlock != null)
  415. {
  416. UnsafeQueueBlockHeader* next = firstBlock->m_NextBlock;
  417. m_QueuePool->FreeBlock(firstBlock);
  418. firstBlock = next;
  419. }
  420. m_Buffer->m_FirstBlock = IntPtr.Zero;
  421. m_Buffer->m_LastBlock = IntPtr.Zero;
  422. m_Buffer->m_CurrentRead = 0;
  423. #if UNITY_2022_2_14F1_OR_NEWER
  424. int maxThreadCount = JobsUtility.ThreadIndexCount;
  425. #else
  426. int maxThreadCount = JobsUtility.MaxJobThreadCount;
  427. #endif
  428. for (int threadIndex = 0; threadIndex < maxThreadCount; ++threadIndex)
  429. {
  430. m_Buffer->SetCurrentWriteBlockTLS(threadIndex, null);
  431. }
  432. }
  433. /// <summary>
  434. /// Whether this queue has been allocated (and not yet deallocated).
  435. /// </summary>
  436. /// <value>True if this queue has been allocated (and not yet deallocated).</value>
  437. public readonly bool IsCreated
  438. {
  439. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  440. get => m_Buffer != null;
  441. }
  442. /// <summary>
  443. /// Releases all resources (memory and safety handles).
  444. /// </summary>
  445. public void Dispose()
  446. {
  447. if (!IsCreated)
  448. {
  449. return;
  450. }
  451. UnsafeQueueData.DeallocateQueue(m_Buffer, m_QueuePool, m_AllocatorLabel);
  452. m_Buffer = null;
  453. m_QueuePool = null;
  454. }
  455. /// <summary>
  456. /// Creates and schedules a job that releases all resources (memory and safety handles) of this queue.
  457. /// </summary>
  458. /// <param name="inputDeps">The dependency for the new job.</param>
  459. /// <returns>The handle of the new job. The job depends upon `inputDeps` and releases all resources (memory and safety handles) of this queue.</returns>
  460. public JobHandle Dispose(JobHandle inputDeps)
  461. {
  462. if (!IsCreated)
  463. {
  464. return inputDeps;
  465. }
  466. var jobHandle = new UnsafeQueueDisposeJob { Data = new UnsafeQueueDispose { m_Buffer = m_Buffer, m_QueuePool = m_QueuePool, m_AllocatorLabel = m_AllocatorLabel } }.Schedule(inputDeps);
  467. m_Buffer = null;
  468. m_QueuePool = null;
  469. return jobHandle;
  470. }
  471. /// <summary>
  472. /// An enumerator over the values of a container.
  473. /// </summary>
  474. /// <remarks>
  475. /// In an enumerator's initial state, <see cref="Current"/> is invalid.
  476. /// The first <see cref="MoveNext"/> call advances the enumerator to the first value.
  477. /// </remarks>
  478. public struct Enumerator : IEnumerator<T>
  479. {
  480. [NativeDisableUnsafePtrRestriction]
  481. internal UnsafeQueueBlockHeader* m_FirstBlock;
  482. [NativeDisableUnsafePtrRestriction]
  483. internal UnsafeQueueBlockHeader* m_Block;
  484. internal int m_Index;
  485. T value;
  486. /// <summary>
  487. /// Does nothing.
  488. /// </summary>
  489. public void Dispose() { }
  490. /// <summary>
  491. /// Advances the enumerator to the next value.
  492. /// </summary>
  493. /// <returns>True if `Current` is valid to read after the call.</returns>
  494. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  495. public bool MoveNext()
  496. {
  497. m_Index++;
  498. for (; m_Block != null
  499. ; m_Block = m_Block->m_NextBlock
  500. )
  501. {
  502. var numItems = m_Block->m_NumItems;
  503. if (m_Index < numItems)
  504. {
  505. value = UnsafeUtility.ReadArrayElement<T>(m_Block + 1, m_Index);
  506. return true;
  507. }
  508. m_Index -= numItems;
  509. }
  510. value = default;
  511. return false;
  512. }
  513. /// <summary>
  514. /// Resets the enumerator to its initial state.
  515. /// </summary>
  516. public void Reset()
  517. {
  518. m_Block = m_FirstBlock;
  519. m_Index = -1;
  520. }
  521. /// <summary>
  522. /// The current value.
  523. /// </summary>
  524. /// <value>The current value.</value>
  525. public T Current
  526. {
  527. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  528. get => value;
  529. }
  530. object IEnumerator.Current => Current;
  531. }
  532. /// <summary>
  533. /// Returns a readonly version of this UnsafeQueue instance.
  534. /// </summary>
  535. /// <remarks>ReadOnly containers point to the same underlying data as the UnsafeQueue it is made from.</remarks>
  536. /// <returns>ReadOnly instance for this.</returns>
  537. public ReadOnly AsReadOnly()
  538. {
  539. return new ReadOnly(ref this);
  540. }
  541. /// <summary>
  542. /// A read-only alias for the value of a UnsafeQueue. Does not have its own allocated storage.
  543. /// </summary>
  544. public struct ReadOnly
  545. : IEnumerable<T>
  546. {
  547. [NativeDisableUnsafePtrRestriction]
  548. UnsafeQueueData* m_Buffer;
  549. internal ReadOnly(ref UnsafeQueue<T> data)
  550. {
  551. m_Buffer = data.m_Buffer;
  552. }
  553. /// <summary>
  554. /// Whether this container been allocated (and not yet deallocated).
  555. /// </summary>
  556. /// <value>True if this container has been allocated (and not yet deallocated).</value>
  557. public readonly bool IsCreated
  558. {
  559. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  560. get
  561. {
  562. return m_Buffer != null;
  563. }
  564. }
  565. /// <summary>
  566. /// Returns true if this queue is empty.
  567. /// </summary>
  568. /// <remarks>Note that getting the count requires traversing the queue's internal linked list of blocks.
  569. /// Where possible, cache this value instead of reading the property repeatedly.</remarks>
  570. /// <returns>True if this queue has no items or if the queue has not been constructed.</returns>
  571. public readonly bool IsEmpty()
  572. {
  573. int count = 0;
  574. var currentRead = m_Buffer->m_CurrentRead;
  575. for (UnsafeQueueBlockHeader* block = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock
  576. ; block != null
  577. ; block = block->m_NextBlock
  578. )
  579. {
  580. count += block->m_NumItems;
  581. if (count > currentRead)
  582. {
  583. return false;
  584. }
  585. }
  586. return count == currentRead;
  587. }
  588. /// <summary>
  589. /// Returns the current number of elements in this queue.
  590. /// </summary>
  591. /// <remarks>Note that getting the count requires traversing the queue's internal linked list of blocks.
  592. /// Where possible, cache this value instead of reading the property repeatedly.</remarks>
  593. /// <returns>The current number of elements in this queue.</returns>
  594. public readonly int Count
  595. {
  596. get
  597. {
  598. int count = 0;
  599. for (UnsafeQueueBlockHeader* block = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock
  600. ; block != null
  601. ; block = block->m_NextBlock
  602. )
  603. {
  604. count += block->m_NumItems;
  605. }
  606. return count - m_Buffer->m_CurrentRead;
  607. }
  608. }
  609. /// <summary>
  610. /// The element at an index.
  611. /// </summary>
  612. /// <param name="index">An index.</param>
  613. /// <value>The element at the index.</value>
  614. /// <exception cref="IndexOutOfRangeException">Thrown if the index is out of bounds.</exception>
  615. public readonly T this[int index]
  616. {
  617. get
  618. {
  619. T result;
  620. if (!TryGetValue(index, out result))
  621. {
  622. ThrowIndexOutOfRangeException(index);
  623. }
  624. return result;
  625. }
  626. }
  627. readonly bool TryGetValue(int index, out T item)
  628. {
  629. if (index >= 0)
  630. {
  631. var idx = index;
  632. for (UnsafeQueueBlockHeader* block = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock
  633. ; block != null
  634. ; block = block->m_NextBlock
  635. )
  636. {
  637. var numItems = block->m_NumItems;
  638. if (idx < numItems)
  639. {
  640. item = UnsafeUtility.ReadArrayElement<T>(block + 1, idx);
  641. return true;
  642. }
  643. idx -= numItems;
  644. }
  645. }
  646. item = default;
  647. return false;
  648. }
  649. /// <summary>
  650. /// Returns an enumerator over the items of this container.
  651. /// </summary>
  652. /// <returns>An enumerator over the items of this container.</returns>
  653. public readonly Enumerator GetEnumerator()
  654. {
  655. return new Enumerator
  656. {
  657. m_FirstBlock = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock,
  658. m_Block = (UnsafeQueueBlockHeader*)m_Buffer->m_FirstBlock,
  659. m_Index = -1,
  660. };
  661. }
  662. /// <summary>
  663. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  664. /// </summary>
  665. /// <returns>Throws NotImplementedException.</returns>
  666. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  667. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  668. {
  669. throw new NotImplementedException();
  670. }
  671. /// <summary>
  672. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  673. /// </summary>
  674. /// <returns>Throws NotImplementedException.</returns>
  675. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  676. IEnumerator IEnumerable.GetEnumerator()
  677. {
  678. throw new NotImplementedException();
  679. }
  680. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  681. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  682. readonly void ThrowIndexOutOfRangeException(int index)
  683. {
  684. throw new IndexOutOfRangeException($"Index {index} is out of bounds [0-{Count}].");
  685. }
  686. }
  687. /// <summary>
  688. /// Returns a parallel writer for this queue.
  689. /// </summary>
  690. /// <returns>A parallel writer for this queue.</returns>
  691. public ParallelWriter AsParallelWriter()
  692. {
  693. ParallelWriter writer;
  694. writer.m_Buffer = m_Buffer;
  695. writer.m_QueuePool = m_QueuePool;
  696. writer.m_ThreadIndex = 0;
  697. return writer;
  698. }
  699. /// <summary>
  700. /// A parallel writer for a UnsafeQueue.
  701. /// </summary>
  702. /// <remarks>
  703. /// Use <see cref="AsParallelWriter"/> to create a parallel writer for a UnsafeQueue.
  704. /// </remarks>
  705. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  706. public unsafe struct ParallelWriter
  707. {
  708. [NativeDisableUnsafePtrRestriction]
  709. internal UnsafeQueueData* m_Buffer;
  710. [NativeDisableUnsafePtrRestriction]
  711. internal UnsafeQueueBlockPoolData* m_QueuePool;
  712. [NativeSetThreadIndex]
  713. internal int m_ThreadIndex;
  714. /// <summary>
  715. /// Adds an element at the front of the queue.
  716. /// </summary>
  717. /// <param name="value">The value to be enqueued.</param>
  718. public void Enqueue(T value)
  719. {
  720. UnsafeQueueBlockHeader* writeBlock = UnsafeQueueData.AllocateWriteBlockMT<T>(m_Buffer, m_QueuePool, m_ThreadIndex);
  721. UnsafeUtility.WriteArrayElement(writeBlock + 1, writeBlock->m_NumItems, value);
  722. ++writeBlock->m_NumItems;
  723. }
  724. /// <summary>
  725. /// Adds an element at the front of the queue.
  726. /// </summary>
  727. /// <param name="value">The value to be enqueued.</param>
  728. /// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
  729. internal void Enqueue(T value, int threadIndexOverride)
  730. {
  731. UnsafeQueueBlockHeader* writeBlock = UnsafeQueueData.AllocateWriteBlockMT<T>(m_Buffer, m_QueuePool, threadIndexOverride);
  732. UnsafeUtility.WriteArrayElement(writeBlock + 1, writeBlock->m_NumItems, value);
  733. ++writeBlock->m_NumItems;
  734. }
  735. }
  736. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  737. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  738. void CheckNotEmpty()
  739. {
  740. if (m_Buffer->m_FirstBlock == (IntPtr)0)
  741. {
  742. ThrowEmpty();
  743. }
  744. }
  745. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  746. static void ThrowEmpty()
  747. {
  748. throw new InvalidOperationException("Trying to read from an empty queue.");
  749. }
  750. }
  751. [GenerateTestsForBurstCompatibility]
  752. internal unsafe struct UnsafeQueueDispose
  753. {
  754. [NativeDisableUnsafePtrRestriction]
  755. internal UnsafeQueueData* m_Buffer;
  756. [NativeDisableUnsafePtrRestriction]
  757. internal UnsafeQueueBlockPoolData* m_QueuePool;
  758. internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
  759. public void Dispose()
  760. {
  761. UnsafeQueueData.DeallocateQueue(m_Buffer, m_QueuePool, m_AllocatorLabel);
  762. }
  763. }
  764. [BurstCompile]
  765. struct UnsafeQueueDisposeJob : IJob
  766. {
  767. public UnsafeQueueDispose Data;
  768. public void Execute()
  769. {
  770. Data.Dispose();
  771. }
  772. }
  773. }