Lookup.cs 15 KB

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