暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

NativeHashSet.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Runtime.InteropServices;
  6. using Unity.Collections.LowLevel.Unsafe;
  7. using Unity.Jobs;
  8. using UnityEngine.Internal;
  9. using Unity.Burst;
  10. namespace Unity.Collections
  11. {
  12. /// <summary>
  13. /// An unordered, expandable set of unique values.
  14. /// </summary>
  15. /// <typeparam name="T">The type of the values.</typeparam>
  16. [StructLayout(LayoutKind.Sequential)]
  17. [DebuggerTypeProxy(typeof(NativeHashSetDebuggerTypeProxy<>))]
  18. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  19. public unsafe struct NativeHashSet<T>
  20. : INativeDisposable
  21. , IEnumerable<T> // Used by collection initializers.
  22. where T : unmanaged, IEquatable<T>
  23. {
  24. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  25. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeHashSet<T>>();
  26. #endif
  27. internal NativeHashMap<T, bool> m_Data;
  28. /// <summary>
  29. /// Initializes and returns an instance of NativeHashSet.
  30. /// </summary>
  31. /// <param name="capacity">The number of values that should fit in the initial allocation.</param>
  32. /// <param name="allocator">The allocator to use.</param>
  33. public NativeHashSet(int capacity, AllocatorManager.AllocatorHandle allocator)
  34. {
  35. m_Data = new NativeHashMap<T, bool>(capacity, allocator);
  36. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  37. CollectionHelper.SetStaticSafetyId<NativeHashSet<T>>(ref m_Data.m_Safety, ref s_staticSafetyId.Data);
  38. #endif
  39. }
  40. /// <summary>
  41. /// Whether this set is empty.
  42. /// </summary>
  43. /// <value>True if this set is empty or if the set has not been constructed.</value>
  44. public bool IsEmpty => m_Data.IsEmpty;
  45. /// <summary>
  46. /// Returns the current number of values in this set.
  47. /// </summary>
  48. /// <returns>The current number of values in this set.</returns>
  49. public int Count() => m_Data.Count();
  50. /// <summary>
  51. /// The number of values that fit in the current allocation.
  52. /// </summary>
  53. /// <value>The number of values that fit in the current allocation.</value>
  54. /// <param name="value">A new capacity. Must be larger than current capacity.</param>
  55. /// <exception cref="Exception">Thrown if `value` is less than the current capacity.</exception>
  56. public int Capacity { get => m_Data.Capacity; set => m_Data.Capacity = value; }
  57. /// <summary>
  58. /// Whether this set has been allocated (and not yet deallocated).
  59. /// </summary>
  60. /// <value>True if this set has been allocated (and not yet deallocated).</value>
  61. public bool IsCreated => m_Data.IsCreated;
  62. /// <summary>
  63. /// Releases all resources (memory and safety handles).
  64. /// </summary>
  65. public void Dispose() => m_Data.Dispose();
  66. /// <summary>
  67. /// Creates and schedules a job that will dispose this set.
  68. /// </summary>
  69. /// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
  70. /// <returns>The handle of a new job that will dispose this set.</returns>
  71. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  72. public JobHandle Dispose(JobHandle inputDeps) => m_Data.Dispose(inputDeps);
  73. /// <summary>
  74. /// Removes all values.
  75. /// </summary>
  76. /// <remarks>Does not change the capacity.</remarks>
  77. public void Clear() => m_Data.Clear();
  78. /// <summary>
  79. /// Adds a new value (unless it is already present).
  80. /// </summary>
  81. /// <param name="item">The value to add.</param>
  82. /// <returns>True if the value was not already present.</returns>
  83. public bool Add(T item) => m_Data.TryAdd(item, false);
  84. /// <summary>
  85. /// Removes a particular value.
  86. /// </summary>
  87. /// <param name="item">The value to remove.</param>
  88. /// <returns>True if the value was present.</returns>
  89. public bool Remove(T item) => m_Data.Remove(item);
  90. /// <summary>
  91. /// Returns true if a particular value is present.
  92. /// </summary>
  93. /// <param name="item">The value to check for.</param>
  94. /// <returns>True if the value was present.</returns>
  95. public bool Contains(T item) => m_Data.ContainsKey(item);
  96. /// <summary>
  97. /// Returns an array with a copy of this set's values (in no particular order).
  98. /// </summary>
  99. /// <param name="allocator">The allocator to use.</param>
  100. /// <returns>An array with a copy of the set's values.</returns>
  101. public NativeArray<T> ToNativeArray(AllocatorManager.AllocatorHandle allocator) => m_Data.GetKeyArray(allocator);
  102. /// <summary>
  103. /// Returns a parallel writer.
  104. /// </summary>
  105. /// <returns>A parallel writer.</returns>
  106. public ParallelWriter AsParallelWriter()
  107. {
  108. ParallelWriter writer;
  109. writer.m_Data = m_Data.AsParallelWriter();
  110. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  111. CollectionHelper.SetStaticSafetyId<ParallelWriter>(ref writer.m_Data.m_Safety, ref ParallelWriter.s_staticSafetyId.Data);
  112. #endif
  113. return writer;
  114. }
  115. /// <summary>
  116. /// A parallel writer for a NativeHashSet.
  117. /// </summary>
  118. /// <remarks>
  119. /// Use <see cref="AsParallelWriter"/> to create a parallel writer for a set.
  120. /// </remarks>
  121. [NativeContainerIsAtomicWriteOnly]
  122. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  123. public struct ParallelWriter
  124. {
  125. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  126. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ParallelWriter>();
  127. #endif
  128. internal NativeHashMap<T, bool>.ParallelWriter m_Data;
  129. /// <summary>
  130. /// The number of values that fit in the current allocation.
  131. /// </summary>
  132. /// <value>The number of values that fit in the current allocation.</value>
  133. public int Capacity => m_Data.Capacity;
  134. /// <summary>
  135. /// Adds a new value (unless it is already present).
  136. /// </summary>
  137. /// <param name="item">The value to add.</param>
  138. /// <returns>True if the value is not already present.</returns>
  139. public bool Add(T item) => m_Data.TryAdd(item, false);
  140. }
  141. /// <summary>
  142. /// Returns an enumerator over the values of this set.
  143. /// </summary>
  144. /// <returns>An enumerator over the values of this set.</returns>
  145. public Enumerator GetEnumerator()
  146. {
  147. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  148. AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Data.m_Safety);
  149. var ash = m_Data.m_Safety;
  150. AtomicSafetyHandle.UseSecondaryVersion(ref ash);
  151. #endif
  152. return new Enumerator
  153. {
  154. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  155. m_Safety = ash,
  156. #endif
  157. m_Enumerator = new UnsafeHashMapDataEnumerator(m_Data.m_HashMapData.m_Buffer),
  158. };
  159. }
  160. /// <summary>
  161. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  162. /// </summary>
  163. /// <returns>Throws NotImplementedException.</returns>
  164. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  165. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  166. {
  167. throw new NotImplementedException();
  168. }
  169. /// <summary>
  170. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  171. /// </summary>
  172. /// <returns>Throws NotImplementedException.</returns>
  173. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  174. IEnumerator IEnumerable.GetEnumerator()
  175. {
  176. throw new NotImplementedException();
  177. }
  178. /// <summary>
  179. /// An enumerator over the values of a set.
  180. /// </summary>
  181. /// <remarks>
  182. /// In an enumerator's initial state, <see cref="Current"/> is invalid.
  183. /// The first <see cref="MoveNext"/> call advances the enumerator to the first value.
  184. /// </remarks>
  185. [NativeContainer]
  186. [NativeContainerIsReadOnly]
  187. public struct Enumerator : IEnumerator<T>
  188. {
  189. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  190. internal AtomicSafetyHandle m_Safety;
  191. #endif
  192. internal UnsafeHashMapDataEnumerator m_Enumerator;
  193. /// <summary>
  194. /// Does nothing.
  195. /// </summary>
  196. public void Dispose() { }
  197. /// <summary>
  198. /// Advances the enumerator to the next value.
  199. /// </summary>
  200. /// <returns>True if `Current` is valid to read after the call.</returns>
  201. public bool MoveNext()
  202. {
  203. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  204. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  205. #endif
  206. return m_Enumerator.MoveNext();
  207. }
  208. /// <summary>
  209. /// Resets the enumerator to its initial state.
  210. /// </summary>
  211. public void Reset()
  212. {
  213. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  214. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  215. #endif
  216. m_Enumerator.Reset();
  217. }
  218. /// <summary>
  219. /// The current value.
  220. /// </summary>
  221. /// <value>The current value.</value>
  222. public T Current
  223. {
  224. get
  225. {
  226. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  227. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  228. #endif
  229. return m_Enumerator.GetCurrentKey<T>();
  230. }
  231. }
  232. /// <summary>
  233. /// Gets the element at the current position of the enumerator in the container.
  234. /// </summary>
  235. object IEnumerator.Current => Current;
  236. }
  237. }
  238. sealed internal class NativeHashSetDebuggerTypeProxy<T>
  239. where T : unmanaged, IEquatable<T>
  240. {
  241. #if !NET_DOTS
  242. NativeHashSet<T> Data;
  243. public NativeHashSetDebuggerTypeProxy(NativeHashSet<T> data)
  244. {
  245. Data = data;
  246. }
  247. public List<T> Items
  248. {
  249. get
  250. {
  251. var result = new List<T>();
  252. using (var keys = Data.ToNativeArray(Allocator.Temp))
  253. {
  254. for (var k = 0; k < keys.Length; ++k)
  255. {
  256. result.Add(keys[k]);
  257. }
  258. }
  259. return result;
  260. }
  261. }
  262. #endif
  263. }
  264. }