Lookup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
  14. {
  15. if (source == null)
  16. {
  17. throw new ArgumentNullException(nameof(source));
  18. }
  19. if (keySelector == null)
  20. {
  21. throw new ArgumentNullException(nameof(keySelector));
  22. }
  23. if (elementSelector == null)
  24. {
  25. throw new ArgumentNullException(nameof(elementSelector));
  26. }
  27. if (comparer == null)
  28. {
  29. throw new ArgumentNullException(nameof(comparer));
  30. }
  31. return ToLookup(source, keySelector, elementSelector, comparer, CancellationToken.None);
  32. }
  33. public static Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
  34. {
  35. if (source == null)
  36. {
  37. throw new ArgumentNullException(nameof(source));
  38. }
  39. if (keySelector == null)
  40. {
  41. throw new ArgumentNullException(nameof(keySelector));
  42. }
  43. if (elementSelector == null)
  44. {
  45. throw new ArgumentNullException(nameof(elementSelector));
  46. }
  47. return ToLookup(source, keySelector, elementSelector, CancellationToken.None);
  48. }
  49. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
  50. {
  51. if (source == null)
  52. {
  53. throw new ArgumentNullException(nameof(source));
  54. }
  55. if (keySelector == null)
  56. {
  57. throw new ArgumentNullException(nameof(keySelector));
  58. }
  59. if (comparer == null)
  60. {
  61. throw new ArgumentNullException(nameof(comparer));
  62. }
  63. return ToLookup(source, keySelector, comparer, CancellationToken.None);
  64. }
  65. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  66. {
  67. if (source == null)
  68. {
  69. throw new ArgumentNullException(nameof(source));
  70. }
  71. if (keySelector == null)
  72. {
  73. throw new ArgumentNullException(nameof(keySelector));
  74. }
  75. return ToLookup(source, keySelector, CancellationToken.None);
  76. }
  77. public static async Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  78. {
  79. if (source == null)
  80. {
  81. throw new ArgumentNullException(nameof(source));
  82. }
  83. if (keySelector == null)
  84. {
  85. throw new ArgumentNullException(nameof(keySelector));
  86. }
  87. if (elementSelector == null)
  88. {
  89. throw new ArgumentNullException(nameof(elementSelector));
  90. }
  91. if (comparer == null)
  92. {
  93. throw new ArgumentNullException(nameof(comparer));
  94. }
  95. var lookup = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken)
  96. .ConfigureAwait(false);
  97. return lookup;
  98. }
  99. public static Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken)
  100. {
  101. if (source == null)
  102. {
  103. throw new ArgumentNullException(nameof(source));
  104. }
  105. if (keySelector == null)
  106. {
  107. throw new ArgumentNullException(nameof(keySelector));
  108. }
  109. if (elementSelector == null)
  110. {
  111. throw new ArgumentNullException(nameof(elementSelector));
  112. }
  113. return source.ToLookup(keySelector, elementSelector, EqualityComparer<TKey>.Default, cancellationToken);
  114. }
  115. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  116. {
  117. if (source == null)
  118. {
  119. throw new ArgumentNullException(nameof(source));
  120. }
  121. if (keySelector == null)
  122. {
  123. throw new ArgumentNullException(nameof(keySelector));
  124. }
  125. if (comparer == null)
  126. {
  127. throw new ArgumentNullException(nameof(comparer));
  128. }
  129. return source.ToLookup(keySelector, x => x, comparer, cancellationToken);
  130. }
  131. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, CancellationToken cancellationToken)
  132. {
  133. if (source == null)
  134. {
  135. throw new ArgumentNullException(nameof(source));
  136. }
  137. if (keySelector == null)
  138. {
  139. throw new ArgumentNullException(nameof(keySelector));
  140. }
  141. return source.ToLookup(keySelector, x => x, EqualityComparer<TKey>.Default, cancellationToken);
  142. }
  143. }
  144. }
  145. // This is internal because System.Linq exposes a public Lookup that we cannot directly use here
  146. namespace System.Linq.Internal
  147. {
  148. internal class Lookup<TKey, TElement> : ILookup<TKey, TElement>, IIListProvider<IAsyncGrouping<TKey, TElement>>
  149. {
  150. private readonly IEqualityComparer<TKey> _comparer;
  151. private Grouping<TKey, TElement>[] _groupings;
  152. private Grouping<TKey, TElement> _lastGrouping;
  153. private Lookup(IEqualityComparer<TKey> comparer)
  154. {
  155. _comparer = comparer ?? EqualityComparer<TKey>.Default;
  156. _groupings = new Grouping<TKey, TElement>[7];
  157. }
  158. public int Count { get; private set; }
  159. public IEnumerable<TElement> this[TKey key]
  160. {
  161. get
  162. {
  163. var grouping = GetGrouping(key, create: false);
  164. if (grouping != null)
  165. {
  166. return grouping;
  167. }
  168. #if NO_ARRAY_EMPTY
  169. return EmptyArray<TElement>.Value;
  170. #else
  171. return Array.Empty<TElement>();
  172. #endif
  173. }
  174. }
  175. public bool Contains(TKey key)
  176. {
  177. return GetGrouping(key, create: false) != null;
  178. }
  179. IEnumerator IEnumerable.GetEnumerator()
  180. {
  181. return GetEnumerator();
  182. }
  183. public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
  184. {
  185. var g = _lastGrouping;
  186. if (g != null)
  187. {
  188. do
  189. {
  190. g = g._next;
  191. yield return g;
  192. } while (g != _lastGrouping);
  193. }
  194. }
  195. public IEnumerable<TResult> ApplyResultSelector<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  196. {
  197. var g = _lastGrouping;
  198. if (g != null)
  199. {
  200. do
  201. {
  202. g = g._next;
  203. g.Trim();
  204. yield return resultSelector(g._key, g._elements.ToAsyncEnumerable());
  205. } while (g != _lastGrouping);
  206. }
  207. }
  208. 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)
  209. {
  210. Debug.Assert(source != null);
  211. Debug.Assert(keySelector != null);
  212. Debug.Assert(elementSelector != null);
  213. var lookup = new Lookup<TKey, TElement>(comparer);
  214. using (var enu = source.GetEnumerator())
  215. {
  216. while (await enu.MoveNext(cancellationToken)
  217. .ConfigureAwait(false))
  218. {
  219. lookup.GetGrouping(keySelector(enu.Current), create: true)
  220. .Add(elementSelector(enu.Current));
  221. }
  222. }
  223. return lookup;
  224. }
  225. internal static async Task<Lookup<TKey, TElement>> CreateAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  226. {
  227. Debug.Assert(source != null);
  228. Debug.Assert(keySelector != null);
  229. var lookup = new Lookup<TKey, TElement>(comparer);
  230. using (var enu = source.GetEnumerator())
  231. {
  232. while (await enu.MoveNext(cancellationToken)
  233. .ConfigureAwait(false))
  234. {
  235. lookup.GetGrouping(keySelector(enu.Current), create: true)
  236. .Add(enu.Current);
  237. }
  238. }
  239. return lookup;
  240. }
  241. internal static async Task<Lookup<TKey, TElement>> CreateForJoinAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  242. {
  243. var lookup = new Lookup<TKey, TElement>(comparer);
  244. using (var enu = source.GetEnumerator())
  245. {
  246. while (await enu.MoveNext(cancellationToken)
  247. .ConfigureAwait(false))
  248. {
  249. var key = keySelector(enu.Current);
  250. if (key != null)
  251. {
  252. lookup.GetGrouping(key, create: true)
  253. .Add(enu.Current);
  254. }
  255. }
  256. }
  257. return lookup;
  258. }
  259. internal Grouping<TKey, TElement> GetGrouping(TKey key, bool create)
  260. {
  261. var hashCode = InternalGetHashCode(key);
  262. for (var g = _groupings[hashCode % _groupings.Length]; g != null; g = g._hashNext)
  263. {
  264. if (g._hashCode == hashCode && _comparer.Equals(g._key, key))
  265. {
  266. return g;
  267. }
  268. }
  269. if (create)
  270. {
  271. if (Count == _groupings.Length)
  272. {
  273. Resize();
  274. }
  275. var index = hashCode % _groupings.Length;
  276. var g = new Grouping<TKey, TElement>
  277. {
  278. _key = key,
  279. _hashCode = hashCode,
  280. _elements = new TElement[1],
  281. _hashNext = _groupings[index]
  282. };
  283. _groupings[index] = g;
  284. if (_lastGrouping == null)
  285. {
  286. g._next = g;
  287. }
  288. else
  289. {
  290. g._next = _lastGrouping._next;
  291. _lastGrouping._next = g;
  292. }
  293. _lastGrouping = g;
  294. Count++;
  295. return g;
  296. }
  297. return null;
  298. }
  299. internal int InternalGetHashCode(TKey key)
  300. {
  301. // Handle comparer implementations that throw when passed null
  302. return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF;
  303. }
  304. internal TResult[] ToArray<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  305. {
  306. var array = new TResult[Count];
  307. var index = 0;
  308. var g = _lastGrouping;
  309. if (g != null)
  310. {
  311. do
  312. {
  313. g = g._next;
  314. g.Trim();
  315. array[index] = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  316. ++index;
  317. } while (g != _lastGrouping);
  318. }
  319. return array;
  320. }
  321. internal List<TResult> ToList<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  322. {
  323. var list = new List<TResult>(Count);
  324. var g = _lastGrouping;
  325. if (g != null)
  326. {
  327. do
  328. {
  329. g = g._next;
  330. g.Trim();
  331. list.Add(resultSelector(g._key, g._elements.ToAsyncEnumerable()));
  332. } while (g != _lastGrouping);
  333. }
  334. return list;
  335. }
  336. private void Resize()
  337. {
  338. var newSize = checked((Count * 2) + 1);
  339. var newGroupings = new Grouping<TKey, TElement>[newSize];
  340. var g = _lastGrouping;
  341. do
  342. {
  343. g = g._next;
  344. var index = g._hashCode % newSize;
  345. g._hashNext = newGroupings[index];
  346. newGroupings[index] = g;
  347. } while (g != _lastGrouping);
  348. _groupings = newGroupings;
  349. }
  350. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  351. {
  352. return Task.FromResult(Count);
  353. }
  354. IAsyncEnumerator<IAsyncGrouping<TKey, TElement>> IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>.GetEnumerator()
  355. {
  356. return Enumerable.Cast<IAsyncGrouping<TKey, TElement>>(this).ToAsyncEnumerable().GetEnumerator();
  357. }
  358. Task<List<IAsyncGrouping<TKey, TElement>>> IIListProvider<IAsyncGrouping<TKey, TElement>>.ToListAsync(CancellationToken cancellationToken)
  359. {
  360. var list = new List<IAsyncGrouping<TKey, TElement>>(Count);
  361. var g = _lastGrouping;
  362. if (g != null)
  363. {
  364. do
  365. {
  366. g = g._next;
  367. list.Add(g);
  368. }
  369. while (g != _lastGrouping);
  370. }
  371. return Task.FromResult(list);
  372. }
  373. Task<IAsyncGrouping<TKey, TElement>[]> IIListProvider<IAsyncGrouping<TKey, TElement>>.ToArrayAsync(CancellationToken cancellationToken)
  374. {
  375. var array = new IAsyncGrouping<TKey, TElement>[Count];
  376. var index = 0;
  377. var g = _lastGrouping;
  378. if (g != null)
  379. {
  380. do
  381. {
  382. g = g._next;
  383. array[index] = g;
  384. ++index;
  385. }
  386. while (g != _lastGrouping);
  387. }
  388. return Task.FromResult(array);
  389. }
  390. }
  391. }