Lookup.cs 22 KB

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