Union.cs 11 KB

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