Union.cs 10 KB

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