Lookup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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>>
  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 Lookup<TKey, TElement> CreateForJoin(IEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer)
  205. {
  206. var lookup = new Lookup<TKey, TElement>(comparer);
  207. foreach (var item in source)
  208. {
  209. var key = keySelector(item);
  210. if (key != null)
  211. {
  212. lookup.GetGrouping(key, create: true)
  213. .Add(item);
  214. }
  215. }
  216. return lookup;
  217. }
  218. internal static async Task<Lookup<TKey, TElement>> CreateForJoinAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  219. {
  220. var lookup = new Lookup<TKey, TElement>(comparer);
  221. using (var enu = source.GetEnumerator())
  222. {
  223. while (await enu.MoveNext(cancellationToken)
  224. .ConfigureAwait(false))
  225. {
  226. var key = keySelector(enu.Current);
  227. if (key != null)
  228. {
  229. lookup.GetGrouping(key, create: true)
  230. .Add(enu.Current);
  231. }
  232. }
  233. }
  234. return lookup;
  235. }
  236. internal Grouping<TKey, TElement> GetGrouping(TKey key, bool create)
  237. {
  238. var hashCode = InternalGetHashCode(key);
  239. for (var g = _groupings[hashCode%_groupings.Length]; g != null; g = g._hashNext)
  240. {
  241. if (g._hashCode == hashCode && _comparer.Equals(g._key, key))
  242. {
  243. return g;
  244. }
  245. }
  246. if (create)
  247. {
  248. if (Count == _groupings.Length)
  249. {
  250. Resize();
  251. }
  252. var index = hashCode%_groupings.Length;
  253. var g = new Grouping<TKey, TElement>();
  254. g._key = key;
  255. g._hashCode = hashCode;
  256. g._elements = new TElement[1];
  257. g._hashNext = _groupings[index];
  258. _groupings[index] = g;
  259. if (_lastGrouping == null)
  260. {
  261. g._next = g;
  262. }
  263. else
  264. {
  265. g._next = _lastGrouping._next;
  266. _lastGrouping._next = g;
  267. }
  268. _lastGrouping = g;
  269. Count++;
  270. return g;
  271. }
  272. return null;
  273. }
  274. internal int InternalGetHashCode(TKey key)
  275. {
  276. // Handle comparer implementations that throw when passed null
  277. return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF;
  278. }
  279. internal TResult[] ToArray<TResult>(Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
  280. {
  281. var array = new TResult[Count];
  282. var index = 0;
  283. var g = _lastGrouping;
  284. if (g != null)
  285. {
  286. do
  287. {
  288. g = g._next;
  289. g.Trim();
  290. array[index] = resultSelector(g._key, g._elements);
  291. ++index;
  292. } while (g != _lastGrouping);
  293. }
  294. return array;
  295. }
  296. internal List<TResult> ToList<TResult>(Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
  297. {
  298. var list = new List<TResult>(Count);
  299. var g = _lastGrouping;
  300. if (g != null)
  301. {
  302. do
  303. {
  304. g = g._next;
  305. g.Trim();
  306. list.Add(resultSelector(g._key, g._elements));
  307. } while (g != _lastGrouping);
  308. }
  309. return list;
  310. }
  311. private void Resize()
  312. {
  313. var newSize = checked((Count*2) + 1);
  314. var newGroupings = new Grouping<TKey, TElement>[newSize];
  315. var g = _lastGrouping;
  316. do
  317. {
  318. g = g._next;
  319. var index = g._hashCode%newSize;
  320. g._hashNext = newGroupings[index];
  321. newGroupings[index] = g;
  322. } while (g != _lastGrouping);
  323. _groupings = newGroupings;
  324. }
  325. IAsyncEnumerator<IGrouping<TKey, TElement>> IAsyncEnumerable<IGrouping<TKey, TElement>>.GetEnumerator()
  326. {
  327. return new AsyncEnumerable.AsyncEnumerableAdapter<IGrouping<TKey, TElement>>(this).GetEnumerator();
  328. }
  329. public Task<IGrouping<TKey, TElement>[]> ToArrayAsync(CancellationToken cancellationToken)
  330. {
  331. var array = new IGrouping<TKey, TElement>[Count];
  332. var index = 0;
  333. var g = _lastGrouping;
  334. if (g != null)
  335. {
  336. do
  337. {
  338. g = g._next;
  339. array[index] = g;
  340. ++index;
  341. }
  342. while (g != _lastGrouping);
  343. }
  344. return Task.FromResult(array);
  345. }
  346. public Task<List<IGrouping<TKey, TElement>>> ToListAsync(CancellationToken cancellationToken)
  347. {
  348. var list = new List<IGrouping<TKey, TElement>>(Count);
  349. var g = _lastGrouping;
  350. if (g != null)
  351. {
  352. do
  353. {
  354. g = g._next;
  355. list.Add(g);
  356. }
  357. while (g != _lastGrouping);
  358. }
  359. return Task.FromResult(list);
  360. }
  361. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  362. {
  363. return Task.FromResult(Count);
  364. }
  365. }
  366. }