Union.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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.Generic;
  5. using System.Diagnostics;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<TSource> Union<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second) =>
  13. Union(first, second, comparer: null);
  14. public static IAsyncEnumerable<TSource> Union<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
  15. {
  16. if (first == null)
  17. throw Error.ArgumentNull(nameof(first));
  18. if (second == null)
  19. throw Error.ArgumentNull(nameof(second));
  20. return first is UnionAsyncIterator<TSource> union && AreEqualityComparersEqual(comparer, union._comparer) ? union.Union(second) : new UnionAsyncIterator2<TSource>(first, second, comparer);
  21. }
  22. private static bool AreEqualityComparersEqual<TSource>(IEqualityComparer<TSource> first, IEqualityComparer<TSource> second)
  23. {
  24. return first == second || (first != null && second != null && first.Equals(second));
  25. }
  26. /// <summary>
  27. /// An iterator that yields distinct values from two or more <see cref="IAsyncEnumerable{TSource}"/>.
  28. /// </summary>
  29. /// <typeparam name="TSource">The type of the source enumerables.</typeparam>
  30. private abstract class UnionAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  31. {
  32. internal readonly IEqualityComparer<TSource> _comparer;
  33. private IAsyncEnumerator<TSource> _enumerator;
  34. private Set<TSource> _set;
  35. private int _index;
  36. protected UnionAsyncIterator(IEqualityComparer<TSource> comparer)
  37. {
  38. _comparer = comparer;
  39. }
  40. public sealed override async ValueTask DisposeAsync()
  41. {
  42. if (_enumerator != null)
  43. {
  44. await _enumerator.DisposeAsync().ConfigureAwait(false);
  45. _enumerator = null;
  46. _set = null;
  47. }
  48. await base.DisposeAsync().ConfigureAwait(false);
  49. }
  50. internal abstract IAsyncEnumerable<TSource> GetEnumerable(int index);
  51. internal abstract UnionAsyncIterator<TSource> Union(IAsyncEnumerable<TSource> next);
  52. private async Task SetEnumeratorAsync(IAsyncEnumerator<TSource> enumerator)
  53. {
  54. if (_enumerator != null)
  55. {
  56. await _enumerator.DisposeAsync().ConfigureAwait(false);
  57. }
  58. _enumerator = enumerator;
  59. }
  60. private void StoreFirst()
  61. {
  62. var set = new Set<TSource>(_comparer);
  63. var element = _enumerator.Current;
  64. set.Add(element);
  65. _current = element;
  66. _set = set;
  67. }
  68. private async ValueTask<bool> GetNextAsync()
  69. {
  70. var set = _set;
  71. Debug.Assert(set != null);
  72. while (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  73. {
  74. var element = _enumerator.Current;
  75. if (set.Add(element))
  76. {
  77. _current = element;
  78. return true;
  79. }
  80. }
  81. return false;
  82. }
  83. protected sealed override async ValueTask<bool> MoveNextCore()
  84. {
  85. switch (_state)
  86. {
  87. case AsyncIteratorState.Allocated:
  88. _index = 0;
  89. for (var enumerable = GetEnumerable(0); enumerable != null; enumerable = GetEnumerable(_index))
  90. {
  91. ++_index;
  92. var enumerator = enumerable.GetAsyncEnumerator(_cancellationToken);
  93. if (await enumerator.MoveNextAsync().ConfigureAwait(false))
  94. {
  95. await SetEnumeratorAsync(enumerator).ConfigureAwait(false);
  96. StoreFirst();
  97. _state = AsyncIteratorState.Iterating;
  98. return true;
  99. }
  100. }
  101. break;
  102. case AsyncIteratorState.Iterating:
  103. while (true)
  104. {
  105. if (await GetNextAsync().ConfigureAwait(false))
  106. {
  107. return true;
  108. }
  109. var enumerable = GetEnumerable(_index);
  110. if (enumerable == null)
  111. {
  112. break;
  113. }
  114. await SetEnumeratorAsync(enumerable.GetAsyncEnumerator(_cancellationToken)).ConfigureAwait(false);
  115. ++_index;
  116. }
  117. break;
  118. }
  119. await DisposeAsync().ConfigureAwait(false);
  120. return false;
  121. }
  122. private async Task<Set<TSource>> FillSetAsync(CancellationToken cancellationToken)
  123. {
  124. cancellationToken.ThrowIfCancellationRequested();
  125. var set = new Set<TSource>(_comparer);
  126. for (var index = 0; ; ++index)
  127. {
  128. var enumerable = GetEnumerable(index);
  129. if (enumerable == null)
  130. {
  131. return set;
  132. }
  133. await foreach (TSource item in enumerable.WithCancellation(cancellationToken).ConfigureAwait(false))
  134. {
  135. set.Add(item);
  136. }
  137. }
  138. }
  139. public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  140. {
  141. var set = await FillSetAsync(cancellationToken).ConfigureAwait(false);
  142. return set.ToArray();
  143. }
  144. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  145. {
  146. var set = await FillSetAsync(cancellationToken).ConfigureAwait(false);
  147. return set.ToList();
  148. }
  149. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  150. {
  151. if (onlyIfCheap)
  152. {
  153. return new ValueTask<int>(-1);
  154. }
  155. return Core();
  156. async ValueTask<int> Core()
  157. {
  158. var set = await FillSetAsync(cancellationToken).ConfigureAwait(false);
  159. return set.Count;
  160. }
  161. }
  162. }
  163. /// <summary>
  164. /// An iterator that yields distinct values from two <see cref="IAsyncEnumerable{TSource}"/>.
  165. /// </summary>
  166. /// <typeparam name="TSource">The type of the source enumerables.</typeparam>
  167. private sealed class UnionAsyncIterator2<TSource> : UnionAsyncIterator<TSource>
  168. {
  169. private readonly IAsyncEnumerable<TSource> _first;
  170. private readonly IAsyncEnumerable<TSource> _second;
  171. public UnionAsyncIterator2(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
  172. : base(comparer)
  173. {
  174. Debug.Assert(first != null);
  175. Debug.Assert(second != null);
  176. _first = first;
  177. _second = second;
  178. }
  179. public override AsyncIteratorBase<TSource> Clone() => new UnionAsyncIterator2<TSource>(_first, _second, _comparer);
  180. internal override IAsyncEnumerable<TSource> GetEnumerable(int index)
  181. {
  182. Debug.Assert(index >= 0 && index <= 2);
  183. switch (index)
  184. {
  185. case 0:
  186. return _first;
  187. case 1:
  188. return _second;
  189. default:
  190. return null;
  191. }
  192. }
  193. internal override UnionAsyncIterator<TSource> Union(IAsyncEnumerable<TSource> next)
  194. {
  195. var sources = new SingleLinkedNode<IAsyncEnumerable<TSource>>(_first).Add(_second).Add(next);
  196. return new UnionAsyncIteratorN<TSource>(sources, 2, _comparer);
  197. }
  198. }
  199. /// <summary>
  200. /// An iterator that yields distinct values from three or more <see cref="IAsyncEnumerable{TSource}"/>.
  201. /// </summary>
  202. /// <typeparam name="TSource">The type of the source enumerables.</typeparam>
  203. private sealed class UnionAsyncIteratorN<TSource> : UnionAsyncIterator<TSource>
  204. {
  205. private readonly SingleLinkedNode<IAsyncEnumerable<TSource>> _sources;
  206. private readonly int _headIndex;
  207. public UnionAsyncIteratorN(SingleLinkedNode<IAsyncEnumerable<TSource>> sources, int headIndex, IEqualityComparer<TSource> comparer)
  208. : base(comparer)
  209. {
  210. Debug.Assert(headIndex >= 2);
  211. Debug.Assert(sources?.GetCount() == headIndex + 1);
  212. _sources = sources;
  213. _headIndex = headIndex;
  214. }
  215. public override AsyncIteratorBase<TSource> Clone() => new UnionAsyncIteratorN<TSource>(_sources, _headIndex, _comparer);
  216. internal override IAsyncEnumerable<TSource> GetEnumerable(int index) => index > _headIndex ? null : _sources.GetNode(_headIndex - index).Item;
  217. internal override UnionAsyncIterator<TSource> Union(IAsyncEnumerable<TSource> next)
  218. {
  219. if (_headIndex == int.MaxValue - 2)
  220. {
  221. // In the unlikely case of this many unions, if we produced a UnionIteratorN
  222. // with int.MaxValue then state would overflow before it matched it's index.
  223. // So we use the naïve approach of just having a left and right sequence.
  224. return new UnionAsyncIterator2<TSource>(this, next, _comparer);
  225. }
  226. return new UnionAsyncIteratorN<TSource>(_sources.Add(next), _headIndex + 1, _comparer);
  227. }
  228. }
  229. }
  230. }