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

NativeParallelHashSet.cs 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. using System.Runtime.CompilerServices;
  11. namespace Unity.Collections
  12. {
  13. /// <summary>
  14. /// An unordered, expandable set of unique values.
  15. /// </summary>
  16. /// <typeparam name="T">The type of the values.</typeparam>
  17. [StructLayout(LayoutKind.Sequential)]
  18. [DebuggerTypeProxy(typeof(NativeParallelHashSetDebuggerTypeProxy<>))]
  19. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  20. public unsafe struct NativeParallelHashSet<T>
  21. : INativeDisposable
  22. , IEnumerable<T> // Used by collection initializers.
  23. where T : unmanaged, IEquatable<T>
  24. {
  25. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  26. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeParallelHashSet<T>>();
  27. #endif
  28. internal NativeParallelHashMap<T, bool> m_Data;
  29. /// <summary>
  30. /// Initializes and returns an instance of NativeParallelHashSet.
  31. /// </summary>
  32. /// <param name="capacity">The number of values that should fit in the initial allocation.</param>
  33. /// <param name="allocator">The allocator to use.</param>
  34. public NativeParallelHashSet(int capacity, AllocatorManager.AllocatorHandle allocator)
  35. {
  36. m_Data = new NativeParallelHashMap<T, bool>(capacity, allocator);
  37. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  38. CollectionHelper.SetStaticSafetyId<NativeParallelHashSet<T>>(ref m_Data.m_Safety, ref s_staticSafetyId.Data);
  39. #endif
  40. }
  41. /// <summary>
  42. /// Whether this set is empty.
  43. /// </summary>
  44. /// <value>True if this set is empty or if the set has not been constructed.</value>
  45. public readonly bool IsEmpty
  46. {
  47. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  48. get => m_Data.IsEmpty;
  49. }
  50. /// <summary>
  51. /// Returns the current number of values in this set.
  52. /// </summary>
  53. /// <returns>The current number of values in this set.</returns>
  54. public int Count() => m_Data.Count();
  55. /// <summary>
  56. /// The number of values that fit in the current allocation.
  57. /// </summary>
  58. /// <value>The number of values that fit in the current allocation.</value>
  59. /// <param name="value">A new capacity. Must be larger than current capacity.</param>
  60. /// <exception cref="InvalidOperationException">Thrown if `value` is less than the current capacity.</exception>
  61. public int Capacity
  62. {
  63. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  64. readonly get => m_Data.Capacity;
  65. set => m_Data.Capacity = value;
  66. }
  67. /// <summary>
  68. /// Whether this set has been allocated (and not yet deallocated).
  69. /// </summary>
  70. /// <value>True if this set has been allocated (and not yet deallocated).</value>
  71. public readonly bool IsCreated
  72. {
  73. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  74. get => m_Data.IsCreated;
  75. }
  76. /// <summary>
  77. /// Releases all resources (memory and safety handles).
  78. /// </summary>
  79. public void Dispose() => m_Data.Dispose();
  80. /// <summary>
  81. /// Creates and schedules a job that will dispose this set.
  82. /// </summary>
  83. /// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
  84. /// <returns>The handle of a new job that will dispose this set.</returns>
  85. public JobHandle Dispose(JobHandle inputDeps) => m_Data.Dispose(inputDeps);
  86. /// <summary>
  87. /// Removes all values.
  88. /// </summary>
  89. /// <remarks>Does not change the capacity.</remarks>
  90. public void Clear() => m_Data.Clear();
  91. /// <summary>
  92. /// Adds a new value (unless it is already present).
  93. /// </summary>
  94. /// <param name="item">The value to add.</param>
  95. /// <returns>True if the value was not already present.</returns>
  96. public bool Add(T item) => m_Data.TryAdd(item, false);
  97. /// <summary>
  98. /// Removes a particular value.
  99. /// </summary>
  100. /// <param name="item">The value to remove.</param>
  101. /// <returns>True if the value was present.</returns>
  102. public bool Remove(T item) => m_Data.Remove(item);
  103. /// <summary>
  104. /// Returns true if a particular value is present.
  105. /// </summary>
  106. /// <param name="item">The value to check for.</param>
  107. /// <returns>True if the value was present.</returns>
  108. public bool Contains(T item) => m_Data.ContainsKey(item);
  109. /// <summary>
  110. /// Returns an array with a copy of this set's values (in no particular order).
  111. /// </summary>
  112. /// <param name="allocator">The allocator to use.</param>
  113. /// <returns>An array with a copy of the set's values.</returns>
  114. public NativeArray<T> ToNativeArray(AllocatorManager.AllocatorHandle allocator) => m_Data.GetKeyArray(allocator);
  115. /// <summary>
  116. /// Returns a parallel writer.
  117. /// </summary>
  118. /// <returns>A parallel writer.</returns>
  119. public ParallelWriter AsParallelWriter()
  120. {
  121. ParallelWriter writer;
  122. writer.m_Data = m_Data.AsParallelWriter();
  123. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  124. CollectionHelper.SetStaticSafetyId<ParallelWriter>(ref writer.m_Data.m_Safety, ref ParallelWriter.s_staticSafetyId.Data);
  125. #endif
  126. return writer;
  127. }
  128. /// <summary>
  129. /// A parallel writer for a NativeParallelHashSet.
  130. /// </summary>
  131. /// <remarks>
  132. /// Use <see cref="AsParallelWriter"/> to create a parallel writer for a set.
  133. /// </remarks>
  134. [NativeContainerIsAtomicWriteOnly]
  135. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  136. public struct ParallelWriter
  137. {
  138. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  139. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ParallelWriter>();
  140. #endif
  141. internal NativeParallelHashMap<T, bool>.ParallelWriter m_Data;
  142. /// <summary>
  143. /// The number of values that fit in the current allocation.
  144. /// </summary>
  145. /// <value>The number of values that fit in the current allocation.</value>
  146. public readonly int Capacity
  147. {
  148. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  149. get => m_Data.Capacity;
  150. }
  151. /// <summary>
  152. /// Adds a new value (unless it is already present).
  153. /// </summary>
  154. /// <param name="item">The value to add.</param>
  155. /// <returns>True if the value is not already present.</returns>
  156. public bool Add(T item) => m_Data.TryAdd(item, false);
  157. /// <summary>
  158. /// Adds a new value (unless it is already present).
  159. /// </summary>
  160. /// <param name="item">The value to add.</param>
  161. /// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
  162. /// <returns>True if the value is not already present.</returns>
  163. internal bool Add(T item, int threadIndexOverride) => m_Data.TryAdd(item, false, threadIndexOverride);
  164. }
  165. /// <summary>
  166. /// Returns an enumerator over the values of this set.
  167. /// </summary>
  168. /// <returns>An enumerator over the values of this set.</returns>
  169. public Enumerator GetEnumerator()
  170. {
  171. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  172. AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Data.m_Safety);
  173. var ash = m_Data.m_Safety;
  174. AtomicSafetyHandle.UseSecondaryVersion(ref ash);
  175. #endif
  176. return new Enumerator
  177. {
  178. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  179. m_Safety = ash,
  180. #endif
  181. m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_Data.m_HashMapData.m_Buffer),
  182. };
  183. }
  184. /// <summary>
  185. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  186. /// </summary>
  187. /// <returns>Throws NotImplementedException.</returns>
  188. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  189. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  190. {
  191. throw new NotImplementedException();
  192. }
  193. /// <summary>
  194. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  195. /// </summary>
  196. /// <returns>Throws NotImplementedException.</returns>
  197. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  198. IEnumerator IEnumerable.GetEnumerator()
  199. {
  200. throw new NotImplementedException();
  201. }
  202. /// <summary>
  203. /// An enumerator over the values of a set.
  204. /// </summary>
  205. /// <remarks>
  206. /// In an enumerator's initial state, <see cref="Current"/> is invalid.
  207. /// The first <see cref="MoveNext"/> call advances the enumerator to the first value.
  208. /// </remarks>
  209. [NativeContainer]
  210. [NativeContainerIsReadOnly]
  211. public struct Enumerator : IEnumerator<T>
  212. {
  213. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  214. internal AtomicSafetyHandle m_Safety;
  215. #endif
  216. internal UnsafeParallelHashMapDataEnumerator m_Enumerator;
  217. /// <summary>
  218. /// Does nothing.
  219. /// </summary>
  220. public void Dispose() { }
  221. /// <summary>
  222. /// Advances the enumerator to the next value.
  223. /// </summary>
  224. /// <returns>True if `Current` is valid to read after the call.</returns>
  225. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  226. public bool MoveNext()
  227. {
  228. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  229. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  230. #endif
  231. return m_Enumerator.MoveNext();
  232. }
  233. /// <summary>
  234. /// Resets the enumerator to its initial state.
  235. /// </summary>
  236. public void Reset()
  237. {
  238. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  239. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  240. #endif
  241. m_Enumerator.Reset();
  242. }
  243. /// <summary>
  244. /// The current value.
  245. /// </summary>
  246. /// <value>The current value.</value>
  247. public T Current
  248. {
  249. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  250. get
  251. {
  252. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  253. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  254. #endif
  255. return m_Enumerator.GetCurrentKey<T>();
  256. }
  257. }
  258. /// <summary>
  259. /// Gets the element at the current position of the enumerator in the container.
  260. /// </summary>
  261. object IEnumerator.Current => Current;
  262. }
  263. /// <summary>
  264. /// Returns a readonly version of this NativeParallelHashSet instance.
  265. /// </summary>
  266. /// <remarks>ReadOnly containers point to the same underlying data as the NativeParallelHashSet it is made from.</remarks>
  267. /// <returns>ReadOnly instance for this.</returns>
  268. public ReadOnly AsReadOnly()
  269. {
  270. return new ReadOnly(ref this);
  271. }
  272. /// <summary>
  273. /// A read-only alias for the value of a NativeParallelHashSet. Does not have its own allocated storage.
  274. /// </summary>
  275. [NativeContainer]
  276. [NativeContainerIsReadOnly]
  277. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
  278. public struct ReadOnly
  279. : IEnumerable<T>
  280. {
  281. internal UnsafeParallelHashMap<T, bool> m_Data;
  282. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  283. AtomicSafetyHandle m_Safety;
  284. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
  285. #endif
  286. internal ReadOnly(ref NativeParallelHashSet<T> data)
  287. {
  288. m_Data = data.m_Data.m_HashMapData;
  289. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  290. m_Safety = data.m_Data.m_Safety;
  291. CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
  292. #endif
  293. }
  294. /// <summary>
  295. /// Whether this hash set has been allocated (and not yet deallocated).
  296. /// </summary>
  297. /// <value>True if this hash set has been allocated (and not yet deallocated).</value>
  298. public readonly bool IsCreated
  299. {
  300. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  301. get
  302. {
  303. CheckRead();
  304. return m_Data.IsCreated;
  305. }
  306. }
  307. /// <summary>
  308. /// Whether this hash set is empty.
  309. /// </summary>
  310. /// <value>True if this hash set is empty or if the map has not been constructed.</value>
  311. public readonly bool IsEmpty
  312. {
  313. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  314. get
  315. {
  316. CheckRead();
  317. if (!m_Data.IsCreated)
  318. {
  319. return true;
  320. }
  321. return m_Data.IsEmpty;
  322. }
  323. }
  324. /// <summary>
  325. /// The current number of items in this hash set.
  326. /// </summary>
  327. /// <returns>The current number of items in this hash set.</returns>
  328. public readonly int Count()
  329. {
  330. CheckRead();
  331. return m_Data.Count();
  332. }
  333. /// <summary>
  334. /// The number of items that fit in the current allocation.
  335. /// </summary>
  336. /// <value>The number of items that fit in the current allocation.</value>
  337. public readonly int Capacity
  338. {
  339. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  340. get
  341. {
  342. CheckRead();
  343. return m_Data.Capacity;
  344. }
  345. }
  346. /// <summary>
  347. /// Returns true if a given item is present in this hash set.
  348. /// </summary>
  349. /// <param name="item">The item to look up.</param>
  350. /// <returns>True if the item was present.</returns>
  351. public readonly bool Contains(T item)
  352. {
  353. CheckRead();
  354. return m_Data.ContainsKey(item);
  355. }
  356. /// <summary>
  357. /// Returns an array with a copy of all this hash set's items (in no particular order).
  358. /// </summary>
  359. /// <param name="allocator">The allocator to use.</param>
  360. /// <returns>An array with a copy of all this hash set's items (in no particular order).</returns>
  361. public readonly NativeArray<T> ToNativeArray(AllocatorManager.AllocatorHandle allocator)
  362. {
  363. CheckRead();
  364. return m_Data.GetKeyArray(allocator);
  365. }
  366. /// <summary>
  367. /// Returns an enumerator over the items of this hash set.
  368. /// </summary>
  369. /// <returns>An enumerator over the items of this hash set.</returns>
  370. public readonly Enumerator GetEnumerator()
  371. {
  372. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  373. AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
  374. var ash = m_Safety;
  375. AtomicSafetyHandle.UseSecondaryVersion(ref ash);
  376. #endif
  377. return new Enumerator
  378. {
  379. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  380. m_Safety = ash,
  381. #endif
  382. m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_Data.m_Buffer),
  383. };
  384. }
  385. /// <summary>
  386. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  387. /// </summary>
  388. /// <returns>Throws NotImplementedException.</returns>
  389. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  390. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  391. {
  392. throw new NotImplementedException();
  393. }
  394. /// <summary>
  395. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  396. /// </summary>
  397. /// <returns>Throws NotImplementedException.</returns>
  398. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  399. IEnumerator IEnumerable.GetEnumerator()
  400. {
  401. throw new NotImplementedException();
  402. }
  403. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  404. readonly void CheckRead()
  405. {
  406. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  407. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  408. #endif
  409. }
  410. }
  411. }
  412. sealed internal class NativeParallelHashSetDebuggerTypeProxy<T>
  413. where T : unmanaged, IEquatable<T>
  414. {
  415. NativeParallelHashSet<T> Data;
  416. public NativeParallelHashSetDebuggerTypeProxy(NativeParallelHashSet<T> data)
  417. {
  418. Data = data;
  419. }
  420. public List<T> Items
  421. {
  422. get
  423. {
  424. var result = new List<T>();
  425. using (var keys = Data.ToNativeArray(Allocator.Temp))
  426. {
  427. for (var k = 0; k < keys.Length; ++k)
  428. {
  429. result.Add(keys[k]);
  430. }
  431. }
  432. return result;
  433. }
  434. }
  435. }
  436. }