Lookup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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)
  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<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, IAsyncEnumerable<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.ToAsyncEnumerable());
  159. } while (g != _lastGrouping);
  160. }
  161. }
  162. 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 = default(CancellationToken))
  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. var enu = source.GetAsyncEnumerator();
  169. try
  170. {
  171. while (await enu.MoveNextAsync(cancellationToken)
  172. .ConfigureAwait(false))
  173. {
  174. lookup.GetGrouping(keySelector(enu.Current), create: true)
  175. .Add(elementSelector(enu.Current));
  176. }
  177. }
  178. finally
  179. {
  180. await enu.DisposeAsync().ConfigureAwait(false);
  181. }
  182. return lookup;
  183. }
  184. internal static async Task<Lookup<TKey, TElement>> CreateAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken = default(CancellationToken))
  185. {
  186. Debug.Assert(source != null);
  187. Debug.Assert(keySelector != null);
  188. var lookup = new Lookup<TKey, TElement>(comparer);
  189. var enu = source.GetAsyncEnumerator();
  190. try
  191. {
  192. while (await enu.MoveNextAsync(cancellationToken)
  193. .ConfigureAwait(false))
  194. {
  195. lookup.GetGrouping(keySelector(enu.Current), create: true)
  196. .Add(enu.Current);
  197. }
  198. }
  199. finally
  200. {
  201. await enu.DisposeAsync().ConfigureAwait(false);
  202. }
  203. return lookup;
  204. }
  205. internal static async Task<Lookup<TKey, TElement>> CreateForJoinAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer)
  206. {
  207. var lookup = new Lookup<TKey, TElement>(comparer);
  208. var enu = source.GetAsyncEnumerator();
  209. try
  210. {
  211. while (await enu.MoveNextAsync()
  212. .ConfigureAwait(false))
  213. {
  214. var key = keySelector(enu.Current);
  215. if (key != null)
  216. {
  217. lookup.GetGrouping(key, create: true)
  218. .Add(enu.Current);
  219. }
  220. }
  221. }
  222. finally
  223. {
  224. await enu.DisposeAsync().ConfigureAwait(false);
  225. }
  226. return lookup;
  227. }
  228. internal Grouping<TKey, TElement> GetGrouping(TKey key, bool create)
  229. {
  230. var hashCode = InternalGetHashCode(key);
  231. for (var g = _groupings[hashCode%_groupings.Length]; g != null; g = g._hashNext)
  232. {
  233. if (g._hashCode == hashCode && _comparer.Equals(g._key, key))
  234. {
  235. return g;
  236. }
  237. }
  238. if (create)
  239. {
  240. if (Count == _groupings.Length)
  241. {
  242. Resize();
  243. }
  244. var index = hashCode%_groupings.Length;
  245. var g = new Grouping<TKey, TElement>
  246. {
  247. _key = key,
  248. _hashCode = hashCode,
  249. _elements = new TElement[1],
  250. _hashNext = _groupings[index]
  251. };
  252. _groupings[index] = g;
  253. if (_lastGrouping == null)
  254. {
  255. g._next = g;
  256. }
  257. else
  258. {
  259. g._next = _lastGrouping._next;
  260. _lastGrouping._next = g;
  261. }
  262. _lastGrouping = g;
  263. Count++;
  264. return g;
  265. }
  266. return null;
  267. }
  268. internal int InternalGetHashCode(TKey key)
  269. {
  270. // Handle comparer implementations that throw when passed null
  271. return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF;
  272. }
  273. internal TResult[] ToArray<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  274. {
  275. var array = new TResult[Count];
  276. var index = 0;
  277. var g = _lastGrouping;
  278. if (g != null)
  279. {
  280. do
  281. {
  282. g = g._next;
  283. g.Trim();
  284. array[index] = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  285. ++index;
  286. } while (g != _lastGrouping);
  287. }
  288. return array;
  289. }
  290. internal List<TResult> ToList<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  291. {
  292. var list = new List<TResult>(Count);
  293. var g = _lastGrouping;
  294. if (g != null)
  295. {
  296. do
  297. {
  298. g = g._next;
  299. g.Trim();
  300. list.Add(resultSelector(g._key, g._elements.ToAsyncEnumerable()));
  301. } while (g != _lastGrouping);
  302. }
  303. return list;
  304. }
  305. private void Resize()
  306. {
  307. var newSize = checked((Count*2) + 1);
  308. var newGroupings = new Grouping<TKey, TElement>[newSize];
  309. var g = _lastGrouping;
  310. do
  311. {
  312. g = g._next;
  313. var index = g._hashCode%newSize;
  314. g._hashNext = newGroupings[index];
  315. newGroupings[index] = g;
  316. } while (g != _lastGrouping);
  317. _groupings = newGroupings;
  318. }
  319. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  320. {
  321. return Task.FromResult(Count);
  322. }
  323. IAsyncEnumerator<IAsyncGrouping<TKey, TElement>> IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>.GetAsyncEnumerator()
  324. {
  325. return Enumerable.Cast<IAsyncGrouping<TKey, TElement>>(this).ToAsyncEnumerable().GetAsyncEnumerator();
  326. }
  327. Task<List<IAsyncGrouping<TKey, TElement>>> IIListProvider<IAsyncGrouping<TKey, TElement>>.ToListAsync(CancellationToken cancellationToken)
  328. {
  329. var list = new List<IAsyncGrouping<TKey, TElement>>(Count);
  330. var g = _lastGrouping;
  331. if (g != null)
  332. {
  333. do
  334. {
  335. g = g._next;
  336. list.Add(g);
  337. }
  338. while (g != _lastGrouping);
  339. }
  340. return Task.FromResult(list);
  341. }
  342. Task<IAsyncGrouping<TKey, TElement>[]> IIListProvider<IAsyncGrouping<TKey, TElement>>.ToArrayAsync(CancellationToken cancellationToken)
  343. {
  344. var array = new IAsyncGrouping<TKey, TElement>[Count];
  345. var index = 0;
  346. var g = _lastGrouping;
  347. if (g != null)
  348. {
  349. do
  350. {
  351. g = g._next;
  352. array[index] = g;
  353. ++index;
  354. }
  355. while (g != _lastGrouping);
  356. }
  357. return Task.FromResult(array);
  358. }
  359. }
  360. }