WeakDictionary.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5. namespace Cysharp.Threading.Tasks.Internal
  6. {
  7. // Add, Remove, Enumerate with sweep. All operations are thread safe(in spinlock).
  8. internal class WeakDictionary<TKey, TValue>
  9. where TKey : class
  10. {
  11. Entry[] buckets;
  12. int size;
  13. SpinLock gate; // mutable struct(not readonly)
  14. readonly float loadFactor;
  15. readonly IEqualityComparer<TKey> keyEqualityComparer;
  16. public WeakDictionary(int capacity = 4, float loadFactor = 0.75f, IEqualityComparer<TKey> keyComparer = null)
  17. {
  18. var tableSize = CalculateCapacity(capacity, loadFactor);
  19. this.buckets = new Entry[tableSize];
  20. this.loadFactor = loadFactor;
  21. this.gate = new SpinLock(false);
  22. this.keyEqualityComparer = keyComparer ?? EqualityComparer<TKey>.Default;
  23. }
  24. public bool TryAdd(TKey key, TValue value)
  25. {
  26. bool lockTaken = false;
  27. try
  28. {
  29. gate.Enter(ref lockTaken);
  30. return TryAddInternal(key, value);
  31. }
  32. finally
  33. {
  34. if (lockTaken) gate.Exit(false);
  35. }
  36. }
  37. public bool TryGetValue(TKey key, out TValue value)
  38. {
  39. bool lockTaken = false;
  40. try
  41. {
  42. gate.Enter(ref lockTaken);
  43. if (TryGetEntry(key, out _, out var entry))
  44. {
  45. value = entry.Value;
  46. return true;
  47. }
  48. value = default(TValue);
  49. return false;
  50. }
  51. finally
  52. {
  53. if (lockTaken) gate.Exit(false);
  54. }
  55. }
  56. public bool TryRemove(TKey key)
  57. {
  58. bool lockTaken = false;
  59. try
  60. {
  61. gate.Enter(ref lockTaken);
  62. if (TryGetEntry(key, out var hashIndex, out var entry))
  63. {
  64. Remove(hashIndex, entry);
  65. return true;
  66. }
  67. return false;
  68. }
  69. finally
  70. {
  71. if (lockTaken) gate.Exit(false);
  72. }
  73. }
  74. bool TryAddInternal(TKey key, TValue value)
  75. {
  76. var nextCapacity = CalculateCapacity(size + 1, loadFactor);
  77. TRY_ADD_AGAIN:
  78. if (buckets.Length < nextCapacity)
  79. {
  80. // rehash
  81. var nextBucket = new Entry[nextCapacity];
  82. for (int i = 0; i < buckets.Length; i++)
  83. {
  84. var e = buckets[i];
  85. while (e != null)
  86. {
  87. AddToBuckets(nextBucket, key, e.Value, e.Hash);
  88. e = e.Next;
  89. }
  90. }
  91. buckets = nextBucket;
  92. goto TRY_ADD_AGAIN;
  93. }
  94. else
  95. {
  96. // add entry
  97. var successAdd = AddToBuckets(buckets, key, value, keyEqualityComparer.GetHashCode(key));
  98. if (successAdd) size++;
  99. return successAdd;
  100. }
  101. }
  102. bool AddToBuckets(Entry[] targetBuckets, TKey newKey, TValue value, int keyHash)
  103. {
  104. var h = keyHash;
  105. var hashIndex = h & (targetBuckets.Length - 1);
  106. TRY_ADD_AGAIN:
  107. if (targetBuckets[hashIndex] == null)
  108. {
  109. targetBuckets[hashIndex] = new Entry
  110. {
  111. Key = new WeakReference<TKey>(newKey, false),
  112. Value = value,
  113. Hash = h
  114. };
  115. return true;
  116. }
  117. else
  118. {
  119. // add to last.
  120. var entry = targetBuckets[hashIndex];
  121. while (entry != null)
  122. {
  123. if (entry.Key.TryGetTarget(out var target))
  124. {
  125. if (keyEqualityComparer.Equals(newKey, target))
  126. {
  127. return false; // duplicate
  128. }
  129. }
  130. else
  131. {
  132. Remove(hashIndex, entry);
  133. if (targetBuckets[hashIndex] == null) goto TRY_ADD_AGAIN; // add new entry
  134. }
  135. if (entry.Next != null)
  136. {
  137. entry = entry.Next;
  138. }
  139. else
  140. {
  141. // found last
  142. entry.Next = new Entry
  143. {
  144. Key = new WeakReference<TKey>(newKey, false),
  145. Value = value,
  146. Hash = h
  147. };
  148. entry.Next.Prev = entry;
  149. }
  150. }
  151. return false;
  152. }
  153. }
  154. bool TryGetEntry(TKey key, out int hashIndex, out Entry entry)
  155. {
  156. var table = buckets;
  157. var hash = keyEqualityComparer.GetHashCode(key);
  158. hashIndex = hash & table.Length - 1;
  159. entry = table[hashIndex];
  160. while (entry != null)
  161. {
  162. if (entry.Key.TryGetTarget(out var target))
  163. {
  164. if (keyEqualityComparer.Equals(key, target))
  165. {
  166. return true;
  167. }
  168. }
  169. else
  170. {
  171. // sweap
  172. Remove(hashIndex, entry);
  173. }
  174. entry = entry.Next;
  175. }
  176. return false;
  177. }
  178. void Remove(int hashIndex, Entry entry)
  179. {
  180. if (entry.Prev == null && entry.Next == null)
  181. {
  182. buckets[hashIndex] = null;
  183. }
  184. else
  185. {
  186. if (entry.Prev == null)
  187. {
  188. buckets[hashIndex] = entry.Next;
  189. }
  190. if (entry.Prev != null)
  191. {
  192. entry.Prev.Next = entry.Next;
  193. }
  194. if (entry.Next != null)
  195. {
  196. entry.Next.Prev = entry.Prev;
  197. }
  198. }
  199. size--;
  200. }
  201. public List<KeyValuePair<TKey, TValue>> ToList()
  202. {
  203. var list = new List<KeyValuePair<TKey, TValue>>(size);
  204. ToList(ref list, false);
  205. return list;
  206. }
  207. // avoid allocate everytime.
  208. public int ToList(ref List<KeyValuePair<TKey, TValue>> list, bool clear = true)
  209. {
  210. if (clear)
  211. {
  212. list.Clear();
  213. }
  214. var listIndex = 0;
  215. bool lockTaken = false;
  216. try
  217. {
  218. for (int i = 0; i < buckets.Length; i++)
  219. {
  220. var entry = buckets[i];
  221. while (entry != null)
  222. {
  223. if (entry.Key.TryGetTarget(out var target))
  224. {
  225. var item = new KeyValuePair<TKey, TValue>(target, entry.Value);
  226. if (listIndex < list.Count)
  227. {
  228. list[listIndex++] = item;
  229. }
  230. else
  231. {
  232. list.Add(item);
  233. listIndex++;
  234. }
  235. }
  236. else
  237. {
  238. // sweap
  239. Remove(i, entry);
  240. }
  241. entry = entry.Next;
  242. }
  243. }
  244. }
  245. finally
  246. {
  247. if (lockTaken) gate.Exit(false);
  248. }
  249. return listIndex;
  250. }
  251. static int CalculateCapacity(int collectionSize, float loadFactor)
  252. {
  253. var size = (int)(((float)collectionSize) / loadFactor);
  254. size--;
  255. size |= size >> 1;
  256. size |= size >> 2;
  257. size |= size >> 4;
  258. size |= size >> 8;
  259. size |= size >> 16;
  260. size += 1;
  261. if (size < 8)
  262. {
  263. size = 8;
  264. }
  265. return size;
  266. }
  267. class Entry
  268. {
  269. public WeakReference<TKey> Key;
  270. public TValue Value;
  271. public int Hash;
  272. public Entry Prev;
  273. public Entry Next;
  274. // debug only
  275. public override string ToString()
  276. {
  277. if (Key.TryGetTarget(out var target))
  278. {
  279. return target + "(" + Count() + ")";
  280. }
  281. else
  282. {
  283. return "(Dead)";
  284. }
  285. }
  286. int Count()
  287. {
  288. var count = 1;
  289. var n = this;
  290. while (n.Next != null)
  291. {
  292. count++;
  293. n = n.Next;
  294. }
  295. return count;
  296. }
  297. }
  298. }
  299. }