No Description
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.

UnsafeRingQueue.cs 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.CompilerServices;
  4. using Unity.Jobs;
  5. using System.Runtime.InteropServices;
  6. namespace Unity.Collections.LowLevel.Unsafe
  7. {
  8. /// <summary>
  9. /// A fixed-size circular buffer.
  10. /// </summary>
  11. /// <typeparam name="T">The type of the elements.</typeparam>
  12. [DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")]
  13. [DebuggerTypeProxy(typeof(UnsafeRingQueueDebugView<>))]
  14. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  15. [StructLayout(LayoutKind.Sequential)]
  16. public unsafe struct UnsafeRingQueue<T>
  17. : INativeDisposable
  18. where T : unmanaged
  19. {
  20. /// <summary>
  21. /// The internal buffer where the content is stored.
  22. /// </summary>
  23. /// <value>The internal buffer where the content is stored.</value>
  24. [NativeDisableUnsafePtrRestriction]
  25. public T* Ptr;
  26. /// <summary>
  27. /// The allocator used to create the internal buffer.
  28. /// </summary>
  29. /// <value>The allocator used to create the internal buffer.</value>
  30. public AllocatorManager.AllocatorHandle Allocator;
  31. internal readonly int m_Capacity;
  32. internal int m_Filled;
  33. internal int m_Write;
  34. internal int m_Read;
  35. /// <summary>
  36. /// Whether the queue is empty.
  37. /// </summary>
  38. /// <value>True if the queue is empty or the queue has not been constructed.</value>
  39. public readonly bool IsEmpty
  40. {
  41. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  42. get => m_Filled == 0;
  43. }
  44. /// <summary>
  45. /// The number of elements currently in this queue.
  46. /// </summary>
  47. /// <value>The number of elements currently in this queue.</value>
  48. public readonly int Length
  49. {
  50. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  51. get => m_Filled;
  52. }
  53. /// <summary>
  54. /// The number of elements that fit in the internal buffer.
  55. /// </summary>
  56. /// <value>The number of elements that fit in the internal buffer.</value>
  57. public readonly int Capacity
  58. {
  59. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  60. get => m_Capacity;
  61. }
  62. /// <summary>
  63. /// Initializes and returns an instance of UnsafeRingQueue which aliasing an existing buffer.
  64. /// </summary>
  65. /// <param name="ptr">An existing buffer to set as the internal buffer.</param>
  66. /// <param name="capacity">The capacity.</param>
  67. public UnsafeRingQueue(T* ptr, int capacity)
  68. {
  69. Ptr = ptr;
  70. Allocator = AllocatorManager.None;
  71. m_Capacity = capacity;
  72. m_Filled = 0;
  73. m_Write = 0;
  74. m_Read = 0;
  75. }
  76. /// <summary>
  77. /// Initializes and returns an instance of UnsafeRingQueue.
  78. /// </summary>
  79. /// <param name="capacity">The capacity.</param>
  80. /// <param name="allocator">The allocator to use.</param>
  81. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  82. public UnsafeRingQueue(int capacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
  83. {
  84. Allocator = allocator;
  85. m_Capacity = capacity;
  86. m_Filled = 0;
  87. m_Write = 0;
  88. m_Read = 0;
  89. var sizeInBytes = capacity * UnsafeUtility.SizeOf<T>();
  90. Ptr = (T*)Memory.Unmanaged.Allocate(sizeInBytes, 16, allocator);
  91. if (options == NativeArrayOptions.ClearMemory)
  92. {
  93. UnsafeUtility.MemClear(Ptr, sizeInBytes);
  94. }
  95. }
  96. internal static UnsafeRingQueue<T>* Alloc(AllocatorManager.AllocatorHandle allocator)
  97. {
  98. UnsafeRingQueue<T>* data = (UnsafeRingQueue<T>*)Memory.Unmanaged.Allocate(sizeof(UnsafeRingQueue<T>), UnsafeUtility.AlignOf<UnsafeRingQueue<T>>(), allocator);
  99. return data;
  100. }
  101. internal static void Free(UnsafeRingQueue<T>* data)
  102. {
  103. if (data == null)
  104. {
  105. throw new InvalidOperationException("UnsafeRingQueue has yet to be created or has been destroyed!");
  106. }
  107. var allocator = data->Allocator;
  108. data->Dispose();
  109. Memory.Unmanaged.Free(data, allocator);
  110. }
  111. /// <summary>
  112. /// Whether this queue has been allocated (and not yet deallocated).
  113. /// </summary>
  114. /// <value>True if this queue has been allocated (and not yet deallocated).</value>
  115. public readonly bool IsCreated
  116. {
  117. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  118. get => Ptr != null;
  119. }
  120. /// <summary>
  121. /// Releases all resources (memory and safety handles).
  122. /// </summary>
  123. public void Dispose()
  124. {
  125. if (!IsCreated)
  126. {
  127. return;
  128. }
  129. if (CollectionHelper.ShouldDeallocate(Allocator))
  130. {
  131. Memory.Unmanaged.Free(Ptr, Allocator);
  132. Allocator = AllocatorManager.Invalid;
  133. }
  134. Ptr = null;
  135. }
  136. /// <summary>
  137. /// Creates and schedules a job that will dispose this queue.
  138. /// </summary>
  139. /// <param name="inputDeps">The handle of a job which the new job will depend upon.</param>
  140. /// <returns>The handle of a new job that will dispose this queue. The new job depends upon inputDeps.</returns>
  141. public JobHandle Dispose(JobHandle inputDeps)
  142. {
  143. if (!IsCreated)
  144. {
  145. return inputDeps;
  146. }
  147. if (CollectionHelper.ShouldDeallocate(Allocator))
  148. {
  149. var jobHandle = new UnsafeDisposeJob { Ptr = Ptr, Allocator = Allocator }.Schedule(inputDeps);
  150. Ptr = null;
  151. Allocator = AllocatorManager.Invalid;
  152. return jobHandle;
  153. }
  154. Ptr = null;
  155. return inputDeps;
  156. }
  157. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  158. bool TryEnqueueInternal(T value)
  159. {
  160. if (m_Filled == m_Capacity)
  161. return false;
  162. Ptr[m_Write] = value;
  163. m_Write++;
  164. if (m_Write == m_Capacity)
  165. m_Write = 0;
  166. m_Filled++;
  167. return true;
  168. }
  169. /// <summary>
  170. /// Adds an element at the front of the queue.
  171. /// </summary>
  172. /// <remarks>Does nothing if the queue is full.</remarks>
  173. /// <param name="value">The value to be added.</param>
  174. /// <returns>True if the value was added.</returns>
  175. public bool TryEnqueue(T value)
  176. {
  177. return TryEnqueueInternal(value);
  178. }
  179. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  180. static void ThrowQueueFull()
  181. {
  182. throw new InvalidOperationException("Trying to enqueue into full queue.");
  183. }
  184. /// <summary>
  185. /// Adds an element at the front of the queue.
  186. /// </summary>
  187. /// <param name="value">The value to be added.</param>
  188. /// <exception cref="InvalidOperationException">Thrown if the queue was full.</exception>
  189. public void Enqueue(T value)
  190. {
  191. if (!TryEnqueueInternal(value))
  192. {
  193. ThrowQueueFull();
  194. }
  195. }
  196. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  197. bool TryDequeueInternal(out T item)
  198. {
  199. item = Ptr[m_Read];
  200. if (m_Filled == 0)
  201. return false;
  202. m_Read = m_Read + 1;
  203. if (m_Read == m_Capacity)
  204. m_Read = 0;
  205. m_Filled--;
  206. return true;
  207. }
  208. /// <summary>
  209. /// Removes the element from the end of the queue.
  210. /// </summary>
  211. /// <remarks>Does nothing if the queue is empty.</remarks>
  212. /// <param name="item">Outputs the element removed.</param>
  213. /// <returns>True if an element was removed.</returns>
  214. public bool TryDequeue(out T item)
  215. {
  216. return TryDequeueInternal(out item);
  217. }
  218. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  219. static void ThrowQueueEmpty()
  220. {
  221. throw new InvalidOperationException("Trying to dequeue from an empty queue");
  222. }
  223. /// <summary>
  224. /// Removes the element from the end of the queue.
  225. /// </summary>
  226. /// <exception cref="InvalidOperationException">Thrown if the queue was empty.</exception>
  227. /// <returns>Returns the removed element.</returns>
  228. public T Dequeue()
  229. {
  230. if (!TryDequeueInternal(out T item))
  231. {
  232. ThrowQueueEmpty();
  233. }
  234. return item;
  235. }
  236. }
  237. internal sealed class UnsafeRingQueueDebugView<T>
  238. where T : unmanaged
  239. {
  240. UnsafeRingQueue<T> Data;
  241. public UnsafeRingQueueDebugView(UnsafeRingQueue<T> data)
  242. {
  243. Data = data;
  244. }
  245. public unsafe T[] Items
  246. {
  247. get
  248. {
  249. T[] result = new T[Data.Length];
  250. var read = Data.m_Read;
  251. var capacity = Data.m_Capacity;
  252. for (var i = 0; i < result.Length; ++i)
  253. {
  254. result[i] = Data.Ptr[(read + i) % capacity];
  255. }
  256. return result;
  257. }
  258. }
  259. }
  260. }