ToHashSet.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using Cysharp.Threading.Tasks.Internal;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. namespace Cysharp.Threading.Tasks.Linq
  5. {
  6. public static partial class UniTaskAsyncEnumerable
  7. {
  8. public static UniTask<HashSet<TSource>> ToHashSetAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  9. {
  10. Error.ThrowArgumentNullException(source, nameof(source));
  11. return Cysharp.Threading.Tasks.Linq.ToHashSet.ToHashSetAsync(source, EqualityComparer<TSource>.Default, cancellationToken);
  12. }
  13. public static UniTask<HashSet<TSource>> ToHashSetAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken = default)
  14. {
  15. Error.ThrowArgumentNullException(source, nameof(source));
  16. Error.ThrowArgumentNullException(comparer, nameof(comparer));
  17. return Cysharp.Threading.Tasks.Linq.ToHashSet.ToHashSetAsync(source, comparer, cancellationToken);
  18. }
  19. }
  20. internal static class ToHashSet
  21. {
  22. internal static async UniTask<HashSet<TSource>> ToHashSetAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  23. {
  24. var set = new HashSet<TSource>(comparer);
  25. var e = source.GetAsyncEnumerator(cancellationToken);
  26. try
  27. {
  28. while (await e.MoveNextAsync())
  29. {
  30. set.Add(e.Current);
  31. }
  32. }
  33. finally
  34. {
  35. if (e != null)
  36. {
  37. await e.DisposeAsync();
  38. }
  39. }
  40. return set;
  41. }
  42. }
  43. }