Empty.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. /// <summary>
  12. /// Returns an empty async-enumerable sequence.
  13. /// </summary>
  14. /// <typeparam name="TValue">The type used for the <see cref="IAsyncEnumerable{T}"/> type parameter of the resulting sequence.</typeparam>
  15. /// <returns>An async-enumerable sequence with no elements.</returns>
  16. public static IAsyncEnumerable<TValue> Empty<TValue>() => EmptyAsyncIterator<TValue>.Instance;
  17. internal sealed class EmptyAsyncIterator<TValue> : IAsyncPartition<TValue>, IAsyncEnumerator<TValue>
  18. {
  19. public static readonly EmptyAsyncIterator<TValue> Instance = new EmptyAsyncIterator<TValue>();
  20. public TValue Current => default!;
  21. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken) => new ValueTask<int>(0);
  22. public IAsyncPartition<TValue> Skip(int count) => this;
  23. public IAsyncPartition<TValue> Take(int count) => this;
  24. public ValueTask<TValue[]> ToArrayAsync(CancellationToken cancellationToken) => new ValueTask<TValue[]>(
  25. #if NO_ARRAY_EMPTY
  26. EmptyArray<TValue>.Value
  27. #else
  28. Array.Empty<TValue>()
  29. #endif
  30. );
  31. public ValueTask<List<TValue>> ToListAsync(CancellationToken cancellationToken) => new ValueTask<List<TValue>>(new List<TValue>());
  32. public ValueTask<Maybe<TValue>> TryGetElementAtAsync(int index, CancellationToken cancellationToken) => new ValueTask<Maybe<TValue>>(new Maybe<TValue>());
  33. public ValueTask<Maybe<TValue>> TryGetFirstAsync(CancellationToken cancellationToken) => new ValueTask<Maybe<TValue>>(new Maybe<TValue>());
  34. public ValueTask<Maybe<TValue>> TryGetLastAsync(CancellationToken cancellationToken) => new ValueTask<Maybe<TValue>>(new Maybe<TValue>());
  35. public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(false);
  36. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
  37. {
  38. cancellationToken.ThrowIfCancellationRequested(); // NB: [LDM-2018-11-28] Equivalent to async iterator behavior.
  39. return this;
  40. }
  41. public ValueTask DisposeAsync() => default;
  42. }
  43. }
  44. }