Lookup.cs 23 KB

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