Нет описания
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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 Unity.Burst;
  8. using Unity.Collections.LowLevel.Unsafe;
  9. using Unity.Collections.NotBurstCompatible;
  10. using Unity.Jobs;
  11. namespace Unity.Collections
  12. {
  13. /// <summary>
  14. /// An iterator over all values associated with an individual key in a multi hash map.
  15. /// </summary>
  16. /// <remarks>The iteration order over the values associated with a key is an implementation detail. Do not rely upon any particular ordering.</remarks>
  17. /// <typeparam name="TKey">The type of the keys.</typeparam>
  18. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  19. public struct NativeParallelMultiHashMapIterator<TKey>
  20. where TKey : unmanaged
  21. {
  22. internal TKey key;
  23. internal int NextEntryIndex;
  24. internal int EntryIndex;
  25. /// <summary>
  26. /// Returns the entry index.
  27. /// </summary>
  28. /// <returns>The entry index.</returns>
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. public int GetEntryIndex() => EntryIndex;
  31. }
  32. /// <summary>
  33. /// An unordered, expandable associative array. Each key can have more than one associated value.
  34. /// </summary>
  35. /// <remarks>
  36. /// Unlike a regular NativeParallelHashMap, a NativeParallelMultiHashMap can store multiple key-value pairs with the same key.
  37. ///
  38. /// The keys are not deduplicated: two key-value pairs with the same key are stored as fully separate key-value pairs.
  39. /// </remarks>
  40. /// <typeparam name="TKey">The type of the keys.</typeparam>
  41. /// <typeparam name="TValue">The type of the values.</typeparam>
  42. [StructLayout(LayoutKind.Sequential)]
  43. [NativeContainer]
  44. [DebuggerTypeProxy(typeof(NativeParallelMultiHashMapDebuggerTypeProxy<,>))]
  45. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
  46. public unsafe struct NativeParallelMultiHashMap<TKey, TValue>
  47. : INativeDisposable
  48. , IEnumerable<KeyValue<TKey, TValue>> // Used by collection initializers.
  49. where TKey : unmanaged, IEquatable<TKey>
  50. where TValue : unmanaged
  51. {
  52. internal UnsafeParallelMultiHashMap<TKey, TValue> m_MultiHashMapData;
  53. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  54. internal AtomicSafetyHandle m_Safety;
  55. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeParallelMultiHashMap<TKey, TValue>>();
  56. #endif
  57. /// <summary>
  58. /// Returns a newly allocated multi hash map.
  59. /// </summary>
  60. /// <param name="capacity">The number of key-value pairs that should fit in the initial allocation.</param>
  61. /// <param name="allocator">The allocator to use.</param>
  62. public NativeParallelMultiHashMap(int capacity, AllocatorManager.AllocatorHandle allocator)
  63. {
  64. this = default;
  65. Initialize(capacity, ref allocator);
  66. }
  67. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })]
  68. internal void Initialize<U>(int capacity, ref U allocator)
  69. where U : unmanaged, AllocatorManager.IAllocator
  70. {
  71. m_MultiHashMapData = new UnsafeParallelMultiHashMap<TKey, TValue>(capacity, allocator.Handle);
  72. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  73. m_Safety = CollectionHelper.CreateSafetyHandle(allocator.ToAllocator);
  74. if (UnsafeUtility.IsNativeContainerType<TKey>() || UnsafeUtility.IsNativeContainerType<TValue>())
  75. AtomicSafetyHandle.SetNestedContainer(m_Safety, true);
  76. CollectionHelper.SetStaticSafetyId<NativeParallelMultiHashMap<TKey, TValue>>(ref m_Safety, ref s_staticSafetyId.Data);
  77. AtomicSafetyHandle.SetBumpSecondaryVersionOnScheduleWrite(m_Safety, true);
  78. #endif
  79. }
  80. /// <summary>
  81. /// Whether this hash map is empty.
  82. /// </summary>
  83. /// <value>True if the hash map is empty or if the hash map has not been constructed.</value>
  84. public readonly bool IsEmpty
  85. {
  86. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  87. get
  88. {
  89. CheckRead();
  90. return m_MultiHashMapData.IsEmpty;
  91. }
  92. }
  93. /// <summary>
  94. /// Returns the current number of key-value pairs in this hash map.
  95. /// </summary>
  96. /// <remarks>Key-value pairs with matching keys are counted as separate, individual pairs.</remarks>
  97. /// <returns>The current number of key-value pairs in this hash map.</returns>
  98. public readonly int Count()
  99. {
  100. CheckRead();
  101. return m_MultiHashMapData.Count();
  102. }
  103. /// <summary>
  104. /// Returns the number of key-value pairs that fit in the current allocation.
  105. /// </summary>
  106. /// <value>The number of key-value pairs that fit in the current allocation.</value>
  107. /// <param name="value">A new capacity. Must be larger than the current capacity.</param>
  108. /// <exception cref="InvalidOperationException">Thrown if `value` is less than the current capacity.</exception>
  109. public int Capacity
  110. {
  111. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  112. readonly get
  113. {
  114. CheckRead();
  115. return m_MultiHashMapData.Capacity;
  116. }
  117. set
  118. {
  119. CheckWrite();
  120. m_MultiHashMapData.Capacity = value;
  121. }
  122. }
  123. /// <summary>
  124. /// Removes all key-value pairs.
  125. /// </summary>
  126. /// <remarks>Does not change the capacity.</remarks>
  127. public void Clear()
  128. {
  129. CheckWrite();
  130. m_MultiHashMapData.Clear();
  131. }
  132. /// <summary>
  133. /// Adds a new key-value pair.
  134. /// </summary>
  135. /// <remarks>
  136. /// If a key-value pair with this key is already present, an additional separate key-value pair is added.
  137. /// </remarks>
  138. /// <param name="key">The key to add.</param>
  139. /// <param name="item">The value to add.</param>
  140. public void Add(TKey key, TValue item)
  141. {
  142. CheckWrite();
  143. m_MultiHashMapData.Add(key, item);
  144. }
  145. /// <summary>
  146. /// Removes a key and its associated value(s).
  147. /// </summary>
  148. /// <param name="key">The key to remove.</param>
  149. /// <returns>The number of removed key-value pairs. If the key was not present, returns 0.</returns>
  150. public int Remove(TKey key)
  151. {
  152. CheckWrite();
  153. return m_MultiHashMapData.Remove(key);
  154. }
  155. /// <summary>
  156. /// Removes a single key-value pair.
  157. /// </summary>
  158. /// <param name="it">An iterator representing the key-value pair to remove.</param>
  159. /// <exception cref="InvalidOperationException">Thrown if the iterator is invalid.</exception>
  160. public void Remove(NativeParallelMultiHashMapIterator<TKey> it)
  161. {
  162. CheckWrite();
  163. m_MultiHashMapData.Remove(it);
  164. }
  165. /// <summary>
  166. /// Gets an iterator for a key.
  167. /// </summary>
  168. /// <param name="key">The key.</param>
  169. /// <param name="item">Outputs the associated value represented by the iterator.</param>
  170. /// <param name="it">Outputs an iterator.</param>
  171. /// <returns>True if the key was present.</returns>
  172. public bool TryGetFirstValue(TKey key, out TValue item, out NativeParallelMultiHashMapIterator<TKey> it)
  173. {
  174. CheckRead();
  175. return m_MultiHashMapData.TryGetFirstValue(key, out item, out it);
  176. }
  177. /// <summary>
  178. /// Advances an iterator to the next value associated with its key.
  179. /// </summary>
  180. /// <param name="item">Outputs the next value.</param>
  181. /// <param name="it">A reference to the iterator to advance.</param>
  182. /// <returns>True if the key was present and had another value.</returns>
  183. public bool TryGetNextValue(out TValue item, ref NativeParallelMultiHashMapIterator<TKey> it)
  184. {
  185. CheckRead();
  186. return m_MultiHashMapData.TryGetNextValue(out item, ref it);
  187. }
  188. /// <summary>
  189. /// Returns true if a given key is present in this hash map.
  190. /// </summary>
  191. /// <param name="key">The key to look up.</param>
  192. /// <returns>True if the key was present in this hash map.</returns>
  193. public bool ContainsKey(TKey key)
  194. {
  195. return TryGetFirstValue(key, out var temp0, out var temp1);
  196. }
  197. /// <summary>
  198. /// Returns the number of values associated with a given key.
  199. /// </summary>
  200. /// <param name="key">The key to look up.</param>
  201. /// <returns>The number of values associated with the key. Returns 0 if the key was not present.</returns>
  202. public int CountValuesForKey(TKey key)
  203. {
  204. if (!TryGetFirstValue(key, out var value, out var iterator))
  205. {
  206. return 0;
  207. }
  208. var count = 1;
  209. while (TryGetNextValue(out value, ref iterator))
  210. {
  211. count++;
  212. }
  213. return count;
  214. }
  215. /// <summary>
  216. /// Sets a new value for an existing key-value pair.
  217. /// </summary>
  218. /// <param name="item">The new value.</param>
  219. /// <param name="it">The iterator representing a key-value pair.</param>
  220. /// <returns>True if a value was overwritten.</returns>
  221. public bool SetValue(TValue item, NativeParallelMultiHashMapIterator<TKey> it)
  222. {
  223. CheckWrite();
  224. return m_MultiHashMapData.SetValue(item, it);
  225. }
  226. /// <summary>
  227. /// Whether this hash map has been allocated (and not yet deallocated).
  228. /// </summary>
  229. /// <value>True if this hash map has been allocated (and not yet deallocated).</value>
  230. public readonly bool IsCreated => m_MultiHashMapData.IsCreated;
  231. /// <summary>
  232. /// Releases all resources (memory and safety handles).
  233. /// </summary>
  234. public void Dispose()
  235. {
  236. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  237. if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
  238. {
  239. AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
  240. }
  241. #endif
  242. if (!IsCreated)
  243. {
  244. return;
  245. }
  246. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  247. CollectionHelper.DisposeSafetyHandle(ref m_Safety);
  248. #endif
  249. m_MultiHashMapData.Dispose();
  250. }
  251. /// <summary>
  252. /// Creates and schedules a job that will dispose this hash map.
  253. /// </summary>
  254. /// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
  255. /// <returns>The handle of a new job that will dispose this hash map.</returns>
  256. public JobHandle Dispose(JobHandle inputDeps)
  257. {
  258. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  259. if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
  260. {
  261. AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
  262. }
  263. #endif
  264. if (!IsCreated)
  265. {
  266. return inputDeps;
  267. }
  268. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  269. var jobHandle = new UnsafeParallelHashMapDataDisposeJob { Data = new UnsafeParallelHashMapDataDispose { m_Buffer = m_MultiHashMapData.m_Buffer, m_AllocatorLabel = m_MultiHashMapData.m_AllocatorLabel, m_Safety = m_Safety } }.Schedule(inputDeps);
  270. AtomicSafetyHandle.Release(m_Safety);
  271. #else
  272. var jobHandle = new UnsafeParallelHashMapDataDisposeJob { Data = new UnsafeParallelHashMapDataDispose { m_Buffer = m_MultiHashMapData.m_Buffer, m_AllocatorLabel = m_MultiHashMapData.m_AllocatorLabel } }.Schedule(inputDeps);
  273. #endif
  274. m_MultiHashMapData.m_Buffer = null;
  275. return jobHandle;
  276. }
  277. /// <summary>
  278. /// Returns an array with a copy of all the keys (in no particular order).
  279. /// </summary>
  280. /// <remarks>A key with *N* values is included *N* times in the array.
  281. ///
  282. /// Use `GetUniqueKeyArray` of <see cref="Unity.Collections.NativeParallelHashMapExtensions"/> instead if you only want one occurrence of each key.</remarks>
  283. /// <param name="allocator">The allocator to use.</param>
  284. /// <returns>An array with a copy of all the keys (in no particular order).</returns>
  285. public NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
  286. {
  287. CheckRead();
  288. return m_MultiHashMapData.GetKeyArray(allocator);
  289. }
  290. /// <summary>
  291. /// Returns an array with a copy of all the values (in no particular order).
  292. /// </summary>
  293. /// <remarks>The values are not deduplicated. If you sort the returned array,
  294. /// you can use <see cref="Unity.Collections.NativeParallelHashMapExtensions.Unique{T}"/> to remove duplicate values.</remarks>
  295. /// <param name="allocator">The allocator to use.</param>
  296. /// <returns>An array with a copy of all the values (in no particular order).</returns>
  297. public NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
  298. {
  299. CheckRead();
  300. return m_MultiHashMapData.GetValueArray(allocator);
  301. }
  302. /// <summary>
  303. /// Returns a NativeKeyValueArrays with a copy of all the keys and values (in no particular order).
  304. /// </summary>
  305. /// <remarks>A key with *N* values is included *N* times in the array.
  306. /// </remarks>
  307. /// <param name="allocator">The allocator to use.</param>
  308. /// <returns>A NativeKeyValueArrays with a copy of all the keys and values (in no particular order).</returns>
  309. public NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
  310. {
  311. CheckRead();
  312. return m_MultiHashMapData.GetKeyValueArrays(allocator);
  313. }
  314. /// <summary>
  315. /// Returns a parallel writer for this hash map.
  316. /// </summary>
  317. /// <returns>A parallel writer for this hash map.</returns>
  318. public ParallelWriter AsParallelWriter()
  319. {
  320. ParallelWriter writer;
  321. writer.m_Writer = m_MultiHashMapData.AsParallelWriter();
  322. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  323. writer.m_Safety = m_Safety;
  324. CollectionHelper.SetStaticSafetyId<ParallelWriter>(ref writer.m_Safety, ref s_staticSafetyId.Data);
  325. #endif
  326. return writer;
  327. }
  328. /// <summary>
  329. /// A parallel writer for a NativeParallelMultiHashMap.
  330. /// </summary>
  331. /// <remarks>
  332. /// Use <see cref="AsParallelWriter"/> to create a parallel writer for a NativeParallelMultiHashMap.
  333. /// </remarks>
  334. [NativeContainer]
  335. [NativeContainerIsAtomicWriteOnly]
  336. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
  337. public unsafe struct ParallelWriter
  338. {
  339. internal UnsafeParallelMultiHashMap<TKey, TValue>.ParallelWriter m_Writer;
  340. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  341. internal AtomicSafetyHandle m_Safety;
  342. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ParallelWriter>();
  343. #endif
  344. /// <summary>
  345. /// Returns the index of the current thread.
  346. /// </summary>
  347. /// <remarks>In a job, each thread gets its own copy of the ParallelWriter struct, and the job system assigns
  348. /// each copy the index of its thread.</remarks>
  349. /// <value>The index of the current thread.</value>
  350. public int m_ThreadIndex => m_Writer.m_ThreadIndex;
  351. /// <summary>
  352. /// Returns the number of key-value pairs that fit in the current allocation.
  353. /// </summary>
  354. /// <value>The number of key-value pairs that fit in the current allocation.</value>
  355. public readonly int Capacity
  356. {
  357. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  358. get
  359. {
  360. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  361. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  362. #endif
  363. return m_Writer.Capacity;
  364. }
  365. }
  366. /// <summary>
  367. /// Adds a new key-value pair.
  368. /// </summary>
  369. /// <remarks>
  370. /// If a key-value pair with this key is already present, an additional separate key-value pair is added.
  371. /// </remarks>
  372. /// <param name="key">The key to add.</param>
  373. /// <param name="item">The value to add.</param>
  374. public void Add(TKey key, TValue item)
  375. {
  376. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  377. AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
  378. #endif
  379. m_Writer.Add(key, item);
  380. }
  381. }
  382. /// <summary>
  383. /// Returns an enumerator over the values of an individual key.
  384. /// </summary>
  385. /// <param name="key">The key to get an enumerator for.</param>
  386. /// <returns>An enumerator over the values of a key.</returns>
  387. public Enumerator GetValuesForKey(TKey key)
  388. {
  389. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  390. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  391. #endif
  392. return new Enumerator { hashmap = this, key = key, isFirst = 1 };
  393. }
  394. /// <summary>
  395. /// An enumerator over the values of an individual key in a multi hash map.
  396. /// </summary>
  397. /// <remarks>
  398. /// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
  399. /// The first <see cref="MoveNext"/> call advances the enumerator to the first value of the key.
  400. /// </remarks>
  401. public struct Enumerator : IEnumerator<TValue>
  402. {
  403. internal NativeParallelMultiHashMap<TKey, TValue> hashmap;
  404. internal TKey key;
  405. internal byte isFirst;
  406. TValue value;
  407. NativeParallelMultiHashMapIterator<TKey> iterator;
  408. /// <summary>
  409. /// Does nothing.
  410. /// </summary>
  411. public void Dispose() { }
  412. /// <summary>
  413. /// Advances the enumerator to the next value of the key.
  414. /// </summary>
  415. /// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
  416. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  417. public bool MoveNext()
  418. {
  419. //Avoids going beyond the end of the collection.
  420. if (isFirst == 1)
  421. {
  422. isFirst = 0;
  423. return hashmap.TryGetFirstValue(key, out value, out iterator);
  424. }
  425. return hashmap.TryGetNextValue(out value, ref iterator);
  426. }
  427. /// <summary>
  428. /// Resets the enumerator to its initial state.
  429. /// </summary>
  430. public void Reset() => isFirst = 1;
  431. /// <summary>
  432. /// The current value.
  433. /// </summary>
  434. /// <value>The current value.</value>
  435. public TValue Current
  436. {
  437. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  438. get
  439. {
  440. return value;
  441. }
  442. }
  443. object IEnumerator.Current => Current;
  444. /// <summary>
  445. /// Returns this enumerator.
  446. /// </summary>
  447. /// <returns>This enumerator.</returns>
  448. public Enumerator GetEnumerator() { return this; }
  449. }
  450. /// <summary>
  451. /// Returns an enumerator over the key-value pairs of this hash map.
  452. /// </summary>
  453. /// <remarks>A key with *N* values is visited by the enumerator *N* times.</remarks>
  454. /// <returns>An enumerator over the key-value pairs of this hash map.</returns>
  455. public KeyValueEnumerator GetEnumerator()
  456. {
  457. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  458. AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
  459. var ash = m_Safety;
  460. AtomicSafetyHandle.UseSecondaryVersion(ref ash);
  461. #endif
  462. return new KeyValueEnumerator
  463. {
  464. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  465. m_Safety = ash,
  466. #endif
  467. m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_MultiHashMapData.m_Buffer),
  468. };
  469. }
  470. /// <summary>
  471. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  472. /// </summary>
  473. /// <returns>Throws NotImplementedException.</returns>
  474. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  475. IEnumerator<KeyValue<TKey, TValue>> IEnumerable<KeyValue<TKey, TValue>>.GetEnumerator()
  476. {
  477. throw new NotImplementedException();
  478. }
  479. /// <summary>
  480. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  481. /// </summary>
  482. /// <returns>Throws NotImplementedException.</returns>
  483. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  484. IEnumerator IEnumerable.GetEnumerator()
  485. {
  486. throw new NotImplementedException();
  487. }
  488. /// <summary>
  489. /// An enumerator over the key-value pairs of a multi hash map.
  490. /// </summary>
  491. /// <remarks>A key with *N* values is visited by the enumerator *N* times.
  492. ///
  493. /// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
  494. /// The first <see cref="MoveNext"/> call advances the enumerator to the first key-value pair.
  495. /// </remarks>
  496. [NativeContainer]
  497. [NativeContainerIsReadOnly]
  498. public struct KeyValueEnumerator : IEnumerator<KeyValue<TKey, TValue>>
  499. {
  500. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  501. internal AtomicSafetyHandle m_Safety;
  502. #endif
  503. internal UnsafeParallelHashMapDataEnumerator m_Enumerator;
  504. /// <summary>
  505. /// Does nothing.
  506. /// </summary>
  507. public void Dispose() { }
  508. /// <summary>
  509. /// Advances the enumerator to the next key-value pair.
  510. /// </summary>
  511. /// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
  512. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  513. public unsafe bool MoveNext()
  514. {
  515. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  516. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  517. #endif
  518. return m_Enumerator.MoveNext();
  519. }
  520. /// <summary>
  521. /// Resets the enumerator to its initial state.
  522. /// </summary>
  523. public void Reset()
  524. {
  525. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  526. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  527. #endif
  528. m_Enumerator.Reset();
  529. }
  530. /// <summary>
  531. /// The current key-value pair.
  532. /// </summary>
  533. /// <value>The current key-value pair.</value>
  534. public readonly KeyValue<TKey, TValue> Current
  535. {
  536. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  537. get
  538. {
  539. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  540. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  541. #endif
  542. return m_Enumerator.GetCurrent<TKey, TValue>();
  543. }
  544. }
  545. object IEnumerator.Current => Current;
  546. }
  547. /// <summary>
  548. /// Returns a readonly version of this NativeParallelHashMap instance.
  549. /// </summary>
  550. /// <remarks>ReadOnly containers point to the same underlying data as the NativeParallelHashMap it is made from.</remarks>
  551. /// <returns>ReadOnly instance for this.</returns>
  552. public ReadOnly AsReadOnly()
  553. {
  554. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  555. var ash = m_Safety;
  556. return new ReadOnly(m_MultiHashMapData, ash);
  557. #else
  558. return new ReadOnly(m_MultiHashMapData);
  559. #endif
  560. }
  561. /// <summary>
  562. /// A read-only alias for the value of a NativeParallelHashMap. Does not have its own allocated storage.
  563. /// </summary>
  564. [NativeContainer]
  565. [NativeContainerIsReadOnly]
  566. [DebuggerTypeProxy(typeof(NativeParallelHashMapDebuggerTypeProxy<,>))]
  567. [DebuggerDisplay("Count = {m_HashMapData.Count()}, Capacity = {m_HashMapData.Capacity}, IsCreated = {m_HashMapData.IsCreated}, IsEmpty = {IsEmpty}")]
  568. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
  569. public struct ReadOnly
  570. : IEnumerable<KeyValue<TKey, TValue>>
  571. {
  572. internal UnsafeParallelMultiHashMap<TKey, TValue> m_MultiHashMapData;
  573. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  574. AtomicSafetyHandle m_Safety;
  575. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
  576. [GenerateTestsForBurstCompatibility(CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
  577. internal ReadOnly(UnsafeParallelMultiHashMap<TKey, TValue> container, AtomicSafetyHandle safety)
  578. {
  579. m_MultiHashMapData = container;
  580. m_Safety = safety;
  581. CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
  582. }
  583. #else
  584. internal ReadOnly(UnsafeParallelMultiHashMap<TKey, TValue> container)
  585. {
  586. m_MultiHashMapData = container;
  587. }
  588. #endif
  589. /// <summary>
  590. /// Whether this hash map has been allocated (and not yet deallocated).
  591. /// </summary>
  592. /// <value>True if this hash map has been allocated (and not yet deallocated).</value>
  593. public readonly bool IsCreated
  594. {
  595. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  596. get => m_MultiHashMapData.IsCreated;
  597. }
  598. /// <summary>
  599. /// Whether this hash map is empty.
  600. /// </summary>
  601. /// <value>True if this hash map is empty or if the map has not been constructed.</value>
  602. public readonly bool IsEmpty
  603. {
  604. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  605. get
  606. {
  607. if (!IsCreated)
  608. {
  609. return true;
  610. }
  611. CheckRead();
  612. return m_MultiHashMapData.IsEmpty;
  613. }
  614. }
  615. /// <summary>
  616. /// The current number of key-value pairs in this hash map.
  617. /// </summary>
  618. /// <returns>The current number of key-value pairs in this hash map.</returns>
  619. public readonly int Count()
  620. {
  621. CheckRead();
  622. return m_MultiHashMapData.Count();
  623. }
  624. /// <summary>
  625. /// The number of key-value pairs that fit in the current allocation.
  626. /// </summary>
  627. /// <value>The number of key-value pairs that fit in the current allocation.</value>
  628. public readonly int Capacity
  629. {
  630. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  631. get
  632. {
  633. CheckRead();
  634. return m_MultiHashMapData.Capacity;
  635. }
  636. }
  637. /// <summary>
  638. /// Gets an iterator for a key.
  639. /// </summary>
  640. /// <param name="key">The key.</param>
  641. /// <param name="item">Outputs the associated value represented by the iterator.</param>
  642. /// <param name="it">Outputs an iterator.</param>
  643. /// <returns>True if the key was present.</returns>
  644. public readonly bool TryGetFirstValue(TKey key, out TValue item, out NativeParallelMultiHashMapIterator<TKey> it)
  645. {
  646. CheckRead();
  647. return m_MultiHashMapData.TryGetFirstValue(key, out item, out it);
  648. }
  649. /// <summary>
  650. /// Advances an iterator to the next value associated with its key.
  651. /// </summary>
  652. /// <param name="item">Outputs the next value.</param>
  653. /// <param name="it">A reference to the iterator to advance.</param>
  654. /// <returns>True if the key was present and had another value.</returns>
  655. public readonly bool TryGetNextValue(out TValue item, ref NativeParallelMultiHashMapIterator<TKey> it)
  656. {
  657. CheckRead();
  658. return m_MultiHashMapData.TryGetNextValue(out item, ref it);
  659. }
  660. /// <summary>
  661. /// Returns true if a given key is present in this hash map.
  662. /// </summary>
  663. /// <param name="key">The key to look up.</param>
  664. /// <returns>True if the key was present.</returns>
  665. public readonly bool ContainsKey(TKey key)
  666. {
  667. CheckRead();
  668. return m_MultiHashMapData.ContainsKey(key);
  669. }
  670. /// <summary>
  671. /// Returns an array with a copy of all this hash map's keys (in no particular order).
  672. /// </summary>
  673. /// <param name="allocator">The allocator to use.</param>
  674. /// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
  675. public readonly NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
  676. {
  677. CheckRead();
  678. return m_MultiHashMapData.GetKeyArray(allocator);
  679. }
  680. /// <summary>
  681. /// Returns an array with a copy of all this hash map's values (in no particular order).
  682. /// </summary>
  683. /// <param name="allocator">The allocator to use.</param>
  684. /// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
  685. public readonly NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
  686. {
  687. CheckRead();
  688. return m_MultiHashMapData.GetValueArray(allocator);
  689. }
  690. /// <summary>
  691. /// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
  692. /// </summary>
  693. /// <remarks>The key-value pairs are copied in no particular order. For all `i`, `Values[i]` will be the value associated with `Keys[i]`.</remarks>
  694. /// <param name="allocator">The allocator to use.</param>
  695. /// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
  696. public readonly NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
  697. {
  698. CheckRead();
  699. return m_MultiHashMapData.GetKeyValueArrays(allocator);
  700. }
  701. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  702. readonly void CheckRead()
  703. {
  704. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  705. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  706. #endif
  707. }
  708. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  709. readonly void ThrowKeyNotPresent(TKey key)
  710. {
  711. throw new ArgumentException($"Key: {key} is not present in the NativeParallelHashMap.");
  712. }
  713. /// <summary>
  714. /// Returns an enumerator over the key-value pairs of this hash map.
  715. /// </summary>
  716. /// <remarks>A key with *N* values is visited by the enumerator *N* times.</remarks>
  717. /// <returns>An enumerator over the key-value pairs of this hash map.</returns>
  718. public KeyValueEnumerator GetEnumerator()
  719. {
  720. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  721. AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
  722. var ash = m_Safety;
  723. AtomicSafetyHandle.UseSecondaryVersion(ref ash);
  724. #endif
  725. return new KeyValueEnumerator
  726. {
  727. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  728. m_Safety = ash,
  729. #endif
  730. m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_MultiHashMapData.m_Buffer),
  731. };
  732. }
  733. /// <summary>
  734. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  735. /// </summary>
  736. /// <returns>Throws NotImplementedException.</returns>
  737. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  738. IEnumerator<KeyValue<TKey, TValue>> IEnumerable<KeyValue<TKey, TValue>>.GetEnumerator()
  739. {
  740. throw new NotImplementedException();
  741. }
  742. /// <summary>
  743. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  744. /// </summary>
  745. /// <returns>Throws NotImplementedException.</returns>
  746. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  747. IEnumerator IEnumerable.GetEnumerator()
  748. {
  749. throw new NotImplementedException();
  750. }
  751. }
  752. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  753. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  754. readonly void CheckRead()
  755. {
  756. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  757. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  758. #endif
  759. }
  760. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  761. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  762. void CheckWrite()
  763. {
  764. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  765. AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
  766. #endif
  767. }
  768. }
  769. internal sealed class NativeParallelMultiHashMapDebuggerTypeProxy<TKey, TValue>
  770. where TKey : unmanaged, IEquatable<TKey>
  771. where TValue : unmanaged
  772. {
  773. NativeParallelMultiHashMap<TKey, TValue> m_Target;
  774. public NativeParallelMultiHashMapDebuggerTypeProxy(NativeParallelMultiHashMap<TKey, TValue> target)
  775. {
  776. m_Target = target;
  777. }
  778. public List<ListPair<TKey, List<TValue>>> Items
  779. {
  780. get
  781. {
  782. var result = new List<ListPair<TKey, List<TValue>>>();
  783. (NativeArray<TKey>, int) keys = default;
  784. using(NativeParallelHashMap<TKey,TValue> uniques = new NativeParallelHashMap<TKey,TValue>(m_Target.Count(),Allocator.Temp))
  785. {
  786. var enumerator = m_Target.GetEnumerator();
  787. while(enumerator.MoveNext())
  788. uniques.TryAdd(enumerator.Current.Key,default);
  789. keys.Item1 = uniques.GetKeyArray(Allocator.Temp);
  790. keys.Item2 = keys.Item1.Length;
  791. }
  792. using (keys.Item1)
  793. {
  794. for (var k = 0; k < keys.Item2; ++k)
  795. {
  796. var values = new List<TValue>();
  797. if (m_Target.TryGetFirstValue(keys.Item1[k], out var value, out var iterator))
  798. {
  799. do
  800. {
  801. values.Add(value);
  802. }
  803. while (m_Target.TryGetNextValue(out value, ref iterator));
  804. }
  805. result.Add(new ListPair<TKey, List<TValue>>(keys.Item1[k], values));
  806. }
  807. }
  808. return result;
  809. }
  810. }
  811. }
  812. /// <summary>
  813. /// Extension methods for NativeParallelMultiHashMap.
  814. /// </summary>
  815. [GenerateTestsForBurstCompatibility]
  816. public unsafe static class NativeParallelMultiHashMapExtensions
  817. {
  818. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int), typeof(AllocatorManager.AllocatorHandle) })]
  819. internal static void Initialize<TKey, TValue, U>(ref this NativeParallelMultiHashMap<TKey, TValue> container,
  820. int capacity,
  821. ref U allocator)
  822. where TKey : unmanaged, IEquatable<TKey>
  823. where TValue : unmanaged
  824. where U : unmanaged, AllocatorManager.IAllocator
  825. {
  826. container.m_MultiHashMapData = new UnsafeParallelMultiHashMap<TKey, TValue>(capacity, allocator.Handle);
  827. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  828. container.m_Safety = CollectionHelper.CreateSafetyHandle(allocator.Handle);
  829. CollectionHelper.SetStaticSafetyId<NativeParallelMultiHashMap<TKey, TValue>>(ref container.m_Safety, ref NativeParallelMultiHashMap<TKey, TValue>.s_staticSafetyId.Data);
  830. #endif
  831. }
  832. }
  833. }