Lookup.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. // This is internal because System.Linq exposes a public Lookup that we cannot directly use here
  10. namespace System.Linq.Internal
  11. {
  12. internal class Lookup<TKey, TElement> : ILookup<TKey, TElement>, IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>
  13. {
  14. private readonly IEqualityComparer<TKey> _comparer;
  15. private Grouping<TKey, TElement>[] _groupings;
  16. private Grouping<TKey, TElement> _lastGrouping;
  17. private Lookup(IEqualityComparer<TKey> comparer)
  18. {
  19. _comparer = comparer ?? EqualityComparer<TKey>.Default;
  20. _groupings = new Grouping<TKey, TElement>[7];
  21. }
  22. public int Count { get; private set; }
  23. public IEnumerable<TElement> this[TKey key]
  24. {
  25. get
  26. {
  27. var grouping = GetGrouping(key, create: false);
  28. if (grouping != null)
  29. {
  30. return grouping;
  31. }
  32. #if NO_ARRAY_EMPTY
  33. return EmptyArray<TElement>.Value;
  34. #else
  35. return Array.Empty<TElement>();
  36. #endif
  37. }
  38. }
  39. public bool Contains(TKey key)
  40. {
  41. return GetGrouping(key, create: false) != null;
  42. }
  43. IEnumerator IEnumerable.GetEnumerator()
  44. {
  45. return GetEnumerator();
  46. }
  47. public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
  48. {
  49. var g = _lastGrouping;
  50. if (g != null)
  51. {
  52. do
  53. {
  54. g = g._next;
  55. yield return g;
  56. } while (g != _lastGrouping);
  57. }
  58. }
  59. public IEnumerable<TResult> ApplyResultSelector<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  60. {
  61. var g = _lastGrouping;
  62. if (g != null)
  63. {
  64. do
  65. {
  66. g = g._next;
  67. g.Trim();
  68. var result = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  69. yield return result;
  70. } while (g != _lastGrouping);
  71. }
  72. }
  73. internal static async Task<Lookup<TKey, TElement>> CreateAsync<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  74. {
  75. Debug.Assert(source != null);
  76. Debug.Assert(keySelector != null);
  77. Debug.Assert(elementSelector != null);
  78. var lookup = new Lookup<TKey, TElement>(comparer);
  79. var enu = source.GetAsyncEnumerator(cancellationToken);
  80. try
  81. {
  82. while (await enu.MoveNextAsync().ConfigureAwait(false))
  83. {
  84. var key = keySelector(enu.Current);
  85. var group = lookup.GetGrouping(key, create: true);
  86. var element = elementSelector(enu.Current);
  87. group.Add(element);
  88. }
  89. }
  90. finally
  91. {
  92. await enu.DisposeAsync().ConfigureAwait(false);
  93. }
  94. return lookup;
  95. }
  96. internal static async Task<Lookup<TKey, TElement>> CreateAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  97. {
  98. Debug.Assert(source != null);
  99. Debug.Assert(keySelector != null);
  100. var lookup = new Lookup<TKey, TElement>(comparer);
  101. var enu = source.GetAsyncEnumerator(cancellationToken);
  102. try
  103. {
  104. while (await enu.MoveNextAsync().ConfigureAwait(false))
  105. {
  106. var key = keySelector(enu.Current);
  107. lookup.GetGrouping(key, create: true).Add(enu.Current);
  108. }
  109. }
  110. finally
  111. {
  112. await enu.DisposeAsync().ConfigureAwait(false);
  113. }
  114. return lookup;
  115. }
  116. internal static async Task<Lookup<TKey, TElement>> CreateForJoinAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  117. {
  118. var lookup = new Lookup<TKey, TElement>(comparer);
  119. var enu = source.GetAsyncEnumerator(cancellationToken);
  120. try
  121. {
  122. while (await enu.MoveNextAsync().ConfigureAwait(false))
  123. {
  124. var key = keySelector(enu.Current);
  125. if (key != null)
  126. {
  127. lookup.GetGrouping(key, create: true).Add(enu.Current);
  128. }
  129. }
  130. }
  131. finally
  132. {
  133. await enu.DisposeAsync().ConfigureAwait(false);
  134. }
  135. return lookup;
  136. }
  137. internal Grouping<TKey, TElement> GetGrouping(TKey key, bool create)
  138. {
  139. var hashCode = InternalGetHashCode(key);
  140. for (var g = _groupings[hashCode % _groupings.Length]; g != null; g = g._hashNext)
  141. {
  142. if (g._hashCode == hashCode && _comparer.Equals(g._key, key))
  143. {
  144. return g;
  145. }
  146. }
  147. if (create)
  148. {
  149. if (Count == _groupings.Length)
  150. {
  151. Resize();
  152. }
  153. var index = hashCode % _groupings.Length;
  154. var g = new Grouping<TKey, TElement>
  155. {
  156. _key = key,
  157. _hashCode = hashCode,
  158. _elements = new TElement[1],
  159. _hashNext = _groupings[index]
  160. };
  161. _groupings[index] = g;
  162. if (_lastGrouping == null)
  163. {
  164. g._next = g;
  165. }
  166. else
  167. {
  168. g._next = _lastGrouping._next;
  169. _lastGrouping._next = g;
  170. }
  171. _lastGrouping = g;
  172. Count++;
  173. return g;
  174. }
  175. return null;
  176. }
  177. internal int InternalGetHashCode(TKey key)
  178. {
  179. // Handle comparer implementations that throw when passed null
  180. return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF;
  181. }
  182. internal TResult[] ToArray<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  183. {
  184. var array = new TResult[Count];
  185. var index = 0;
  186. var g = _lastGrouping;
  187. if (g != null)
  188. {
  189. do
  190. {
  191. g = g._next;
  192. g.Trim();
  193. array[index] = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  194. ++index;
  195. } while (g != _lastGrouping);
  196. }
  197. return array;
  198. }
  199. internal List<TResult> ToList<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  200. {
  201. var list = new List<TResult>(Count);
  202. var g = _lastGrouping;
  203. if (g != null)
  204. {
  205. do
  206. {
  207. g = g._next;
  208. g.Trim();
  209. var result = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  210. list.Add(result);
  211. } while (g != _lastGrouping);
  212. }
  213. return list;
  214. }
  215. private void Resize()
  216. {
  217. var newSize = checked((Count * 2) + 1);
  218. var newGroupings = new Grouping<TKey, TElement>[newSize];
  219. var g = _lastGrouping;
  220. do
  221. {
  222. g = g._next;
  223. var index = g._hashCode % newSize;
  224. g._hashNext = newGroupings[index];
  225. newGroupings[index] = g;
  226. } while (g != _lastGrouping);
  227. _groupings = newGroupings;
  228. }
  229. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  230. {
  231. return Task.FromResult(Count);
  232. }
  233. IAsyncEnumerator<IAsyncGrouping<TKey, TElement>> IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>.GetAsyncEnumerator(CancellationToken cancellationToken)
  234. {
  235. return Enumerable.Cast<IAsyncGrouping<TKey, TElement>>(this).ToAsyncEnumerable().GetAsyncEnumerator(cancellationToken);
  236. }
  237. Task<List<IAsyncGrouping<TKey, TElement>>> IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>.ToListAsync(CancellationToken cancellationToken)
  238. {
  239. var list = new List<IAsyncGrouping<TKey, TElement>>(Count);
  240. var g = _lastGrouping;
  241. if (g != null)
  242. {
  243. do
  244. {
  245. g = g._next;
  246. list.Add(g);
  247. }
  248. while (g != _lastGrouping);
  249. }
  250. return Task.FromResult(list);
  251. }
  252. Task<IAsyncGrouping<TKey, TElement>[]> IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>.ToArrayAsync(CancellationToken cancellationToken)
  253. {
  254. var array = new IAsyncGrouping<TKey, TElement>[Count];
  255. var index = 0;
  256. var g = _lastGrouping;
  257. if (g != null)
  258. {
  259. do
  260. {
  261. g = g._next;
  262. array[index] = g;
  263. ++index;
  264. }
  265. while (g != _lastGrouping);
  266. }
  267. return Task.FromResult(array);
  268. }
  269. }
  270. internal class LookupWithTask<TKey, TElement> : ILookup<TKey, TElement>, IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>
  271. {
  272. private readonly IEqualityComparer<TKey> _comparer;
  273. private Grouping<TKey, TElement>[] _groupings;
  274. private Grouping<TKey, TElement> _lastGrouping;
  275. private LookupWithTask(IEqualityComparer<TKey> comparer)
  276. {
  277. _comparer = comparer ?? EqualityComparer<TKey>.Default;
  278. _groupings = new Grouping<TKey, TElement>[7];
  279. }
  280. public int Count { get; private set; }
  281. public IEnumerable<TElement> this[TKey key]
  282. {
  283. get
  284. {
  285. var grouping = GetGrouping(key, create: false);
  286. if (grouping != null)
  287. {
  288. return grouping;
  289. }
  290. #if NO_ARRAY_EMPTY
  291. return EmptyArray<TElement>.Value;
  292. #else
  293. return Array.Empty<TElement>();
  294. #endif
  295. }
  296. }
  297. public bool Contains(TKey key)
  298. {
  299. return GetGrouping(key, create: false) != null;
  300. }
  301. IEnumerator IEnumerable.GetEnumerator()
  302. {
  303. return GetEnumerator();
  304. }
  305. public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
  306. {
  307. var g = _lastGrouping;
  308. if (g != null)
  309. {
  310. do
  311. {
  312. g = g._next;
  313. yield return g;
  314. } while (g != _lastGrouping);
  315. }
  316. }
  317. internal static async Task<LookupWithTask<TKey, TElement>> CreateAsync<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, Task<TKey>> keySelector, Func<TSource, Task<TElement>> elementSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  318. {
  319. Debug.Assert(source != null);
  320. Debug.Assert(keySelector != null);
  321. Debug.Assert(elementSelector != null);
  322. var lookup = new LookupWithTask<TKey, TElement>(comparer);
  323. var enu = source.GetAsyncEnumerator(cancellationToken);
  324. try
  325. {
  326. while (await enu.MoveNextAsync().ConfigureAwait(false))
  327. {
  328. var key = await keySelector(enu.Current).ConfigureAwait(false);
  329. var group = lookup.GetGrouping(key, create: true);
  330. var element = await elementSelector(enu.Current).ConfigureAwait(false);
  331. group.Add(element);
  332. }
  333. }
  334. finally
  335. {
  336. await enu.DisposeAsync().ConfigureAwait(false);
  337. }
  338. return lookup;
  339. }
  340. internal static async Task<LookupWithTask<TKey, TElement>> CreateAsync(IAsyncEnumerable<TElement> source, Func<TElement, Task<TKey>> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  341. {
  342. Debug.Assert(source != null);
  343. Debug.Assert(keySelector != null);
  344. var lookup = new LookupWithTask<TKey, TElement>(comparer);
  345. var enu = source.GetAsyncEnumerator(cancellationToken);
  346. try
  347. {
  348. while (await enu.MoveNextAsync().ConfigureAwait(false))
  349. {
  350. var key = await keySelector(enu.Current).ConfigureAwait(false);
  351. lookup.GetGrouping(key, create: true).Add(enu.Current);
  352. }
  353. }
  354. finally
  355. {
  356. await enu.DisposeAsync().ConfigureAwait(false);
  357. }
  358. return lookup;
  359. }
  360. internal static async Task<LookupWithTask<TKey, TElement>> CreateForJoinAsync(IAsyncEnumerable<TElement> source, Func<TElement, Task<TKey>> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  361. {
  362. var lookup = new LookupWithTask<TKey, TElement>(comparer);
  363. var enu = source.GetAsyncEnumerator(cancellationToken);
  364. try
  365. {
  366. while (await enu.MoveNextAsync().ConfigureAwait(false))
  367. {
  368. var key = await keySelector(enu.Current).ConfigureAwait(false);
  369. if (key != null)
  370. {
  371. lookup.GetGrouping(key, create: true).Add(enu.Current);
  372. }
  373. }
  374. }
  375. finally
  376. {
  377. await enu.DisposeAsync().ConfigureAwait(false);
  378. }
  379. return lookup;
  380. }
  381. internal Grouping<TKey, TElement> GetGrouping(TKey key, bool create)
  382. {
  383. var hashCode = InternalGetHashCode(key);
  384. for (var g = _groupings[hashCode % _groupings.Length]; g != null; g = g._hashNext)
  385. {
  386. if (g._hashCode == hashCode && _comparer.Equals(g._key, key))
  387. {
  388. return g;
  389. }
  390. }
  391. if (create)
  392. {
  393. if (Count == _groupings.Length)
  394. {
  395. Resize();
  396. }
  397. var index = hashCode % _groupings.Length;
  398. var g = new Grouping<TKey, TElement>
  399. {
  400. _key = key,
  401. _hashCode = hashCode,
  402. _elements = new TElement[1],
  403. _hashNext = _groupings[index]
  404. };
  405. _groupings[index] = g;
  406. if (_lastGrouping == null)
  407. {
  408. g._next = g;
  409. }
  410. else
  411. {
  412. g._next = _lastGrouping._next;
  413. _lastGrouping._next = g;
  414. }
  415. _lastGrouping = g;
  416. Count++;
  417. return g;
  418. }
  419. return null;
  420. }
  421. internal int InternalGetHashCode(TKey key)
  422. {
  423. // Handle comparer implementations that throw when passed null
  424. return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF;
  425. }
  426. internal async Task<TResult[]> ToArray<TResult>(Func<TKey, IAsyncEnumerable<TElement>, Task<TResult>> resultSelector)
  427. {
  428. var array = new TResult[Count];
  429. var index = 0;
  430. var g = _lastGrouping;
  431. if (g != null)
  432. {
  433. do
  434. {
  435. g = g._next;
  436. g.Trim();
  437. array[index] = await resultSelector(g._key, g._elements.ToAsyncEnumerable()).ConfigureAwait(false);
  438. ++index;
  439. } while (g != _lastGrouping);
  440. }
  441. return array;
  442. }
  443. internal async Task<List<TResult>> ToList<TResult>(Func<TKey, IAsyncEnumerable<TElement>, Task<TResult>> resultSelector)
  444. {
  445. var list = new List<TResult>(Count);
  446. var g = _lastGrouping;
  447. if (g != null)
  448. {
  449. do
  450. {
  451. g = g._next;
  452. g.Trim();
  453. var result = await resultSelector(g._key, g._elements.ToAsyncEnumerable()).ConfigureAwait(false);
  454. list.Add(result);
  455. } while (g != _lastGrouping);
  456. }
  457. return list;
  458. }
  459. private void Resize()
  460. {
  461. var newSize = checked((Count * 2) + 1);
  462. var newGroupings = new Grouping<TKey, TElement>[newSize];
  463. var g = _lastGrouping;
  464. do
  465. {
  466. g = g._next;
  467. var index = g._hashCode % newSize;
  468. g._hashNext = newGroupings[index];
  469. newGroupings[index] = g;
  470. } while (g != _lastGrouping);
  471. _groupings = newGroupings;
  472. }
  473. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  474. {
  475. return Task.FromResult(Count);
  476. }
  477. IAsyncEnumerator<IAsyncGrouping<TKey, TElement>> IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>.GetAsyncEnumerator(CancellationToken cancellationToken)
  478. {
  479. return Enumerable.Cast<IAsyncGrouping<TKey, TElement>>(this).ToAsyncEnumerable().GetAsyncEnumerator(cancellationToken);
  480. }
  481. Task<List<IAsyncGrouping<TKey, TElement>>> IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>.ToListAsync(CancellationToken cancellationToken)
  482. {
  483. var list = new List<IAsyncGrouping<TKey, TElement>>(Count);
  484. var g = _lastGrouping;
  485. if (g != null)
  486. {
  487. do
  488. {
  489. g = g._next;
  490. list.Add(g);
  491. }
  492. while (g != _lastGrouping);
  493. }
  494. return Task.FromResult(list);
  495. }
  496. Task<IAsyncGrouping<TKey, TElement>[]> IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>.ToArrayAsync(CancellationToken cancellationToken)
  497. {
  498. var array = new IAsyncGrouping<TKey, TElement>[Count];
  499. var index = 0;
  500. var g = _lastGrouping;
  501. if (g != null)
  502. {
  503. do
  504. {
  505. g = g._next;
  506. array[index] = g;
  507. ++index;
  508. }
  509. while (g != _lastGrouping);
  510. }
  511. return Task.FromResult(array);
  512. }
  513. }
  514. }