Lookup.cs 17 KB

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