Skip to content

Commit

Permalink
Added async singleton collection
Browse files Browse the repository at this point in the history
  • Loading branch information
sakno committed Oct 8, 2024
1 parent 7c97196 commit aeb6598
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/DotNext.Tests/Collections/Generic/AsyncEnumerableTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,11 @@ public static async Task SkipNullsTestAsync()
True(Array.Exists(array, "a".Equals));
True(Array.Exists(array, "b".Equals));
}

[Fact]
public static void Singleton()
{
var enumerable = AsyncEnumerable.Singleton(42);
Equal(42, Single(enumerable));
}
}
9 changes: 9 additions & 0 deletions src/DotNext/Collections/Generic/AsyncEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,13 @@ public static IAsyncEnumerable<T> Throw<T>(Exception e)

return new ThrowingEnumerator<T>(e);
}

/// <summary>
/// Constructs read-only sequence with a single item in it.
/// </summary>
/// <param name="item">An item to be placed into list.</param>
/// <typeparam name="T">Type of list items.</typeparam>
/// <returns>Read-only list containing single item.</returns>
public static IAsyncEnumerable<T> Singleton<T>(T item)
=> new Specialized.SingletonList<T> { Item = item };
}
6 changes: 5 additions & 1 deletion src/DotNext/Collections/Specialized/SingletonList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace DotNext.Collections.Specialized;
/// </summary>
/// <typeparam name="T">The type of the element in the list.</typeparam>
[StructLayout(LayoutKind.Auto)]
public struct SingletonList<T> : IReadOnlyList<T>, IList<T>, ITuple, IReadOnlySet<T>
public struct SingletonList<T> : IReadOnlyList<T>, IList<T>, ITuple, IReadOnlySet<T>, IAsyncEnumerable<T>
{
/// <summary>
/// Represents an enumerator over the collection containing a single element.
Expand Down Expand Up @@ -145,6 +145,10 @@ readonly IEnumerator<T> IEnumerable<T>.GetEnumerator()
readonly IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator().ToClassicEnumerator<Enumerator, T>();

/// <inheritdoc />
readonly IAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(CancellationToken token)
=> GetEnumerator().ToAsyncEnumerator<Enumerator, T>(token);

/// <summary>
/// Converts a value to the read-only list.
/// </summary>
Expand Down

0 comments on commit aeb6598

Please sign in to comment.