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

NativeHashMap.cs 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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.Jobs;
  10. namespace Unity.Collections
  11. {
  12. [NativeContainer]
  13. [GenerateTestsForBurstCompatibility]
  14. internal unsafe struct NativeHashMapDispose
  15. {
  16. [NativeDisableUnsafePtrRestriction]
  17. internal UnsafeHashMap<int, int>* m_HashMapData;
  18. internal AllocatorManager.AllocatorHandle m_Allocator;
  19. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  20. internal AtomicSafetyHandle m_Safety;
  21. #endif
  22. internal void Dispose()
  23. {
  24. var hashMapData = (HashMapHelper<int>*)m_HashMapData;
  25. HashMapHelper<int>.Free(hashMapData);
  26. }
  27. }
  28. [BurstCompile]
  29. internal unsafe struct NativeHashMapDisposeJob : IJob
  30. {
  31. internal NativeHashMapDispose Data;
  32. public void Execute()
  33. {
  34. Data.Dispose();
  35. }
  36. }
  37. /// <summary>
  38. /// A key-value pair.
  39. /// </summary>
  40. /// <remarks>Used for enumerators.</remarks>
  41. /// <typeparam name="TKey">The type of the keys.</typeparam>
  42. /// <typeparam name="TValue">The type of the values.</typeparam>
  43. [DebuggerDisplay("Key = {Key}, Value = {Value}")]
  44. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
  45. public unsafe struct KVPair<TKey, TValue>
  46. where TKey : unmanaged, IEquatable<TKey>
  47. where TValue : unmanaged
  48. {
  49. internal HashMapHelper<TKey>* m_Data;
  50. internal int m_Index;
  51. internal int m_Next;
  52. /// <summary>
  53. /// An invalid KeyValue.
  54. /// </summary>
  55. /// <value>In a hash map enumerator's initial state, its <see cref="UnsafeHashMap{TKey,TValue}.Enumerator.Current"/> value is Null.</value>
  56. public static KVPair<TKey, TValue> Null => new KVPair<TKey, TValue> { m_Index = -1 };
  57. /// <summary>
  58. /// The key.
  59. /// </summary>
  60. /// <value>The key. If this KeyValue is Null, returns the default of TKey.</value>
  61. public TKey Key
  62. {
  63. get
  64. {
  65. if (m_Index != -1)
  66. {
  67. return m_Data->Keys[m_Index];
  68. }
  69. return default;
  70. }
  71. }
  72. /// <summary>
  73. /// Value of key/value pair.
  74. /// </summary>
  75. public ref TValue Value
  76. {
  77. get
  78. {
  79. #if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
  80. if (m_Index == -1)
  81. throw new ArgumentException("must be valid");
  82. #endif
  83. return ref UnsafeUtility.AsRef<TValue>(m_Data->Ptr + sizeof(TValue) * m_Index);
  84. }
  85. }
  86. /// <summary>
  87. /// Gets the key and the value.
  88. /// </summary>
  89. /// <param name="key">Outputs the key. If this KeyValue is Null, outputs the default of TKey.</param>
  90. /// <param name="value">Outputs the value. If this KeyValue is Null, outputs the default of TValue.</param>
  91. /// <returns>True if the key-value pair is valid.</returns>
  92. public bool GetKeyValue(out TKey key, out TValue value)
  93. {
  94. if (m_Index != -1)
  95. {
  96. key = m_Data->Keys[m_Index];
  97. value = UnsafeUtility.ReadArrayElement<TValue>(m_Data->Ptr, m_Index);
  98. return true;
  99. }
  100. key = default;
  101. value = default;
  102. return false;
  103. }
  104. }
  105. /// <summary>
  106. /// An unordered, expandable associative array.
  107. /// </summary>
  108. /// <remarks>
  109. /// Not suitable for parallel write access. Use <see cref="NativeParallelHashMap{TKey, TValue}"/> instead.
  110. /// </remarks>
  111. /// <typeparam name="TKey">The type of the keys.</typeparam>
  112. /// <typeparam name="TValue">The type of the values.</typeparam>
  113. [StructLayout(LayoutKind.Sequential)]
  114. [NativeContainer]
  115. [DebuggerTypeProxy(typeof(NativeHashMapDebuggerTypeProxy<,>))]
  116. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
  117. public unsafe struct NativeHashMap<TKey, TValue>
  118. : INativeDisposable
  119. , IEnumerable<KVPair<TKey, TValue>> // Used by collection initializers.
  120. where TKey : unmanaged, IEquatable<TKey>
  121. where TValue : unmanaged
  122. {
  123. [NativeDisableUnsafePtrRestriction]
  124. internal HashMapHelper<TKey>* m_Data;
  125. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  126. internal AtomicSafetyHandle m_Safety;
  127. static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeHashMap<TKey, TValue>>();
  128. #endif
  129. /// <summary>
  130. /// Initializes and returns an instance of UnsafeHashMap.
  131. /// </summary>
  132. /// <param name="initialCapacity">The number of key-value pairs that should fit in the initial allocation.</param>
  133. /// <param name="allocator">The allocator to use.</param>
  134. public NativeHashMap(int initialCapacity, AllocatorManager.AllocatorHandle allocator)
  135. {
  136. m_Data = HashMapHelper<TKey>.Alloc(initialCapacity, sizeof(TValue), HashMapHelper<TKey>.kMinimumCapacity, allocator);
  137. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  138. m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
  139. if (UnsafeUtility.IsNativeContainerType<TKey>() || UnsafeUtility.IsNativeContainerType<TValue>())
  140. AtomicSafetyHandle.SetNestedContainer(m_Safety, true);
  141. CollectionHelper.SetStaticSafetyId<NativeHashMap<TKey, TValue>>(ref m_Safety, ref s_staticSafetyId.Data);
  142. AtomicSafetyHandle.SetBumpSecondaryVersionOnScheduleWrite(m_Safety, true);
  143. #endif
  144. }
  145. /// <summary>
  146. /// Releases all resources (memory).
  147. /// </summary>
  148. public void Dispose()
  149. {
  150. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  151. if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
  152. {
  153. AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
  154. }
  155. #endif
  156. if (!IsCreated)
  157. {
  158. return;
  159. }
  160. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  161. CollectionHelper.DisposeSafetyHandle(ref m_Safety);
  162. #endif
  163. HashMapHelper<TKey>.Free(m_Data);
  164. m_Data = null;
  165. }
  166. /// <summary>
  167. /// Creates and schedules a job that will dispose this hash map.
  168. /// </summary>
  169. /// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
  170. /// <returns>The handle of a new job that will dispose this hash map.</returns>
  171. public JobHandle Dispose(JobHandle inputDeps)
  172. {
  173. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  174. if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
  175. {
  176. AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
  177. }
  178. #endif
  179. if (!IsCreated)
  180. {
  181. return inputDeps;
  182. }
  183. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  184. var jobHandle = new NativeHashMapDisposeJob { Data = new NativeHashMapDispose { m_HashMapData = (UnsafeHashMap<int, int>*)m_Data, m_Safety = m_Safety } }.Schedule(inputDeps);
  185. AtomicSafetyHandle.Release(m_Safety);
  186. #else
  187. var jobHandle = new NativeHashMapDisposeJob { Data = new NativeHashMapDispose { m_HashMapData = (UnsafeHashMap<int, int>*)m_Data } }.Schedule(inputDeps);
  188. #endif
  189. m_Data = null;
  190. return jobHandle;
  191. }
  192. /// <summary>
  193. /// Whether this hash map has been allocated (and not yet deallocated).
  194. /// </summary>
  195. /// <value>True if this hash map has been allocated (and not yet deallocated).</value>
  196. public readonly bool IsCreated
  197. {
  198. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  199. get => m_Data != null && m_Data->IsCreated;
  200. }
  201. /// <summary>
  202. /// Whether this hash map is empty.
  203. /// </summary>
  204. /// <value>True if this hash map is empty or if the map has not been constructed.</value>
  205. public readonly bool IsEmpty
  206. {
  207. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  208. get
  209. {
  210. if (!IsCreated)
  211. {
  212. return true;
  213. }
  214. CheckRead();
  215. return m_Data->IsEmpty;
  216. }
  217. }
  218. /// <summary>
  219. /// The current number of key-value pairs in this hash map.
  220. /// </summary>
  221. /// <returns>The current number of key-value pairs in this hash map.</returns>
  222. public readonly int Count
  223. {
  224. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  225. get
  226. {
  227. CheckRead();
  228. return m_Data->Count;
  229. }
  230. }
  231. /// <summary>
  232. /// The number of key-value pairs that fit in the current allocation.
  233. /// </summary>
  234. /// <value>The number of key-value pairs that fit in the current allocation.</value>
  235. /// <param name="value">A new capacity. Must be larger than the current capacity.</param>
  236. public int Capacity
  237. {
  238. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  239. readonly get
  240. {
  241. CheckRead();
  242. return m_Data->Capacity;
  243. }
  244. set
  245. {
  246. CheckWrite();
  247. m_Data->Resize(value);
  248. }
  249. }
  250. /// <summary>
  251. /// Removes all key-value pairs.
  252. /// </summary>
  253. /// <remarks>Does not change the capacity.</remarks>
  254. public void Clear()
  255. {
  256. CheckWrite();
  257. m_Data->Clear();
  258. }
  259. /// <summary>
  260. /// Adds a new key-value pair.
  261. /// </summary>
  262. /// <remarks>If the key is already present, this method returns false without modifying the hash map.</remarks>
  263. /// <param name="key">The key to add.</param>
  264. /// <param name="item">The value to add.</param>
  265. /// <returns>True if the key-value pair was added.</returns>
  266. public bool TryAdd(TKey key, TValue item)
  267. {
  268. CheckWrite();
  269. var idx = m_Data->TryAdd(key);
  270. if (-1 != idx)
  271. {
  272. UnsafeUtility.WriteArrayElement(m_Data->Ptr, idx, item);
  273. return true;
  274. }
  275. return false;
  276. }
  277. /// <summary>
  278. /// Adds a new key-value pair.
  279. /// </summary>
  280. /// <remarks>If the key is already present, this method throws without modifying the hash map.</remarks>
  281. /// <param name="key">The key to add.</param>
  282. /// <param name="item">The value to add.</param>
  283. /// <exception cref="ArgumentException">Thrown if the key was already present.</exception>
  284. public void Add(TKey key, TValue item)
  285. {
  286. var result = TryAdd(key, item);
  287. if (!result)
  288. {
  289. ThrowKeyAlreadyAdded(key);
  290. }
  291. }
  292. /// <summary>
  293. /// Removes a key-value pair.
  294. /// </summary>
  295. /// <param name="key">The key to remove.</param>
  296. /// <returns>True if a key-value pair was removed.</returns>
  297. public bool Remove(TKey key)
  298. {
  299. CheckWrite();
  300. return -1 != m_Data->TryRemove(key);
  301. }
  302. /// <summary>
  303. /// Returns the value associated with a key.
  304. /// </summary>
  305. /// <param name="key">The key to look up.</param>
  306. /// <param name="item">Outputs the value associated with the key. Outputs default if the key was not present.</param>
  307. /// <returns>True if the key was present.</returns>
  308. public bool TryGetValue(TKey key, out TValue item)
  309. {
  310. CheckRead();
  311. return m_Data->TryGetValue(key, out item);
  312. }
  313. /// <summary>
  314. /// Returns true if a given key is present in this hash map.
  315. /// </summary>
  316. /// <param name="key">The key to look up.</param>
  317. /// <returns>True if the key was present.</returns>
  318. public bool ContainsKey(TKey key)
  319. {
  320. CheckRead();
  321. return -1 != m_Data->Find(key);
  322. }
  323. /// <summary>
  324. /// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
  325. /// </summary>
  326. public void TrimExcess()
  327. {
  328. CheckWrite();
  329. m_Data->TrimExcess();
  330. }
  331. /// <summary>
  332. /// Gets and sets values by key.
  333. /// </summary>
  334. /// <remarks>Getting a key that is not present will throw. Setting a key that is not already present will add the key.</remarks>
  335. /// <param name="key">The key to look up.</param>
  336. /// <value>The value associated with the key.</value>
  337. /// <exception cref="ArgumentException">For getting, thrown if the key was not present.</exception>
  338. public TValue this[TKey key]
  339. {
  340. get
  341. {
  342. CheckRead();
  343. TValue result;
  344. if (!m_Data->TryGetValue(key, out result))
  345. {
  346. ThrowKeyNotPresent(key);
  347. }
  348. return result;
  349. }
  350. set
  351. {
  352. CheckWrite();
  353. var idx = m_Data->Find(key);
  354. if (-1 == idx)
  355. {
  356. TryAdd(key, value);
  357. return;
  358. }
  359. UnsafeUtility.WriteArrayElement(m_Data->Ptr, idx, value);
  360. }
  361. }
  362. /// <summary>
  363. /// Returns an array with a copy of all this hash map's keys (in no particular order).
  364. /// </summary>
  365. /// <param name="allocator">The allocator to use.</param>
  366. /// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
  367. public NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
  368. {
  369. CheckRead();
  370. return m_Data->GetKeyArray(allocator);
  371. }
  372. /// <summary>
  373. /// Returns an array with a copy of all this hash map's values (in no particular order).
  374. /// </summary>
  375. /// <param name="allocator">The allocator to use.</param>
  376. /// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
  377. public NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
  378. {
  379. CheckRead();
  380. return m_Data->GetValueArray<TValue>(allocator);
  381. }
  382. /// <summary>
  383. /// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
  384. /// </summary>
  385. /// <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>
  386. /// <param name="allocator">The allocator to use.</param>
  387. /// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
  388. public NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
  389. {
  390. CheckRead();
  391. return m_Data->GetKeyValueArrays<TValue>(allocator);
  392. }
  393. /// <summary>
  394. /// Returns an enumerator over the key-value pairs of this hash map.
  395. /// </summary>
  396. /// <returns>An enumerator over the key-value pairs of this hash map.</returns>
  397. public Enumerator GetEnumerator()
  398. {
  399. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  400. AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
  401. var ash = m_Safety;
  402. AtomicSafetyHandle.UseSecondaryVersion(ref ash);
  403. #endif
  404. return new Enumerator
  405. {
  406. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  407. m_Safety = ash,
  408. #endif
  409. m_Enumerator = new HashMapHelper<TKey>.Enumerator(m_Data),
  410. };
  411. }
  412. /// <summary>
  413. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  414. /// </summary>
  415. /// <returns>Throws NotImplementedException.</returns>
  416. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  417. IEnumerator<KVPair<TKey, TValue>> IEnumerable<KVPair<TKey, TValue>>.GetEnumerator()
  418. {
  419. throw new NotImplementedException();
  420. }
  421. /// <summary>
  422. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  423. /// </summary>
  424. /// <returns>Throws NotImplementedException.</returns>
  425. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  426. IEnumerator IEnumerable.GetEnumerator()
  427. {
  428. throw new NotImplementedException();
  429. }
  430. /// <summary>
  431. /// An enumerator over the key-value pairs of a container.
  432. /// </summary>
  433. /// <remarks>
  434. /// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
  435. /// From this state, the first <see cref="MoveNext"/> call advances the enumerator to the first key-value pair.
  436. /// </remarks>
  437. [NativeContainer]
  438. [NativeContainerIsReadOnly]
  439. public struct Enumerator : IEnumerator<KVPair<TKey, TValue>>
  440. {
  441. [NativeDisableUnsafePtrRestriction]
  442. internal HashMapHelper<TKey>.Enumerator m_Enumerator;
  443. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  444. internal AtomicSafetyHandle m_Safety;
  445. #endif
  446. /// <summary>
  447. /// Does nothing.
  448. /// </summary>
  449. public void Dispose() { }
  450. /// <summary>
  451. /// Advances the enumerator to the next key-value pair.
  452. /// </summary>
  453. /// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
  454. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  455. public bool MoveNext()
  456. {
  457. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  458. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  459. #endif
  460. return m_Enumerator.MoveNext();
  461. }
  462. /// <summary>
  463. /// Resets the enumerator to its initial state.
  464. /// </summary>
  465. public void Reset()
  466. {
  467. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  468. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  469. #endif
  470. m_Enumerator.Reset();
  471. }
  472. /// <summary>
  473. /// The current key-value pair.
  474. /// </summary>
  475. /// <value>The current key-value pair.</value>
  476. public KVPair<TKey, TValue> Current
  477. {
  478. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  479. get => m_Enumerator.GetCurrent<TValue>();
  480. }
  481. /// <summary>
  482. /// Gets the element at the current position of the enumerator in the container.
  483. /// </summary>
  484. object IEnumerator.Current => Current;
  485. }
  486. /// <summary>
  487. /// Returns a readonly version of this NativeHashMap instance.
  488. /// </summary>
  489. /// <remarks>ReadOnly containers point to the same underlying data as the NativeHashMap it is made from.</remarks>
  490. /// <returns>ReadOnly instance for this.</returns>
  491. public ReadOnly AsReadOnly()
  492. {
  493. return new ReadOnly(ref this);
  494. }
  495. /// <summary>
  496. /// A read-only alias for the value of a NativeHashMap. Does not have its own allocated storage.
  497. /// </summary>
  498. [NativeContainer]
  499. [NativeContainerIsReadOnly]
  500. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
  501. public struct ReadOnly
  502. : IEnumerable<KVPair<TKey, TValue>>
  503. {
  504. [NativeDisableUnsafePtrRestriction]
  505. internal HashMapHelper<TKey>* m_Data;
  506. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  507. AtomicSafetyHandle m_Safety;
  508. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
  509. #endif
  510. internal ReadOnly(ref NativeHashMap<TKey, TValue> data)
  511. {
  512. m_Data = data.m_Data;
  513. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  514. m_Safety = data.m_Safety;
  515. CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
  516. #endif
  517. }
  518. /// <summary>
  519. /// Whether this hash map has been allocated (and not yet deallocated).
  520. /// </summary>
  521. /// <value>True if this hash map has been allocated (and not yet deallocated).</value>
  522. public readonly bool IsCreated
  523. {
  524. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  525. get
  526. {
  527. CheckRead();
  528. return m_Data->IsCreated;
  529. }
  530. }
  531. /// <summary>
  532. /// Whether this hash map is empty.
  533. /// </summary>
  534. /// <value>True if this hash map is empty or if the map has not been constructed.</value>
  535. public readonly bool IsEmpty
  536. {
  537. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  538. get
  539. {
  540. CheckRead();
  541. if (!m_Data->IsCreated)
  542. {
  543. return true;
  544. }
  545. return m_Data->IsEmpty;
  546. }
  547. }
  548. /// <summary>
  549. /// The current number of key-value pairs in this hash map.
  550. /// </summary>
  551. /// <returns>The current number of key-value pairs in this hash map.</returns>
  552. public readonly int Count
  553. {
  554. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  555. get
  556. {
  557. CheckRead();
  558. return m_Data->Count;
  559. }
  560. }
  561. /// <summary>
  562. /// The number of key-value pairs that fit in the current allocation.
  563. /// </summary>
  564. /// <value>The number of key-value pairs that fit in the current allocation.</value>
  565. public readonly int Capacity
  566. {
  567. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  568. get
  569. {
  570. CheckRead();
  571. return m_Data->Capacity;
  572. }
  573. }
  574. /// <summary>
  575. /// Returns the value associated with a key.
  576. /// </summary>
  577. /// <param name="key">The key to look up.</param>
  578. /// <param name="item">Outputs the value associated with the key. Outputs default if the key was not present.</param>
  579. /// <returns>True if the key was present.</returns>
  580. public readonly bool TryGetValue(TKey key, out TValue item)
  581. {
  582. CheckRead();
  583. return m_Data->TryGetValue(key, out item);
  584. }
  585. /// <summary>
  586. /// Returns true if a given key is present in this hash map.
  587. /// </summary>
  588. /// <param name="key">The key to look up.</param>
  589. /// <returns>True if the key was present.</returns>
  590. public readonly bool ContainsKey(TKey key)
  591. {
  592. CheckRead();
  593. return -1 != m_Data->Find(key);
  594. }
  595. /// <summary>
  596. /// Gets values by key.
  597. /// </summary>
  598. /// <remarks>Getting a key that is not present will throw.</remarks>
  599. /// <param name="key">The key to look up.</param>
  600. /// <value>The value associated with the key.</value>
  601. /// <exception cref="ArgumentException">For getting, thrown if the key was not present.</exception>
  602. public readonly TValue this[TKey key]
  603. {
  604. get
  605. {
  606. CheckRead();
  607. TValue result;
  608. if (!m_Data->TryGetValue(key, out result))
  609. {
  610. ThrowKeyNotPresent(key);
  611. }
  612. return result;
  613. }
  614. }
  615. /// <summary>
  616. /// Returns an array with a copy of all this hash map's keys (in no particular order).
  617. /// </summary>
  618. /// <param name="allocator">The allocator to use.</param>
  619. /// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
  620. public readonly NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
  621. {
  622. CheckRead();
  623. return m_Data->GetKeyArray(allocator);
  624. }
  625. /// <summary>
  626. /// Returns an array with a copy of all this hash map's values (in no particular order).
  627. /// </summary>
  628. /// <param name="allocator">The allocator to use.</param>
  629. /// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
  630. public readonly NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
  631. {
  632. CheckRead();
  633. return m_Data->GetValueArray<TValue>(allocator);
  634. }
  635. /// <summary>
  636. /// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
  637. /// </summary>
  638. /// <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>
  639. /// <param name="allocator">The allocator to use.</param>
  640. /// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
  641. public readonly NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
  642. {
  643. CheckRead();
  644. return m_Data->GetKeyValueArrays<TValue>(allocator);
  645. }
  646. /// <summary>
  647. /// Returns an enumerator over the key-value pairs of this hash map.
  648. /// </summary>
  649. /// <returns>An enumerator over the key-value pairs of this hash map.</returns>
  650. public readonly Enumerator GetEnumerator()
  651. {
  652. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  653. AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
  654. var ash = m_Safety;
  655. AtomicSafetyHandle.UseSecondaryVersion(ref ash);
  656. #endif
  657. return new Enumerator
  658. {
  659. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  660. m_Safety = ash,
  661. #endif
  662. m_Enumerator = new HashMapHelper<TKey>.Enumerator(m_Data),
  663. };
  664. }
  665. /// <summary>
  666. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  667. /// </summary>
  668. /// <returns>Throws NotImplementedException.</returns>
  669. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  670. IEnumerator<KVPair<TKey, TValue>> IEnumerable<KVPair<TKey, TValue>>.GetEnumerator()
  671. {
  672. throw new NotImplementedException();
  673. }
  674. /// <summary>
  675. /// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
  676. /// </summary>
  677. /// <returns>Throws NotImplementedException.</returns>
  678. /// <exception cref="NotImplementedException">Method is not implemented.</exception>
  679. IEnumerator IEnumerable.GetEnumerator()
  680. {
  681. throw new NotImplementedException();
  682. }
  683. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  684. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  685. readonly void CheckRead()
  686. {
  687. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  688. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  689. #endif
  690. }
  691. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  692. readonly void ThrowKeyNotPresent(TKey key)
  693. {
  694. throw new ArgumentException($"Key: {key} is not present.");
  695. }
  696. }
  697. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  698. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  699. readonly void CheckRead()
  700. {
  701. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  702. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  703. #endif
  704. }
  705. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  706. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  707. void CheckWrite()
  708. {
  709. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  710. AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
  711. #endif
  712. }
  713. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  714. void ThrowKeyNotPresent(TKey key)
  715. {
  716. throw new ArgumentException($"Key: {key} is not present.");
  717. }
  718. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  719. void ThrowKeyAlreadyAdded(TKey key)
  720. {
  721. throw new ArgumentException($"An item with the same key has already been added: {key}");
  722. }
  723. }
  724. internal unsafe sealed class NativeHashMapDebuggerTypeProxy<TKey, TValue>
  725. where TKey : unmanaged, IEquatable<TKey>
  726. where TValue : unmanaged
  727. {
  728. HashMapHelper<TKey>* Data;
  729. public NativeHashMapDebuggerTypeProxy(NativeHashMap<TKey, TValue> target)
  730. {
  731. Data = target.m_Data;
  732. }
  733. public NativeHashMapDebuggerTypeProxy(NativeHashMap<TKey, TValue>.ReadOnly target)
  734. {
  735. Data = target.m_Data;
  736. }
  737. public List<Pair<TKey, TValue>> Items
  738. {
  739. get
  740. {
  741. if (Data == null)
  742. {
  743. return default;
  744. }
  745. var result = new List<Pair<TKey, TValue>>();
  746. using (var kva = Data->GetKeyValueArrays<TValue>(Allocator.Temp))
  747. {
  748. for (var i = 0; i < kva.Length; ++i)
  749. {
  750. result.Add(new Pair<TKey, TValue>(kva.Keys[i], kva.Values[i]));
  751. }
  752. }
  753. return result;
  754. }
  755. }
  756. }
  757. }