ToAsyncEnumerable.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  11. public static partial class AsyncEnumerable
  12. {
  13. /// <summary>
  14. /// Converts an enumerable sequence to an async-enumerable sequence.
  15. /// </summary>
  16. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  17. /// <param name="source">Enumerable sequence to convert to an async-enumerable sequence.</param>
  18. /// <returns>The async-enumerable sequence whose elements are pulled from the given enumerable sequence.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  20. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this IEnumerable<TSource> source)
  21. {
  22. if (source == null)
  23. throw Error.ArgumentNull(nameof(source));
  24. return source switch
  25. {
  26. IList<TSource> list => new AsyncIListEnumerableAdapter<TSource>(list),
  27. ICollection<TSource> collection => new AsyncICollectionEnumerableAdapter<TSource>(collection),
  28. _ => new AsyncEnumerableAdapter<TSource>(source),
  29. };
  30. }
  31. private sealed class AsyncEnumerableAdapter<T> : AsyncIterator<T>, IAsyncIListProvider<T>
  32. {
  33. private readonly IEnumerable<T> _source;
  34. private IEnumerator<T>? _enumerator;
  35. public AsyncEnumerableAdapter(IEnumerable<T> source)
  36. {
  37. _source = source;
  38. }
  39. public override AsyncIteratorBase<T> Clone() => new AsyncEnumerableAdapter<T>(_source);
  40. public override async ValueTask DisposeAsync()
  41. {
  42. if (_enumerator != null)
  43. {
  44. _enumerator.Dispose();
  45. _enumerator = null;
  46. }
  47. await base.DisposeAsync().ConfigureAwait(false);
  48. }
  49. protected override async ValueTask<bool> MoveNextCore()
  50. {
  51. switch (_state)
  52. {
  53. case AsyncIteratorState.Allocated:
  54. _enumerator = _source.GetEnumerator();
  55. _state = AsyncIteratorState.Iterating;
  56. goto case AsyncIteratorState.Iterating;
  57. case AsyncIteratorState.Iterating:
  58. if (_enumerator!.MoveNext())
  59. {
  60. _current = _enumerator.Current;
  61. return true;
  62. }
  63. await DisposeAsync().ConfigureAwait(false);
  64. break;
  65. }
  66. return false;
  67. }
  68. //
  69. // NB: These optimizations rely on the System.Linq implementation of IEnumerable<T> operators to optimize
  70. // and short-circuit as appropriate.
  71. //
  72. public ValueTask<T[]> ToArrayAsync(CancellationToken cancellationToken)
  73. {
  74. cancellationToken.ThrowIfCancellationRequested();
  75. return new ValueTask<T[]>(_source.ToArray());
  76. }
  77. public ValueTask<List<T>> ToListAsync(CancellationToken cancellationToken)
  78. {
  79. cancellationToken.ThrowIfCancellationRequested();
  80. return new ValueTask<List<T>>(_source.ToList());
  81. }
  82. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  83. {
  84. cancellationToken.ThrowIfCancellationRequested();
  85. return new ValueTask<int>(_source.Count());
  86. }
  87. }
  88. private sealed class AsyncIListEnumerableAdapter<T> : AsyncIterator<T>, IAsyncIListProvider<T>, IList<T>
  89. {
  90. private readonly IList<T> _source;
  91. private IEnumerator<T>? _enumerator;
  92. public AsyncIListEnumerableAdapter(IList<T> source)
  93. {
  94. _source = source;
  95. }
  96. public override AsyncIteratorBase<T> Clone() => new AsyncIListEnumerableAdapter<T>(_source);
  97. public override async ValueTask DisposeAsync()
  98. {
  99. if (_enumerator != null)
  100. {
  101. _enumerator.Dispose();
  102. _enumerator = null;
  103. }
  104. await base.DisposeAsync().ConfigureAwait(false);
  105. }
  106. protected override async ValueTask<bool> MoveNextCore()
  107. {
  108. switch (_state)
  109. {
  110. case AsyncIteratorState.Allocated:
  111. _enumerator = _source.GetEnumerator();
  112. _state = AsyncIteratorState.Iterating;
  113. goto case AsyncIteratorState.Iterating;
  114. case AsyncIteratorState.Iterating:
  115. if (_enumerator!.MoveNext())
  116. {
  117. _current = _enumerator.Current;
  118. return true;
  119. }
  120. await DisposeAsync().ConfigureAwait(false);
  121. break;
  122. }
  123. return false;
  124. }
  125. public override IAsyncEnumerable<TResult> Select<TResult>(Func<T, TResult> selector) => new SelectIListIterator<T, TResult>(_source, selector);
  126. //
  127. // NB: These optimizations rely on the System.Linq implementation of IEnumerable<T> operators to optimize
  128. // and short-circuit as appropriate.
  129. //
  130. public ValueTask<T[]> ToArrayAsync(CancellationToken cancellationToken)
  131. {
  132. cancellationToken.ThrowIfCancellationRequested();
  133. return new ValueTask<T[]>(_source.ToArray());
  134. }
  135. public ValueTask<List<T>> ToListAsync(CancellationToken cancellationToken)
  136. {
  137. cancellationToken.ThrowIfCancellationRequested();
  138. return new ValueTask<List<T>>(_source.ToList());
  139. }
  140. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  141. {
  142. cancellationToken.ThrowIfCancellationRequested();
  143. return new ValueTask<int>(_source.Count);
  144. }
  145. IEnumerator<T> IEnumerable<T>.GetEnumerator() => _source.GetEnumerator();
  146. IEnumerator IEnumerable.GetEnumerator() => _source.GetEnumerator();
  147. void ICollection<T>.Add(T item) => _source.Add(item);
  148. void ICollection<T>.Clear() => _source.Clear();
  149. bool ICollection<T>.Contains(T item) => _source.Contains(item);
  150. void ICollection<T>.CopyTo(T[] array, int arrayIndex) => _source.CopyTo(array, arrayIndex);
  151. bool ICollection<T>.Remove(T item) => _source.Remove(item);
  152. int ICollection<T>.Count => _source.Count;
  153. bool ICollection<T>.IsReadOnly => _source.IsReadOnly;
  154. int IList<T>.IndexOf(T item) => _source.IndexOf(item);
  155. void IList<T>.Insert(int index, T item) => _source.Insert(index, item);
  156. void IList<T>.RemoveAt(int index) => _source.RemoveAt(index);
  157. T IList<T>.this[int index]
  158. {
  159. get => _source[index];
  160. set => _source[index] = value;
  161. }
  162. }
  163. private sealed class AsyncICollectionEnumerableAdapter<T> : AsyncIterator<T>, IAsyncIListProvider<T>, ICollection<T>
  164. {
  165. private readonly ICollection<T> _source;
  166. private IEnumerator<T>? _enumerator;
  167. public AsyncICollectionEnumerableAdapter(ICollection<T> source)
  168. {
  169. _source = source;
  170. }
  171. public override AsyncIteratorBase<T> Clone() => new AsyncICollectionEnumerableAdapter<T>(_source);
  172. public override async ValueTask DisposeAsync()
  173. {
  174. if (_enumerator != null)
  175. {
  176. _enumerator.Dispose();
  177. _enumerator = null;
  178. }
  179. await base.DisposeAsync().ConfigureAwait(false);
  180. }
  181. protected override async ValueTask<bool> MoveNextCore()
  182. {
  183. switch (_state)
  184. {
  185. case AsyncIteratorState.Allocated:
  186. _enumerator = _source.GetEnumerator();
  187. _state = AsyncIteratorState.Iterating;
  188. goto case AsyncIteratorState.Iterating;
  189. case AsyncIteratorState.Iterating:
  190. if (_enumerator!.MoveNext())
  191. {
  192. _current = _enumerator.Current;
  193. return true;
  194. }
  195. await DisposeAsync().ConfigureAwait(false);
  196. break;
  197. }
  198. return false;
  199. }
  200. //
  201. // NB: These optimizations rely on the System.Linq implementation of IEnumerable<T> operators to optimize
  202. // and short-circuit as appropriate.
  203. //
  204. public ValueTask<T[]> ToArrayAsync(CancellationToken cancellationToken)
  205. {
  206. cancellationToken.ThrowIfCancellationRequested();
  207. return new ValueTask<T[]>(_source.ToArray());
  208. }
  209. public ValueTask<List<T>> ToListAsync(CancellationToken cancellationToken)
  210. {
  211. cancellationToken.ThrowIfCancellationRequested();
  212. return new ValueTask<List<T>>(_source.ToList());
  213. }
  214. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  215. {
  216. cancellationToken.ThrowIfCancellationRequested();
  217. return new ValueTask<int>(_source.Count);
  218. }
  219. IEnumerator<T> IEnumerable<T>.GetEnumerator() => _source.GetEnumerator();
  220. IEnumerator IEnumerable.GetEnumerator() => _source.GetEnumerator();
  221. void ICollection<T>.Add(T item) => _source.Add(item);
  222. void ICollection<T>.Clear() => _source.Clear();
  223. bool ICollection<T>.Contains(T item) => _source.Contains(item);
  224. void ICollection<T>.CopyTo(T[] array, int arrayIndex) => _source.CopyTo(array, arrayIndex);
  225. bool ICollection<T>.Remove(T item) => _source.Remove(item);
  226. int ICollection<T>.Count => _source.Count;
  227. bool ICollection<T>.IsReadOnly => _source.IsReadOnly;
  228. }
  229. }
  230. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  231. }