Union.cs 11 KB

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